Programs & Examples On #Grant

GRANT is a SQL standard command that authorizes one or more users to perform an operation or a set of operations on an object.

grant remote access of MySQL database from any IP address

In website panels like cPanel you may add a single % (percentage sign) in allowed hostnames to access your MySQL database.

By adding a single % you can access your database from any IP or website even from desktop applications.

Grant SELECT on multiple tables oracle

This worked for me on my Oracle database:

SELECT   'GRANT SELECT, insert, update, delete ON mySchema.' || TABLE_NAME || ' to myUser;'
FROM     user_tables
where table_name like 'myTblPrefix%'

Then, copy the results, paste them into your editor, then run them like a script.

You could also write a script and use "Execute Immediate" to run the generated SQL if you don't want the extra copy/paste steps.

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

Granting Rights on Stored Procedure to another user of Oracle

You can't do what I think you're asking to do.

The only privileges you can grant on procedures are EXECUTE and DEBUG.

If you want to allow user B to create a procedure in user A schema, then user B must have the CREATE ANY PROCEDURE privilege. ALTER ANY PROCEDURE and DROP ANY PROCEDURE are the other applicable privileges required to alter or drop user A procedures for user B. All are wide ranging privileges, as it doesn't restrict user B to any particular schema. User B should be highly trusted if granted these privileges.

EDIT:

As Justin mentioned, the way to give execution rights to A for a procedure owned by B:

GRANT EXECUTE ON b.procedure_name TO a;

How can I list ALL grants a user received?

Sorry guys, but selecting from all_tab_privs_recd where grantee = 'your user' will not give any output except public grants and current user grants if you run the select from a different (let us say, SYS) user. As documentation says,

ALL_TAB_PRIVS_RECD describes the following types of grants:

Object grants for which the current user is the grantee
Object grants for which an enabled role or PUBLIC is the grantee

So, if you're a DBA and want to list all object grants for a particular (not SYS itself) user, you can't use that system view.

In this case, you must perform a more complex query. Here is one taken (traced) from TOAD to select all object grants for a particular user:

select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 0, 'NEXT OBJECT', 1, 'INDEX', 2, 'TABLE', 3, 'CLUSTER',
                       4, 'VIEW', 5, 'SYNONYM', 6, 'SEQUENCE',
                       7, 'PROCEDURE', 8, 'FUNCTION', 9, 'PACKAGE',
                       11, 'PACKAGE BODY', 12, 'TRIGGER',
                       13, 'TYPE', 14, 'TYPE BODY',
                       19, 'TABLE PARTITION', 20, 'INDEX PARTITION', 21, 'LOB',
                       22, 'LIBRARY', 23, 'DIRECTORY', 24, 'QUEUE',
                       28, 'JAVA SOURCE', 29, 'JAVA CLASS', 30, 'JAVA RESOURCE',
                       32, 'INDEXTYPE', 33, 'OPERATOR',
                       34, 'TABLE SUBPARTITION', 35, 'INDEX SUBPARTITION',
                       40, 'LOB PARTITION', 41, 'LOB SUBPARTITION',
                       42, 'MATERIALIZED VIEW',
                       43, 'DIMENSION',
                       44, 'CONTEXT', 46, 'RULE SET', 47, 'RESOURCE PLAN',
                       66, 'JOB', 67, 'PROGRAM', 74, 'SCHEDULE',
                       48, 'CONSUMER GROUP',
                       51, 'SUBSCRIPTION', 52, 'LOCATION',
                       55, 'XML SCHEMA', 56, 'JAVA DATA',
                       57, 'EDITION', 59, 'RULE',
                       62, 'EVALUATION CONTEXT',
                       'UNDEFINED') object_type,
       o.name object_name,
       '' column_name
        from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
             table_privilege_map tpm
        where oa.obj# = o.obj#
          and oa.grantor# = ur.user#
          and oa.grantee# = ue.user#
          and oa.col# is null
          and oa.privilege# = tpm.privilege
          and u.user# = o.owner#
          and o.TYPE# in (2, 4, 6, 9, 7, 8, 42, 23, 22, 13, 33, 32, 66, 67, 74, 57)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0
union all -- column level grants
select tpm.name privilege,
       decode(mod(oa.option$,2), 1, 'YES', 'NO') grantable,
       ue.name grantee,
       ur.name grantor,
       u.name owner,
       decode(o.TYPE#, 2, 'TABLE', 4, 'VIEW', 42, 'MATERIALIZED VIEW') object_type,
       o.name object_name,
       c.name column_name
from sys.objauth$ oa, sys.obj$ o, sys.user$ u, sys.user$ ur, sys.user$ ue,
     sys.col$ c, table_privilege_map tpm
where oa.obj# = o.obj#
  and oa.grantor# = ur.user#
  and oa.grantee# = ue.user#
  and oa.obj# = c.obj#
  and oa.col# = c.col#
  and bitand(c.property, 32) = 0 /* not hidden column */
  and oa.col# is not null
  and oa.privilege# = tpm.privilege
  and u.user# = o.owner#
  and o.TYPE# in (2, 4, 42)
  and ue.name = 'your user'
  and bitand (o.flags, 128) = 0;

This will list all object grants (including column grants) for your (specified) user. If you don't want column level grants then delete all part of the select beginning with 'union' clause.

UPD: Studying the documentation I found another view that lists all grants in much simpler way:

select * from DBA_TAB_PRIVS where grantee = 'your user';

Bear in mind that there's no DBA_TAB_PRIVS_RECD view in Oracle.

Query grants for a table in postgres

\z mytable from psql gives you all the grants from a table, but you'd then have to split it up by individual user.

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

How to grant remote access permissions to mysql server for user?

You need to take some steps to make sure first mysql and then root user is accessible from outside:

  1. Disable skip-networking in my.cnf (i.e: /etc/mysql/my.cnf)

  2. Check value of bind-address in my.cnf, if it's set to 127.0.0.1, you can change it to 0.0.0.0 to allow access from all IPs or whatever ip that you want to connect from.

  3. Grant remote access the root user from any ip (or specify your ip instead of %)

    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'
        IDENTIFIED BY 'your_root_password'
        WITH GRANT OPTION;
    FLUSH PRIVILEGES;`
    
  4. Restart mysql service:

    sudo service mysql restart
    

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

How to grant remote access to MySQL for a whole subnet?

Motivated by @Malvineaus answer I tried it myself and noticed that it didn't work for me.

You can specify subnet masks with '192.168.1.%' or '192.168.1.0/255.255.255.0' but the subnet must always be on complete octets. see https://mariadb.com/kb/en/create-user/#host-name-component. As result the functionality between one way of specification and the other is the same.

For example '192.168.1.0/255.255.255.128' will not work as it is not on a complete octet boundary.

Give all permissions to a user on a PostgreSQL database

In PostgreSQL 9.0+ you would do the following:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA MY_SCHEMA TO MY_GROUP;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA MY_SCHEMA TO MY_GROUP;

If you want to enable this for newly created relations too, then set the default permissions:

ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON TABLES TO MY_GROUP;
ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON SEQUENCES TO MY_GROUP;

However, seeing that you use 8.1 you have to code it yourself:

CREATE FUNCTION grant_all_in_schema (schname name, grant_to name) RETURNS integer AS $$
DECLARE
  rel RECORD;
BEGIN
  FOR rel IN
    SELECT c.relname
    FROM pg_class c
    JOIN pg_namespace s ON c.namespace = s.oid
    WHERE s.nspname = schname
  LOOP
    EXECUTE 'GRANT ALL PRIVILEGES ON ' || quote_ident(schname) || '.' || rel.relname || ' TO ' || quote_ident(grant_to);
  END LOOP;
  RETURN 1;
END; $$ LANGUAGE plpgsql STRICT;
REVOKE ALL ON FUNCTION grant_all_in_schema(name, name) FROM PUBLIC;

This will set the privileges on all relations: tables, views, indexes, sequences, etc. If you want to restrict that, filter on pg_class.relkind. See the pg_class docs for details.

You should run this function as superuser and as regular as your application requires. An option would be to package this in a cron job that executes every day or every hour.

Permission denied for relation

Connect to the right database first, then run:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

How do I remove version tracking from a project cloned from git?

In a Windows environment you can remove Git tracking from a project's directory by simply typing the below.

rd .git /S/Q

How to get my project path?

This gives you the root folder:

System.AppDomain.CurrentDomain.BaseDirectory

You can navigate from here using .. or ./ etc.. , Appending .. takes you to folder where .sln file can be found

For .NET framework (thanks to Adiono comment)

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"..\\..\\"))

For .NET core here is a way to do it (thanks to nopara73 comment)

Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")) ;

Creating csv file with php

@Baba's answer is great. But you don't need to use explode because fputcsv takes an array as a parameter

For instance, if you have a three columns, four lines document, here's a more straight version:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');

$user_CSV[0] = array('first_name', 'last_name', 'age');

// very simple to increment with i++ if looping through a database result 
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);

$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
    // though CSV stands for "comma separated value"
    // in many countries (including France) separator is ";"
    fputcsv($fp, $line, ',');
}
fclose($fp);

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Include <tchar.h> which has the line:

#define _tWinMain wWinMain

Standardize data columns in R

Realizing that the question is old and one answer is accepted, I'll provide another answer for reference.

scale is limited by the fact that it scales all variables. The solution below allows to scale only specific variable names while preserving other variables unchanged (and the variable names could be dynamically generated):

library(dplyr)

set.seed(1234)
dat <- data.frame(x = rnorm(10, 30, .2), 
                  y = runif(10, 3, 5),
                  z = runif(10, 10, 20))
dat

dat2 <- dat %>% mutate_at(c("y", "z"), ~(scale(.) %>% as.vector))
dat2

which gives me this:

> dat
          x        y        z
1  29.75859 3.633225 14.56091
2  30.05549 3.605387 12.65187
3  30.21689 3.318092 13.04672
4  29.53086 3.079992 15.07307
5  30.08582 3.437599 11.81096
6  30.10121 4.621197 17.59671
7  29.88505 4.051395 12.01248
8  29.89067 4.829316 12.58810
9  29.88711 4.662690 19.92150
10 29.82199 3.091541 18.07352

and

> dat2 <- dat %>% mutate_at(c("y", "z"), ~(scale(.) %>% as.vector))
> dat2
          x          y           z
1  29.75859 -0.3004815 -0.06016029
2  30.05549 -0.3423437 -0.72529604
3  30.21689 -0.7743696 -0.58772361
4  29.53086 -1.1324181  0.11828039
5  30.08582 -0.5946582 -1.01827752
6  30.10121  1.1852038  0.99754666
7  29.88505  0.3283513 -0.94806607
8  29.89067  1.4981677 -0.74751378
9  29.88711  1.2475998  1.80753470
10 29.82199 -1.1150515  1.16367556

EDIT 1 (2016): Addressed Julian's comment: the output of scale is Nx1 matrix so ideally we should add an as.vector to convert the matrix type back into a vector type. Thanks Julian!

EDIT 2 (2019): Quoting Duccio A.'s comment: For the latest dplyr (version 0.8) you need to change dplyr::funcs with list, like dat %>% mutate_each_(list(~scale(.) %>% as.vector), vars=c("y","z"))

EDIT 3 (2020): Thanks to @mj_whales: the old solution is deprecated and now we need to use mutate_at.

restrict edittext to single line

android:imeOptions="actionDone"

worked for me.

Java: splitting the filename into a base and extension

Maybe you could use String#split

To answer your comment:

I'm not sure if there can be more than one . in a filename, but whatever, even if there are more dots you can use the split. Consider e.g. that:

String input = "boo.and.foo";

String[] result = input.split(".");

This will return an array containing:

{ "boo", "and", "foo" }

So you will know that the last index in the array is the extension and all others are the base.

C# Iterating through an enum? (Indexing a System.Array)

Here is a simple way to iterate through your custom Enum object

For Each enumValue As Integer In [Enum].GetValues(GetType(MyEnum))

     Print([Enum].GetName(GetType(MyEnum), enumValue).ToString)

Next

How to resize the jQuery DatePicker control

$('.ui-datepicker').css('font-size', $('.ui-datepicker').width() / 20 + 'px');

Integer division with remainder in JavaScript?

I did some speed tests on Firefox.

-100/3             // -33.33..., 0.3663 millisec
Math.floor(-100/3) // -34,       0.5016 millisec
~~(-100/3)         // -33,       0.3619 millisec
(-100/3>>0)        // -33,       0.3632 millisec
(-100/3|0)         // -33,       0.3856 millisec
(-100-(-100%3))/3  // -33,       0.3591 millisec

/* a=-100, b=3 */
a/b                // -33.33..., 0.4863 millisec
Math.floor(a/b)    // -34,       0.6019 millisec
~~(a/b)            // -33,       0.5148 millisec
(a/b>>0)           // -33,       0.5048 millisec
(a/b|0)            // -33,       0.5078 millisec
(a-(a%b))/b        // -33,       0.6649 millisec

The above is based on 10 million trials for each.

Conclusion: Use (a/b>>0) (or (~~(a/b)) or (a/b|0)) to achieve about 20% gain in efficiency. Also keep in mind that they are all inconsistent with Math.floor, when a/b<0 && a%b!=0.

Java double.MAX_VALUE?

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

Understanding PIVOT function in T-SQL

FOR XML PATH might not work on Microsoft Azure Synapse Serve. A possible alternative, following @Taryn dynamic generated cols approach, same results is obtained by using STRING_AGG.

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)

SELECT @cols = STRING_AGG(QUOTENAME(c.phaseid),', ')
/*OPTIONAL: within group (order by cast(t1.[FLOW_SP_SLPM] as INT) asc)*/
FROM (SELECT phaseid FROM temp
GROUP BY phaseid) c

set @query = 'SELECT elementid,' + @cols + ' from 
             (
                select elementid,
                phaseid,
                effort
                from temp
            ) x
            PIVOT 
            (
                max(effort)
                for phaseid in (' + @cols + ')
            ) p '

execute(@query)

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

How do I detect a click outside an element?

$(document).on("click",function (event)   
 {   
     console.log(event);
   if ($(event.target).closest('.element').length == 0)
     {
    //your code here
      if ($(".element").hasClass("active"))
      {
        $(".element").removeClass("active");
      }
     }
 });

Try this coding for getting the solution.

"Fatal error: Cannot redeclare <function>"

This errors says your function is already defined ; which can mean :

  • you have the same function defined in two files
  • or you have the same function defined in two places in the same file
  • or the file in which your function is defined is included two times (so, it seems the function is defined two times)

To help with the third point, a solution would be to use include_once instead of include when including your functions.php file -- so it cannot be included more than once.

Python IndentationError: unexpected indent

find all tabs and replaced by 4 spaces in notepad ++ .It worked.

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.

How to return a specific status code and no contents from Controller?

The best way to do it is:

return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");

'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/

Once you choose your StatusCode, return it with a message.

Regex lookahead, lookbehind and atomic groups

Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.

Read regular-expression.info for more details.

  • Positive lookahead:

Syntax:

(?=REGEX_1)REGEX_2

Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.

example:

(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}

REGEX_1 is [a-z0-9]{4}$ which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3} which matches one or two letters followed by two or three digits.

REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.

  • Negative lookahead

Syntax:

(?!REGEX_1)REGEX_2

Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.

example:

(?!.*\bFWORD\b)\w{10,30}$

The look-ahead part checks for the FWORD in the string and fails if it finds it. If it doesn't find FWORD, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_

Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.

  • Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches. Check this page for examples of atomic groups

Are there constants in JavaScript?

Are you trying to protect the variables against modification? If so, then you can use a module pattern:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.

If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.

What does <T> denote in C#

It is a generic type parameter, see Generics documentation.

T is not a reserved keyword. T, or any given name, means a type parameter. Check the following method (just as a simple example).

T GetDefault<T>()
{
    return default(T);
}

Note that the return type is T. With this method you can get the default value of any type by calling the method as:

GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00

.NET uses generics in collections, ... example:

List<int> integerList = new List<int>();

This way you will have a list that only accepts integers, because the class is instancited with the type T, in this case int, and the method that add elements is written as:

public class List<T> : ...
{
    public void Add(T item);
}

Some more information about generics.

You can limit the scope of the type T.

The following example only allows you to invoke the method with types that are classes:

void Foo<T>(T item) where T: class
{
}

The following example only allows you to invoke the method with types that are Circle or inherit from it.

void Foo<T>(T item) where T: Circle
{
}

And there is new() that says you can create an instance of T if it has a parameterless constructor. In the following example T will be treated as Circle, you get intellisense...

void Foo<T>(T item) where T: Circle, new()
{
    T newCircle = new T();
}

As T is a type parameter, you can get the object Type from it. With the Type you can use reflection...

void Foo<T>(T item) where T: class
{
    Type type = typeof(T);
}

As a more complex example, check the signature of ToDictionary or any other Linq method.

public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

There isn't a T, however there is TKey and TSource. It is recommended that you always name type parameters with the prefix T as shown above.

You could name TSomethingFoo if you want to.

How to add a border just on the top side of a UIView

For Xamarin in C# I just create the border inline when adding the sub layer

  View.Layer.AddSublayer(new CALayer()
    {
        BackgroundColor = UIColor.Black.CGColor,
        Frame = new CGRect(0, 0, View.Frame.Width, 0.5f)
    });

You can arrange this (as suggested by others) for bottom, left and right borders.

How to scroll to bottom in a ScrollView on activity startup

Right after you append data to the view add this single line:

yourScrollview.fullScroll(ScrollView.FOCUS_DOWN);

Convert A String (like testing123) To Binary In Java

A String in Java can be converted to "binary" with its getBytes(Charset) method.

byte[] encoded = "????????!".getBytes(StandardCharsets.UTF_8);

The argument to this method is a "character-encoding"; this is a standardized mapping between a character and a sequence of bytes. Often, each character is encoded to a single byte, but there aren't enough unique byte values to represent every character in every language. Other encodings use multiple bytes, so they can handle a wider range of characters.

Usually, the encoding to use will be specified by some standard or protocol that you are implementing. If you are creating your own interface, and have the freedom to choose, "UTF-8" is an easy, safe, and widely supported encoding.

  • It's easy, because rather than including some way to note the encoding of each message, you can default to UTF-8.
  • It's safe, because UTF-8 can encode any character that can be used in a Java character string.
  • It's widely supported, because it is one of a small handful of character encodings that is required to be present in any Java implementation, all the way down to J2ME. Most other platforms support it too, and it's used as a default in standards like XML.

php error: Class 'Imagick' not found

Docker container installation for php:XXX Debian based images:

RUN apt-get update && apt-get install -y --no-install-recommends libmagickwand-dev
RUN pecl install imagick && docker-php-ext-enable imagick
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* || true

How do you get the selected value of a Spinner?

This is another way:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int pos, long arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

How to strip all whitespace from string

For Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...handles any whitespace characters that you're not thinking of - and believe us, there are plenty.

\s on its own always covers the ASCII whitespace:

  • (regular) space
  • tab
  • new line (\n)
  • carriage return (\r)
  • form feed
  • vertical tab

Additionally:

  • for Python 2 with re.UNICODE enabled,
  • for Python 3 without any extra actions,

...\s also covers the Unicode whitespace characters, for example:

  • non-breaking space,
  • em space,
  • ideographic space,

...etc. See the full list here, under "Unicode characters with White_Space property".

However \s DOES NOT cover characters not classified as whitespace, which are de facto whitespace, such as among others:

  • zero-width joiner,
  • Mongolian vowel separator,
  • zero-width non-breaking space (a.k.a. byte order mark),

...etc. See the full list here, under "Related Unicode characters without White_Space property".

So these 6 characters are covered by the list in the second regex, \u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

Sources:

Double free or corruption after queue::push

Let's talk about copying objects in C++.

Test t;, calls the default constructor, which allocates a new array of integers. This is fine, and your expected behavior.

Trouble comes when you push t into your queue using q.push(t). If you're familiar with Java, C#, or almost any other object-oriented language, you might expect the object you created earler to be added to the queue, but C++ doesn't work that way.

When we take a look at std::queue::push method, we see that the element that gets added to the queue is "initialized to a copy of x." It's actually a brand new object that uses the copy constructor to duplicate every member of your original Test object to make a new Test.

Your C++ compiler generates a copy constructor for you by default! That's pretty handy, but causes problems with pointer members. In your example, remember that int *myArray is just a memory address; when the value of myArray is copied from the old object to the new one, you'll now have two objects pointing to the same array in memory. This isn't intrinsically bad, but the destructor will then try to delete the same array twice, hence the "double free or corruption" runtime error.

How do I fix it?

The first step is to implement a copy constructor, which can safely copy the data from one object to another. For simplicity, it could look something like this:

Test(const Test& other){
    myArray = new int[10];
    memcpy( myArray, other.myArray, 10 );
}

Now when you're copying Test objects, a new array will be allocated for the new object, and the values of the array will be copied as well.

We're not completely out trouble yet, though. There's another method that the compiler generates for you that could lead to similar problems - assignment. The difference is that with assignment, we already have an existing object whose memory needs to be managed appropriately. Here's a basic assignment operator implementation:

Test& operator= (const Test& other){
    if (this != &other) {
        memcpy( myArray, other.myArray, 10 );
    }
    return *this;
}

The important part here is that we're copying the data from the other array into this object's array, keeping each object's memory separate. We also have a check for self-assignment; otherwise, we'd be copying from ourselves to ourselves, which may throw an error (not sure what it's supposed to do). If we were deleting and allocating more memory, the self-assignment check prevents us from deleting memory from which we need to copy.

How to create a Java cron job

You can use TimerTask for Cronjobs.

Main.java

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);
   }

}

MyTask.java

class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs
   }

   @Override
   public void run() {
     System.out.println("Hi see you after 10 seconds");
   }

}

Alternative You can also use ScheduledExecutorService.

Installed Java 7 on Mac OS X but Terminal is still using version 6

You can execute following command in your terminal :

export PATH="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin:$PATH"

And this replaces the java old with new one.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

" netsh wlan start hostednetwork " command not working no matter what I try

This was a real issue for me, and quite a sneaky problem to try and remedy...

The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).

To fix it:

  1. Hold the Windows Key + Push R
  2. Type: ncpa.cpl in to the box, and hit OK.
  3. Identify the network adapter you want to use for the hostednetwork, right-click it, and select Properties.
  4. You'll see a big box in the middle of the properties window, under the heading The connection uses the following items:. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK.
  5. Try running the netsh wlan start hostednetwork command again.
  6. Repeat steps 4 and 5 as necessary.

In my case my adapter was running a module called SoftEther Lightweight Network Protocol, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.

If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.

Getting a Request.Headers value

string strHeader = Request.Headers["XYZComponent"]
bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;

if "true" than true
if "false" or anything else ("fooBar") than false

or

string strHeader = Request.Headers["XYZComponent"]
bool b;
bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);

if "true" than true
if "false" than false
else ("fooBar") than null

use jQuery to get values of selected checkboxes

Jquery 3.3.1 , getting values for all checked check boxes on button click

_x000D_
_x000D_
$(document).ready(function(){_x000D_
 $(".btn-submit").click(function(){_x000D_
  $('.cbCheck:checkbox:checked').each(function(){_x000D_
 alert($(this).val())_x000D_
  });_x000D_
 });   _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">_x000D_
  <label for="vehicle1"> I have a bike</label><br>_x000D_
  <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">_x000D_
  <label for="vehicle2"> I have a car</label><br>_x000D_
  <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">_x000D_
  <label for="vehicle3"> I have a boat</label><br><br>_x000D_
  <input type="submit" value="Submit" class="btn-submit">
_x000D_
_x000D_
_x000D_

How can I initialize an ArrayList with all zeroes in Java?

Java 8 implementation (List initialized with 60 zeroes):

List<Integer> list = IntStream.of(new int[60])
                    .boxed()
                    .collect(Collectors.toList());
  • new int[N] - creates an array filled with zeroes & length N
  • boxed() - each element boxed to an Integer
  • collect(Collectors.toList()) - collects elements of stream

How to change colour of blue highlight on select box dropdown

To both style the hover color and avoid the OS default color in Firefox, you need to add a box-shadow to both the select option and select option:hover declarations, setting the color of the box-shadow on "select option" to the menu background color.

select option {
  background: #f00; 
  color: #fff; 
  box-shadow: inset 20px 20px #f00
} 

select option:hover {
  color: #000; 
  box-shadow: inset 20px 20px #00f;
}

How to enable scrolling on website that disabled scrolling?

With Chrome, one way to automatically re-enable scrolling on a website is to download the Tampermonkey extension, then add this script (click "Install this script").

In general, if you have a URL for a script where the URL ends in .user.js and have Tampermonkey installed, you can paste it into Chrome's Omnibox to install the script. More ways to install scripts with Tampermonkey can be found here.

How to get the scroll bar with CSS overflow on iOS

::-webkit-scrollbar {
    width: 15px;
    height: 15px;
}

::-webkit-scrollbar-thumb {
    border-radius: 8px;
    background-color: #C3C3C3;
    border: 2px solid #eee;
}

Use this code, it work in ios/android APP webview; It delete some not portable css code;

PHP sessions default timeout

You can set the session time out in php.ini. The default value is 1440 seconds

session.gc_maxlifetime = 1440

; NOTE: If you are using the subdirectory option for storing session files
;       (see session.save_path above), then garbage collection does *not*
;       happen automatically.  You will need to do your own garbage
;       collection through a shell script, cron entry, or some other method.
;       For example, the following script would is the equivalent of
;       setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
;          find /path/to/sessions -cmin +24 -type f | xargs rm

Prevent any form of page refresh using jQuery/Javascript

You can't prevent the user from refreshing, nor should you really be trying. You should go back to why you need this solution, what's the root problem here?. Start there and find a different way to go about solving the problem. Perhaps is you elaborated on why you think you need to do this it would help in finding such a solution.

Breaking fundamental browser features is never a good idea, over 99.999999999% of the internet works and refreshes with F5, this is an expectation of the user, one you shouldn't break.

How to set the color of an icon in Angular Material?

<mat-icon style="-webkit-text-fill-color:blue">face</mat-icon>

MVC ajax post to controller action method

Your Action is expecting string parameters, but you're sending a composite object.

You need to create an object that matches what you're sending.

public class Data
{
    public string username { get;set; }
    public string password { get;set; }
}

public JsonResult Login(Data data)
{
}

EDIT

In addition, toStringify() is probably not what you want here. Just send the object itself.

data: data,

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

javac : command not found

Linux Mint 19.3

I installed Java Oracle manually, like this:

$ sudo ln -s /usr/lib/jvm/java-1.8.0_211/bin/javac /usr/bin/javac

How do I get class name in PHP?

I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.

<?php
class X {
    function getStatic() {
        // gets THIS class of instance of object
        // that extends class in which is definied function
        return static::class;
    }
    function getSelf() {
        // gets THIS class of class in which function is declared
        return self::class;
    }
}

class Y extends X {
}
class Z extends Y {
}

$x = new X();
$y = new Y();
$z = new Z();

echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() . 
    ', Y: ' . $y->getStatic() . ', ' . $y->getSelf() . 
    ', Z: ' . $z->getStatic() . ', ' . $z->getSelf();

Results:

X: X, X
Y: Y, X
Z: Z, X

Node.js - get raw request body using Express

This is a variation on hexacyanide's answer above. This middleware also handles the 'data' event but does not wait for the data to be consumed before calling 'next'. This way both this middleware and bodyParser may coexist, consuming the stream in parallel.

app.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf8');

  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });

  next();
});
app.use(express.bodyParser());

How do I turn a String into a InputStreamReader in java?

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

Difference in days between two dates in Java?

It depends on what you define as the difference. To compare two dates at midnight you can do.

long day1 = ...; // in milliseconds.
long day2 = ...; // in milliseconds.
long days = (day2 - day1) / 86400000;

How to change Named Range Scope

I found the solution! Just copy the sheet with your named variables. Then delete the original sheet. The copied sheet will now have the same named variables, but with a local scope (scope= the copied sheet).

However, I don't know how to change from local variables to global..

How to toggle boolean state of react component?

Use checked to get the value. During onChange, checked will be true and it will be a type of boolean.

Hope this helps!

_x000D_
_x000D_
class A extends React.Component {_x000D_
  constructor() {_x000D_
    super()_x000D_
    this.handleCheckBox = this.handleCheckBox.bind(this)_x000D_
    this.state = {_x000D_
      checked: false_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  handleCheckBox(e) {_x000D_
    this.setState({_x000D_
      checked: e.target.checked_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render(){_x000D_
    return <input type="checkbox" onChange={this.handleCheckBox} checked={this.state.checked} />_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<A/>, document.getElementById('app'))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

No provider for HttpClient

I was also facing similar issue by doing below changes, it worked for me

In app.modules.ts

import {HttpClientModule} from '@angular/common/http' 

and in corresponding service class

import { HttpClient } from '@angular/common/http'

constructor should look like as below

constructor(private http: HttpClient, private xyz: xyzService) {}

In test file

import { HttpClientTestingModule } from '@angular/common/http/testing'

  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule]
  }));

Display a tooltip over a button using Windows Forms

The .NET framework provides a ToolTip class. Add one of those to your form and then on the MouseHover event for each item you would like a tooltip for, do something like the following:

private void checkBox1_MouseHover(object sender, EventArgs e)
{
    toolTip1.Show("text", checkBox1);
}

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

highlight the navigation menu for the current page

<script id="add-active-to-current-page-nav-link" type="text/javascript">
    function setSelectedPageNav() {
        var pathName = document.location.pathname;
        if ($("nav ul li a") != null) {
            var currentLink = $("nav ul li a[href='" + pathName + "']");
            currentLink.addClass("active");
        }
    }
    setSelectedPageNav();
</script>

No Spring WebApplicationInitializer types detected on classpath

Watch out if you are using Maven. Your folder's structure must be right.

When using Maven, the WEB-INF directory must be inside webapp:

src/main/webapp/WEB-INF

window.onload vs document.onload

In short

  • window.onload is not supported by IE 6-8
  • document.onload is not supported by any modern browser (event is never fired)

_x000D_
_x000D_
window.onload   = () => console.log('window.onload works');   // fired
document.onload = () => console.log('document.onload works'); // not fired
_x000D_
_x000D_
_x000D_

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

Jan 2021 - Got around this in VS2019 by setting Menu > Git > Settings > Git Global Settings > Cryptographic Network Provider > [Secure Channel] instead of [OpenSSL]

Git SSL certificate problem unable to get local issuer certificate (fix)

PS: Didn't need to set --global or --local http.sslVerify false. I was cloning an Azure DevOps repo which wasn't using any self signed certs.. This seems like an issue with either VS2019 or Git for Windows.. They need to fix it !!

xml.LoadData - Data at the root level is invalid. Line 1, position 1

Main culprit for this error is logic which determines encoding when converting Stream or byte[] array to .NET string.

Using StreamReader created with 2nd constructor parameter detectEncodingFromByteOrderMarks set to true, will determine proper encoding and create string which does not break XmlDocument.LoadXml method.

public string GetXmlString(string url)
{
    using var stream = GetResponseStream(url);
    using var reader = new StreamReader(stream, true);
    return reader.ReadToEnd(); // no exception on `LoadXml`
}

Common mistake would be to just blindly use UTF8 encoding on the stream or byte[]. Code bellow would produce string that looks valid when inspected in Visual Studio debugger, or copy-pasted somewhere, but it will produce the exception when used with Load or LoadXml if file is encoded differently then UTF8 without BOM.

public string GetXmlString(string url)
{
    byte[] bytes = GetResponseByteArray(url);
    return System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`
}

Hiding elements in responsive layout?

All hidden-*-up, hidden-* classes doesn't work for me, so I'm adding self-made hidden class before visible-*(which works for current bootstrap version). It is very useful if you need to show div only for one screen, and hide for all others.

CSS:

.hidden {display:none;}

HTML:

<div class="col-xs-12 hidden visible-xs visible-sm">
   <img src="photo.png" style="width:100%">
</div>

Markdown open a new window link

As suggested by this answer:

[link](url){:target="_blank"}

Works for jekyll or more specifically kramdown, which is a superset of markdown, as part of Jekyll's (default) configuration. But not for plain markdown. ^_^

What are some ways of accessing Microsoft SQL Server from Linux?

If you use eclipse you can install Data Tools Platform plugin on it and use it for every DB engines including MS SQLServer. It just needs to get JDBC driver for that DB engine.

Load resources from relative path using local html in uiwebview

In Swift 3.01 using WKWebView:

let localURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "CWP")!)
myWebView.load(NSURLRequest.init(url: localURL) as URLRequest)

This adjusts for some of the finer syntax changes in 3.01 and keeps the directory structure in place so you can embed related HTML files.

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

Using regular expressions to do mass replace in Notepad++ and Vim

In Notepad++ :

<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D


Find what: (.*)(>)(.)
Replace with: \3

Replace All


A
B
C
D

SQL ROWNUM how to return rows between a specific range

 SELECT * from
 (
 select m.*, rownum r
 from maps006 m
 )
 where r > 49 and r < 101

Access Control Request Headers, is added to header in AJAX request with jQuery

This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.

$.ajax({
    url: 'YourRestEndPoint',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);
    }
  });

HttpClient.GetAsync(...) never returns when using await/async

I was using to many await, so i was not getting response , i converted in to sync call its started working

            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Method = HttpMethod.Get;
                request.RequestUri = new Uri(URL);
                var response = client.GetAsync(URL).Result;
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result;
               

Find records from one table which don't exist in another

SELECT DISTINCT Call.id 
FROM Call 
LEFT OUTER JOIN Phone_book USING (id) 
WHERE Phone_book.id IS NULL

This will return the extra id-s that are missing in your Phone_book table.

How to add custom method to Spring Data JPA

There's a slightly modified solution that does not require additional interfaces.

As specificed in the documented functionality, the Impl suffix allows us to have such clean solution:

  • Define in you regular @Repository interface, say MyEntityRepository the custom methods (in addition to your Spring Data methods)
  • Create a class MyEntityRepositoryImpl (the Impl suffix is the magic) anywhere (doesn't even need to be in the same package) that implements the custom methods only and annotate such class with @Component** (@Repository will not work).
    • This class can even inject MyEntityRepository via @Autowired for use in the custom methods.

Example:

Entity class (for completeness):

package myapp.domain.myentity;
@Entity
public class MyEntity {
    @Id     private Long id;
    @Column private String comment;
}

Repository interface:

package myapp.domain.myentity;

@Repository
public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {

    // EXAMPLE SPRING DATA METHOD
    List<MyEntity> findByCommentEndsWith(String x);

    List<MyEntity> doSomeHql(Long id);   // custom method, code at *Impl class below

    List<MyEntity> useTheRepo(Long id);  // custom method, code at *Impl class below

}

Custom methods implementation bean:

package myapp.infrastructure.myentity;

@Component // Must be @Component !!
public class MyEntityRepositoryImpl { // must have the exact repo name + Impl !!

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private MyEntityRepository myEntityRepository;

    @SuppressWarnings("unused")
    public List<MyEntity> doSomeHql(Long id) {
        String hql = "SELECT eFROM MyEntity e WHERE e.id = :id";
        TypedQuery<MyEntity> query = entityManager.createQuery(hql, MyEntity.class);
        query.setParameter("id", id);
        return query.getResultList();
    }

    @SuppressWarnings("unused")
    public List<MyEntity> useTheRepo(Long id) {
        List<MyEntity> es = doSomeHql(id);
        es.addAll(myEntityRepository.findByCommentEndsWith("DO"));
        es.add(myEntityRepository.findById(2L).get());
        return es;
    }

}

Usage:

// You just autowire the the MyEntityRepository as usual
// (the Impl class is just impl detail, the clients don't even know about it)
@Service
public class SomeService {
    @Autowired
    private MyEntityRepository myEntityRepository;

    public void someMethod(String x, long y) {
        // call any method as usual
        myEntityRepository.findByCommentEndsWith(x);
        myEntityRepository.doSomeHql(y);
    }
}

And that's all, no need for any interfaces other than the Spring Data repo one you already have.


The only possible drawbacks I identified are:

  • The custom methods in the Impl class are marked as unused by the compiler, thus the @SuppressWarnings("unused") suggestion.
  • You have a limit of one Impl class. (Whereas in the regular fragment interfaces implementation the docs suggest you could have many.)
  • If you place the Impl class at a different package and your test uses only @DataJpaTest, you have to add @ComponentScan("package.of.the.impl.clazz") to your test, so Spring loads it.

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

Also remember to check permission of root directory itself!

You may find:

drwxr-xr-x  9 not-you www-data  4096 Aug  8 16:36 ./
-rw-r--r--  1     you www-data  3012 Aug  8 16:36 README.txt
-rw-r--r--  1     you www-data  3012 Aug  8 16:36 UPDATE.txt

and 'permission denied' error will pop up.

How to pause / sleep thread or process in Android?

This is what I did at the end of the day - works fine now :

@Override
    public void onClick(View v) {
        my_button.setBackgroundResource(R.drawable.icon);
        // SLEEP 2 SECONDS HERE ...
        final Handler handler = new Handler(); 
        Timer t = new Timer(); 
        t.schedule(new TimerTask() { 
                public void run() { 
                        handler.post(new Runnable() { 
                                public void run() { 
                                 my_button.setBackgroundResource(R.drawable.defaultcard); 
                                } 
                        }); 
                } 
        }, 2000); 
    }

100% width Twitter Bootstrap 3 template

Using Bootstrap 3.3.5 and .container-fluid, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid was re-introduced in 3.1.

Full width on mobile/tablet, 1/4 screen on desktop

<div class="container-fluid"> <!-- Adds 15px left/right padding --> 
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
      <!-- Full-width for mobile -->
      <!-- 1/4 screen width for desktop -->
    </div>
  </div>
</div>

Full width on all resolutions (mobile, table, desktop)

<div class="container-fluid"> <!-- Adds 15px left/right padding -->
  <div class="row"> <!-- Adds -15px left/right margins -->
    <div>
      <!-- Full-width content -->
    </div>
  </div>
</div>

Disable browser's back button

Globally, disabling the back button is indeed bad practice. But, in certain situations, the back button functionality doesn't make sense.

Here's one way to prevent unwanted navigation between pages:

Top page (file top.php):

<?php
    session_start();
    $_SESSION[pid]++;
    echo "top page $_SESSION[pid]";
    echo "<BR><a href='secondary.php?pid=$_SESSION[pid]'>secondary page</a>";
?>

Secondary page (file secondary.php):

<?php
    session_start();
    if ($_SESSION[pid] != $_GET[pid]) 
        header("location: top.php");
    else {
        echo "secondary page $_SESSION[pid]";
        echo "<BR><a href='top.php'>top</a>";
    }
?>

The effect is to allow navigating from the top page forward to the secondary page and back (e.g. Cancel) using your own links. But, after returning to the top page the browser back button is prevented from navigating to the secondary page.

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

How to open generated pdf using jspdf in new window

this code will help you to open generated pdf in new tab with required title

 let pdf = new jsPDF();
 pdf.setProperties({
          title: "Report"
      });
      pdf.output('dataurlnewwindow');

Creating SVG graphics using Javascript?

I like jQuery SVG library very much. It helps me every time I need to manipulate with SVG. It really facilitate the work with SVG from JavaScript.

Why do I get an error instantiating an interface?

IUser is the interface, you can't instantiate the interface.

You need to instantiate the concrete class that implements the interface.

IUser user = new User();

or

User user = new User();

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

How do I check if a property exists on a dynamic anonymous type in c#?

Merging and fixing answers from Serj-TM and user3359453 so that it works with both ExpandoObject and DynamicJsonObject. This works for me.

public static bool HasPropertyExist(dynamic settings, string name)
{
    if (settings is System.Dynamic.ExpandoObject)
        return ((IDictionary<string, object>)settings).ContainsKey(name);

    if (settings is System.Web.Helpers.DynamicJsonObject)
    try
    {
        return settings[name] != null;
    }
    catch (KeyNotFoundException)
    {
        return false;
    }


    return settings.GetType().GetProperty(name) != null;
}

How to get first element in a list of tuples?

you can unpack your tuples and get only the first element using a list comprehension:

l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]

output:

[1, 2]

this will work no matter how many elements you have in a tuple:

l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]

output:

[1, 2]

How do I call ::CreateProcess in c++ to launch a Windows executable?

Here is a new example that works on windows 10. When using the windows10 sdk you have to use CreateProcessW instead. This example is commented and hopefully self explanatory.

#ifdef _WIN32
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <string>
#include <algorithm>

class process
{
public:

    static PROCESS_INFORMATION launchProcess(std::string app, std::string arg)
    {

        // Prepare handles.
        STARTUPINFO si;
        PROCESS_INFORMATION pi; // The function returns this
        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        //Prepare CreateProcess args
        std::wstring app_w(app.length(), L' '); // Make room for characters
        std::copy(app.begin(), app.end(), app_w.begin()); // Copy string to wstring.

        std::wstring arg_w(arg.length(), L' '); // Make room for characters
        std::copy(arg.begin(), arg.end(), arg_w.begin()); // Copy string to wstring.

        std::wstring input = app_w + L" " + arg_w;
        wchar_t* arg_concat = const_cast<wchar_t*>( input.c_str() );
        const wchar_t* app_const = app_w.c_str();

        // Start the child process.
        if( !CreateProcessW(
            app_const,      // app path
            arg_concat,     // Command line (needs to include app path as first argument. args seperated by whitepace)
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            NULL,           // Use parent's starting directory
            &si,            // Pointer to STARTUPINFO structure
            &pi )           // Pointer to PROCESS_INFORMATION structure
        )
        {
            printf( "CreateProcess failed (%d).\n", GetLastError() );
            throw std::exception("Could not create child process");
        }
        else
        {
            std::cout << "[          ] Successfully launched child process" << std::endl;
        }

        // Return process handle
        return pi;
    }

    static bool checkIfProcessIsActive(PROCESS_INFORMATION pi)
    {
        // Check if handle is closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle is closed or invalid (%d).\n", GetLastError());
                return FALSE;
            }

        // If handle open, check if process is active
        DWORD lpExitCode = 0;
        if( GetExitCodeProcess(pi.hProcess, &lpExitCode) == 0)
        {
            printf( "Cannot return exit code (%d).\n", GetLastError() );
            throw std::exception("Cannot return exit code");
        }
        else
        {
            if (lpExitCode == STILL_ACTIVE)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
    }

    static bool stopProcess( PROCESS_INFORMATION &pi)
    {
        // Check if handle is invalid or has allready been closed
            if ( pi.hProcess == NULL )
            {
                printf( "Process handle invalid. Possibly allready been closed (%d).\n");
                return 0;
            }

        // Terminate Process
            if( !TerminateProcess(pi.hProcess,1))
            {
                printf( "ExitProcess failed (%d).\n", GetLastError() );
                return 0;
            }

        // Wait until child process exits.
            if( WaitForSingleObject( pi.hProcess, INFINITE ) == WAIT_FAILED)
            {
                printf( "Wait for exit process failed(%d).\n", GetLastError() );
                return 0;
            }

        // Close process and thread handles.
            if( !CloseHandle( pi.hProcess ))
            {
                printf( "Cannot close process handle(%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                pi.hProcess = NULL;
            }

            if( !CloseHandle( pi.hThread ))
            {
                printf( "Cannot close thread handle (%d).\n", GetLastError() );
                return 0;
            }
            else
            {
                 pi.hProcess = NULL;
            }
            return 1;
    }
};//class process
#endif //win32

Disabling user input for UITextfield in swift

Try this:

Swift 2.0:

textField.userInteractionEnabled = false

Swift 3.0:

textField.isUserInteractionEnabled = false

Or in storyboard uncheck "User Interaction Enabled"

enter image description here

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

Ran into this issue and was able to solve by 2 main steps:

1 - Update to latest chromedriver via homebrew cli

brew cask upgrade chromedriver

2 - update to lastest ver via Chrome GUI

chrome://settings/help or cmd + , then tacking on help at the end (your choice)

from there you should land on the About Chrome Page. Here you will need to verify that you are on the latest and greatest version (problem i was running into stemmed from a mismatch in the cli vs the current chrome version)

if you getting the error, you will see a update & relaunch primary action button.

after chrome "relaunches" it will now have the newest version matching your cli

example:

Google Chrome is up to date
Version 80.0.3987.87 (Official Build) (64-bit)

Recursively find files with a specific extension

Using find's -regex argument:

find . -regex '.*/Robert\.\(h\|cpp\)$'

Or just using -name:

find . -name 'Robert.*' -a \( -name '*.cpp' -o -name '*.h' \)

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

How to add extension methods to Enums

According to this site:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions 
{
  public static DateTime From(this Duration duration, DateTime dateTime) 
  {
    switch (duration) 
    {
      case Day:   return dateTime.AddDays(1);
      case Week:  return dateTime.AddDays(7);
      case Month: return dateTime.AddMonths(1);
      default:    throw new ArgumentOutOfRangeException("duration");
    }
  }
}

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

You can read more here at Microsft MSDN.

INNER JOIN same table

Your query should work fine, but you have to use the alias parent to show the values of the parent table like this:

select 
  CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
  CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

create a view on the custom cell in the table view and apply PanGestureRecognizer to the view on the cell.Add the buttons to the custom cell, when you swipe the view on the custom cell then the buttons on the custom cell will be visible.

 UIGestureRecognizer* recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    recognizer.delegate = self;
    [YourView addGestureRecognizer:recognizer];

And handle the panning on the view in the method

 if (recognizer.state == UIGestureRecognizerStateBegan) {
    // if the gesture has just started, record the current centre location
    _originalCenter = vwCell.center;
}

// 2
if (recognizer.state == UIGestureRecognizerStateChanged) {
    // translate the center
    CGPoint translation = [recognizer translationInView:self];
    vwCell.center = CGPointMake(_originalCenter.x + translation.x, _originalCenter.y);
    // determine whether the item has been dragged far enough to initiate  / complete
    _OnDragRelease = vwCell.frame.origin.x < -vwCell.frame.size.width / 2;

}

// 3
if (recognizer.state == UIGestureRecognizerStateEnded) {
    // the frame this cell would have had before being dragged
    CGPoint translation = [recognizer translationInView:self];

    if (_originalCenter.x+translation.x<22) {
          vwCell.center = CGPointMake(22, _originalCenter.y);
        IsvwRelease=YES;

    }
    CGRect originalFrame = CGRectMake(0, vwCell.frame.origin.y,
                                      vwCell.bounds.size.width, vwCell.bounds.size.height);
    if (!_deleteOnDragRelease) {
        // if the item is not being dragged far enough , snap back to the original location
        [UIView animateWithDuration:0.2
                         animations:^{
                             vwCell.frame = originalFrame;
                         }
         ];
    }
}

What is the purpose of using WHERE 1=1 in SQL statements?

Using 1=1 is actually not a very good idea as this can cause full table scans by itself.

See this--> T-SQL 1=1 Performance Hit

How can I Convert HTML to Text in C#?

You could use this:

 public static string StripHTML(string HTMLText, bool decode = true)
        {
            Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
            var stripped = reg.Replace(HTMLText, "");
            return decode ? HttpUtility.HtmlDecode(stripped) : stripped;
        }

Updated

Thanks for the comments I have updated to improve this function

WPF checkbox binding

if you have the property "MyProperty" on your data-class, then you bind the IsChecked like this.... (the converter is optional, but sometimes you need that)

<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>

How to quickly and conveniently create a one element arraylist

Fixed size List

The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T...) like

// Returns a List backed by a varargs T.
return Arrays.asList(s);

Variable size List

If it needs vary in size you can construct an ArrayList and the fixed-sizeList like

return new ArrayList<String>(Arrays.asList(s));

and (in Java 7+) you can use the diamond operator <> to make it

return new ArrayList<>(Arrays.asList(s));

Single Element List

Collections can return a list with a single element with list being immutable:

Collections.singletonList(s)

The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.

SQL changing a value to upper or lower case

LCASE or UCASE respectively.

Example:

SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

After this question was asked, Facebook launched HipHop for PHP which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.

Beyond that, googling PHP compiler turns up a number of 3rd party solutions.

PeachPie

  • PeachPie GitHub
  • compiles PHP to .NET and .NET Core
  • can be compiled into self-contained binary file
  • runs on Mac, Linux, Windows, Windows Core, ARM, ...

Phalanger

  • GitHub (download), Wikipedia
  • compiles to .NET (CIL) looks discontinued from July 2017 and doesn't seem to support PHP 7.

phc

  • compiles to native binaries
  • not very active now (February 2014) – last version in 2011, last change in summer 2013

Roadsend PHP Compiler

bcompiler

  • PECL extension of PHP
  • experimental
  • compiles to PHP bytecode, but can wrap it in Windows binary that loads PHP interpreter (see bcompiler_write_exe_footer() manual)
  • looks discontinued now (February 2014) – last change in 2011

Project Zero

  • Wikipedia, IBM
  • incubator of changes for WebSphere sMash
  • supported by IBM
  • compiles to Java bytecode
  • looks discontinued now (February 2014) – website down, looks like big hype in 2008 and 2009

Bambalam

  • compiles to stand-alone Windows binaries
  • the binaries contain bytecode and a launcher
  • looks discontinued now (February 2014) – last change in 2006

BinaryPHP

  • compiles to C++
  • looks discontinued now (February 2014) – last change in 2003

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Libraries cannot be directly used in any program if not properly added to the project gradle files.

This can easily be done in smart IDEs like inteli J.

1) First as a convention add a folder names 'libs' under your project src file. (this can easily be done using the IDE itself)

2) then copy or add your library file (eg: .jar file) to the folder named 'libs'

3) now you can see the library file inside the libs folder. Now right click on the file and select 'add as library'. And this will fix all the relevant files in your program and library will be directly available for your use.

Please note:

Whenever you are adding libraries to a project, make sure that the project supports the library

Loop through columns and add string lengths as new columns

You need to use [[, the programmatic equivalent of $. Otherwise, for example, when i is col1, R will look for df$i instead of df$col1.

for(i in names(df)){
  df[[paste(i, 'length', sep="_")]] <- str_length(df[[i]])
}

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

How to rotate portrait/landscape Android emulator?

Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.

In practise it's a bit quirky.

  1. Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.

  2. You have to release Ctrl before you can rotate again.

  3. KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).

  4. The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.

Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.

Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.

How to convert .pfx file to keystore with private key?

I found this page which tells you how to import a PFX to JKS (Java Key Store):

keytool -importkeystore -srckeystore PFX_P12_FILE_NAME -srcstoretype pkcs12 -srcstorepass PFX_P12_FILE -srcalias SOURCE_ALIAS -destkeystore KEYSTORE_FILE -deststoretype jks -deststorepass PASSWORD -destalias ALIAS_NAME

Having trouble setting working directory

The command setwd("~/") should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/" as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.

As you have tagged the post using RStudio:

  • In the bottom right window move the tab over to 'files'.
  • Navigate through there to whichever folder you were planning to use as your working directory.
  • Under 'more' click 'set as working directory'

You will now have set the folder as your working directory. Use the command getwd() to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd with that string as the argument, so that each time you run the script you use the same directory.

For example at the top of my script I would have:

work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)

Should I make HTML Anchors with 'name' or 'id'?

Heads up for JavaScript users: all IDs become global variables under window.

<h1 id="foo">Foo Title</h1>

Just created the JS global:

window.foo

The value of window.foo will be the HTMLElement for the h1.

Unless you can guarantee all values used in id attributes are safe, you may prefer sticking to name:

<h1 name="foo">Foo Title</h1>

Print Pdf in C#

The easiest way is to create C# Process and launch external tool to print your PDF file

private static void ExecuteRawFilePrinter() {
    Process process = new Process();
    process.StartInfo.FileName = "c:\\Program Files (x86)\\RawFilePrinter\\RawFilePrinter.exe";
    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    process.StartInfo.Arguments = string.Format("-p \"c:\\Users\\Me\\Desktop\\mypdffile.pdf\" \"gdn02ptr006\"");
    process.Start();
    process.WaitForExit();
}

Code above launches RawFilePrinter.exe (similar to 2Printer.exe), but with better support. It is not free, but by making donation allow you to use it everywhere and redistribute with your application. Latest version to download: http://bigdotsoftware.pl/rawfileprinter

Updating state on props change in React Form

componentWillReceiveProps is depcricated since react 16: use getDerivedStateFromProps instead

If I understand correctly, you have a parent component that is passing start_time down to the ModalBody component which assigns it to its own state? And you want to update that time from the parent, not a child component.

React has some tips on dealing with this scenario. (Note, this is an old article that has since been removed from the web. Here's a link to the current doc on component props).

Using props to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.

Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.

Basically, whenever you assign parent's props to a child's state the render method isn't always called on prop update. You have to invoke it manually, using the componentWillReceiveProps method.

componentWillReceiveProps(nextProps) {
  // You don't have to do this check first, but it can help prevent an unneeded render
  if (nextProps.startTime !== this.state.startTime) {
    this.setState({ startTime: nextProps.startTime });
  }
}

mssql '5 (Access is denied.)' error during restoring database

I tried the above scenario and got the same error 5 (access denied). I did a deep dive and found that the file .bak should have access to the SQL service account. If you are not sure, type services.msc in Start -> Run then check for SQL Service logon account.

Then go to the file, right-click and select Security tab in Properties, then edit to add the new user.

Finally then give full permission to it in order to give full access.

Then from SSMS try to restore the backup.

Removing rounded corners from a <select> element in Chrome/Webkit

firefox: 18

.squaredcorners {
    -moz-appearance: none;
}

Font-awesome, input type 'submit'

You can use button classes btn-link and btn-xs with type submit, which will make a small invisible button with an icon inside of it. Example:

<button class="btn btn-link btn-xs" type="submit" name="action" value="delete">
    <i class="fa fa-times text-danger"></i>
</button>

Most Pythonic way to provide global configuration variables in config.py?

A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:

#globals.py

class dbinfo :      # for database globals
    username = 'abcd'
    password = 'xyz'

class runtime :
    debug = False
    output = 'stdio'

Then, if you have two code files c1.py and c2.py, both can have at the top

import globals as gl

Now all code can access and set values, as such:

gl.runtime.debug = False
print(gl.dbinfo.username)

People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.

By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.

This lacks some of the clever error checking of other approaches, but is simple and easy to follow.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

Use of #pragma in C

#pragma is for compiler directives that are machine-specific or operating-system-specific, i.e. it tells the compiler to do something, set some option, take some action, override some default, etc. that may or may not apply to all machines and operating systems.

See msdn for more info.

How can I get last characters of a string

Here 2 examples that will show you always the last character

_x000D_
_x000D_
var id="ctl03_Tabs1";

console.log(id.charAt(id.length - 1)); 

console.log(id[id.length - 1]); 
_x000D_
_x000D_
_x000D_

How to use jQuery to call an ASP.NET web service?

Here is an example to call your webservice using jQuery.get:

$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.

Why is the Android emulator so slow? How can we speed up the Android emulator?

I just started yesterday on Windows 7 and was facing the same problem. The easiest solution, I found and is working for me is to use the low config device in the emulator. I used Nexus One instead of Nexus 7 and select the snapshot for the device in Android Virtual Device.

And, also important is to leave open the emulator. It works both in Eclipse and Android Studio.

In a window, it says snapshot does not generally work when RAM is more than ~700. So, selecting a lower configured one easily help to test Hello World and then for developing your application. Later, we can test on a high-end device.

For me, virtualization support does not work as my hardware does not support it.

How to achieve function overloading in C?

Try to declare these functions as extern "C++" if your compiler supports this, http://msdn.microsoft.com/en-us/library/s6y4zxec(VS.80).aspx

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

git add only modified changes and ignore untracked files

To stage modified and deleted files

git add -u

How do you convert Html to plain text?

The simplest way I found:

HtmlFilter.ConvertToPlainText(html);

The HtmlFilter class is located in Microsoft.TeamFoundation.WorkItemTracking.Controls.dll

The dll can be found in folder like this: %ProgramFiles%\Common Files\microsoft shared\Team Foundation Server\14.0\

In VS 2015, the dll also requires reference to Microsoft.TeamFoundation.WorkItemTracking.Common.dll, located in the same folder.

How to check if a String is numeric in Java

Here are two methods that might work. (Without using Exceptions). Note : Java is a pass-by-value by default and a String's value is the address of the String's object data. So , when you are doing

stringNumber = stringNumber.replaceAll(" ", "");

You have changed the input value to have no spaces. You can remove that line if you want.

private boolean isValidStringNumber(String stringNumber)
{
    if(stringNumber.isEmpty())
    {
        return false;
    }

    stringNumber = stringNumber.replaceAll(" ", "");

    char [] charNumber = stringNumber.toCharArray();
    for(int i =0 ; i<charNumber.length ;i++)
    {
        if(!Character.isDigit(charNumber[i]))
        {
            return false;
        }
    }
    return true;
}

Here is another method in case you want to allow floats This method allegedly allows numbers in the form to pass 1,123,123,123,123,123.123 i have just made it , and i think it needs further testing to ensure it is working.

private boolean isValidStringTrueNumber(String stringNumber)
{
    if(stringNumber.isEmpty())
    {
        return false;
    }

    stringNumber = stringNumber.replaceAll(" ", "");
    int countOfDecimalPoint = 0;
    boolean decimalPointPassed = false;
    boolean commaFound = false;
    int countOfDigitsBeforeDecimalPoint = 0;
    int countOfDigitsAfterDecimalPoint =0 ;
    int commaCounter=0;
    int countOfDigitsBeforeFirstComma = 0;

    char [] charNumber = stringNumber.toCharArray();
    for(int i =0 ; i<charNumber.length ;i++)
    {
        if((commaCounter>3)||(commaCounter<0))
        {
            return false;
        }
        if(!Character.isDigit(charNumber[i]))//Char is not a digit.
        {
            if(charNumber[i]==',')
            {
                if(decimalPointPassed)
                {
                    return false;
                }
                commaFound = true;
                //check that next three chars are only digits.
                commaCounter +=3;
            }
            else if(charNumber[i]=='.')
            {
                decimalPointPassed = true;
                countOfDecimalPoint++;
            }
            else
            {
                return false;
            }
        }
        else //Char is a digit.
        {
            if ((commaCounter>=0)&&(commaFound))
            {
                if(!decimalPointPassed)
                {
                    commaCounter--;
                }
            }

            if(!commaFound)
            {
                countOfDigitsBeforeFirstComma++;
            }

            if(!decimalPointPassed)
            {
                countOfDigitsBeforeDecimalPoint++;
            }
            else
            {
                countOfDigitsAfterDecimalPoint++;
            }
        }
    }
    if((commaFound)&&(countOfDigitsBeforeFirstComma>3))
    {
        return false;
    }
    if(countOfDecimalPoint>1)
    {
        return false;
    }

    if((decimalPointPassed)&&((countOfDigitsBeforeDecimalPoint==0)||(countOfDigitsAfterDecimalPoint==0)))
    {
        return false;
    }
    return true;
}

How to get current CPU and RAM usage in Python?

Below codes, without external libraries worked for me. I tested at Python 2.7.9

CPU Usage

import os

    CPU_Pct=str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))

    #print results
    print("CPU Usage = " + CPU_Pct)

And Ram Usage, Total, Used and Free

import os
mem=str(os.popen('free -t -m').readlines())
"""
Get a whole line of memory output, it will be something like below
['             total       used       free     shared    buffers     cached\n', 
'Mem:           925        591        334         14         30        355\n', 
'-/+ buffers/cache:        205        719\n', 
'Swap:           99          0         99\n', 
'Total:        1025        591        434\n']
 So, we need total memory, usage and free memory.
 We should find the index of capital T which is unique at this string
"""
T_ind=mem.index('T')
"""
Than, we can recreate the string with this information. After T we have,
"Total:        " which has 14 characters, so we can start from index of T +14
and last 4 characters are also not necessary.
We can create a new sub-string using this information
"""
mem_G=mem[T_ind+14:-4]
"""
The result will be like
1025        603        422
we need to find first index of the first space, and we can start our substring
from from 0 to this index number, this will give us the string of total memory
"""
S1_ind=mem_G.index(' ')
mem_T=mem_G[0:S1_ind]
"""
Similarly we will create a new sub-string, which will start at the second value. 
The resulting string will be like
603        422
Again, we should find the index of first space and than the 
take the Used Memory and Free memory.
"""
mem_G1=mem_G[S1_ind+8:]
S2_ind=mem_G1.index(' ')
mem_U=mem_G1[0:S2_ind]

mem_F=mem_G1[S2_ind+8:]
print 'Summary = ' + mem_G
print 'Total Memory = ' + mem_T +' MB'
print 'Used Memory = ' + mem_U +' MB'
print 'Free Memory = ' + mem_F +' MB'

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Cannot use a leading ../ to exit above the top directory

It means that one of the paths has a ".." at the beginning of it that would result in exiting the web site's root folder hierarchy. You need to google "asp.net relative paths" or something like that to help you with your problem.

BTW, a hint to where the problem is is included in the exception page that you saw. It will actually tell you what file it found the problem in.

To head off future occurences of this exception, do a search in the entire solution for this string: "../". If you find any of those in files in the root path of your web site, address them.

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

The EntityManager is closed

// first need to reset current manager
$em->resetManager();
// and then get new
$em = $this->getContainer()->get("doctrine");
// or in this way, depending of your environment:
$em = $this->getDoctrine();

Is there a Mutex in Java?

To ensure that a Semaphore is binary you just need to make sure you pass in the number of permits as 1 when creating the semaphore. The Javadocs have a bit more explanation.

Change bootstrap navbar collapse breakpoint without using LESS

Your best bet would be to use a port of the CSS processor you use.

I'm a big fan of SASS so I currently use https://github.com/thomas-mcdonald/bootstrap-sass

It looks like there's a fork for Stylus here: https://github.com/Acquisio/bootstrap-stylus

Otherwise, Search & Replace is your best friend right in the css version...

In Tensorflow, get the names of all the Tensors in a graph

There is a way to do it slightly faster than in Yaroslav's answer by using get_operations. Here is a quick example:

import tensorflow as tf

a = tf.constant(1.3, name='const_a')
b = tf.Variable(3.1, name='variable_b')
c = tf.add(a, b, name='addition')
d = tf.multiply(c, a, name='multiply')

for op in tf.get_default_graph().get_operations():
    print(str(op.name))

Null check in an enhanced for loop

For anyone uninterested in writing their own static null safety method you can use: commons-lang's org.apache.commons.lang.ObjectUtils.defaultIfNull(Object, Object). For example:

    for (final String item : 
    (List<String>)ObjectUtils.defaultIfNull(items, Collections.emptyList())) { ... }

ObjectUtils.defaultIfNull JavaDoc

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

A tool to convert MATLAB code to Python

There are several tools for converting Matlab to Python code.

The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).

Other options include:

  • LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago).
  • OMPC: Matlab to Python (a bit outdated).

Also, for those interested in an interface between the two languages and not conversion:

  • pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.
  • Python-Matlab wormholes: both directions of interaction supported.
  • Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython.
  • PyMat: Control Matlab session from Python.
  • pymat2: continuation of the seemingly abandoned PyMat.
  • mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).
  • oct2py: run GNU Octave commands from within Python.
  • pymex: Embeds the Python Interpreter in Matlab, also on File Exchange.
  • matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).
  • MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface.

Btw might be helpful to look here for other migration tips:

On a different note, though I'm not a fortran fan at all, for people who might find it useful there is:

Looping Over Result Sets in MySQL

Use cursors.

A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I really like SCFrench's answer - I would like to point out that it can easily be modified to import the functions directly to the workspace using the assignin function. (Doing it like this reminds me a lot of Python's "import x from y" way of doing things)

function message = makefuns
  assignin('base','fun1',@fun1);
  assignin('base','fun2',@fun2);
  message='Done importing functions to workspace';
end

function y=fun1(x)
  y=x;
end

function z=fun2
  z=1;
end

And then used thusly:

>> makefuns
ans =
Done importing functions to workspace

>> fun1(123)
ans =
   123

>> fun2()
ans =
     1

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

What precisely does 'Run as administrator' do?

UPDATE

"Run as Aministrator" is just a command, enabling the program to continue some operations that require the Administrator privileges, without displaying the UAC alerts.

Even if your user is a member of administrators group, some applications like yours need the Administrator privileges to continue running, because the application is considered not safe, if it is doing some special operation, like editing a system file or something else. This is the reason why Windows needs the Administrator privilege to execute the application and it notifies you with a UAC alert. Not all applications need an Amnistrator account to run, and some applications, like yours, need the Administrator privileges.

If you execute the application with 'run as administrator' command, you are notifying the system that your application is safe and doing something that requires the administrator privileges, with your confirm.

If you want to avoid this, just disable the UAC on Control Panel.

If you want to go further, read the question Difference between "Run as Administrator" and Windows 7 Administrators Group on Microsoft forum or this SuperUser question.

What is the "assert" function?

There are three main reasons for using the assert() function over the normal if else and printf

  1. assert() function is mainly used in the debugging phase, it is tedious to write if else with a printf statement everytime you want to test a condition which might not even make its way in the final code.

  2. In large software deployments , assert comes very handy where you can make the compiler ignore the assert statements using the NDEBUG macro defined before linking the header file for assert() function.

  3. assert() comes handy when you are designing a function or some code and want to get an idea as to what limits the code will and not work and finally include an if else for evaluating it basically playing with assumptions.

Example of SOAP request authenticated with WS-UsernameToken

The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:

Digest Password Support

The WSS 1.1 Username Token Profile allows digest passwords to be sent in a wsse:UsernameToken of a SOAP message. Two more optional elements are included in the wsse:UsernameToken in this case: wsse:Nonce and wsse:Created. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )

This is how a UsernameToken with Digest Password looks like:

<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
   <wsse:Username>Alice</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
   <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
   <wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>

Create a directory if it does not exist and then create the files in that directory as well

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

JavaFX open new window

If you just want a button to open up a new window, then something like this works:

btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
            Stage stage = new Stage();
            stage.setTitle("My New Stage Title");
            stage.setScene(new Scene(root, 450, 450));
            stage.show();
            // Hide this current window (if this is what you want)
            ((Node)(event.getSource())).getScene().getWindow().hide();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to have a a razor action link open in a new tab?

You are setting it't type as submit. That means that browser should post your <form> data to the server.

In fact a tag has no type attribute according to w3schools.

So remote type attribute and it should work for you.

Updating the list view when the adapter data changes

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

How to make a .NET Windows Service start right after the installation?

The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long

@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"

echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause

Add SUM of values of two LISTS into new LIST

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = map(lambda x,y: x+y,first,second)
print three



Output 
[7, 9, 11, 13, 15]

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

If all fails, as was the case with me, Uninstall GIT, reinstall. For some reason this fixes.

P.S.

  1. I tried generating new Keys and Updating at SSH public keys
  2. Also tried deleting all keys and tried to create a fresh key.
  3. And NO, nothing wrong with my .gitconfig

Dynamically changing font size of UILabel

Single line- There are two ways, you can simply change.

1- Pragmatically (Swift 3)

Just add the following code

    yourLabel.numberOfLines = 1;
    yourLabel.minimumScaleFactor = 0.7;
    yourLabel.adjustsFontSizeToFitWidth = true;

2 - Using UILabel Attributes inspector

i- Select your label- Set number of lines 1.
ii- Autoshrink-  Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)

enter image description here

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

Add a linebreak in an HTML text area

Escape sequences like "\n" work fine ! even with text area! I passed a java string with the "\n" to a html textarea and it worked fine as it works on consoles for java!

How to sort a NSArray alphabetically?

This already has good answers for most purposes, but I'll add mine which is more specific.

In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".

This does that for you.

It would probably be best to put these in categories.

// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.

-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {

    NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {

        //find the strings that will actually be compared for alphabetical ordering
        NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
        NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];

        return [firstStringToCompare compare:secondStringToCompare];
    }];
    return sortedArray;
}

// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.

-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
    NSString* result;
    if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
        result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    else {
        result = originalString;
    }
    return result;
}

How to do perspective fixing?

The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.

The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.

Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.

int to unsigned int conversion

Edit: As has been noted in the other answers, the standard actually guarantees that "the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type)". So even if your platform did not store signed ints as two's complement, the behavior would be the same.


Apparently your signed integer -62 is stored in two's complement (Wikipedia) on your platform:

62 as a 32-bit integer written in binary is

0000 0000 0000 0000 0000 0000 0011 1110

To compute the two's complement (for storing -62), first invert all the bits

1111 1111 1111 1111 1111 1111 1100 0001

then add one

1111 1111 1111 1111 1111 1111 1100 0010

And if you interpret this as an unsigned 32-bit integer (as your computer will do if you cast it), you'll end up with 4294967234 :-)

Run parallel multiple commands at once in the same terminal

Based on comment of @alessandro-pezzato. Run multiples commands by using & between the commands.

Example:

$ sleep 3 & sleep 5 & sleep 2 &

It's will execute the commands in background.

jQuery Datepicker localization

You can do like this

 $.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
    prevText: '&lt;Préc', prevStatus: 'Voir le mois précédent',
    nextText: 'Suiv&gt;', nextStatus: 'Voir le mois suivant',
    currentText: 'Courant', currentStatus: 'Voir le mois courant',
    monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    'Jul','Aoû','Sep','Oct','Nov','Déc'],
    monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 0, 
    initStatus: 'Choisir la date', isRTL: false};
 $.datepicker.setDefaults($.datepicker.regional['fr']);

Deserializing a JSON file with JavaScriptSerializer()

For .Net 4+:

string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";

var serializer = new JavaScriptSerializer();
dynamic usr = serializer.DeserializeObject(s);
var UserId = usr["user"]["id"];

For .Net 2/3.5: This code should work on JSON with 1 level

samplejson.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
var UserId = result["id"];
 %>
 <%=UserId %>

And for a 2 level JSON:

sample2.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"user\" : {    \"id\" : 12345,    \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
 %>
 <%= UserId %>

AngularJS - Access to child scope

While jm-'s answer is the best way to handle this case, for future reference it is possible to access child scopes using a scope's $$childHead, $$childTail, $$nextSibling and $$prevSibling members. These aren't documented so they might change without notice, but they're there if you really need to traverse scopes.

// get $$childHead first and then iterate that scope's $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
    // cs is child scope
}

Fiddle

Radio button validation in javascript

1st: If you know that your code isn't right, you should fix it before do anything!

You could do something like this:

function validateForm() {
    var radios = document.getElementsByName("yesno");
    var formValid = false;

    var i = 0;
    while (!formValid && i < radios.length) {
        if (radios[i].checked) formValid = true;
        i++;        
    }

    if (!formValid) alert("Must check some option!");
    return formValid;
}?

See it in action: http://jsfiddle.net/FhgQS/

Get product id and product type in magento?

Item collection.

$_item->product_type;
$_item->getId()

Product :

$product->getTypeId();
$product->getId()

How to linebreak an svg text within javascript?

This is not something that SVG 1.1 supports. SVG 1.2 does have the textArea element, with automatic word wrapping, but it's not implemented in all browsers. SVG 2 does not plan on implementing textArea, but it does have auto-wrapped text.

However, given that you already know where your linebreaks should occur, you can break your text into multiple <tspan>s, each with x="0" and dy="1.4em" to simulate actual lines of text. For example:

<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
  <text x="0" y="0">
    <tspan x="0" dy="1.2em">very long text</tspan>
    <tspan x="0" dy="1.2em">I would like to linebreak</tspan>
  </text>
</g>

Of course, since you want to do that from JavaScript, you'll have to manually create and insert each element into the DOM.

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

Priority queue in .Net

You might like IntervalHeap from the C5 Generic Collection Library. To quote the user guide

Class IntervalHeap<T> implements interface IPriorityQueue<T> using an interval heap stored as an array of pairs. The FindMin and FindMax operations, and the indexer’s get-accessor, take time O(1). The DeleteMin, DeleteMax, Add and Update operations, and the indexer’s set-accessor, take time O(log n). In contrast to an ordinary priority queue, an interval heap offers both minimum and maximum operations with the same efficiency.

The API is simple enough

> var heap = new C5.IntervalHeap<int>();
> heap.Add(10);
> heap.Add(5);
> heap.FindMin();
5

Install from Nuget https://www.nuget.org/packages/C5 or GitHub https://github.com/sestoft/C5/

Angular 2 TypeScript how to find element in Array

Transform the data structure to a map if you frequently use this search

mapPersons: Map<number, Person>;

// prepare the map - call once or when person array change
populateMap() : void {
    this.mapPersons = new Map();
    for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
    return this.mapPersons.get(id);
}

Start a fragment via Intent within a Fragment

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

How to move the cursor word by word in the OS X Terminal

As answered previously, you can add set -o vi in your ~/.bashrc to use vi/vim key bindings, or else you can add following part in .bashrc to move with Ctrl and arrow keys:

# bindings to move 1 word left/right with ctrl+left/right in terminal, just some apple stuff!
bind '"\e[5C": forward-word'
bind '"\e[5D": backward-word'
# bindings to move 1 word left/right with ctrl+left/right in iTerm2, just some apple stuff!
bind '"\e[1;5C": forward-word'
bind '"\e[1;5D": backward-word'

To start effect of these lines of code, either source ~/.bashrc or start a new terminal session.

What does <![CDATA[]]> in XML mean?

Note that the CDATA construct is only needed if placing text directly in the XML text file.

That is, you only need to use CDATA if hand typing or programmatically building the XML text directly.

Any text entered using a DOM processor API or SimpleXML will be automatically escaped to prevent running foul of XML content rules.

Notwithstanding that, there can be times where using CDATA can reduce the text size that would otherwise be produced with all entities encoded, such as for css in style tags or javascript in script tags, where many language constructs use characters in HTML|XML, like < and >.

How to check if String is null

To sure, you should use function to check is null and empty as below:

string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}

Remove legend ggplot 2.2

from r cookbook, where bp is your ggplot:

Remove legend for a particular aesthetic (fill):

bp + guides(fill=FALSE)

It can also be done when specifying the scale:

bp + scale_fill_discrete(guide=FALSE)

This removes all legends:

bp + theme(legend.position="none")

@property retain, assign, copy, nonatomic in Objective-C

Atomic property can be accessed by only one thread at a time. It is thread safe. Default is atomic .Please note that there is no keyword atomic

Nonatomic means multiple thread can access the item .It is thread unsafe

So one should be very careful while using atomic .As it affect the performance of your code

How to change default Anaconda python environment

Overview
Some people have multiple Anaconda environments with different versions of python for compatibility reasons. In this case, you should have a script that sets your default environment. With this method, you can preserve the versions of python you use in your environments.

The following assumes environment_name is the name of your environment

Mac / Linux:
Edit your bash profile so that the last line is source activate environment_name. In Mac OSX this is ~/.bash_profile, in other environments this may be ~/.bashrc

Example:
Here's how i did it on Mac OSX

  1. Open Terminal and type:

    nano ~/.bash_profile

  2. Go to end of file and type the following, where "p3.5" is my environment:

    source activate p3.5

  3. Exit File. Start a new terminal window.

  4. Type the following to see what environment is active

    conda info -e

The result shows that I'm using my p3.5 environment by default.

For Windows:
Create a command file (.cmd) with activate environment_name and follow these instructions to have it execute whenever you open a command prompt

  1. Create a batch file command, e.g. "my_conda.cmd", put it in the Application Data folder.
  2. Configure it to be started automatically whenever you open cmd. This setting is in Registry:
    key: HKCU\SOFTWARE\Microsoft\Command Processor
    value: AutoRun
    type: REG_EXPAND_SZ
    data: "%AppData%\my_conda.cmd"

from this answer: https://superuser.com/a/302553/143794

How can I use regex to get all the characters after a specific character, e.g. comma (",")

.+,(.+)

Explanation:

.+,

will search for everything before the comma, including the comma.

(.+) 

will search for everything after the comma, and depending on your regex environment,

\1

is the reference for the first parentheses captured group that you need, in this example, everything after the comma.

Working copy XXX locked and cleanup failed in SVN

In solution explorer, right click on the project, in the opening sub-menu click on subversion and select clean-up. It will solve the problem, as it did for me. Hope it will work.

Rendering HTML elements to <canvas>

RasterizeHTML is a very good project, but if you need to access the canvas it wont work on chrome. due to the use of <foreignObject>.

If you need to access the canvas then you can use html2canvas

I am trying to find another project as html2canvas is very slow in performance

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

Change the

private static final long serialVersionUID = 1L;

to any other value like

private static final long serialVersionUID = 102831973239L;

also you can generate it automatically in eclipse.

It is because each servlet in a app has a unique id.and tomcat causes problem with two servlets having same id...

Tomcat Server not starting with in 45 seconds

If you are using any Databases such as Oracle/Mysql then first check this databases services are start

Parsing HTTP Response in Python

You can also use python's requests library instead.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()

Now you can manipulate the "dict" like a python dictionary.

error: resource android:attr/fontVariationSettings not found

If anybody has this error using phonegap or cordova with the cordova-plugin-fcm-ng or cordova-plugin-fcm plugin, the solution that worked for me is creating the extra config file for gradle "build-extras.gradle" in the \platforms\android\app folder, and putting the following lines in it

configurations.all {
 resolutionStrategy {
  force 'com.google.firebase:firebase-messaging:18.0.0'
  force 'com.google.firebase:firebase-core:16.0.8'
 }
}

I found this solution reading this page https://github.com/facebook/react-native/issues/25371, in particular comment of shreyakupadhyay on 30/07/19 and consulting https://developers.google.com/android/guides/releases#may_07_2019 about last libraries version.

How can I uninstall npm modules in Node.js?

If it doesn't work with npm uninstall <module_name> try it globally by typing -g.

Maybe you just need to do it as an superUser/administrator with sudo npm uninstall <module_name>.

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

Change event on select with knockout binding, how can I know if it is a real change?

Try this one:

self.GetHierarchyNodeList = function (data, index, event)
{
    debugger;
    if (event.type != "change") {
        return;
    }        
} 

event.type == "change"
event.type == "load" 

Reading Data From Database and storing in Array List object

Try creating new instance of customer every time e.g.

         while (rs.next()) {

        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));
        customer.setName(rs.getString("name"));

        customer.setAddress(rs.getString("address"));
        customer.setPhone(rs.getString("phone"));
        customer.setEmail(rs.getString("email"));
        customer.setBountPoints(rs.getInt("bonuspoint"));
        customer.setTotalsale(rs.getInt("totalsale"));

        customers.add(customer);


    }

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

suppose you need a label with text customername than you can achive it using 2 ways

[1]@Html.Label("CustomerName")

[2]@Html.LabelFor(a => a.CustomerName)  //strongly typed

2nd method used a property from your model. If your view implements a model then you can use the 2nd method.

More info please visit below link

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

Convert double to float in Java

First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float. Float is short for floating point, and floating point types of various precisions exist. Java types float and double are both floating point types of different precision. In a database both are called FLOAT. Since double has a higher precision than float, it probably is a better idea not to cast your value to a float, because you might lose precision.

You might also use BigDecimal, which represent an arbitrary-precision number.

select and echo a single field from mysql db using PHP

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

Usually you do something like this:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

html script src="" triggering redirection with button

I was having this problem but i found out that it was a permissions problem I changed my permissions to 0744 and now it works. I don't know if this was your problem but it worked for me.

What's the best practice to "git clone" into an existing folder?

To clone a git repo into an empty existing directory do the following:

cd myfolder
git clone https://myrepo.com/git.git . 

Notice the . at the end of your git clone command. That will download the repo into the current working directory.

python: creating list from string

I know this is old but here's a one liner list comprehension:

data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']

[[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data]

or

[int(item) if item.isdigit() else item for items in data for item in items.split(', ')]

How can I remove specific rules from iptables?

Assume that, if you want to remove NAT rules,

List the appended IPtables using the command below,

# sudo iptables -L -t nat -v

Chain PREROUTING (policy ACCEPT 18 packets, 1382 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    7   420 DNAT       tcp  --  any    any     anywhere             saltmaster           tcp dpt:http to:172.31.5.207:80
    0     0 DNAT       tcp  --  eth0   any     anywhere             anywhere             tcp dpt:http to:172.31.5.207:8080

If you would like to remove the nat rule from the IPtables, just execute the command,

# sudo iptables -F -t nat -v

Flushing chain `PREROUTING'
Flushing chain `INPUT'
Flushing chain `OUTPUT'
Flushing chain `POSTROUTING'

Then, you can verify that,

# sudo iptables -L -t nat -v

Select values of checkbox group with jQuery

You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):

$("input[name='user_group[]']:checked")

With those checked items, you can either create a collection of those values or do something to the collection:

var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
  values.push($(this).val());
  // or you can do something to the actual checked checkboxes by working directly with  'this'
  // something like $(this).hide() (only something useful, probably) :P
});

Jackson - Deserialize using generic class

public class Data<T> extends JsonDeserializer implements ContextualDeserializer {
    private Class<T> cls;
    public JsonDeserializer createContextual(DeserializationContext ctx, BeanProperty prop) throws JsonMappingException {
        cls = (Class<T>) ctx.getContextualType().getRawClass();
        return this;
    }
    ...
 }

Using async/await with a forEach loop

Instead of Promise.all in conjunction with Array.prototype.map (which does not guarantee the order in which the Promises are resolved), I use Array.prototype.reduce, starting with a resolved Promise:

async function printFiles () {
  const files = await getFilePaths();

  await files.reduce(async (promise, file) => {
    // This line will wait for the last async function to finish.
    // The first iteration uses an already resolved Promise
    // so, it will immediately continue.
    await promise;
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }, Promise.resolve());
}

Rails filtering array of objects by attribute value

I'd go about this slightly differently. Structure your query to retrieve only what you need and split from there.

So make your query the following:

#                                vv or Job.find(1) vv
attachments = Attachment.where(job_id: @job.id, file_type: ["logo", "image"])
# or 
Job.includes(:attachments).where(id: your_job_id, attachments: { file_type: ["logo", "image"] })

And then partition the data:

@logos, @images = attachments.partition { |attachment| attachment.file_type == "logo" }

That will get the data you're after in a neat and efficient manner.

Detecting when the 'back' button is pressed on a navbar

For the record, I think this is more of what he was looking for…

    UIBarButtonItem *l_backButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind target:self action:@selector(backToRootView:)];

    self.navigationItem.leftBarButtonItem = l_backButton;


    - (void) backToRootView:(id)sender {

        // Perform some custom code

        [self.navigationController popToRootViewControllerAnimated:YES];
    }

Save file/open file dialog box, using Swing & Netbeans GUI editor

Here is an example

private void doOpenFile() {
    int result = myFileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        Path path = myFileChooser.getSelectedFile().toPath();

        try {
            String contentString = "";

            for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
                contentString += s;
            }

            jText.setText(contentString);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void doSaveFile() {
    int result = myFileChooser.showSaveDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        // We'll be making a mytmp.txt file, write in there, then move it to
        // the selected
        // file. This takes care of clearing that file, should there be
        // content in it.
        File targetFile = myFileChooser.getSelectedFile();

        try {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }

            FileWriter fw = new FileWriter(targetFile);

            fw.write(jText.getText());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul tag. Let's consider all the rules with a margin property used by the OP.

body {

margin:0px;
...
}

The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.

#mainNav{
    margin:0 auto;
    ...
}

This is a better attempt, a more specific selector #mainNav, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul element is still below this element in the DOM.

#mainNav ul li{
    ...
    margin:0;
    ...
}

This went too far down in the DOM! Now, the selector matches the li element, which is below the ul element.

So, assuming that the UA rule used the selector ul and not !important, which is most likely the case, the solution would have been a simple ul { margin: 0; }, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }.

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

How to make the 'cut' command treat same sequental delimiters as one?

This Perl one-liner shows how closely Perl is related to awk:

perl -lane 'print $F[3]' text.txt

However, the @F autosplit array starts at index $F[0] while awk fields start with $1

How to reset radiobuttons in jQuery so that none is checked

Why don't you do:

$("#radio1, #radio2, #radio3, #radio4").checked = false;