Programs & Examples On #Locking

Locking allows different types of resources to be used exclusively by one process at a time.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The answer is not efficiency. Non-reentrant mutexes lead to better code.

Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.

Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.

The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.

If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.

How does lock work exactly?

The lock statement is translated to calls to the Enter and Exit methods of Monitor.

The lock statement will wait indefinitely for the locking object to be released.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Mine is that if you set MASM listing file option some extra selection, it will give you this error.

Just use

 Enable Assembler Generated Code Listing   Yes/Sg
 Assembled Code Listing $(ProjectName).lst

it is fine.

But any extra you have issue.

How to detect query which holds the lock in Postgres?

From this excellent article on query locks in Postgres, one can get blocked query and blocker query and their information from the following query.

CREATE VIEW lock_monitor AS(
SELECT
  COALESCE(blockingl.relation::regclass::text,blockingl.locktype) as locked_item,
  now() - blockeda.query_start AS waiting_duration, blockeda.pid AS blocked_pid,
  blockeda.query as blocked_query, blockedl.mode as blocked_mode,
  blockinga.pid AS blocking_pid, blockinga.query as blocking_query,
  blockingl.mode as blocking_mode
FROM pg_catalog.pg_locks blockedl
JOIN pg_stat_activity blockeda ON blockedl.pid = blockeda.pid
JOIN pg_catalog.pg_locks blockingl ON(
  ( (blockingl.transactionid=blockedl.transactionid) OR
  (blockingl.relation=blockedl.relation AND blockingl.locktype=blockedl.locktype)
  ) AND blockedl.pid != blockingl.pid)
JOIN pg_stat_activity blockinga ON blockingl.pid = blockinga.pid
  AND blockinga.datid = blockeda.datid
WHERE NOT blockedl.granted
AND blockinga.datname = current_database()
);

SELECT * from lock_monitor;

As the query is long but useful, the article author has created a view for it to simplify it's usage.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

It's been a while, but last time I had something similar:

ROLLBACK TRAN

or trying to

COMMIT

what had allready been done free'd everything up so I was able to clear things out and start again.

Detecting locked tables (locked by LOCK TABLE)

Use SHOW OPEN TABLES: http://dev.mysql.com/doc/refman/5.1/en/show-open-tables.html

You can do something like this

SHOW OPEN TABLES WHERE `Table` LIKE '%[TABLE_NAME]%' AND `Database` LIKE '[DBNAME]' AND In_use > 0;

to check any locked tables in a database.

Optimistic vs. Pessimistic locking

Optimistic locking is used when you don't expect many collisions. It costs less to do a normal operation but if the collision DOES occur you would pay a higher price to resolve it as the transaction is aborted.

Pessimistic locking is used when a collision is anticipated. The transactions which would violate synchronization are simply blocked.

To select proper locking mechanism you have to estimate the amount of reads and writes and plan accordingly.

Git 'fatal: Unable to write new index file'

I had the same problem. I restarted my computer and the issue was resolved.

How to find locked rows in Oracle

The below PL/SQL block finds all locked rows in a table. The other answers only find the blocking session, finding the actual locked rows requires reading and testing each row.

(However, you probably do not need to run this code. If you're having a locking problem, it's usually easier to find the culprit using GV$SESSION.BLOCKING_SESSION and other related data dictionary views. Please try another approach before you run this abysmally slow code.)

First, let's create a sample table and some data. Run this in session #1.

--Sample schema.
create table test_locking(a number);
insert into test_locking values(1);
insert into test_locking values(2);
commit;
update test_locking set a = a+1 where a = 1;

In session #2, create a table to hold the locked ROWIDs.

--Create table to hold locked ROWIDs.
create table locked_rowids(the_rowid rowid);
--Remove old rows if table is already created:
--delete from locked_rowids;
--commit;

In session #2, run this PL/SQL block to read the entire table, probe each row, and store the locked ROWIDs. Be warned, this may be ridiculously slow. In your real version of this query, change both references to TEST_LOCKING to your own table.

--Save all locked ROWIDs from a table.
--WARNING: This PL/SQL block will be slow and will temporarily lock rows.
--You probably don't need this information - it's usually good enough to know
--what other sessions are locking a statement, which you can find in
--GV$SESSION.BLOCKING_SESSION.
declare
    v_resource_busy exception;
    pragma exception_init(v_resource_busy, -00054);
    v_throwaway number;
    type rowid_nt is table of rowid;
    v_rowids rowid_nt := rowid_nt();
begin
    --Loop through all the rows in the table.
    for all_rows in
    (
        select rowid
        from test_locking
    ) loop
        --Try to look each row.
        begin
            select 1
            into v_throwaway
            from test_locking
            where rowid = all_rows.rowid
            for update nowait;
        --If it doesn't lock, then record the ROWID.
        exception when v_resource_busy then
            v_rowids.extend;
            v_rowids(v_rowids.count) := all_rows.rowid;
        end;

        rollback;
    end loop;

    --Display count:
    dbms_output.put_line('Rows locked: '||v_rowids.count);

    --Save all the ROWIDs.
    --(Row-by-row because ROWID type is weird and doesn't work in types.)
    for i in 1 .. v_rowids.count loop
        insert into locked_rowids values(v_rowids(i));
    end loop;
    commit;
end;
/

Finally, we can view the locked rows by joining to the LOCKED_ROWIDS table.

--Display locked rows.
select *
from test_locking
where rowid in (select the_rowid from locked_rowids);


A
-
1

How to disable Home and other system buttons in Android?

I too was searching for this for sometime, and finally was able to do it as I needed, ie Navigation Bar is inaccessible, status bar is inaccessible, even if you long press power button, neither the power menu nor navigation buttons are shown. Thanks to @Assaf Gamliel , his answer took me to the right path. I followed this tutorial with some slight modifications. While specifying Type, I specified WindowManager.LayoutParams.TYPE_SYSTEM_ERROR instead of WindowManager.LayoutParams.TYPE_PHONE, else our "overlay" won't hide the system bars. You can play around with the Flags, Height, Width etc so that it'll behave as you want it to.

Any way to select without causing locking in MySQL?

another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE

SELECT * FROM TABLE_NAME LOCK IN SHARE MODE; 

What is a deadlock?

A deadlock is a state of a system in which no single process/thread is capable of executing an action. As mentioned by others, a deadlock is typically the result of a situation where each process/thread wishes to acquire a lock to a resource that is already locked by another (or even the same) process/thread.

There are various methods to find them and avoid them. One is thinking very hard and/or trying lots of things. However, dealing with parallelism is notoriously difficult and most (if not all) people will not be able to completely avoid problems.

Some more formal methods can be useful if you are serious about dealing with these kinds of issues. The most practical method that I'm aware of is to use the process theoretic approach. Here you model your system in some process language (e.g. CCS, CSP, ACP, mCRL2, LOTOS) and use the available tools to (model-)check for deadlocks (and perhaps some other properties as well). Examples of toolset to use are FDR, mCRL2, CADP and Uppaal. Some brave souls might even prove their systems deadlock free by using purely symbolic methods (theorem proving; look for Owicki-Gries).

However, these formal methods typically do require some effort (e.g. learning the basics of process theory). But I guess that's simply a consequence of the fact that these problems are hard.

Lock, mutex, semaphore... what's the difference?

Using C programming on a Linux variant as a base case for examples.

Lock:

• Usually a very simple construct binary in operation either locked or unlocked

• No concept of thread ownership, priority, sequencing etc.

• Usually a spin lock where the thread continuously checks for the locks availability.

• Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc.

• Usually requires hardware support for atomic operation.

File Locks:

• Usually used to coordinate access to a file via multiple processes.

• Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock.

• Example : flock, fcntl etc..

Mutex:

• Mutex function calls usually work in kernel space and result in system calls.

• It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it.

• Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE).

• Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc.

• Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems.

Semaphore:

• This is a kernel maintained integer whose values is not allowed to fall below zero.

• It can be used to synchronize processes.

• The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available.

• A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore.

How to implement a lock in JavaScript

Here's a simple lock mechanism, implemented via closure

_x000D_
_x000D_
const createLock = () => {

    let lockStatus = false

    const release = () => {
        lockStatus = false
    }

    const acuire = () => {
        if (lockStatus == true)
            return false
        lockStatus = true
        return true
    }
    
    return {
        lockStatus: lockStatus, 
        acuire: acuire,
        release: release,
    }
}

lock = createLock() // create a lock
lock.acuire() // acuired a lock

if (lock.acuire()){
  console.log("Was able to acuire");
} else {
  console.log("Was not to acuire"); // This will execute
}

lock.release() // now the lock is released

if(lock.acuire()){
  console.log("Was able to acuire"); // This will execute
} else {
  console.log("Was not to acuire"); 
}

lock.release() // Hey don't forget to release
_x000D_
_x000D_
_x000D_

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

TLDR; Neither use the synchronized modifier nor the synchronized(this){...} expression but synchronized(myLock){...} where myLock is a final instance field holding a private object.


The difference between using the synchronized modifier on the method declaration and the synchronized(..){ } expression in the method body are this:

  • The synchronized modifier specified on the method's signature
    1. is visible in the generated JavaDoc,
    2. is programmatically determinable via reflection when testing a method's modifier for Modifier.SYNCHRONIZED,
    3. requires less typing and indention compared to synchronized(this) { .... }, and
    4. (depending on your IDE) is visible in the class outline and code completion,
    5. uses the this object as lock when declared on non-static method or the enclosing class when declared on a static method.
  • The synchronized(...){...} expression allows you
    1. to only synchronize the execution of parts of a method's body,
    2. to be used within a constructor or a (static) initialization block,
    3. to choose the lock object which controls the synchronized access.

However, using the synchronized modifier or synchronized(...) {...} with this as the lock object (as in synchronized(this) {...}), have the same disadvantage. Both use it's own instance as the lock object to synchronize on. This is dangerous because not only the object itself but any other external object/code that holds a reference to that object can also use it as a synchronization lock with potentially severe side effects (performance degradation and deadlocks).

Therefore best practice is to neither use the synchronized modifier nor the synchronized(...) expression in conjunction with this as lock object but a lock object private to this object. For example:

public class MyService {
    private final lock = new Object();

    public void doThis() {
       synchronized(lock) {
          // do code that requires synchronous execution
        }
    }

    public void doThat() {
       synchronized(lock) {
          // do code that requires synchronous execution
        }
    }
}

You can also use multiple lock objects but special care needs to be taken to ensure this does not result in deadlocks when used nested.

public class MyService {
    private final lock1 = new Object();
    private final lock2 = new Object();

    public void doThis() {
       synchronized(lock1) {
          synchronized(lock2) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThat() and doMore().
          }
    }

    public void doThat() {
       synchronized(lock1) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThis().
              // doMore() may execute concurrently
        }
    }

    public void doMore() {
       synchronized(lock2) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThis().
              // doThat() may execute concurrently
        }
    }
}

How to check if a table is locked in sql server

Better yet, consider sp_getapplock which is designed for this. Or use SET LOCK_TIMEOUT

Otherwise, you'd have to do something with sys.dm_tran_locks which I'd use only for DBA stuff: not for user defined concurrency.

Show all current locks from get_lock

Starting with MySQL 5.7, the performance schema exposes all metadata locks, including locks related to the GET_LOCK() function.

See http://dev.mysql.com/doc/refman/5.7/en/metadata-locks-table.html

Find out who is locking a file on a network share

Just in case someone looking for a solution to this for a Windows based system or NAS:

There is a built-in function in Windows that shows you what files on the local computer are open/locked by remote computer (which has the file open through a file share):

  • Select "Manage Computer" (Open "Computer Management")
  • click "Shared Folders"
  • choose "Open Files"

There you can even close the file forcefully.

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

How to find out what is locking my tables?

For getting straight to "who is blocked/blocking" I combined/abbreviated sp_who and sp_lock into a single query which gives a nice overview of who has what object locked to what level.

--Create Procedure WhoLock
--AS
set nocount on
if object_id('tempdb..#locksummary') is not null Drop table #locksummary
if object_id('tempdb..#lock') is not null Drop table #lock
create table #lock (    spid int,    dbid int,    objId int,    indId int,    Type char(4),    resource nchar(32),    Mode char(8),    status char(6))
Insert into #lock exec sp_lock
if object_id('tempdb..#who') is not null Drop table #who
create table #who (     spid int, ecid int, status char(30),
            loginame char(128), hostname char(128),
            blk char(5), dbname char(128), cmd char(16)
            --
            , request_id INT --Needed for SQL 2008 onwards
            --
         )
Insert into #who exec sp_who
Print '-----------------------------------------'
Print 'Lock Summary for ' + @@servername  + ' (excluding tempdb):'
Print '-----------------------------------------' + Char(10)
Select     left(loginame, 28) as loginame, 
    left(db_name(dbid),128) as DB,
    left(object_name(objID),30) as object,
    max(mode) as [ToLevel],
    Count(*) as [How Many],
    Max(Case When mode= 'X' Then cmd Else null End) as [Xclusive lock for command],
    l.spid, hostname
into #LockSummary
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and l.status='GRANT'
group by dbID, objID, l.spid, hostname, loginame

Select * from #LockSummary order by [ToLevel] Desc, [How Many] Desc, loginame, DB, object

Print '--------'
Print 'Who is blocking:'
Print '--------' + char(10)
SELECT p.spid
,convert(char(12), d.name) db_name
, program_name
, p.loginame
, convert(char(12), hostname) hostname
, cmd
, p.status
, p.blocked
, login_time
, last_batch
, p.spid
FROM      master..sysprocesses p
JOIN      master..sysdatabases d ON p.dbid =  d.dbid
WHERE     EXISTS (  SELECT 1
          FROM      master..sysprocesses p2
          WHERE     p2.blocked = p.spid )

Print '--------'
Print 'Details:'
Print '--------' + char(10)
Select     left(loginame, 30) as loginame,  l.spid,
    left(db_name(dbid),15) as DB,
    left(object_name(objID),40) as object,
    mode ,
    blk,
    l.status
from #lock l join #who w on l.spid= w.spid
where dbID != db_id('tempdb') and blk <>0
Order by mode desc, blk, loginame, dbID, objID, l.status

(For what the lock level abbreviations mean, see e.g. https://technet.microsoft.com/en-us/library/ms175519%28v=sql.105%29.aspx)

Copied from: sp_WhoLock – a T-SQL stored proc combining sp_who and sp_lock...

NB the [Xclusive lock for command] column can be misleading -- it shows the current command for that spid; but the X lock could have been triggered by an earlier command in the transaction.

Java synchronized method lock on object, or method?

This might not work as the boxing and autoboxing from Integer to int and viceversa is dependant on JVM and there is high possibility that two different numbers might get hashed to same address if they are between -128 and 127.

SQL Server - How to lock a table until a stored procedure finishes

BEGIN TRANSACTION

select top 1 *
from table1
with (tablock, holdlock)

-- You do lots of things here

COMMIT

This will hold the 'table lock' until the end of your current "transaction".

Command-line tool for finding out who is locking a file

Download Handle.

https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt", run this:

handle "C:\path\path\file.txt"

This will tell you what process(es) have the file (or folder) locked.

Volatile vs. Interlocked vs. lock

"volatile" does not replace Interlocked.Increment! It just makes sure that the variable is not cached, but used directly.

Incrementing a variable requires actually three operations:

  1. read
  2. increment
  3. write

Interlocked.Increment performs all three parts as a single atomic operation.

Effect of NOLOCK hint in SELECT statements

1) Yes, a select with NOLOCK will complete faster than a normal select.

2) Yes, a select with NOLOCK will allow other queries against the effected table to complete faster than a normal select.

Why would this be?

NOLOCK typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.

You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a NOLOCK read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.

You really have no way to know what the state of the data is.

If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then NOLOCK is a good way to boost performance for these queries and avoid having them negatively impact database performance.

Always use the NOLOCK hint with great caution and treat any data it returns suspiciously.

Why is lock(this) {...} bad?

...and the exact same arguments apply to this construct as well:

lock(typeof(SomeObject))

Java: Multiple class declarations in one file

javac doesn't actively prohibit this, but it does have a limitation that pretty much means that you'd never want to refer to a top-level class from another file unless it has the same name as the file it's in.

Suppose you have two files, Foo.java and Bar.java.

Foo.java contains:

  • public class Foo

Bar.java contains:

  • public class Bar
  • class Baz

Let's also say that all of the classes are in the same package (and the files are in the same directory).

What happens if Foo.java refers to Baz but not Bar and we try to compile Foo.java? The compilation fails with an error like this:

Foo.java:2: cannot find symbol
symbol  : class Baz
location: class Foo
  private Baz baz;
          ^
1 error

This makes sense if you think about it. If Foo.java refers to Baz, but there is no Baz.java (or Baz.class), how can javac know what source file to look in?

If you instead tell javac to compile Foo.java and Bar.java at the same time, or even if you had previously compiled Bar.java (leaving the Baz.class where javac can find it) then this error goes away. This makes your build process feel very unreliable and flaky, however.

Because the actual limitation, which is more like "don't refer to a top-level class from another file unless it has the same name as the file it's in or you're also referring to a class that's in that same file that's named the same thing as the file" is kind of hard to follow, people usually go with the much more straightforward (though stricter) convention of just putting one top-level class in each file. This is also better if you ever change your mind about whether a class should be public or not.

Sometimes there really is a good reason why everybody does something in a particular way.

Convert Text to Uppercase while typing in Text box

I use to do this thing (Code Behind) ASP.NET using VB.NET:

1) Turn AutoPostBack = True in properties of said Textbox

2) Code for Textbox (Event : TextChanged) Me.TextBox1.Text = Me.TextBox1.Text.ToUpper

3) Observation After entering the string variables in TextBox1, when user leaves TextBox1, AutoPostBack fires the code when Text was changed during "TextChanged" event.

JMS Topic vs Queues

As for the order preservation, see this ActiveMQ page. In short: order is preserved for single consumers, but with multiple consumers order of delivery is not guaranteed.

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

<?php
$url=parse_url("http://domain.com/site/gallery/1?user=12#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
?>

This is should work

How to make div follow scrolling smoothly with jQuery?

That code doesn't work very well i fixed it a little bit

var el = $('.caja-pago');
var elpos_original = el.offset().top;

 $(window).scroll(function(){
     var elpos = el.offset().top;
     var windowpos = $(window).scrollTop();
     var finaldestination = windowpos;
     if(windowpos<elpos_original) {
         finaldestination = elpos_original;
         el.stop().animate({'top':400},500);
     } else {
         el.stop().animate({'top':windowpos+10},500);
     }
 });

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

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

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

How to multi-line "Replace in files..." in Notepad++

It's easy to do multiline replace in Notepad++. You have to use \n to represent the newline in your string, and it works for both search and replace strings. You have to make sure to select "Extended" search mode in the bottom left corner of the search window.

I found a good article describing the features here: http://markantoniou.blogspot.com/2008/06/notepad-how-to-use-regular-expressions.html

Array initialization in Perl

If I understand you, perhaps you don't need an array of zeroes; rather, you need a hash. The hash keys will be the values in the other array and the hash values will be the number of times the value exists in the other array:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my %tallies;
$tallies{$_} ++ for @other_array;

print "$_ => $tallies{$_}\n" for sort {$a <=> $b} keys %tallies;    

Output:

0 => 3
1 => 1
2 => 2
3 => 3
4 => 1

To answer your specific question more directly, to create an array populated with a bunch of zeroes, you can use the technique in these two examples:

my @zeroes = (0) x 5;            # (0,0,0,0,0)

my @zeroes = (0) x @other_array; # A zero for each item in @other_array.
                                 # This works because in scalar context
                                 # an array evaluates to its size.

Android and Facebook share intent

Facebook does not allow to share plain text data with Intent.EXTRA_TEXT but You can share text+link with facebook messanger using this, this works fine for me

            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, text+url link);
            sendIntent.setType("text/plain");
            sendIntent.setPackage("com.facebook.orca");
            startActivity(sendIntent);

Import SQL dump into PostgreSQL database

psql databasename < data_base_dump

That's the command you are looking for.

Beware: databasename must be created before importing. Have a look at the PostgreSQL Docs Chapter 23. Backup and Restore.

What does "for" attribute do in HTML <label> tag?

The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together.

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

What is the difference between Cygwin and MinGW?

To add to the other answers, Cygwin comes with the MinGW libraries and headers and you can compile without linking to the cygwin1.dll by using -mno-cygwin flag with gcc. I greatly prefer this to using plain MinGW and MSYS.

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

What tools do you use to test your public REST API?

If you're just testing your APIs manually, we've found RestClient 2.3 or the Poster add-on for Firefox to be pretty helpful. Both of these let you build requests that GET, PUT, POST, or DELETE. You can save these requests to rerun later.

For simple automated testing try the Linux (or Cygwin) 'curl' command in a shell script.

From something more industrial strength you can move up to Apache JMeter. JMeter is great for load testing.

31 October 2014: HTTPRequester is now a better choice for Firefox.

July 2015: Postman is a good choice for Chrome

C# equivalent of the IsNull() function in SQL Server

    public static T IsNull<T>(this T DefaultValue, T InsteadValue)
    {

        object obj="kk";

        if((object) DefaultValue == DBNull.Value)
        {
            obj = null;
        }

        if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
        {
            return InsteadValue;
        }
        else
        {
            return DefaultValue;
        }

    }

//This method can work with DBNull and null value. This method is question's answer

`require': no such file to load -- mkmf (LoadError)

I got the similar error when install bundle

sudo apt-get install ruby-dev

Works great for me and solve the problem Mint 16 ruby1.9.3

How to include "zero" / "0" results in COUNT aggregate?

USE join to get 0 count in the result using GROUP BY.

simply 'join' does Inner join in MS SQL so , Go for left or right join.

If the table which contains the primary key is mentioned first in the QUERY then use LEFT join else RIGHT join.

EG:

select WARDNO,count(WARDCODE) from MAIPADH 
right join  MSWARDH on MSWARDH.WARDNO= MAIPADH.WARDCODE
group by WARDNO

.

select WARDNO,count(WARDCODE) from MSWARDH
left join  MAIPADH on MSWARDH.WARDNO= MAIPADH.WARDCODE group by WARDNO

Take group by from the table which has Primary key and count from the another table which has actual entries/details.

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

I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.

How can I read inputs as numbers?

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

This means that, just like raw_input, input in Python 3.x always returns a string object.

To fix the problem, you need to explicitly make those inputs into integers by putting them in int:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

How to access site through IP address when website is on a shared host?

You can access you website using your IP address and your cPanel username with ~ symbols. For Example: http://serverip/~cpusername like as https://xxx.xxx.xx.xx/~mohidul

Get output parameter value in ADO.NET

For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.

using (SqlConnection conn = new SqlConnection())
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters
    SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
    outputParam.Direction = ParameterDirection.Output;

    conn.Open();

    using(IDataReader reader = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            //read in data
        }
    }
    // reader is closed/disposed after exiting the using statement
    int id = outputParam.Value;
}

How to change the default encoding to UTF-8 for Apache?

<meta charset='utf-8'> overrides the apache default charset (cf /etc/apache2/conf.d/charset)

If this is not enough, then you probably created your original file with iso-8859-1 encoding character set. You have to convert it to the proper character set:

iconv -f ISO-8859-1 -t UTF-8 source_file.php -o new file.php

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

removing bold styling from part of a header

Yes you can add text inside <span> and override css. jsfiddle

html:

<h1>**This text should be bold**, <span>but this text should not</span><h1>

css:

span{
   font-weight: normal;
}

What does enctype='multipart/form-data' mean?

Set the method attribute to POST because file content can't be put inside a URL parameter using a form.

Set the value of enctype to multipart/form-data because the data will be split into multiple parts, one for each file plus one for the text of the form body that may be sent with them.

How to use basic authorization in PHP curl

Its Simple Way To Pass Header

function get_data($url) {

$ch = curl_init();
$timeout = 5;
$username = 'c4f727b9646045e58508b20ac08229e6';        // Put Username 
$password = '';                                        // Put Password
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");    // Add This Line
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = "https://storage.scrapinghub.com/items/397187/2/127";
$data = get_data($url);
echo '<pre>';`print_r($data_json);`die;    // For Print Value

Check My JSON Value

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Delete ActionLink with confirm dialog

You can also customize the by passing the delete item along with the message. In my case using MVC and Razor, so I could do this:

@Html.ActionLink("Delete", 
    "DeleteTag", new { id = t.IDTag }, 
    new { onclick = "return confirm('Do you really want to delete the tag " + @t.Tag + "?')" })

Finding an element in an array in Java

There is a contains method for lists, so you should be able to do:

Arrays.asList(yourArray).contains(yourObject);

Warning: this might not do what you (or I) expect, see Tom's comment below.

Increment a Integer's int value?

As Grodriguez says, Integer objects are immutable. The problem here is that you're trying to increment the int value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++.

As a side note, never ever call Integer's constructor. Take advantage of autoboxing by just assigning ints to Integers directly, like Integer foo = 5. This will use Integer.valueOf(int) transparently, which is superior to the constructor because it doesn't always have to create a new object.

How can I take an UIImage and give it a black border?

In Swift 3 here's how you do it to the UIImage itself:

let size = CGSize(width: image.size.width, height: image.size.height)
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
image?.draw(in: rect, blendMode: .normal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.stroke(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

self.imageView.image = newImage

Replacement for deprecated sizeWithFont: in iOS 7?

Alternate solution-

CGSize expectedLabelSize;
if ([subTitle respondsToSelector:@selector(sizeWithAttributes:)])
{
    expectedLabelSize = [subTitle sizeWithAttributes:@{NSFontAttributeName:subTitleLabel.font}];
}else{
    expectedLabelSize = [subTitle sizeWithFont:subTitleLabel.font constrainedToSize:subTitleLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
}

There is an error in XML document (1, 41)

First check the variables declared using proper Datatypes. I had a same problem then I have checked, by mistake I declared SAPUser as int datatype so that the error occurred. One more thing XML file stores its data using concept like array but its first index starts having +1. e.g. if error is in(7,2) then check for 6th line always.....

PostgreSQL DISTINCT ON with different ORDER BY

Window function may solve that in one pass:

SELECT DISTINCT ON (address_id) 
   LAST_VALUE(purchases.address_id) OVER wnd AS address_id
FROM "purchases"
WHERE "purchases"."product_id" = 1
WINDOW wnd AS (
   PARTITION BY address_id ORDER BY purchases.purchased_at DESC
   ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

How to redirect to an external URL in Angular2?

After ripping my head off, the solution is just to add http:// to href.

<a href="http://www.URL.com">Go somewhere</a>

How would I access variables from one class to another?

Can you explain why you want to do this?

You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:

class ClassA(object):
   var1 = 1
   var2 = 2
   @classmethod
   def method(cls):
       cls.var1 = cls.var1 + cls.var2
       return cls.var1

In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.

I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...

Where can I find documentation on formatting a date in JavaScript?

I made this very simple formatter, it's cut/n/pastable (Updated with neater version):

function DateFmt(fstr) {
  this.formatString = fstr

  var mthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  var dayNames = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
  var zeroPad = function(number) {
     return ("0"+number).substr(-2,2);
  }

  var dateMarkers = {
    d:['getDate',function(v) { return zeroPad(v)}],
    m:['getMonth',function(v) { return zeroPad(v+1)}],
    n:['getMonth',function(v) { return mthNames[v]; }],
    w:['getDay',function(v) { return dayNames[v]; }],
    y:['getFullYear'],
    H:['getHours',function(v) { return zeroPad(v)}],
    M:['getMinutes',function(v) { return zeroPad(v)}],
    S:['getSeconds',function(v) { return zeroPad(v)}],
    i:['toISOString']
  };

  this.format = function(date) {
    var dateTxt = this.formatString.replace(/%(.)/g, function(m, p) {
      var rv = date[(dateMarkers[p])[0]]()

      if ( dateMarkers[p][1] != null ) rv = dateMarkers[p][1](rv)

      return rv

    });

    return dateTxt
  }

}

fmt = new DateFmt("%w %d:%n:%y - %H:%M:%S  %i")
v = fmt.format(new Date())

http://snipplr.com/view/66968.82825/

How do I print the content of httprequest request?

More details that help in logging

    String client = request.getRemoteAddr();
    logger.info("###### requested client: {} , Session ID : {} , URI :" + request.getMethod() + ":" + request.getRequestURI() + "", client, request.getSession().getId());

    Map params = request.getParameterMap();
    Iterator i = params.keySet().iterator();
    while (i.hasNext()) {
        String key = (String) i.next();
        String value = ((String[]) params.get(key))[0];
        logger.info("###### Request Param Name : {} , Value :  {} ", key, value);
    }

Is there a way to specify a max height or width for an image?

If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

Remove "Using default security password" on Spring Boot

When spring boot is used we should exclude the SecurityAutoConfiguration.class both in application class and where exactly you are configuring the security like below.

Then only we can avoid the default security password.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
@EnableJpaRepositories
@EnableResourceServer
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

    @Configuration
    @EnableWebSecurity
    @EnableAutoConfiguration(exclude = { 
            org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class 
        })
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity.authorizeRequests().anyRequest().authenticated();
            httpSecurity.headers().cacheControl();
        }
    }

How to redirect 'print' output to a file using python?

The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python) I'm guessing you're on a UNIX system. Just use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

./script.py

to run the file, use

./script.py > <filename>

where you replace <filename> with the name of the file you want the output to go in to. The > token tells (most) shells to set stdout to the file described by the following token.

One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py to run.

So before running ./script.py,execute this command

chmod a+x script.py (make the script executable for all users)

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

My problem turned out to be blank spaces in the txt file that I was using to feed the WMI Powershell script.

jQuery UI Tabs - How to Get Currently Selected Tab Index

In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.

<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus"><a href="#tabs-4">Tab 5</a></li>

The following will get you the href value of the link which should be the same as the id for your tab container:

jQuery('.ui-tabs-selected a',window.parent.document).attr('href')

This should also work in place of: $tabs.tabs('option', 'selected');

It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.

Diff files present in two different directories

If you specifically don't want to compare contents of files and only check which one are not present in both of the directories, you can compare lists of files, generated by another command.

diff <(find DIR1 -printf '%P\n' | sort) <(find DIR2 -printf '%P\n' | sort) | grep '^[<>]'

-printf '%P\n' tells find to not prefix output paths with the root directory.

I've also added sort to make sure the order of files will be the same in both calls of find.

The grep at the end removes information about identical input lines.

This Handler class should be static or leaks might occur: IncomingHandler

I am not sure but you can try intialising handler to null in onDestroy()

How do I concatenate two lists in Python?

You can use the + operator to combine them:

listone = [1,2,3]
listtwo = [4,5,6]

joinedlist = listone + listtwo

Output:

>>> joinedlist
[1,2,3,4,5,6]

How can moment.js be imported with typescript?

Not sure when this changed, but with the latest version of typescript, you just need to use import moment from 'moment'; and everything else should work as normal.

UPDATE:

Looks like moment recent fixed their import. As of at least 2.24.0 you'll want to use import * as moment from 'moment';

Java: How to convert String[] to List or Set

java.util.Arrays.asList(new String[]{"a", "b"})

don't fail jenkins build if execute shell fails

I was able to get this working using the answer found here:

How to git commit nothing without an error?

git diff --quiet --exit-code --cached || git commit -m 'bla'

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

you have to be aware that when using interface builder and creating a Xib (nib) containing one cell that there is also a placeholder created that points to the class that will be used. Meaning, when you place two UITableViewCell in one Xib file you possibly run into the exact same trouble causing an *** Assertion failure .... The placeholder mechanism doesn't work adn will be confused then. Instead placing different placeholders in one Xib read on..

The most easy solution (even if that seems a bit to simple) is to place one Cell at a time in one Xib. IB will create a placeholder for you and all works as expected then. But this then leads directly to one extra line of code, because then you need to load the correct nib/xib asking for the reuseIdentified Cell where it resides in. So the following example code focuses the use of multiple Cell Indentifiers in one tableview where an Assertion Failure is very common.

// possibly above class implementation
static NSString *firstCellIdentifier = @"firstCellIdentifier";
static NSString *secondCellIdentifier = @"secondCellIdentifier";

// possibly in -(instancetype)init 
UINib *firstNib = [UINib nibWithNibName:@"FirstCell" bundle:nil];
[self.tableView registerNib:firstNib forCellReuseIdentifier:firstCellIdentifier];
UINib *secondNib = [UINib nibWithNibName:@"SecondCell" bundle:nil];
[self.tableView registerNib:secondNib forCellReuseIdentifier:secondCellIdentifier];

Another trouble with the use of two CellIdentifier's in one UITableView is that row height and/or section height have to be taken care of. Two cells can have different heights of course.

When registering classes for reuse the code should look different.

The "simple solution" looks also much different when your cells reside inside a Storyboard instead of Xib's. Watch out for the placeholders.

Keep also in mind that interface builder files have version wise variations and need to be set to a version that your targeted OS version supports. Even if you may be lucky that the particular feature you placed in your Xib is not changed since the last IB version and does not throw errors yet. So a Xib made with IB set to be compatible to iOS 13+ but used in a target that is compiled on an earlier version iOS 12.4 will cause also trouble and can end up with Assertion failure.

How to copy a huge table data into another table in SQL Server

Simple Insert/Select sp's work great until the row count exceeds 1 mil. I've watched tempdb file explode trying to insert/select 20 mil + rows. The simplest solution is SSIS setting the batch row size buffer to 5000 and commit size buffer to 1000.

How do I compare two columns for equality in SQL Server?

What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.

CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult

should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.

How update the _id of one MongoDB Document?

In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):

db.someCollection.find().snapshot().forEach(function(doc) { 
   if (doc._id.indexOf("2019:") != 0) {
       print("Processing: " + doc._id);
       var oldDocId = doc._id;
       doc._id = "2019:" + doc._id; 
       db.someCollection.insert(doc);
       db.someCollection.remove({_id: oldDocId});
   }
});

if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.

Automatic HTTPS connection/redirect with node.js/express

you can use "net" module to listening for HTTP & HTTPS on the same port

var https = require('https');
var http = require('http');
var fs = require('fs');

var net=require('net');
var handle=net.createServer().listen(8000)

var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(handle);

http.createServer(function(req,res){
  res.writeHead(200);
  res.end("hello world\n");
}).listen(handle)

How do I put a variable inside a string?

plot.savefig('hanning(%d).pdf' % num)

The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

How to make multiple divs display in one line but still retain width?

You can float your column divs using float: left; and give them widths.

And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.

Hope this helps.

Copy file(s) from one project to another using post build event...VS2010

xcopy "$(TargetDir)*$(TargetExt)" "$(SolutionDir)\Scripts\MigrationScripts\Library\" /F /R /Y /I

/F – Displays full source & target file names

/R – This will overwrite read-only files

/Y – Suppresses prompting to overwrite an existing file(s)

/I – Assumes that destination is directory (but must ends with )

A little trick – in target you must end with character \ to tell xcopy that target is directory and not file!

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

Why is textarea filled with mysterious white spaces?

I know its late but may help others.

use this in when document indentation is required.

$('document').ready(function()
{
    $('textarea').each(function(){
            $(this).val($(this).val().trim());
        }
    );
});

same question

Call Activity method from adapter

Original:

I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter(RecyclerView.Adapter) and an Activity.

In your Activity:

This will implement the interface that we have in our Adapter. In this example, it will be called when the user clicks on an item in the RecyclerView.

public class MyActivity extends Activity implements AdapterCallback {

    private MyAdapter myAdapter;

    @Override
    public void onMethodCallback() {
       // do something
    }

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

        myAdapter = new MyAdapter(this);
    }
}

In your Adapter:

In the Activity, we initiated our Adapter and passed this as an argument to the constructer. This will initiate our interface for our callback method. You can see that we use our callback method for user clicks.

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private AdapterCallback adapterCallback;

    public MyAdapter(Context context) {
        try {
            adapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.", e);
        }
    }

    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
        // simple example, call interface here
        // not complete
        viewHolder.itemView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    adapterCallback.onMethodCallback();
                } catch (ClassCastException e) {
                   // do something
                }
            }
        });
    }

    public static interface AdapterCallback {
        void onMethodCallback();
    }
}

Options for initializing a string array

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

How to extract base URL from a string in JavaScript?

A lightway but complete approach to getting basic values from a string representation of an URL is Douglas Crockford's regexp rule:

var yourUrl = "http://www.sitename.com/article/2009/09/14/this-is-an-article/";
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var parts = parse_url.exec( yourUrl );
var result = parts[1]+':'+parts[2]+parts[3]+'/' ;

If you are looking for a more powerful URL manipulation toolkit try URI.js It supports getters, setter, url normalization etc. all with a nice chainable api.

If you are looking for a jQuery Plugin, then jquery.url.js should help you

A simpler way to do it is by using an anchor element, as @epascarello suggested. This has the disadvantage that you have to create a DOM Element. However this can be cached in a closure and reused for multiple urls:

var parseUrl = (function () {
  var a = document.createElement('a');
  return function (url) {
    a.href = url;
    return {
      host: a.host,
      hostname: a.hostname,
      pathname: a.pathname,
      port: a.port,
      protocol: a.protocol,
      search: a.search,
      hash: a.hash
    };
  }
})();

Use it like so:

paserUrl('http://google.com');

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

How to insert values in two dimensional array programmatically?

Try to code below,

String[][] shades = new String[4][3];
for(int i = 0; i < 4; i++)
{
  for(int y = 0; y < 3; y++)
  {
    shades[i][y] = value;
  }
}

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

Two HTML tables side by side, centered on the page

<style>
#outer { text-align: center; }
#inner { width:500px; text-align: left; margin: 0 auto; }
.t { float: left; width:240px; border: 1px solid black;}
#clearit { clear: both; }
</style>

How to wait for a JavaScript Promise to resolve before resuming function?

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

Get device token for push notification

If you are still not getting device token, try putting following code so to register your device for push notification.

It will also work on ios8 or more.

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000

    if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeSound];

    }
#else
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     UIRemoteNotificationTypeBadge |
     UIRemoteNotificationTypeAlert |
     UIRemoteNotificationTypeSound];

#endif

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

Get the _id of inserted document in Mongo database in NodeJS

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

What is the role of "Flatten" in Keras?

short read:

Flattening a tensor means to remove all of the dimensions except for one. This is exactly what the Flatten layer do.

long read:

If we take the original model (with the Flatten layer) created in consideration we can get the following model summary:

Layer (type)                 Output Shape              Param #   
=================================================================
D16 (Dense)                  (None, 3, 16)             48        
_________________________________________________________________
A (Activation)               (None, 3, 16)             0         
_________________________________________________________________
F (Flatten)                  (None, 48)                0         
_________________________________________________________________
D4 (Dense)                   (None, 4)                 196       
=================================================================
Total params: 244
Trainable params: 244
Non-trainable params: 0

For this summary the next image will hopefully provide little more sense on the input and output sizes for each layer.

The output shape for the Flatten layer as you can read is (None, 48). Here is the tip. You should read it (1, 48) or (2, 48) or ... or (16, 48) ... or (32, 48), ...

In fact, None on that position means any batch size. For the inputs to recall, the first dimension means the batch size and the second means the number of input features.

The role of the Flatten layer in Keras is super simple:

A flatten operation on a tensor reshapes the tensor to have the shape that is equal to the number of elements contained in tensor non including the batch dimension.

enter image description here


Note: I used the model.summary() method to provide the output shape and parameter details.

How can I pass an argument to a PowerShell script?

Let PowerShell analyze and decide the data type. It internally uses a 'Variant' for this.

And generally it does a good job...

param($x)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x
}

Or if you need to pass multiple parameters:

param($x1, $x2)
$iTunes = New-Object -ComObject iTunes.Application
if ($iTunes.playerstate -eq 1)
{
    $iTunes.PlayerPosition = $iTunes.PlayerPosition + $x1
    $iTunes.<AnyProperty>  = $x2
}

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);

Sending private messages to user

In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)

Hence, the answer is: message.author.send("Your message here.")

I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.

How to open a URL in a new Tab using JavaScript or jQuery?

if you mean to opening all links on new tab, try to use this jquery

$(document).on('click', 'a', function(e){ 
    e.preventDefault(); 
    var url = $(this).attr('href'); 
    window.open(url, '_blank');
});

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

your nested for loop

 for(int j = 0; j < array2.size(); i++){

is infinite as j will always equal to zero, on the other hand, i will be increased at will in this loop. You get OutOfBoundaryException when i is larger than plusArray.size()

How to declare a variable in SQL Server and use it in the same Stored Procedure

None of the above methods worked for me so i'm posting the way i did

DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN 

DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID  int;
SELECT BrandID = BrandID FROM tblBrand 
WHERE BrandName = BrandName;

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (CategoryID, BrandID);
END$$

Count number of days between two dates

to get the number of days in a time range (just a count of all days)

(start_date..end_date).count
(start_date..end_date).to_a.size
#=> 32

to get the number of days between 2 dates

(start_date...end_date).count
(start_date...end_date).to_a.size
#=> 31

Chrome Dev Tools - Modify javascript and reload

I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler

(pretty sure some of the web devs already know about this tool)

  1. Save the file locally
  2. Edit as required
  3. Profit!

enter image description here

Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder

PS. I would rather have it implemented in Chrome as a flag preserve after reload, cannot do this now, forums and discussion groups blocked on corporate network :)

MySQL Select Query - Get only first 10 characters of a value

Using the below line

SELECT LEFT(subject , 10) FROM tbl 

MySQL Doc.

How to parse JSON response from Alamofire API in Swift?

 pod 'Alamofire'
 pod 'SwiftyJSON'
 pod 'ReachabilitySwift'



import UIKit
import Alamofire
import SwiftyJSON
import SystemConfiguration

class WebServiceHelper: NSObject {

    typealias SuccessHandler = (JSON) -> Void
    typealias FailureHandler = (Error) -> Void

    // MARK: - Internet Connectivity

    class func isConnectedToNetwork() -> Bool {

        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
                SCNetworkReachabilityCreateWithAddress(nil, $0)
            }
        }) else {
            return false
        }

        var flags: SCNetworkReachabilityFlags = []
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
            return false
        }

        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)

        return (isReachable && !needsConnection)
    }

    // MARK: - Helper Methods

    class func getWebServiceCall(_ strURL : String, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)
    {
        if isConnectedToNetwork() {

            print(strURL)

            if isShowLoader == true {

                AppDelegate.getDelegate().showLoader()
            }

            Alamofire.request(strURL).responseJSON { (resObj) -> Void in

                print(resObj)

                if resObj.result.isSuccess {
                    let resJson = JSON(resObj.result.value!)

                    if isShowLoader == true {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    debugPrint(resJson)
                    success(resJson)
                }
                if resObj.result.isFailure {
                    let error : Error = resObj.result.error!

                    if isShowLoader == true {
                        AppDelegate.getDelegate().dismissLoader()
                    }
                    debugPrint(error)
                    failure(error)
                }
            }
        }else {


            CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
        }
    }

    class func getWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler,  failure :@escaping FailureHandler){
        if isConnectedToNetwork() {

            if isShowLoader == true {
                AppDelegate.getDelegate().showLoader()
            }


            Alamofire.request(strURL, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in

                print(resObj)

                if resObj.result.isSuccess {
                    let resJson = JSON(resObj.result.value!)

                    if isShowLoader == true {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    success(resJson)
                }
                if resObj.result.isFailure {
                    let error : Error = resObj.result.error!

                    if isShowLoader == true {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    failure(error)
                }

            })
        }
    else {

            CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
    }

    }



    class func postWebServiceCall(_ strURL : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure :@escaping FailureHandler)
    {
        if isConnectedToNetwork()
        {

            if isShowLoader == true
            {
                AppDelegate.getDelegate().showLoader()
            }

            Alamofire.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: {(resObj) -> Void in

                print(resObj)

                if resObj.result.isSuccess
                {
                    let resJson = JSON(resObj.result.value!)

                    if isShowLoader == true
                    {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    success(resJson)
                }

                if resObj.result.isFailure
                {
                    let error : Error = resObj.result.error!

                    if isShowLoader == true
                    {
                        AppDelegate.getDelegate().dismissLoader()
                    }

                    failure(error)
                }
            })
        }else {
            CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
        }
    }


    class func postWebServiceCallWithImage(_ strURL : String, image : UIImage!, strImageParam : String, params : [String : AnyObject]?, isShowLoader : Bool, success : @escaping SuccessHandler, failure : @escaping FailureHandler)
    {
        if isConnectedToNetwork() {
            if isShowLoader == true
            {
                AppDelegate.getDelegate().showLoader()
            }

            Alamofire.upload(
                multipartFormData: { multipartFormData in
                    if let imageData = UIImageJPEGRepresentation(image, 0.5) {
                        multipartFormData.append(imageData, withName: "Image.jpg")
                    }

                    for (key, value) in params! {

                        let data = value as! String

                        multipartFormData.append(data.data(using: String.Encoding.utf8)!, withName: key)
                        print(multipartFormData)
                    }
                },
                to: strURL,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        upload.responseJSON { response in
                            debugPrint(response)
                            //let datastring = String(data: response, encoding: String.Encoding.utf8)
                           // print(datastring)
                        }
                    case .failure(let encodingError):
                        print(encodingError)
                        if isShowLoader == true
                        {
                            AppDelegate.getDelegate().dismissLoader()
                        }

                        let error : NSError = encodingError as NSError
                        failure(error)
                    }

                    switch encodingResult {
                    case .success(let upload, _, _):
                        upload.responseJSON { (response) -> Void in

                            if response.result.isSuccess
                            {
                                let resJson = JSON(response.result.value!)

                                if isShowLoader == true
                                {
                                    AppDelegate.getDelegate().dismissLoader()
                                }

                                success(resJson)
                            }

                            if response.result.isFailure
                            {
                                let error : Error = response.result.error! as Error

                                if isShowLoader == true
                                {
                                    AppDelegate.getDelegate().dismissLoader()
                                }

                                failure(error)
                            }

                        }
                    case .failure(let encodingError):
                        if isShowLoader == true
                        {
                            AppDelegate.getDelegate().dismissLoader()
                        }

                        let error : NSError = encodingError as NSError
                        failure(error)
                    }
                }
            )
        }
        else
        {
            CommonMethods.showAlertWithError("", strMessage: Messages.NO_NETWORK, withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
        }
    }

}


==================================


Call Method


let aParams : [String : String] = [
                "ReqCode" : Constants.kRequestCodeLogin,
                ]

            WebServiceHelper.postWebServiceCall(Constants.BaseURL, params: aParams as [String : AnyObject]?, isShowLoader: true, success: { (responceObj) in


                if "\(responceObj["RespCode"])" != "1"
                {
                    let alert = UIAlertController(title: Constants.kAppName, message: "\(responceObj["RespMsg"])", preferredStyle: UIAlertControllerStyle.alert)
                    let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
                    }
                    alert.addAction(OKAction)
                    self.present(alert, animated: true, completion: nil)
                }
                else
                {
                    let aParams : [String : String] = [
                        "Password" : self.dictAddLogin[AddLoginConstants.kPassword]!,
                        ]
                    CommonMethods.saveCustomObject(aParams as AnyObject?, key: Constants.kLoginData)

                }
                }, failure:
                { (error) in

                    CommonMethods.showAlertWithError(Constants.kALERT_TITLE_Error, strMessage: error.localizedDescription,withTarget: (AppDelegate.getDelegate().window!.rootViewController)!)
            })
        }

Maven error :Perhaps you are running on a JRE rather than a JDK?

Problem statement = No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Solution

Please set the Environment variable like below to solve the issue

Variable name : JAVA_HOME

Variable Value : C:\Program Files\Java\jdk1.8.0_202

Variable name : M2_HOME

Variable Value : C:\Program Files\apache-maven-3.6.0

Moreover, Add Java and maven path in "System Variables" like below:

  1. C:\Program Files\Java\jdk1.8.0_202\bin
  2. C:\Program Files\apache-maven-3.6.0\bin

Github permission denied: ssh add agent has no identities

For my mac Big Sur, with gist from answers above, following steps work for me.

$ ssh-keygen -q -t rsa -N 'password' -f ~/.ssh/id_rsa
$ ssh-add ~/.ssh/id_rsa

And added ssh public key to git hub by following instruction;

https://docs.github.com/en/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account

If all gone well, you should be able to get the following result;

$ ssh -T [email protected]
Hi user_name! You've successfully authenticated,...

JavaScript Promises - reject vs. throw

The difference is ternary operator

  • You can use
return condition ? someData : Promise.reject(new Error('not OK'))
  • You can't use
return condition ? someData  : throw new Error('not OK')

How to round an image with Glide library?

implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'


RequestOptions options=new RequestOptions();
        options.centerCrop().placeholder(getResources().getDrawable(R.drawable.user_placeholder));
        Glide.with(this)
                .load(preferenceSingleTon.getImage())
                .apply(options)
                .into(ProfileImage);

HTML entity for the middle dot

Try the HTML code: &#0149;

Which will appear as: •

Recommended website resolution (width and height)?

Whatever your target browser size, make sure to include space for browser toolbars, status bars, and scroll bars as above. Internet Explorer (IME) often has over 100px of vertical space in toolbars and status bars. Typically, if I'm shooting for 1024 x 768, I would try to create a design of around 960 - 980px wide and 600px high to be safe. That way you accomodate scrolling if necessary and some nice white space (if the design requires it). I highly recommend YUI grids for instances where you need to target specific sizes:

YUI Grid

Algorithm to return all combinations of k elements from n

short python code, yielding index positions

def yield_combos(n,k):
    # n is set size, k is combo size

    i = 0
    a = [0]*k

    while i > -1:
        for j in range(i+1, k):
            a[j] = a[j-1]+1
        i=j
        yield a
        while a[i] == i + n - k:
            i -= 1
        a[i] += 1

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Try to make pairs of numbers from the set. The first + the last; the second + the one before last. It means n-1 + 1; n-2 + 2. The result is always n. And since you are adding two numbers together, there are only (n-1)/2 pairs that can be made from (n-1) numbers.

So it is like (N-1)/2 * N.

Moving all files from one directory to another using Python

import shutil 
import os 
import logging

source = '/var/spools/asterisk/monitor' 
dest1 = '/tmp/'


files = os.listdir(source)

for f in files:
        shutil.move(source+f, dest1)

logging.basicConfig(filename='app.log', filemode='w', format='%(name)s
- %(levelname)s - %(message)s')

logging.info('directories moved')

A little bit cooked code with log feature. You can also configure this to run at some period of time using crontab.

* */1 * * * python /home/yourprogram.py > /dev/null 2>&1

runs every hour! cheers

How do I use spaces in the Command Prompt?

I just figured out that for a case where the path involves the use of white space characters, for example, when I need to access the app xyz which location is :

C:\Program Files\ab cd\xyz.exe

To run this from windows cmd prompt, you need to use

C:\"Program Files"\"ab cd"\xyz.exe

or

"C:\Program Files\ab cd\xyz.exe"

How do I determine scrollHeight?

You can also use:

$('#test').context.scrollHeight

How can I stop the browser back button using JavaScript?

Just run code snippet right away and try going back

_x000D_
_x000D_
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
_x000D_
_x000D_
_x000D_

Powershell: Get FQDN Hostname

Here is a way to determine the FQDN of a server based on the "Name" and "DistinguishedName". Works for multiple domains:

$server = Get-ADComputer serverName -Server domainName -Properties * | select Name, DistinguishedName
$domain = $server.DistinguishedName -split ","
$domain = $domain | ? {$_ -like 'DC=*'}
$domain = $domain -join "."
$domain = $domain -replace "DC="
$FQDN = $server.Name + "." + $domain

MySQL JDBC Driver 5.1.33 - Time Zone Issue

I solved putting below connection string in the URL

jdbc:mysql://localhost:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

You have to set the runtime for your web project to the Tomcat installation you are using; you can do it in the "Targeted runtimes" section of the project configuration.

In this way you will allow Eclipse to add Tomcat's Java EE Web Profile jars to the build path.

Remember that the HttpServlet class isn't in a JRE, but at least in an Enterprise Web Profile (e.g. a servlet container runtime /lib folder).

Node.js quick file server (static files over HTTP)

Below worked for me:

Create a file app.js with below contents:

// app.js

var fs = require('fs'),
    http = require('http');

http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);

Create a file index.html with below contents:

Hi

Start a command line:

cmd

Run below in cmd:

node app.js

Goto below URL, in chrome:

http://localhost:8080/index.html

That's all. Hope that helps.

Source: https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

Writing your own square root function

The first thing comes to my mind is: this is a good place to use Binary search (inspired by this great tutorials.)

To find the square root of vaule ,we are searching the number in (1..value) where the predictor is true for the first time. The predictor we are choosing is number * number - value > 0.00001.

double square_root_of(double value)
{
     assert(value >= 1);
     double lo = 1.0;
     double hi = value;

     while( hi - lo > 0.00001)
     {
          double mid = lo + (hi - lo) / 2 ;
          std::cout << lo << "," << hi << "," << mid << std::endl;
          if( mid * mid - value > 0.00001)    //this is the predictors we are using 
          {
              hi = mid;
          } else {
              lo = mid;
          }

     }

    return lo;
 }

read.csv warning 'EOF within quoted string' prevents complete reading of file

The readr package will fix this issue.

install.packages('readr')
library(readr)
readr::read_csv('yourfile.csv')

What is the <leader> in a .vimrc file?

In my system its the \ key. it's used for commands so that you can combine it with other chars.

Set color of TextView span in Android

Set your TextView´s text spannable and define a ForegroundColorSpan for your text.

TextView textView = (TextView)findViewById(R.id.mytextview01);    
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");          
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);    
textView.setText(wordtoSpan);

Trying to create a file in Android: open failed: EROFS (Read-only file system)

I have tried this with and without the WRITE_INTERNAL_STORAGE permission.

There is no WRITE_INTERNAL_STORAGE permission in Android.

How do I create this file for writing?

You don't, except perhaps on a rooted device, if your app is running with superuser privileges. You are trying to write to the root of internal storage, which apps do not have access to.

Please use the version of the FileOutputStream constructor that takes a File object. Create that File object based off of some location that you can write to, such as:

  • getFilesDir() (called on your Activity or other Context)
  • getExternalFilesDir() (called on your Activity or other Context)

The latter will require WRITE_EXTERNAL_STORAGE as a permission.

Is there an easier way than writing it to a file then reading from it again?

You can temporarily put it in a static data member.

because many people don't have SD card slots

"SD card slots" are irrelevant, by and large. 99% of Android device users will have external storage -- the exception will be 4+ year old devices where the user removed their SD card. Devices manufactured since mid-2010 have external storage as part of on-board flash, not as removable media.

QString to char* conversion

If your string contains non-ASCII characters - it's better to do it this way: s.toUtf8().data() (or s->toUtf8().data())

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

javax.websocket client simple example

Have a look at this Java EE 7 examples from Arun Gupta.

I forked it on github.

Main

/**
 * @author Arun Gupta
 */
public class Client {

    final static CountDownLatch messageLatch = new CountDownLatch(1);

    public static void main(String[] args) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            String uri = "ws://echo.websocket.org:80/";
            System.out.println("Connecting to " + uri);
            container.connectToServer(MyClientEndpoint.class, URI.create(uri));
            messageLatch.await(100, TimeUnit.SECONDS);
        } catch (DeploymentException | InterruptedException | IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

ClientEndpoint

/**
 * @author Arun Gupta
 */
@ClientEndpoint
public class MyClientEndpoint {
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to endpoint: " + session.getBasicRemote());
        try {
            String name = "Duke";
            System.out.println("Sending message to endpoint: " + name);
            session.getBasicRemote().sendText(name);
        } catch (IOException ex) {
            Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @OnMessage
    public void processMessage(String message) {
        System.out.println("Received message in client: " + message);
        Client.messageLatch.countDown();
    }

    @OnError
    public void processError(Throwable t) {
        t.printStackTrace();
    }
}

how to convert a string to an array in php

With explode function of php

$array=explode(" ",$str); 

This is a quick example for you http://codepad.org/Pbg4n76i

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

How to pass an object into a state using UI-router?

There are two parts of this problem

1) using a parameter that would not alter an url (using params property):

$stateProvider
    .state('login', {
        params: [
            'toStateName',
            'toParamsJson'
        ],
        templateUrl: 'partials/login/Login.html'
    })

2) passing an object as parameter: Well, there is no direct way how to do it now, as every parameter is converted to string (EDIT: since 0.2.13, this is no longer true - you can use objects directly), but you can workaround it by creating the string on your own

toParamsJson = JSON.stringify(toStateParams);

and in target controller deserialize the object again

originalParams = JSON.parse($stateParams.toParamsJson);

ImportError: No module named requests

On OSX, the command will depend on the flavour of python installation you have.

Python 2.x - Default

sudo pip install requests

Python 3.x

sudo pip3 install requests

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

YouTube Video Embedded via iframe Ignoring z-index?

The answers abow didnt really work for me, i had a click event on the wrapper and ie 7,8,9,10 ignored the z-index, so my fix was giving the wrapper a background-color and it all of a sudden worked. Al though it was suppose to be transparent, so i defined the wrapper with the background-color white, and then opacity 0.01, and now it works. I also have the functions above, so it could be a combination.

I dont know why it works, im just happy it does.

How to set environment variables in PyCharm?

None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:

setx YOUR_VAR "VALUE"

You can access it in your scripts using os.environ['YOUR_VAR'].

What is System, out, println in System.out.println() in Java

Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.

From the javadoc about System, here's what the doc says:

public final class System
extends Object

The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Since:
JDK1.0

Regarding System.out

public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:

     System.out.println(data)

Select all where [first letter starts with B]

You can use:

WHERE LEFT (name_field, 1) = 'B';

View tabular file such as CSV from command line

Ofri's answer gives you everything you asked for. But.. if you don't want to remember the command you can add this to your ~/.bashrc (or equivalent):

csview()
{
local file="$1"
sed "s/,/\t/g" "$file" | less -S
}

This is exactly the same as Ofri's answer except I have wrapped it in a shell function and am using the less -S option to stop the wrapping of lines (makes less behaves more like a office/oocalc).

Open a new shell (or type source ~/.bashrc in your current shell) and run the command using:

csview <filename>

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

How to locate the php.ini file (xampp)

For Windows, you can find the file in the C:\xampp\php\php.ini-Folder (Windows) or in the etc-Folder (within the xampp-Folder).

Under Linux, most distributions put lampp under /opt/lampp, so the file can be found under /opt/lampp/etc/php.ini.

It can be edited using a normal Text-Editor.

Clarification:

  • Xampp (X (for "some OS"), Apache, MySQL, Perl, PHP)
  • Lampp (Linux, Apache, MySQL, Perl, PHP)

in this context, they can be substituted for one another.

Checking if a folder exists (and creating folders) in Qt, C++

If you need an empty folder you can loop until you get an empty folder

    QString folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    while(QDir(folder).exists())
    {
         folder= QString ("%1").arg(QDateTime::currentMSecsSinceEpoch());
    }
    QDir().mkdir(folder);

This case you will get a folder name with a number .

How to run a JAR file

Eclipse Runnable JAR File

Create a Java Project – RunnableJAR

  • If any jar files are used then add them to project build path.
  • Select the class having main() while creating Runnable Jar file. enter image description here

Main Class

public class RunnableMainClass {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Name : "+args[0]);
        System.out.println(" ID  : "+args[1]);
    }
}

Run Jar file using java program (cmd) by supplying arguments and get the output and display in eclipse console.

public class RunJar { 
    static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) throws IOException {
        String jarfile = "D:\\JarLocation\\myRunnable.jar";
        String name = "Yash";
        String id = "777";

        try { // jarname arguments has to be saperated by spaces
            Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar "+jarfile+" "+name+" "+id);
                    //.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
            String line = null;
            while ((line = br.readLine()) != null){
                sb.append(line).append("\n");
            }
            System.out.println("Console OUTPUT : \n"+sb.toString());
            process.destroy();
        }catch (Exception e){
            System.err.println(e.getMessage());
        }
   }
}

In Eclipse to find Short cuts:

Help ? Help Contents ? Java development user guide ? References ? Menus and Actions

How to convert int[] to Integer[] in Java?

Simply use:

public static int[] intArrayToIntegerArray(int[] a) {
    Integer[] b = new Integer[a.length];
    for(int i = 0; i < array.length; i++){
        b[i] = a[i];
    }
    return g;
}

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is only acceptable on TIMESTAMP fields. DATETIME fields must be left either with a null default value, or no default value at all - default values must be a constant value, not the result of an expression.

relevant docs: http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

You can work around this by setting a post-insert trigger on the table to fill in a "now" value on any new records.

Rails: Check output of path helper from console

You can always check the output of path_helpers in console. Just use the helper with app

app.post_path(3)
#=> "/posts/3"

app.posts_path
#=> "/posts"

app.posts_url
#=> "http://www.example.com/posts"

How to get all selected values of a multiple select box?

You may use jquery plugin chosen .

<head>
 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
 <script>
        jQuery(document).ready(function(){
            jQuery(".chosen").data("placeholder","Select Frameworks...").chosen();
        });
 </script>
</head>

 <body> 
   <label for="Test" class="col-md-3 control label">Test</label>
      <select class="chosen" style="width:350px" multiple="true">
            <option>Choose...</option>
            <option>Java</option>                           
            <option>C++</option>
            <option>Python</option>
     </select>
 </body>

How to serialize an Object into a list of URL query parameters?

Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')

What's the difference between Perl's backticks, system, and exec?

What's the difference between Perl's backticks (`), system, and exec?

exec -> exec "command"; ,
system -> system("command"); and 
backticks -> print `command`;

exec

exec executes a command and never resumes the Perl script. It's to a script like a return statement is to a function.

If the command is not found, exec returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT, STDERR or exit status of the command. You can find documentation about it in perlfunc, because it is a function.

E.g.:

#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";

In above code, there are three print statements, but due to exec leaving the script, only the first print statement is executed. Also, the exec command output is not being assigned to any variable.

Here, only you're only getting the output of the first print statement and of executing the ls command on standard out.

system

system executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.

E.g.:

#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements. As the script is resumed after the system command, all three print statements are executed.

Also, the result of running system is assigned to data2, but the assigned value is 0 (the exit code from ls).

Here, you're getting the output of the first print statement, then that of the ls command, followed by the outputs of the final two print statements on standard out.

backticks (`)

Like system, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system, the return value is STDOUT of the command. qx// is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec, it is an operator.

E.g.:

#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";

In above code, there are three print statements and all three are being executed. The output of ls is not going to standard out directly, but assigned to the variable data2 and then printed by the final print statement.

Firefox setting to enable cross domain Ajax request

For modern browsers, you may try the following approach:

https://developer.mozilla.org/en/HTTP_access_control

In short, you need to add the following into the SERVER response header (the following allows access from foo.example):

Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000

Note that the X-PINGOTHER is the custom header that is inserted by JavaScript, and should differ from site to site.

If you want any site access your server in Ajax, use * instead.


Edit:

When I first answered the question by 2009, I actually hit the same problem, and I worked around it using the server side config.

There was no plugin on FF or Chrome by then.

However, now we do have alternatives using the browser side plugin, please check the answer of tsds

How to compare two Carbon Timestamps?

Carbon has a bunch of comparison functions with mnemonic names:

  • equalTo()
  • notEqualTo()
  • greaterThan()
  • greaterThanOrEqualTo()
  • lessThan()
  • lessThanOrEqualTo()

Usage:

 if($model->edited_at->greaterThan($model->created_at)){
     // edited at is newer than created at
 }

Valid for nesbot/carbon 1.36.2

if you are not sure what Carbon version you are on, run this

$composer show "nesbot/carbon"

documentation: https://carbon.nesbot.com/docs/#api-comparison

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

Undoing a 'git push'

you can use the command reset

git reset --soft HEAD^1

then:

git reset <files>
git commit --amend

and

git push -f

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).

Benefits

  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

I solved the problem as follows:

  1. run MySQLInstanceConfig.exe

    C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin\MySQLInstanceConfig.exe

  2. Follow to the end without changing anything.

How to hide a column (GridView) but still access its value?

<head runat="server">
<title>Accessing GridView Hidden Column value </title>
<style type="text/css">
  .hiddencol
  {
    display: none;
  }
</style>

<asp:BoundField HeaderText="Email ID" DataField="EmailId" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
</asp:BoundField>

ArrayList EmailList = new ArrayList();
foreach (GridViewRow itemrow in gvEmployeeDetails.Rows)
{
  EmailList.Add(itemrow.Cells[YourIndex].Text);
}

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

Stream.of(objects)
    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)
    .map(Client::getID)
    .forEach(System.out::println);

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

Stream.of(objects)
    .filter(Client.class::isInstance)
    .map(Client.class::cast)
    .map(Client::getID)
    .forEach(System.out::println);

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

You can't, you can NEVER restore from a higher version to a lower version of SQL Server. Your only option is to script out the database and then transfer the data via SSIS, BCP, linked server or scripting out the data

How to center-justify the last line of text in CSS?

There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.

I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.

Find the most frequent number in a NumPy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1

How to allocate aligned memory only using the standard library?

usage of memalign, Aligned-Memory-Blocks might be a good solution for the problem.

git: How to diff changed files versus previous versions after a pull?

I like to use:

git diff HEAD^

Or if I only want to diff a specific file:

git diff HEAD^ -- /foo/bar/baz.txt

PostgreSQL ERROR: canceling statement due to conflict with recovery

As stated here about hot_standby_feedback = on :

Well, the disadvantage of it is that the standby can bloat the master, which might be surprising to some people, too

And here:

With what setting of max_standby_streaming_delay? I would rather default that to -1 than default hot_standby_feedback on. That way what you do on the standby only affects the standby


So I added

max_standby_streaming_delay = -1

And no more pg_dump error for us, nor master bloat :)

For AWS RDS instance, check http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.html

varbinary to string on SQL Server

Try this

SELECT CONVERT(varchar(5000), yourvarbincolumn, 0)

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

CSS "and" and "or"

You can somehow reproduce the behavior of "OR" using & and :not.

SomeElement.SomeClass [data-statement="things are getting more complex"]  :not(:not(A):not(B))     {
    /* things aren't so complex for A or B */
}

Missing maven .m2 folder

If the default .m2 is unable to find, maybe someone changed the default path. Issue the following command to find out where is the Maven local repository,

mvn help:evaluate -Dexpression=settings.localRepository

The above command will scan for projects and run some tasks. Final outcome will be like below

enter image description here

As you can see in the picture the maven local repository is C:\Users\INOVA\.m2\repository

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

Short version :

run iptables on the host before to run it in the virtual server (I'm pretty sure this is some sort of LXC or OpenVZ container here).

Long version :

The problem is due to the fact that the ip_table module is loaded on demand. So, after a reboot, on any machine that does not have any iptables rules loaded at boot time, the ip_tables module is not loaded (no demand for the modules == the module is not loaded). Consequently, the LXC or OpenVZ containers cannot use iptables (since they share the host kernel but cannot modify which modules are loaded) until the host has somehow loaded the ip_tables module.

Google Maps API 3 - Custom marker color for default (dot) marker

I try two ways to create the custom google map marker, this run code used canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.

_x000D_
_x000D_
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
  var map = new google.maps.Map(document.getElementById('map'), {_x000D_
    zoom: 13,_x000D_
    center: {_x000D_
      lat: 59.325,_x000D_
      lng: 18.070_x000D_
    }_x000D_
  });_x000D_
  var markerOption = {_x000D_
    latitude: 59.327,_x000D_
    longitude: 18.067,_x000D_
    color: "#" + "000",_x000D_
    text: "ha"_x000D_
  };_x000D_
  marker = createMarker(markerOption);_x000D_
  marker.setMap(map);_x000D_
  marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
  var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
  marker.setOptions( {_x000D_
                icon: iconTmpObj_x000D_
            } );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
  //IE MarkerShape has problem_x000D_
  var markerObj = new google.maps.Marker({_x000D_
    icon: createSvgIcon(options.color, options.text),_x000D_
    position: {_x000D_
      lat: parseFloat(options.latitude),_x000D_
      lng: parseFloat(options.longitude)_x000D_
    },_x000D_
    draggable: false,_x000D_
    visible: true,_x000D_
    zIndex: 10,_x000D_
    shape: {_x000D_
      coords: CustomShapeCoords,_x000D_
      type: 'poly'_x000D_
    }_x000D_
  });_x000D_
_x000D_
  return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
  var div = $("<div></div>");_x000D_
_x000D_
  var svg = $(_x000D_
    '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
    '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
    '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
    '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
    '</svg>'_x000D_
  );_x000D_
  div.append(svg);_x000D_
_x000D_
  var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
  var svgHtml = div[0].innerHTML;_x000D_
_x000D_
  //todo yao gai bu dui_x000D_
  canvg(dd[0], svgHtml);_x000D_
_x000D_
  var imgSrc = dd[0].toDataURL("image/png");_x000D_
  //"scaledSize" and "optimized: false" together seems did the tricky ---IE11  &&  viewBox influent IE scaledSize_x000D_
  //var svg = '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
  //    + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
  //    + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
  //    + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
  //    + '</svg>';_x000D_
  //var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
  var iconObj = {_x000D_
    size: new google.maps.Size(32, 43),_x000D_
    url: imgSrc,_x000D_
    scaledSize: new google.maps.Size(32, 43)_x000D_
  };_x000D_
_x000D_
  return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Your Custom Marker </title>_x000D_
  <style>_x000D_
    /* Always set the map height explicitly to define the size of the div_x000D_
       * element that contains the map. */_x000D_
    #map {_x000D_
      height: 100%;_x000D_
    }_x000D_
    /* Optional: Makes the sample page fill the window. */_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="map"></div>_x000D_
    <script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reading rows from a CSV file in Python

The csv module handles csv files by row. If you want to handle it by column, pandas is a good solution.

Besides, there are 2 ways to get all (or specific) columns with pure simple Python code.

1. csv.DictReader

with open('demo.csv') as file:
    data = {}
    for row in csv.DictReader(file):
        for key, value in row.items():
            if key not in data:
                data[key] = []
            data[key].append(value)

It is easy to understand.

2. csv.reader with zip

with open('demo.csv') as file:
    data = {values[0]: values[1:] for values in zip(*csv.reader(file))}

This is not very clear, but efficient.

zip(x, y, z) transpose (x, y, z), while x, y, z are lists. *csv.reader(file) make (x, y, z) for zip, with column names.

Demo Result

The content of demo.csv:

a,b,c
1,2,3
4,5,6
7,8,9

The result of 1:

>>> print(data)
{'c': ['3', '6', '9'], 'b': ['2', '5', '8'], 'a': ['1', '4', '7']}

The result of 2:

>>> print(data)
{'c': ('3', '6', '9'), 'b': ('2', '5', '8'), 'a': ('1', '4', '7')}

How can I install a previous version of Python 3 in macOS using homebrew?

I tried all the answers above to install Python 3.4.4. The installation of python worked, but PIP would not be installed and nothing I could do to make it work. I was using Mac OSX Mojave, which cause some issues with zlib, openssl.

What not to do:

  • Try to avoid using Homebrew for previous version given by the formula Python or Python3.
  • Do not try to compile Python

Solution:

  1. Download the macOS 64-bit installer or macOS 64-bit/32-bit installer: https://www.python.org/downloads/release/python-365/
  2. In previous step, it will download Python 3.6.5, if for example, you want to download Python 3.4.4, replace in the url above python-365 by python-344
  3. Download click on the file you downloaded a GUI installer will open
  4. If you downloaded python-365, after installation, to launch this version of python, you will type in your terminal python365, same thing for pip, it will be pip365

p.s: You don't have to uninstall your other version of Python on your system.


Edit:


I found a much much much better solution that work on MacOSX, Windows, Linux, etc.

  1. It doesn't matter if you have already python installed or not.
  2. Download Anaconda
  3. Once installed, in terminal type: conda init
  4. In terminal,create virtual environment with any python version, for example, I picked 3.4.4: conda create -n [NameOfYour VirtualEnvironment] python=3.4.4
  5. Then, in terminal, you can check all the virtual environment you ahave created with the command: conda info --envs
  6. Then, in terminal, activate the virtual environment of your choice with: conda activate [The name of your virtual environment that was shown with the command at step 5]

Set selected option of select box

Addition to @icksde and @Korah (thx both!)

When building the options with AJAX the document.ready may be triggered before the list is built, so

This doesn't work

$(document).ready(function() {
    $("#gate").val('Gateway 2');
});

This does

A timeout does work but as @icksde says it's fragile (I did actually need 20ms in stead of 10ms). It's better to fit it inside the AJAX function like this:

$("#someObject").change(function() {
    $.get("website/page.php", {parameters}, function(data) {
        $("#gate").append("<option value='Gateway 2'">" + "Gateway 2" + "</option>");
        $("#gate").val('Gateway 2');
    }, "json");
});

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

jquery, find next element by class

To find the next element with the same class:

$(".class").eq( $(".class").index( $(element) ) + 1 )

Automatically start a Windows Service on install

Here is a procedure and code using generated ProjectInstaller in Visual Studio:

  1. Create Windows Service project in Visual Studio
  2. Generate installers to the service
  3. Open ProjectInstaller in design editor (it should open automatically when installer is created) and set properties of generated serviceProcessInstaller1 (e.g. Account: LocalSystem) and serviceInstaller1 (e.g. StartType: Automatic)
  4. Open ProjectInstaller in code editor (press F7 in design editor) and add event handler to ServiceInstaller.AfterInstall - see the following code. It will start the service after its installation.

ProjectInstaller class:

using System.ServiceProcess;


[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent(); //generated code including property settings from previous steps
        this.serviceInstaller1.AfterInstall += Autorun_AfterServiceInstall; //use your ServiceInstaller name if changed from serviceInstaller1
    }

    void Autorun_AfterServiceInstall(object sender, InstallEventArgs e)
    {
        ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
        using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
        {
            sc.Start();
        }
    }
}

Float and double datatype in Java

This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.

int bits = Float.floatToIntBits(-0.005f);
int sign = bits >>> 31;
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1);
int mantissa = bits & ((1 << 23) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa));

The same approach can be used for double’s (11 bit exponent and 52 bit mantissa).

long bits = Double.doubleToLongBits(-0.005);
long sign = bits >>> 63;
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1);
long mantissa = bits & ((1L << 52) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
  Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa));

Credit: http://s-j.github.io/java-float/

Can I use Objective-C blocks as properties?

For Swift, just use closures: example.


In Objective-C:

@property (copy)void

@property (copy)void (^doStuff)(void);

It's that simple.

Here is the actual Apple documentation, which states precisely what to use:

Apple doco.

In your .h file:

// Here is a block as a property:
//
// Someone passes you a block. You "hold on to it",
// while you do other stuff. Later, you use the block.
//
// The property 'doStuff' will hold the incoming block.

@property (copy)void (^doStuff)(void);

// Here's a method in your class.
// When someone CALLS this method, they PASS IN a block of code,
// which they want to be performed after the method is finished.

-(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater;

// We will hold on to that block of code in "doStuff".

Here's your .m file:

 -(void)doSomethingAndThenDoThis:(void(^)(void))pleaseDoMeLater
    {
    // Regarding the incoming block of code, save it for later:
    self.doStuff = pleaseDoMeLater;

    // Now do other processing, which could follow various paths,
    // involve delays, and so on. Then after everything:
    [self _alldone];
    }

-(void)_alldone
    {
    NSLog(@"Processing finished, running the completion block.");
    // Here's how to run the block:
    if ( self.doStuff != nil )
       self.doStuff();
    }

Beware of out-of-date example code.

With modern (2014+) systems, do what is shown here. It is that simple.

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

How to create user for a db in postgresql?

Create the user with a password :

http://www.postgresql.org/docs/current/static/sql-createuser.html

CREATE USER name [ [ WITH ] option [ ... ] ]

where option can be:

      SUPERUSER | NOSUPERUSER
    | CREATEDB | NOCREATEDB
    | CREATEROLE | NOCREATEROLE
    | CREATEUSER | NOCREATEUSER
    | INHERIT | NOINHERIT
    | LOGIN | NOLOGIN
    | REPLICATION | NOREPLICATION
    | CONNECTION LIMIT connlimit
    | [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
    | VALID UNTIL 'timestamp'
    | IN ROLE role_name [, ...]
    | IN GROUP role_name [, ...]
    | ROLE role_name [, ...]
    | ADMIN role_name [, ...]
    | USER role_name [, ...]
    | SYSID uid

Then grant the user rights on a specific database :

http://www.postgresql.org/docs/current/static/sql-grant.html

Example :

grant all privileges on database db_name to someuser;

How to format a Java string with leading zero?

It isn't pretty, but it works. If you have access apache commons i would suggest that use that

if (val.length() < 8) {
  for (int i = 0; i < val - 8; i++) {
    val = "0" + val;
  }
}

Search for string within text column in MySQL

Using like might take longer time so use full_text_search:

SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')

Multiple submit buttons in the same form calling different Servlets

In addition to the previous response, the best option to submit a form with different buttons without language problems is actually using a button tag.

<form>
    ...
    <button type="submit" name="submit" value="servlet1">Go to 1st Servlet</button>
    <button type="submit" name="submit" value="servlet2">Go to 2nd Servlet</button>
</form>

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Just add this

buildscript {
    repositories {
        ...
        google() 
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0' 
    }
}

It works...Cheers!!!

Extracting jar to specified directory

This is what I ended up using inside my .bat file. Windows only of course.

set CURRENT_DIR=%cd%
mkdir ./directoryToExtractTo
cd ./directoryToExtractTo
jar xvf %CURRENT_DIR%\myJar.jar
cd %CURRENT_DIR%

How to create Toast in Flutter?

For android original graphics toast you can use this: https://pub.dartlang.org/packages/fluttertoast

Works fine on Android and iOS. enter image description here

How to automatically reload a page after a given period of inactivity

<script type="text/javascript">
  var timeout = setTimeout("location.reload(true);",600000);
  function resetTimeout() {
    clearTimeout(timeout);
    timeout = setTimeout("location.reload(true);",600000);
  }
</script>

Above will refresh the page every 10 minutes unless resetTimeout() is called. For example:

<a href="javascript:;" onclick="resetTimeout();">clicky</a>

Socket.IO - how do I get a list of connected sockets/clients?

I've gone through this pain today. Socket.io will be much better if they could make a proper documentation for their API.

Anyway, I tried to look into io.sockets and found a number of options we can use:

io.sockets.connected //Return {socket_1_id: {}, socket_2_id: {}} . This is the most convenient one, since you can just refer to io.sockets.connected[id] then do common things like emit()
io.sockets.sockets //Returns [{socket_1}, {socket_2}, ....]. Can refer to socket_i.id to distinguish
io.sockets.adapter.sids //Return {socket_1_id: {}, socket_2_id: {}} . Looks similar to the first one but the object is not actually the socket, just the information.

// Not directly helps but still relevant
io.sockets.adapter.rooms //Returns {room_1_id: {}, room_2_id: {}}
io.sockets.server.eio.clients //Return client sockets
io.sockets.server.eio.clientsCount //Return number of connected clients

Also, do note that when using socket.io with namespace, the above methods will break since io.sockets becomes an array instead of an object. To resolve, just replace io.sockets by io (i.e io.sockets.connected becomes io.connected, io.sockets.adapter.rooms becomes io.adapter.rooms ...)

Tested on socket.io 1.3.5

iOS for VirtualBox

Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator

PHP filesize MB/KB conversion

All the answers to the question uses that 1 kilobyte = 1024 bytes which is wrong! (1 kibibyte = 1024 bytes)

since the question asks to convert file sizes, it should use that 1 kilobyte = 1000 bytes (see https://wiki.ubuntu.com/UnitsPolicy)

function format_bytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB');

    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1000));
    $pow = min($pow, count($units) - 1);

    $bytes /= pow(1000, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
}

Fatal error: Call to undefined function pg_connect()

The solution has to do with the fact that your the file holding your php configurations. i.e php.ini has uncommented the extension responsible for acting as the middleman between php and postgres, by placing a ";" in front of the statement "extension=pdo_pgsql"

Quick Fix

  1. Open the php.ini file in your favourite editor. (atom )
  2. Search for the line "extension=pdo_pgsql", which is under the "Dynamic Extensions" section. (a simple ctrl + f) would get you there quick.
  3. Remove the ";" in front of the line ";extension=pdo_pgsql".
  4. Restart your server.
  5. Go fix more errors like a rock star.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.

   <style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="toolbarStyle">@style/MyToolBarStyle</item>
    </style>
    <style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
        <item name="android:background">#80deea</item>
        <item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
        <item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
    </style>
    <style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">35dp</item>
        <item name="android:textColor">#ff3d00</item>
    </style>
    <style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
        <item name="android:textSize">30dp</item>
        <item name="android:textColor">#1976d2</item>
    </style>

Calling async method synchronously

You should be able to get this done using delegates, lambda expression

private void button2_Click(object sender, EventArgs e)
    {

        label1.Text = "waiting....";

        Task<string> sCode = Task.Run(async () =>
        {
            string msg =await GenerateCodeAsync();
            return msg;
        });

        label1.Text += sCode.Result;

    }

    private Task<string> GenerateCodeAsync()
    {
        return Task.Run<string>(() => GenerateCode());
    }

    private string GenerateCode()
    {
        Thread.Sleep(2000);
        return "I m back" ;
    }

IO Error: The Network Adapter could not establish the connection

I figured out that in my case, my database was in different subnet than the subnet from where i was trying to access the db.

PHP how to get local IP of system

$_SERVER['SERVER_NAME']

It worked for me.

Is there a reason for C#'s reuse of the variable in a foreach?

Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:

foreach (var s in strings)
    query = query.Where(i => i.Prop == s); // access to modified closure

I do:

foreach (var s in strings)
{
    string search = s;
    query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}        

Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

Can be triggered by a stray comma (,) in an RxJS pipe(...)

The compile won't catch this extra comma at the end:

pipe(first(), map(result => ({ event: 'completed', result: result}),);

It becomes an 'invisible' undefined operator which screws the whole pipe up, and leads to a very confusing error message - which in this case has nothing to do with my actual logic.

Vertically centering a div inside another div

This works for me. Width and hight of the outer div can be defined.

Here the code:

_x000D_
_x000D_
.outer {_x000D_
  position: relative;_x000D_
  text-align: center;_x000D_
  width: 100%;_x000D_
  height: 150px; // Any height is allowed, also in %._x000D_
  background: gray;_x000D_
}_x000D_
_x000D_
.outer > div:first-child {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 100%;_x000D_
  -webkit-transform: translate(-50%, -50%);_x000D_
  -ms-transform: translate(-50%, -50%);_x000D_
  transform: translate(-50%, -50%);_x000D_
  background: red;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    Put here your text or div content!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Disable form auto submit on button click

another one:

if(this.checkValidity() == false) {

                $(this).addClass('was-validated');
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();

                return false;
}

How to find the index of an element in an int array?

Integer[] array = {1, 2, 3, 4, 5, 6};

for (int i = 0; i < array.length; i++) {
    if (array[i] == 4) {
        system.out.println(i);
        break;
    }
}

How to stop a thread created by implementing runnable interface?

Thread.currentThread().isInterrupted() is superbly working. but this code is only pause the timer.

This code is stop and reset the thread timer. h1 is handler name. This code is add on inside your button click listener. w_h =minutes w_m =milli sec i=counter

 i=0;
            w_h = 0;
            w_m = 0;


            textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
                        hl.removeCallbacksAndMessages(null);
                        Thread.currentThread().isInterrupted();


                        }


                    });


                }`

Property [title] does not exist on this collection instance

$about->first()->id or $stm->first()->title and your problem is sorted out.

Interface extends another interface but implements its methods

ad 1. It does not implement its methods.

ad 4. The purpose of one interface extending, not implementing another, is to build a more specific interface. For example, SortedMap is an interface that extends Map. A client not interested in the sorting aspect can code against Map and handle all the instances of for example TreeMap, which implements SortedMap. At the same time, another client interested in the sorted aspect can use those same instances through the SortedMap interface.

In your example you are repeating the methods from the superinterface. While legal, it's unnecessary and doesn't change anything in the end result. The compiled code will be exactly the same whether these methods are there or not. Whatever Eclipse's hover says is irrelevant to the basic truth that an interface does not implement anything.

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

python: create list of tuples from lists

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

Custom date format with jQuery validation plugin

$.validator.addMethod("mydate", function (value, element) {

        return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);

    });

you can input like yyyy-mm-dd also yyyy/mm/dd

but can't judge the the size of the month sometime Feb just 28 or 29 days.

Remove Null Value from String array in java

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
  public static void main( String args[] ) {
    String[] firstArray = {"test1", "", "test2", "test4", "", null};

    List<String> list = new ArrayList<String>();

    for(String s : firstArray) {
       if(s != null && s.length() > 0) {
          list.add(s);
       }
    }

    firstArray = list.toArray(new String[list.size()]);
  }
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
    public static void main( String args[] ) {
        String[] firstArray = {"test1", "", "test2", "test4", "", null};

        firstArray = Arrays.stream(firstArray)
                     .filter(s -> (s != null && s.length() > 0))
                     .toArray(String[]::new);    

    }
}

where does MySQL store database files?

For WampServer, click on its tray icon and then in the popup cascading menu select

MySQL | MySQL settings | datadir

MySQL Data Directory

Get the records of last month in SQL server

DECLARE @curDate INT = datepart( Month,GETDATE())
IF (@curDate = 1)
    BEGIN
        select * from Featured_Deal
        where datepart( Month,Created_Date)=12 AND datepart(Year,Created_Date) = (datepart(Year,GETDATE())-1)

    END
ELSE
    BEGIN
        select * from Featured_Deal
        where datepart( Month,Created_Date)=(datepart( Month,GETDATE())-1) AND datepart(Year,Created_Date) = datepart(Year,GETDATE())

    END 

Which UUID version to use?

That's a very general question. One answer is: "it depends what kind of UUID you wish to generate". But a better one is this: "Well, before I answer, can you tell us why you need to code up your own UUID generation algorithm instead of calling the UUID generation functionality that most modern operating systems provide?"

Doing that is easier and safer, and since you probably don't need to generate your own, why bother coding up an implementation? In that case, the answer becomes use whatever your O/S, programming language or framework provides. For example, in Windows, there is CoCreateGuid or UuidCreate or one of the various wrappers available from the numerous frameworks in use. In Linux there is uuid_generate.

If you, for some reason, absolutely need to generate your own, then at least have the good sense to stay away from generating v1 and v2 UUIDs. It's tricky to get those right. Stick, instead, to v3, v4 or v5 UUIDs.

Update: In a comment, you mention that you are using Python and link to this. Looking through the interface provided, the easiest option for you would be to generate a v4 UUID (that is, one created from random data) by calling uuid.uuid4().

If you have some data that you need to (or can) hash to generate a UUID from, then you can use either v3 (which relies on MD5) or v5 (which relies on SHA1). Generating a v3 or v5 UUID is simple: first pick the UUID type you want to generate (you should probably choose v5) and then pick the appropriate namespace and call the function with the data you want to use to generate the UUID from. For example, if you are hashing a URL you would use NAMESPACE_URL:

uuid.uuid3(uuid.NAMESPACE_URL, 'https://ripple.com')

Please note that this UUID will be different than the v5 UUID for the same URL, which is generated like this:

uuid.uuid5(uuid.NAMESPACE_URL, 'https://ripple.com')

A nice property of v3 and v5 URLs is that they should be interoperable between implementations. In other words, if two different systems are using an implementation that complies with RFC4122, they will (or at least should) both generate the same UUID if all other things are equal (i.e. generating the same version UUID, with the same namespace and the same data). This property can be very helpful in some situations (especially in content-addressible storage scenarios), but perhaps not in your particular case.

set environment variable in python script

Compact solution (provided you don't need other environment variables):

call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
      env=dict(LD_LIBRARY_PATH=my_path))

Using the env command line tool:

call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())

How can I select an element with multiple classes in jQuery?

The problem you're having, is that you are using a Group Selector, whereas you should be using a Multiples selector! To be more specific, you're using $('.a, .b') whereas you should be using $('.a.b').

For more information, see the overview of the different ways to combine selectors herebelow!


Group Selector : ","

Select all <h1> elements AND all <p> elements AND all <a> elements :

$('h1, p, a')

Multiples selector : "" (no character)

Select all <input> elements of type text, with classes code and red :

$('input[type="text"].code.red')

Descendant Selector : " " (space)

Select all <i> elements inside <p> elements:

$('p i')

Child Selector : ">"

Select all <ul> elements that are immediate children of a <li> element:

$('li > ul')

Adjacent Sibling Selector : "+"

Select all <a> elements that are placed immediately after <h2> elements:

$('h2 + a')

General Sibling Selector : "~"

Select all <span> elements that are siblings of <div> elements:

$('div ~ span')

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

For following Error:

ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.

Run following NPM command:

$ npm install [email protected]

Source Link

Calculate date from week number

I improved a little on Thomas' solution with an override:

   public static DateTime FirstDateOfWeek(int year, int weekOfYear)
    {
      return Timer.FirstDateOfWeekOfMonth(year, 1, weekOfYear);
    }

    public static DateTime FirstDateOfWeekOfMonth(int year, int month, 
    int weekOfYear)
    {
      DateTime dtFirstDayOfMonth = new DateTime(year, month, 1);

       //I also commented out this part:
      /*
      if (firstWeek <= 1)
      {
        weekOfYear -= 1;
      }
      */

Otherwise the date was preceding by one week..

Thank you Thomas, great help.

Failed to execute 'createObjectURL' on 'URL':

If you are using ajax, it is possible to add the options xhrFields: { responseType: 'blob' }:

$.ajax({
  url: 'yourURL',
  type: 'POST',
  data: yourData,
  xhrFields: { responseType: 'blob' },
  success: function (data, textStatus, jqXHR) {
    let src = window.URL.createObjectURL(data);
  }
});

How to split data into 3 sets (train, validation and test)?

However, one approach to dividing the dataset into train, test, cv with 0.6, 0.2, 0.2 would be to use the train_test_split method twice.

from sklearn.model_selection import train_test_split

x, x_test, y, y_test = train_test_split(xtrain,labels,test_size=0.2,train_size=0.8)
x_train, x_cv, y_train, y_cv = train_test_split(x,y,test_size = 0.25,train_size =0.75)

How to use ClassLoader.getResources() correctly?

MRalwasser, I'd give you a hint, cast the URL.getConnection() to JarURLConnection. Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.

The rest I leave to you.

Hope this helps!

How do you check for permissions to write to a directory or file?

When your code does the following:

  1. Checks the current user has permission to do something.
  2. Carries out the action that needs the entitlements checked in 1.

You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.

Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.

Example (derived from Josh's example):

//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

//2. Attempt the action but handle permission changes.
try
{
    using (FileStream fstream = new FileStream(filename, FileMode.Create))
    using (TextWriter writer = new StreamWriter(fstream))
    {
        writer.WriteLine("sometext");
    }
}
catch (UnauthorizedAccessException ex)
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.