Programs & Examples On #Atomic

An atomic operation is indivisible. This term is used to describe transactions in databases, low-level accesses in multithreaded programs, and file system operations, amongst others.

What's the difference between the atomic and nonatomic attributes?

The last two are identical; "atomic" is the default behavior (note that it is not actually a keyword; it is specified only by the absence of nonatomic -- atomic was added as a keyword in recent versions of llvm/clang).

Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: @synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an _ prepended to their name to prevent accidental direct access).

With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.

In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic".

What "atomic" does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.

Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.

Adding to this:

atomicity of a single property also cannot guarantee thread safety when multiple dependent properties are in play.

Consider:

 @property(atomic, copy) NSString *firstName;
 @property(atomic, copy) NSString *lastName;
 @property(readonly, atomic, copy) NSString *fullName;

In this case, thread A could be renaming the object by calling setFirstName: and then calling setLastName:. In the meantime, thread B may call fullName in between thread A's two calls and will receive the new first name coupled with the old last name.

To address this, you need a transactional model. I.e. some other kind of synchronization and/or exclusion that allows one to exclude access to fullName while the dependent properties are being updated.

What does "atomic" mean in programming?

"Atomic operation" means an operation that appears to be instantaneous from the perspective of all other threads. You don't need to worry about a partly complete operation when the guarantee applies.

Practical uses for AtomicInteger

I used AtomicInteger to solve the Dining Philosopher's problem.

In my solution, AtomicInteger instances were used to represent the forks, there are two needed per philosopher. Each Philosopher is identified as an integer, 1 through 5. When a fork is used by a philosopher, the AtomicInteger holds the value of the philosopher, 1 through 5, otherwise the fork is not being used so the value of the AtomicInteger is -1.

The AtomicInteger then allows to check if a fork is free, value==-1, and set it to the owner of the fork if free, in one atomic operation. See code below.

AtomicInteger fork0 = neededForks[0];//neededForks is an array that holds the forks needed per Philosopher
AtomicInteger fork1 = neededForks[1];
while(true){    
    if (Hungry) {
        //if fork is free (==-1) then grab it by denoting who took it
        if (!fork0.compareAndSet(-1, p) || !fork1.compareAndSet(-1, p)) {
          //at least one fork was not succesfully grabbed, release both and try again later
            fork0.compareAndSet(p, -1);
            fork1.compareAndSet(p, -1);
            try {
                synchronized (lock) {//sleep and get notified later when a philosopher puts down one fork                    
                    lock.wait();//try again later, goes back up the loop
                }
            } catch (InterruptedException e) {}

        } else {
            //sucessfully grabbed both forks
            transition(fork_l_free_and_fork_r_free);
        }
    }
}

Because the compareAndSet method does not block, it should increase throughput, more work done. As you may know, the Dining Philosophers problem is used when controlled accessed to resources is needed, i.e. forks, are needed, like a process needs resources to continue doing work.

What exactly is std::atomic?

std::atomic exists because many ISAs have direct hardware support for it

What the C++ standard says about std::atomic has been analyzed in other answers.

So now let's see what std::atomic compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as std::mutex, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic because std::mutex it makes futex system calls in Linux, which is way slower than the userland instructions emitted by std::atomic, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

void threadMain() {
    for (size_t i = 0; i < niters; ++i) {
#if LOCK
        __asm__ __volatile__ (
            "lock incq %0;"
            : "+m" (global),
              "+g" (i) // to prevent loop unrolling
            :
            :
        );
#else
        __asm__ __volatile__ (
            ""
            : "+g" (i) // to prevent he loop from being optimized to a single add
            : "g" (global)
            :
        );
        global++;
#endif
    }
}

int main(int argc, char **argv) {
    size_t nthreads;
    if (argc > 1) {
        nthreads = std::stoull(argv[1], NULL, 0);
    } else {
        nthreads = 2;
    }
    if (argc > 2) {
        niters = std::stoull(argv[2], NULL, 0);
    } else {
        niters = 10;
    }
    std::vector<std::thread> threads(nthreads);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i] = std::thread(threadMain);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i].join();
    uint64_t expect = nthreads * niters;
    std::cout << "expect " << expect << std::endl;
    std::cout << "global " << global << std::endl;
}

GitHub upstream.

Compile, run and disassemble:

comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out       -DLOCK       $common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out

Extremely likely "wrong" race condition output for main_fail.out:

expect 400000
global 100000

and deterministic "right" output of the others:

expect 400000
global 400000

Disassembly of main_fail.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
   0x000000000000278b <+11>:    test   %rcx,%rcx
   0x000000000000278e <+14>:    je     0x27b4 <threadMain()+52>
   0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
   0x0000000000002797 <+23>:    xor    %eax,%eax
   0x0000000000002799 <+25>:    nopl   0x0(%rax)
   0x00000000000027a0 <+32>:    add    $0x1,%rax
   0x00000000000027a4 <+36>:    add    $0x1,%rdx
   0x00000000000027a8 <+40>:    cmp    %rcx,%rax
   0x00000000000027ab <+43>:    jb     0x27a0 <threadMain()+32>
   0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
   0x00000000000027b4 <+52>:    retq

Disassembly of main_std_atomic.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a6 <threadMain()+38>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock addq $0x1,0x299f(%rip)        # 0x5138 <global>
   0x0000000000002799 <+25>:    add    $0x1,%rax
   0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
   0x00000000000027a4 <+36>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a6 <+38>:    retq   

Disassembly of main_lock.out:

Dump of assembler code for function threadMain():
   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a5 <threadMain()+37>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
   0x0000000000002798 <+24>:    add    $0x1,%rax
   0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
   0x00000000000027a3 <+35>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a5 <+37>:    retq

Conclusions:

  • the non-atomic version saves the global to a register, and increments the register.

    Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000.

  • std::atomic compiles to lock addq. The LOCK prefix makes the following inc fetch, modify and update memory atomically.

  • our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic, except that our inc is used instead of add. Not sure why GCC chose add, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

What is the difference between atomic / volatile / synchronized?

I know that two threads can not enter in Synchronize block at the same time

Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.

private Integer i = 0;

synchronized(i) {
   i++;
}

This will not behave as expected as it could be locking on a different object each time.

if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??

yes. It doesn't use locking to achieve thread safety.

If you want to know how they work in more detail, you can read the code for them.

And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??

Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.

i read in some article that thread has local copy of variables what is that ??

I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.

This is only an issue when memory is shared at least one thread updates it.

How do I find the number of arguments passed to a Bash script?

that value is contained in the variable $#

Clearing a text field on button click

How about just a simple reset button?

<form>

  <input type="text" id="textfield1" size="5">
  <input type="text" id="textfield2" size="5">

  <input type="reset" value="Reset">

</form>

Xcode 10: A valid provisioning profile for this executable was not found

In my case, where nothing else helped, i did the following:

  1. change the AppID to a new one
  2. XCode automatically generated new provisioning profiles
  3. run the app on real device -> now it has worked
  4. change back the AppID to the original id
  5. works

Before this i have tried out every step that was mentioned here. But only this helped.

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

stale element reference: element is not attached to the page document

Whenever you face this issue, just define the web element once again above the line in which you are getting an Error.

Example:

WebElement button = driver.findElement(By.xpath("xpath"));
button.click();

//here you do something like update or save 

//then you try to use the button WebElement again to click 
button.click();

Since the DOM has changed e.g. through the update action, you are receiving a StaleElementReference Error.

Solution:

WebElement button = driver.findElement(By.xpath("xpath"));
button.click();

//here you do something like update or save 

//then you define the button element again before you use it
WebElement button1 = driver.findElement(By.xpath("xpath"));
//that new element will point to the same element in the new DOM
button1.click();

How does the bitwise complement operator (~ tilde) work?

Basically action is a complement not a negation .

Here x= ~x produce results -(x+1) always .

x = ~2

-(2+1)

-3

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Set -XX:PermSize=64m -XX:MaxPermSize=128m. Later on you may also try increasing MaxPermSize. Hope it'll work. The same works for me. Setting only MaxPermSize didn't worked for me.

How to run vbs as administrator from vbs?

If UAC is enabled on the computer, something like this should work:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

'actual code

Convert a list to a dictionary in Python

b = dict(zip(a[::2], a[1::2]))

If a is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.

from itertools import izip
i = iter(a)
b = dict(izip(i, i))

In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range() and len(), which would normally be a code smell.

b = {a[i]: a[i+1] for i in range(0, len(a), 2)}

So the iter()/izip() method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip() is already lazy in Python 3 so you don't need izip().

i = iter(a)
b = dict(zip(i, i))

If you want it on one line, you'll have to cheat and use a semicolon. ;-)

How to get the max of two values in MySQL?

You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).

select 
    if(
        fieldA is NULL, 
        if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
        if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
    ) as maxValue

You can change NULL to your preferred default value (if both values is NULL).

Basic authentication for REST API using spring restTemplate

(maybe) the easiest way without importing spring-boot.

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

Are strongly-typed functions as parameters possible in TypeScript?

If you define function type first then it would be looked like

type Callback = (n: number) => void;

class Foo {
    save(callback: Callback) : void {        
        callback(42);
    }
}

var foo = new Foo();
var stringCallback = (result: string) : void => {
    console.log(result);
}

var numberCallback = (result: number) : void => {
    console.log(result);
}

foo.save(stringCallback); //--will be showing error
foo.save(numberCallback);

Without function type by using plain property syntax it would be:

class Foo {
    save(callback: (n: number) => void) : void {        
        callback(42);
    }
}

var foo = new Foo();
var stringCallback = (result: string) : void => {
    console.log(result);
}

var numberCallback = (result: number) : void => {
    console.log(result);
}

foo.save(stringCallback); //--will be showing error
foo.save(numberCallback);

If you want by using an interface function like c# generic delegates it would be:

interface CallBackFunc<T, U>
{
    (input:T): U;
};

class Foo {
    save(callback: CallBackFunc<number,void>) : void {        
        callback(42);
    }
}

var foo = new Foo();
var stringCallback = (result: string) : void => {
    console.log(result);
}

var numberCallback = (result: number) : void => {
    console.log(result);
}

let strCBObj:CallBackFunc<string,void> = stringCallback;
let numberCBObj:CallBackFunc<number,void> = numberCallback;

foo.save(strCBObj); //--will be showing error
foo.save(numberCBObj);

C# ListView Column Width Auto

This solution will first resize the columns based on column data, if the resized width is smaller than header size, it will resize columns to at least fit the header. This is a pretty ugly solution, but it works.

lstContacts.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
colFirstName.Width = (colFirstName.Width < 60 ? 60 : colFirstName.Width);
colLastName.Width = (colLastName.Width < 61 ? 61 : colLastName.Width);
colPhoneNumber.Width = (colPhoneNumber.Width < 81 ? 81 : colPhoneNumber.Width);
colEmail.Width = (colEmail.Width < 40 ? 40 : colEmail.Width);

lstContacts is the ListView. colFirstName is a column, where 60 is the width required to fit the title. Etc.

jQuery .search() to any string

search() is a String method.

You are executing the attr function on every <li> element. You need to invoke each and use the this reference within.

Example:

$('li').each(function() {
    var isFound = $(this).attr('title').search(/string/i);
    //do something based on isFound...
});

How can I load storyboard programmatically from class?

In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

No generated R.java file in my project

now you have imported android.R instead of your own R... Try to take a look on your "problems" view if you have errors in one of your xml files... get rid of the import android.R and comment out all usages of R.*

Cleaning should help when your project has no other errors, so check your xml files or file naming in your res folders

How to compile LEX/YACC files on Windows?

Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:

choco install winflexbison

...which at the time of writing contains Bison 2.7 & Flex 2.6.3.

There is also winflexbison3 which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.

spark submit add multiple jars in classpath

You can use * for import all jars into a folder when adding in conf/spark-defaults.conf .

spark.driver.extraClassPath /fullpath/*
spark.executor.extraClassPath /fullpath/*

Set specific precision of a BigDecimal

The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.

Some examples in Clojure.

(.scale     0.00123M) ; 5
(.precision 0.00123M) ; 3

(In Clojure, The M designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

But you can't decrease the scale in the exact same way:

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.

So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!

It is easy to decrease the precision:

(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M

But it is not obvious how to increase the precision:

(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)

For the skeptical, this is not just a matter of trailing zeros not being displayed:

(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6 
; (same as above, still unexpected)

FWIW, Clojure is careful with trailing zeros and will show them:

4.0000M ; 4.0000M
(.precision 4.0000M) ; 5

Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:

(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M

So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?

So, best I can tell, if you want to change precision, you'll need to do these steps:

  1. Lookup the current precision.
  2. Lookup the current scale.
  3. Calculate the scale change.
  4. Set the new scale

These steps, as Clojure code:

(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M

I know, this is a lot of steps just to change the precision!

Why doesn't BigDecimal already provide this? Did I overlook something?

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

HTML tag inside JavaScript

<div id="demo"></div>

<script type="text/javascript">
    if(document.getElementById('number1').checked) {
        var demo = document.getElementById("demo");    
        demo.innerHtml='<h1>Hello member</h1>';
    } else {
        demo.innerHtml='';
    }
</script>

How to get text from EditText?

String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);

Get current index from foreach loop

You can't, because IEnumerable doesn't have an index at all... if you are sure your enumerable has less than int.MaxValue elements (or long.MaxValue if you use a long index), you can:

  1. Don't use foreach, and use a for loop, converting your IEnumerable to a generic enumerable first:

    var genericList = list.Cast<object>();
    for(int i = 0; i < genericList.Count(); ++i)
    {
       var row = genericList.ElementAt(i);
       /* .... */
    }
    
  2. Have an external index:

    int i = 0;
    foreach(var row in list)
    {
       /* .... */
       ++i;
    }
    
  3. Get the index via Linq:

    foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i}))
    {
      var row = rowObject.Row;
      var i = rowObject.Index;
      /* .... */    
    }
    

In your case, since your IEnumerable is not a generic one, I'd rather use the foreach with external index (second method)... otherwise, you may want to make the Cast<object> outside your loop to convert it to an IEnumerable<object>.

Your datatype is not clear from the question, but I'm assuming object since it's an items source (it could be DataGridRow)... you may want to check if it's directly convertible to a generic IEnumerable<object> without having to call Cast<object>(), but I'll make no such assumptions.


All this said:

The concept of an "index" is foreign to an IEnumerable. An IEnumerable can be potentially infinite. In your example, you are using the ItemsSource of a DataGrid, so more likely your IEnumerable is just a list of objects (or DataRows), with a finite (and hopefully less than int.MaxValue) number of members, but IEnumerable can represent anything that can be enumerated (and an enumeration can potentially never end).

Take this example:

public static IEnumerable InfiniteEnumerable()
{
  var rnd = new Random();
  while(true)
  {
    yield return rnd.Next();
  }
}

So if you do:

foreach(var row in InfiniteEnumerable())
{
  /* ... */
}

Your foreach will be infinite: if you used an int (or long) index, you'll eventually overflow it (and unless you use an unchecked context, it'll throw an exception if you keep adding to it: even if you used unchecked, the index would be meaningless also... at some point -when it overflows- the index will be the same for two different values).

So, while the examples given work for a typical usage, I'd rather not use an index at all if you can avoid it.

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

How can I change the image displayed in a UIImageView programmatically?

Following Jordan's advice (which should work actually), try to set the UIImageView to be visible:

 [imageView setHidden: NO];

and also - don't forget to attach it to the main UIView:

[mainView addSubview: imageView];

and to bring to the front:

[mainView bringSubviewToFront: imageView];

Hope combining all these steps will help you solve the mystery.

Running JAR file on Windows

There are many methods for running .jar file on windows. One of them is using the command prompt.

Steps :

  1. Open command prompt(Run as administrator)
  2. Now write "cd\" command for root directory
  3. Type "java jar filename.jar" Note: you can also use any third party apps like WinRAR, jarfix, etc.

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Get checkbox value in jQuery

Best way is $('input[name="line"]:checked').val()

And also you can get selected text $('input[name="line"]:checked').text()

Add value attribute and name to your radio button inputs. Make sure all inputs have same name attribute.

<div class="col-8 m-radio-inline">
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="1" checked> Value Text 1
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="2"> Value Text 2
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="3"> Value Text 3
    </label>
</div>

EditText onClickListener in Android

The problem with solutions using OnFocusChangeListener is that they interpret any focus gain as a click. This is not 100% correct: your EditText might gain focus from something else than a click.

If you strictly care about click and want to detect click consistently (regardless of focus), you can use a GestureDetector:

editText.setOnConsistentClickListener { /* do something */ }

fun EditText.setOnConsistentClickListener(doOnClick: (View) -> Unit) {
    val gestureDetector = GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
        override fun onSingleTapUp(event: MotionEvent?): Boolean {
            doOnClick(this@setOnConsistentClickListener)
            return false
        }
    })

    this.setOnTouchListener { _, motionEvent -> gestureDetector.onTouchEvent(motionEvent) }
}

Text Editor For Linux (Besides Vi)?

First I don't want to start a war..

I haven't used TextMate but I have used its Windows equivalent, e-TextEditor and I could understand why people love it.

I've also tried many text editors and IDEs in my quest in finding the perfect text editor on Linux. I've tried jEdit, vim, emacs (although I used to love when I was at uni) and various others.

On Linux I've settled with gEdit. Although I do use Komodo Edit from time to time. When I'm in a hurry I use gEdit purely because it is quicker than Komodo Edit. gEdit has plenty of plugins and comes with some nice colour schemes. I reckon once gEdit has a proper code-tidy facility it'll be cool. I think the only reason I use Komodo Edit is the project file facility.

I have a friend who donated his 'Vi Improved' book in the hope that he can convert me to Vim. The book is over an inch thick and completely put me off in investing time in learning Vim..

Everytime I find an editor - I always find myself going back to gEdit. It is a frills-in-the-right-places editor. Give gEdit a go, it is the default text editor in Ubuntu and Linux Mint.

Here is a link to an excellent guide on how to get gEdit to look and behave (somewhat) like TextMate: http://grigio.org/pimp_my_gedit_was_textmate_linux

Hope that helps.

How do you remove duplicates from a list whilst preserving order?

In CPython 3.6+ (and all other Python implementations starting with Python 3.7+), dictionaries are ordered, so the way to remove duplicates from an iterable while keeping it in the original order is:

>>> list(dict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

In Python 3.5 and below (including Python 2.7), use the OrderedDict. My timings show that this is now both the fastest and shortest of the various approaches for Python 3.5.

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

How do I search for an object by its ObjectId in the mongo console?

Once you opened the mongo CLI, connected and authorized on the right database.

The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:

db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})

Convert a PHP object to an associative array

What about get_object_vars($obj)? It seems useful if you only want to access the public properties of an object.

See get_object_vars.

MySQL set current date in a DATETIME field on insert

Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.

  1. http://www.mysqltutorial.org/sql-triggers.aspx
  2. http://www.tutorialspoint.com/plsql/plsql_triggers.htm

These two toturial will help to implement the trigger.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

Setting a font-size (for input fields) equal to the body's font-size, seems to be what prevents the browser from zooming out or in. I'd suggest to use font-size: 1rem as a more elegant solution.

Configure DataSource programmatically in Spring Boot

I customized Tomcat DataSource in Spring-Boot 2.

Dependency versions:

  • spring-boot: 2.1.9.RELEASE
  • tomcat-jdbc: 9.0.20

May be it will be useful for somebody.

application.yml

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        type: org.apache.tomcat.jdbc.pool.DataSource
        url: jdbc:postgresql://${spring.datasource.database.host}:${spring.datasource.database.port}/${spring.datasource.database.name}
        database:
            host: localhost
            port: 5432
            name: rostelecom
        username: postgres
        password: postgres
        tomcat:
            validation-query: SELECT 1
            validation-interval: 30000           
            test-on-borrow: true
            remove-abandoned: true
            remove-abandoned-timeout: 480
            test-while-idle: true
            time-between-eviction-runs-millis: 60000
            log-validation-errors: true
            log-abandoned: true

Java

@Bean
@Primary
@ConfigurationProperties("spring.datasource.tomcat")
public PoolConfiguration postgresDataSourceProperties() {
    return new PoolProperties();
}

@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
    PoolConfiguration properties = postgresDataSourceProperties();
    return new DataSource(properties);
}

The main reason why it had been done is several DataSources in application and one of them it is necessary to mark as a @Primary.

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

Install Nuget for Oracle.ManagedDataAccess

Make sure you are using header for Oracle:

using Oracle.ManagedDataAccess.Client;

This Worked for me.

How to find tag with particular text with Beautiful Soup?

result = soup.find('strong', text='text I am looking for').text

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

How would one write object-oriented code in C?

I think that the first thing to say is that (IMHO at least) C's implementation of function pointers is REALLY hard to use. I would jump through a WHOLE lot of hoops to avoid function pointers...

that said, I think that what other people have said is pretty good. you have structures, you have modules, instead of foo->method(a,b,c), you end up with method(foo,a,b,c) If you have more than one type with a "method" method, then you can prefix it with the type, so FOO_method(foo,a,b,c), as others have said... with good use of .h files you can get private and public, etc.

Now, there are a few things that this technique WON'T give you. It won't give you private data fields. that, I think, you have to do with willpower and good coding hygiene... Also, there isn't an easy way to do inheritance with this.

Those are the easy parts at least...the rest, I think is a 90/10 kind of situation. 10% of the benefit will require 90% of the work...

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

Check if a class `active` exist on element with jquery

i wrote a helper method to help me go through all my selected elements and remove the active class.

    function removeClassFromElem(classSelect, classToRemove){
      $(classSelect).each(function(){
        var currElem=$(this);
        if(currElem.hasClass(classToRemove)){
          currElem.removeClass(classToRemove);
        }
      });
    }

    //usage
    removeClassFromElem('.someclass', 'active');

Add image to layout in ruby on rails

It's working for me:

<%= image_tag( root_url + "images/rss.jpg", size: "50x50", :alt => "rss feed") -%>

Print commit message of a given commit in git

It's not "plumbing", but it'll do exactly what you want:

$ git log --format=%B -n 1 <commit>

If you absolutely need a "plumbing" command (not sure why that's a requirement), you can use rev-list:

$ git rev-list --format=%B --max-count=1 <commit>

Although rev-list will also print out the commit sha (on the first line) in addition to the commit message.

https with WCF error: "Could not find base address that matches scheme https"

In my case i am setting security mode to "TransportCredentialOnly" instead of "Transport" in binding. Changing it resolved the issue

<bindings>
  <webHttpBinding>
    <binding name="webHttpSecure">
      <security mode="Transport">
        <transport clientCredentialType="Windows" ></transport>
      </security>
      </binding>
  </webHttpBinding>
</bindings>

How to escape a JSON string containing newline characters using JavaScript?

There is also second parameter on JSON.stringify. So, more elegant solution would be:

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; 
}

var myJSONString = JSON.stringify(myJSON,escape);

How to Bulk Insert from XLSX file extension?

It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

Operator overloading ==, !=, Equals

In fact, this is a "how to" subject. So, here is the reference implementation:

    public class BOX
    {
        double height, length, breadth;

        public static bool operator == (BOX b1, BOX b2)
        {
            if ((object)b1 == null)
                return (object)b2 == null;

            return b1.Equals(b2);
        }

        public static bool operator != (BOX b1, BOX b2)
        {
            return !(b1 == b2);
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
                return false;

            var b2 = (BOX)obj;
            return (length == b2.length && breadth == b2.breadth && height == b2.height);
        }

        public override int GetHashCode()
        {
            return height.GetHashCode() ^ length.GetHashCode() ^ breadth.GetHashCode();
        }
    }

REF: https://msdn.microsoft.com/en-us/library/336aedhh(v=vs.100).aspx#Examples

UPDATE: the cast to (object) in the operator == implementation is important, otherwise, it would re-execute the operator == overload, leading to a stackoverflow. Credits to @grek40.

This (object) cast trick is from Microsoft String == implementaiton. SRC: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs#L643

Using GroupBy, Count and Sum in LINQ Lambda Expressions

    var ListByOwner = list.GroupBy(l => l.Owner)
                          .Select(lg => 
                                new { 
                                    Owner = lg.Key, 
                                    Boxes = lg.Count(),
                                    TotalWeight = lg.Sum(w => w.Weight), 
                                    TotalVolume = lg.Sum(w => w.Volume) 
                                });

Play audio with Python

Aaron's answer appears to be about 10x more complicated than necessary. Just do this if you only need an answer that works on OS X:

from AppKit import NSSound

sound = NSSound.alloc()
sound.initWithContentsOfFile_byReference_('/path/to/file.wav', True)
sound.play()

One thing... this returns immediately. So you might want to also do this, if you want the call to block until the sound finishes playing.

from time import sleep

sleep(sound.duration())

Edit: I took this function and combined it with variants for Windows and Linux. The result is a pure python, cross platform module with no dependencies called playsound. I've uploaded it to pypi.

pip install playsound

Then run it like this:

from playsound import playsound
playsound('/path/to/file.wav', block = False)

MP3 files also work on OS X. WAV should work on all platforms. I don't know what other combinations of platform/file format do or don't work - I haven't tried them yet.

MySQL error 1449: The user specified as a definer does not exist

Try this This is simple solution

mysql -u root -p
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

more at https://stackoverflow.com/a/42183702/5407056

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

Static Vs. Dynamic Binding in Java

Because the compiler knows the binding at compile time. If you invoke a method on an interface, for example, then the compiler can't know and the binding is resolved at runtime because the actual object having a method invoked on it could possible be one of several. Therefore that is runtime or dynamic binding.

Your invocation is bound to the Animal class at compile time because you've specified the type. If you passed that variable into another method somewhere else, noone would know (apart from you because you wrote it) what actual class it would be. The only clue is the declared type of Animal.

Clearing an input text field in Angular2

This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

  clear() {
    this.myForm.get('someControlName').reset()
  }

Adding elements to a collection during iteration

Besides the solution of using an additional list and calling addAll to insert the new items after the iteration (as e.g. the solution by user Nat), you can also use concurrent collections like the CopyOnWriteArrayList.

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

With this special collection (usually used for concurrent access) it is possible to manipulate the underlying list while iterating over it. However, the iterator will not reflect the changes.

Is this better than the other solution? Probably not, I don't know the overhead introduced by the Copy-On-Write approach.

recyclerview No adapter attached; skipping layout

Can you make sure that you are calling these statements from the "main" thread outside of a delayed asynchronous callback (for example inside the onCreate() method). As soon as I call the same statements from a "delayed" method. In my case a ResultCallback, I get the same message.

In my Fragment, calling the code below from inside a ResultCallback method produces the same message. After moving the code to the onConnected() method within my app, the message was gone...

LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
list.setLayoutManager(llm);
list.setAdapter( adapter );

Django Admin - change header 'Django administration' text

You can use these following lines in your main urls.py

you can add the text in the quotes to be displayed

To replace the text Django admin use admin.site.site_header = ""

To replace the text Site Administration use admin.site.site_title = ""

To replace the site name you can use admin.site.index_title = ""

To replace the url of the view site button you can use admin.site.site_url = ""

How do I create a random alpha-numeric string in C++?

Let's make random convenient again!

I made up a nice C++11 header only solution. You could easily add one header file to your project and then add your tests or use random strings for another purposes.

That's a quick description, but you can follow the link to check full code. The main part of solution is in class Randomer:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /* ... some convenience ctors ... */

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

Randomer incapsulates all random stuff and you can add your own functionality to it easily. After we have Randomer, it's very easy to generate strings:

std::string GenerateString(size_t len) {
    std::string str;
    auto rand_char = [](){ return alphabet[randomer()]; };
    std::generate_n(std::back_inserter(str), len, rand_char);
    return str;
}

Write your suggestions for improvement below. https://gist.github.com/VjGusev/e6da2cb4d4b0b531c1d009cd1f8904ad

Ajax request returns 200 OK, but an error event is fired instead of success

I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.

Then in your Ajax call please mention dataType='text'.

It will resolve the problem.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

I get exception when using Thread.sleep(x) or wait()

Thread.sleep() is simple for the beginners and may be appropriate for unit tests and proofs of concept.

But please DO NOT use sleep() for production code. Eventually sleep() may bite you badly.

Best practice for multithreaded/multicore java applications to use the "thread wait" concept. Wait releases all the locks and monitors held by the thread, which allows other threads to acquire those monitors and proceed while your thread is sleeping peacefully.

Code below demonstrates that technique:

import java.util.concurrent.TimeUnit;
public class DelaySample {
    public static void main(String[] args) {
       DelayUtil d = new DelayUtil();
       System.out.println("started:"+ new Date());
       d.delay(500);
       System.out.println("half second after:"+ new Date());
       d.delay(1, TimeUnit.MINUTES); 
       System.out.println("1 minute after:"+ new Date());
    }
}

DelayUtil implementation:

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DelayUtil {
    /** 
    *  Delays the current thread execution. 
    *  The thread loses ownership of any monitors. 
    *  Quits immediately if the thread is interrupted
    *  
    * @param durationInMillis the time duration in milliseconds
    */
   public void delay(final long durationInMillis) {
      delay(durationInMillis, TimeUnit.MILLISECONDS);
   }

   /** 
    * @param duration the time duration in the given {@code sourceUnit}
    * @param unit
    */
    public void delay(final long duration, final TimeUnit unit) {
        long currentTime = System.currentTimeMillis();
        long deadline = currentTime+unit.toMillis(duration);
        ReentrantLock lock = new ReentrantLock();
        Condition waitCondition = lock.newCondition();

        while ((deadline-currentTime)>0) {
            try {
                lock.lockInterruptibly();    
                waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
            currentTime = System.currentTimeMillis();
        }
    }
}

How to return JSON with ASP.NET & jQuery

This structure works for me - I used it in a small tasks management application.

The controller:

public JsonResult taskCount(string fDate)
{
  // do some stuff based on the date

  // totalTasks is a count of the things I need to do today
  // tasksDone is a count of the tasks I actually did
  // pcDone is the percentage of tasks done

  return Json(new {
    totalTasks = totalTasks,
    tasksDone = tasksDone,
    percentDone = pcDone
  });
}

In the AJAX call I access the data like this:

.done(function (data) {
  // data.totalTasks
  // data.tasksDone
  // data.percentDone
});

How to know Laravel version and where is it defined?

  1)  php artisan -V

  2)  php artisan --version

AND its define at the composer.json file

"require": {
        ...........
        "laravel/framework": "^6.2",
        ...........
    },

Why is the GETDATE() an invalid identifier

getdate() for MS-SQL, sysdate for Oracle server

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

Add a thousands separator to a total with Javascript or jQuery?

This will add thousand separators while retaining the decimal part of a given number:

function format(n, sep, decimals) {
    sep = sep || "."; // Default to period as decimal separator
    decimals = decimals || 2; // Default to 2 decimals

    return n.toLocaleString().split(sep)[0]
        + sep
        + n.toFixed(decimals).split(sep)[1];
}

format(4567354.677623); // 4,567,354.68

You could also probe for the locale's decimal separator with:

var sep = (0).toFixed(1)[1];

draw diagonal lines in div background with CSS

All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:

_x000D_
_x000D_
.crossed {_x000D_
    position: relative;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 1px;_x000D_
    bottom: 1px;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 1px;_x000D_
    right: 1px;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_

Explanation, as requested:

Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:

_x000D_
_x000D_
.r1 { width: 10px;_x000D_
      height: 0;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: red blue;_x000D_
      margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
      height: 10px;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_

Finally, use the :before and :after pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.

Convert from enum ordinal to enum type

This is almost certainly a bad idea. Certainly if the ordinal is de-facto persisted (e.g. because someone has bookmarked the URL) - it means that you must always preserve the enum ordering in future, which may not be obvious to code maintainers down the line.

Why not encode the enum using myEnumValue.name() (and decode via ReportTypeEnum.valueOf(s)) instead?

Resolve absolute path from relative path and/or file name

Without having to have another batch file to pass arguments to (and use the argument operators), you can use FOR /F:

FOR /F %%i IN ("..\relativePath") DO echo absolute path: %%~fi

where the i in %%~fi is the variable defined at /F %%i. eg. if you changed that to /F %%a then the last part would be %%~fa.

To do the same thing right at the command prompt (and not in a batch file) replace %% with %...

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

How to create a byte array in C++?

You could use Qt which, in case you don't know, is C++ with a bunch of additional libraries and classes and whatnot. Qt has a very convenient QByteArray class which I'm quite sure would suit your needs.

http://qt-project.org/

How to get setuptools and easy_install?

For linux versions(ubuntu/linux mint), you can always type this in the command prompt:

sudo apt-get install python-setuptools

this will automatically install eas-_install

Java - JPA - @Version annotation

Although @Pascal answer is perfectly valid, from my experience I find the code below helpful to accomplish optimistic locking:

@Entity
public class MyEntity implements Serializable {    
    // ...

    @Version
    @Column(name = "optlock", columnDefinition = "integer DEFAULT 0", nullable = false)
    private long version = 0L;

    // ...
}

Why? Because:

  1. Optimistic locking won't work if field annotated with @Version is accidentally set to null.
  2. As this special field isn't necessarily a business version of the object, to avoid a misleading, I prefer to name such field to something like optlock rather than version.

First point doesn't matter if application uses only JPA for inserting data into the database, as JPA vendor will enforce 0 for @version field at creation time. But almost always plain SQL statements are also in use (at least during unit and integration testing).

What is the email subject length limit?

See RFC 2822, section 2.1.1 to start.

There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.

As the RFC states later, you can work around this limit (not that you should) by folding the subject over multiple lines.

Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field:

       Subject: This is a test

can be represented as:

       Subject: This
        is a test

The recommendation for no more than 78 characters in the subject header sounds reasonable. No one wants to scroll to see the entire subject line, and something important might get cut off on the right.

Move textfield when keyboard appears swift

None of them worked for and I ended up using content insets to move my view up when the keyboard appears.

Note: I was using a UITableView

Referenced solution @ keyboard-content-offset which was entirely written in objective C, the below solution is clean Swift.

Add the notification observer @ viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(yourClass.keyboardWillBeShown), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(yourClass.keyboardWillBeHidden), name:UIKeyboardWillHideNotification, object: nil);

To get the keyboard size, we first get the userInfo dictionary from the notification object, which stores any additional objects that our receiver might use.

From that dictionary we can get the CGRect object describing the keyboard’s frame by using the key UIKeyboardFrameBeginUserInfoKey.

Apply the content inset for the table view @ keyboardWillBeShown method,

func keyboardWillBeShown(sender: NSNotification)
{        
    // Move the table view

    if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
    {
        let contentInsets = UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0);

        yourTableView.contentInset = contentInsets;

        yourTableView.scrollIndicatorInsets = contentInsets;
    }
}

Restore the view @ keyboardWillBeHidden method

func keyboardWillBeHidden(sender: NSNotification)
{
    // Moving back the table view back to the default position

    yourTableView.contentInset = UIEdgeInsetsZero;

    yourTableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

If you want to keep the device orientation also into consideration, use conditional statements to tailor the code to your needs.

// Portrait
UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.height), 0.0);

// Landscape
UIEdgeInsetsMake(0.0, 0.0, (keyboardSize.width), 0.0);

Angularjs $q.all

$http is a promise too, you can make it simpler:

return $q.all(tasks.map(function(d){
        return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
    }));

C# Clear all items in ListView

I would suggest to remove the rows from the underlying DataTable, or if you don't need the datatable anymore, set the datasource to null.

Dynamically Dimensioning A VBA Array?

You need to use a constant.

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

Git: how to reverse-merge a commit?

To create a new commit that 'undoes' the changes of a past commit, use:

$ git revert <commit-hash>

It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).

If your previous commit is a merge commit you can run this command

$ git revert -m 1 <commit-hash>

See schacon.github.com/git/howto/revert-a-faulty-merge.txt for proper ways to re-merge an un-merged branch

send Content-Type: application/json post with node.js

Mikeal's request module can do this easily:

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

Cannot stop or restart a docker container

Worth knowing:

If you are running an ENTRYPOINT script ... the script will work with the shebang

#!/bin/bash -x

But will stop the container from stopping with

#!/bin/bash -xe

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

Javascript Audio Play on click

JavaScript

function playAudio(url) {
  new Audio(url).play();
}


HTML

<img src="image.png" onclick="playAudio('mysound.mp3')">


Supported in most modern browsers and easy to embed into HTML elements.

Convert special characters to HTML in Javascript

a workaround:

var temp = $("div").text("<");
var afterEscape = temp.html(); // afterEscape == "&lt;"

Get the position of a spinner in Android

if (position ==0) {
    if (rYes.isChecked()) {
        Toast.makeText(SportActivity.this, "yes ur answer is right", Toast.LENGTH_LONG).show();
    } else if (rNo.isChecked()) {
        Toast.makeText(SportActivity.this, "no.ur answer is wrong", Toast.LENGTH_LONG).show();
    }
}

This code is supposed to select both check boxes.
Is there a problem with it?

Swift error : signal SIGABRT how to solve it

A common reason for this type of error is that you might have changed the name of your IBOutlet or IBAction you can simply check this by going to source code.

Click on the main.storyboard and then select open as and then select source code enter image description here

source code will open

and then check whether there is the name of the iboutlet or ibaction that you have changed , if there is then select the part and delete it and then again create iboutlet or ibaction. This should resolve your problem

upstream sent too big header while reading response header from upstream

Plesk instructions

I combined the top two answers here

In Plesk 12, I had nginx running as a reverse proxy (which I think is the default). So the current top answer doesn't work as nginx is also being run as a proxy.

I went to Subscriptions | [subscription domain] | Websites & Domains (tab) | [Virtual Host domain] | Web Server Settings.

Then at the bottom of that page you can set the Additional nginx directives which I set to be a combination of the top two answers here:

fastcgi_buffers         16  16k;
fastcgi_buffer_size         32k;
proxy_buffer_size          128k;
proxy_buffers            4 256k;
proxy_busy_buffers_size    256k;

load and execute order of scripts

The browser will execute the scripts in the order it finds them. If you call an external script, it will block the page until the script has been loaded and executed.

To test this fact:

// file: test.php
sleep(10);
die("alert('Done!');");

// HTML file:
<script type="text/javascript" src="test.php"></script>

Dynamically added scripts are executed as soon as they are appended to the document.

To test this fact:

<!DOCTYPE HTML>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <script type="text/javascript">
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.src = "link.js"; // file contains alert("hello!");
        document.body.appendChild(s);
        alert("appended");
    </script>
    <script type="text/javascript">
        alert("final");
    </script>
</body>
</html>

Order of alerts is "appended" -> "hello!" -> "final"

If in a script you attempt to access an element that hasn't been reached yet (example: <script>do something with #blah</script><div id="blah"></div>) then you will get an error.

Overall, yes you can include external scripts and then access their functions and variables, but only if you exit the current <script> tag and start a new one.

How to add to an NSDictionary

A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.

create and add:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue];

What is the difference between "expose" and "publish" in Docker?

Basically, you have three options:

  1. Neither specify EXPOSE nor -p
  2. Only specify EXPOSE
  3. Specify EXPOSE and -p

1) If you specify neither EXPOSE nor -p, the service in the container will only be accessible from inside the container itself.

2) If you EXPOSE a port, the service in the container is not accessible from outside Docker, but from inside other Docker containers. So this is good for inter-container communication.

3) If you EXPOSE and -p a port, the service in the container is accessible from anywhere, even outside Docker.

The reason why both are separated is IMHO because:

  • choosing a host port depends on the host and hence does not belong to the Dockerfile (otherwise it would be depending on the host),
  • and often it's enough if a service in a container is accessible from other containers.

The documentation explicitly states:

The EXPOSE instruction exposes ports for use within links.

It also points you to how to link containers, which basically is the inter-container communication I talked about.

PS: If you do -p, but do not EXPOSE, Docker does an implicit EXPOSE. This is because if a port is open to the public, it is automatically also open to other Docker containers. Hence -p includes EXPOSE. That's why I didn't list it above as a fourth case.

How to get the cell value by column name not by index in GridView in asp.net

For Lambda lovers

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var boundFields = e.Row.Cells.Cast<DataControlFieldCell>()
            .Select(cell => cell.ContainingField).Cast<BoundField>().ToList();

        int idx = boundFields.IndexOf(
            boundFields.FirstOrDefault(f => f.DataField == "ColName"));

        e.Row.Cells[idx].Text = modification;        
    }
}

Close/kill the session when the browser or tab is closed

As you said the event window.onbeforeunload fires when the users clicks on a link or refreshes the page, so it would not a good even to end a session.

http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx describes all situations where window.onbeforeonload is triggered. (IE)

However, you can place a JavaScript global variable on your pages to identify actions that should not trigger a logoff (by using an AJAX call from onbeforeonload, for example).

The script below relies on JQuery

/*
* autoLogoff.js
*
* Every valid navigation (form submit, click on links) should
* set this variable to true.
*
* If it is left to false the page will try to invalidate the
* session via an AJAX call
*/
var validNavigation = false;

/*
* Invokes the servlet /endSession to invalidate the session.
* No HTML output is returned
*/
function endSession() {
   $.get("<whatever url will end your session>");
}

function wireUpEvents() {

  /*
  * For a list of events that triggers onbeforeunload on IE
  * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
  */
  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
     validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
     validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
    wireUpEvents();  
});

This script may be included in all pages

<script type="text/javascript" src="js/autoLogoff.js"></script>

Let's go through this code:

  var validNavigation = false;

  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
     validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
     validNavigation = true;
  });

A global variable is defined at page level. If this variable is not set to true then the event windows.onbeforeonload will terminate the session.

An event handler is attached to every link and form in the page to set this variable to true, thus preventing the session from being terminated if the user is just submitting a form or clicking on a link.

function endSession() {
   $.get("<whatever url will end your session>");
}

The session is terminated if the user closed the browser/tab or navigated away. In this case the global variable was not set to true and the script will do an AJAX call to whichever URL you want to end the session

This solution is server-side technology agnostic. It was not exaustively tested but it seems to work fine in my tests

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

Border Height on CSS

No, there isn't. The border will always be as tall as the element.

You can achieve the same effect by wrapping the contents of the cell in a <span>, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:

background:url(line.png) bottom right no-repeat;

Perform an action in every sub-directory using Bash

The simplest non recursive way is:

for d in */; do
    echo "$d"
done

The / at the end tells, use directories only.

There is no need for

  • find
  • awk
  • ...

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Quoting from the gcc website:

C++11 features are available as part of the "mainline" GCC compiler in the trunk of GCC's Subversion repository and in GCC 4.3 and later. To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

So probably you use a version of g++ which doesn't support -std=c++11. Try -std=c++0x instead.

Availability of C++11 features is for versions >= 4.3 only.

batch file to copy files to another location?

@echo off cls echo press any key to continue backup ! pause xcopy c:\users\file*.* e:\backup*.* /s /e echo backup complete pause


file = name of file your wanting to copy

backup = where u want the file to be moved to

Hope this helps

Correct way to read a text file into a buffer in C?

char source[1000000];

FILE *fp = fopen("TheFile.txt", "r");
if(fp != NULL)
{
    while((symbol = getc(fp)) != EOF)
    {
        strcat(source, &symbol);
    }
    fclose(fp);
}

There are quite a few things wrong with this code:

  1. It is very slow (you are extracting the buffer one character at a time).
  2. If the filesize is over sizeof(source), this is prone to buffer overflows.
  3. Really, when you look at it more closely, this code should not work at all. As stated in the man pages:

The strcat() function appends a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'.

You are appending a character (not a NUL-terminated string!) to a string that may or may not be NUL-terminated. The only time I can imagine this working according to the man-page description is if every character in the file is NUL-terminated, in which case this would be rather pointless. So yes, this is most definitely a terrible abuse of strcat().

The following are two alternatives to consider using instead.

If you know the maximum buffer size ahead of time:

#include <stdio.h>
#define MAXBUFLEN 1000000

char source[MAXBUFLEN + 1];
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
    size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp);
    if ( ferror( fp ) != 0 ) {
        fputs("Error reading file", stderr);
    } else {
        source[newLen++] = '\0'; /* Just to be safe. */
    }

    fclose(fp);
}

Or, if you do not:

#include <stdio.h>
#include <stdlib.h>

char *source = NULL;
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
    /* Go to the end of the file. */
    if (fseek(fp, 0L, SEEK_END) == 0) {
        /* Get the size of the file. */
        long bufsize = ftell(fp);
        if (bufsize == -1) { /* Error */ }

        /* Allocate our buffer to that size. */
        source = malloc(sizeof(char) * (bufsize + 1));

        /* Go back to the start of the file. */
        if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }

        /* Read the entire file into memory. */
        size_t newLen = fread(source, sizeof(char), bufsize, fp);
        if ( ferror( fp ) != 0 ) {
            fputs("Error reading file", stderr);
        } else {
            source[newLen++] = '\0'; /* Just to be safe. */
        }
    }
    fclose(fp);
}

free(source); /* Don't forget to call free() later! */

How can I list all collections in the MongoDB shell?

For MongoDB 3.0 deployments using the WiredTiger storage engine, if you run db.getCollectionNames() from a version of the mongo shell before 3.0 or a version of the driver prior to 3.0 compatible version, db.getCollectionNames() will return no data, even if there are existing collections.

For further details, please refer to this.

How can I use async/await at the top level?

Since main() runs asynchronously it returns a promise. You have to get the result in then() method. And because then() returns promise too, you have to call process.exit() to end the program.

main()
   .then(
      (text) => { console.log('outside: ' + text) },
      (err)  => { console.log(err) }
   )
   .then(() => { process.exit() } )

Show Error on the tip of the Edit Text Android

u can use this :

@Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            if (s.length() == Bank.PAN_MINIMUM_RECOGNIZABLE_LENGTH + 10) {
                Bank bank = BankUtil.findByPan(s.toString());
                if (null != bank && mNewPanEntered && !mNameDefined) {
                    mNewPanEntered = false;
                    suggestCardName(bank);
                }

private void suggestCardName(Bank bank) {
    mLastSuggestTime = System.currentTimeMillis();
    if (!bank.getName().trim().matches(getActivity().getString(R.string.bank_eghtesadnovin))) {
        inputCardNumber.setError(R.string.balance_not_enmb, true);

    }
}

Calculate correlation with cor(), only for numerical columns

I found an easier way by looking at the R script generated by Rattle. It looks like below:

correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")

What is the most appropriate way to store user settings in Android application

In general SharedPreferences are your best bet for storing preferences, so in general I'd recommend that approach for saving application and user settings.

The only area of concern here is what you're saving. Passwords are always a tricky thing to store, and I'd be particularly wary of storing them as clear text. The Android architecture is such that your application's SharedPreferences are sandboxed to prevent other applications from being able to access the values so there's some security there, but physical access to a phone could potentially allow access to the values.

If possible I'd consider modifying the server to use a negotiated token for providing access, something like OAuth. Alternatively you may need to construct some sort of cryptographic store, though that's non-trivial. At the very least, make sure you're encrypting the password before writing it to disk.

How to determine the Boost version on a system?

If you only need to know for your own information, just look in /usr/include/boost/version.hpp (Ubuntu 13.10) and read the information directly

Calculate a Running Total in SQL Server

In SQL Server 2012 you can use SUM() with the OVER() clause.

select id,
       somedate,
       somevalue,
       sum(somevalue) over(order by somedate rows unbounded preceding) as runningtotal
from TestTable

SQL Fiddle

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

Try localhost instead of 127.0.0.1 to connect or in your connection-config. Worked for me on a Debian Squeeze Server

How to convert between bytes and strings in Python 3?

TRY THIS:

StringVariable=ByteVariable.decode('UTF-8','ignore')

TO TEST TYPE:

print(type(StringVariable))

Here 'StringVariable' represented as a string. 'ByteVariable' represent as Byte. Its not relevent to question Variables..

How to remove old Docker containers

docker rm -f $(docker ps -a -q) will do the trick. It will stop the containers and remove them too.

Javascript: How to pass a function with string parameters as a parameter to another function

One way would be to just escape the quotes properly:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
               'myfuncionOnOK(\'/myController2/myAction2\', 
                   \'myParameter2\');',
               'myfuncionOnCancel(\'/myController3/myAction3\', 
                   \'myParameter3\');');">

In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
                function() { myfuncionOnOK('/myController2/myAction2', 
                             'myParameter2'); },
                function() { myfuncionOnCancel('/myController3/myAction3', 
                             'myParameter3'); });">

And then, you could call them from within myfunction like this:

function myfunction(url, onOK, onCancel)
{
    // Do whatever myfunction would normally do...

    if (okClicked)
    {
        onOK();
    }

    if (cancelClicked)
    {
        onCancel();
    }
}

That's probably not what myfunction would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.

swift 3.0 Data to String?

here is my data extension. add this and you can call data.ToString()

import Foundation

extension Data
{
    func toString() -> String?
    {
        return String(data: self, encoding: .utf8)
    }
}

VBA for filtering columns

Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:

Sub FilterAndCopy()
Dim LastRow As Long

Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
    .Range("$A:$E").AutoFilter
    .Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
    .Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
    .Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
    .Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
            Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub

As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.

Resource interpreted as Document but transferred with MIME type application/zip

I've faced this today, and my issue was that my Content-Disposition tag was wrongly set. It looks like for both pdf & application/x-zip-compressed, you're supposed to set it to inline instead of attachment.

So to set your header, Java code would look like this:

...
String fileName = "myFileName.zip";
String contentDisposition = "attachment";
if ("application/pdf".equals(contentType)
    || "application/x-zip-compressed".equals(contentType)) {
    contentDisposition = "inline";
}
response.addHeader("Content-Disposition", contentDisposition + "; filename=\"" + fileName + "\"");
...

WordPress asking for my FTP credentials to install plugins

I did a local install of WordPress on Ubuntu 14.04 following the steps outlined here and simply running:

sudo chown -R www-data:www-data {path_to_your_project_directory}

solved my issue with downloading plugins. The only reason I'm leaving this post here is because when I googled my issue, this was one of the first results and it led me to the solution to my problem.

Hope this one helps to anyone!

Bootstrap: align input with button

Bootstrap 4:

<div class="input-group">
  <input type="text" class="form-control">
  <div class="input-group-append">
    <button class="btn btn-success" type="button">Button</button>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/input-group/

Creating runnable JAR with Gradle

An executable jar file is just a jar file containing a Main-Class entry in its manifest. So you just need to configure the jar task in order to add this entry in its manifest:

jar {
    manifest {
        attributes 'Main-Class': 'com.foo.bar.MainClass'
    }
}

You might also need to add classpath entries in the manifest, but that would be done the same way.

See http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html

Javascript Get Values from Multiple Select Option Box

Here i am posting the answer just for reference which may become useful.

<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
     var InvForm = document.forms.form;
     var SelBranchVal = "";
     var x = 0;
     for (x=0;x<InvForm.kb.length;x++)
         {
            if(InvForm.kb[x].selected)
            {
             //alert(InvForm.kb[x].value);
             SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
            }
         }
         alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
 onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>

Better way to sort array in descending order

Sure, You can customize the sort.

You need to give the Sort() a delegate to a comparison method which it will use to sort.

Using an anonymous method:

Array.Sort<int>( array,
delegate(int a, int b)
  {
    return b - a; //Normal compare is a-b
  }); 

Read more about it:

Sorting arrays
MSDN - Array.Sort Method (T[], Comparison)

How do I use a PriorityQueue?

Just to answer the add() vs offer() question (since the other one is perfectly answered imo, and this might not be):

According to JavaDoc on interface Queue, "The offer method inserts an element if possible, otherwise returning false. This differs from the Collection.add method, which can fail to add an element only by throwing an unchecked exception. The offer method is designed for use when failure is a normal, rather than exceptional occurrence, for example, in fixed-capacity (or "bounded") queues."

That means if you can add the element (which should always be the case in a PriorityQueue), they work exactly the same. But if you can't add the element, offer() will give you a nice and pretty false return, while add() throws a nasty unchecked exception that you don't want in your code. If failure to add means code is working as intended and/or it is something you'll check normally, use offer(). If failure to add means something is broken, use add() and handle the resulting exception thrown according to the Collection interface's specifications.

They are both implemented this way to fullfill the contract on the Queue interface that specifies offer() fails by returning a false (method preferred in capacity-restricted queues) and also maintain the contract on the Collection interface that specifies add() always fails by throwing an exception.

Anyway, hope that clarifies at least that part of the question.

How do I capture response of form.submit

I am not sure that you understand what submit() does...

When you do form1.submit(); the form information is sent to the webserver.

The WebServer will do whatever its supposed to do and return a brand new webpage to the client(usually the same page with something changed).

So, there is no way you can "catch" the return of a form.submit() action.

Is there a way to return a list of all the image file names from a folder using only Javascript?

IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just .hide() them all with JQuery or display: none; in CSS.

Also you can perform prefetching, like this:

<link rel="prefetch" href="imagefolder/clouds.jpg" />

That way you don't have to hide it and still can extract the path to the image.

How to get past the login page with Wget?

Based on the manual page:

# Log in to the server.  This only needs to be done once.
wget --save-cookies cookies.txt \
     --keep-session-cookies \
     --post-data 'user=foo&password=bar' \
     --delete-after \
     http://server.com/auth.php

# Now grab the page or pages we care about.
wget --load-cookies cookies.txt \
     http://server.com/interesting/article.php

Make sure the --post-data parameter is properly percent-encoded (especially ampersands!) or the request will probably fail. Also make sure that user and password are the correct keys; you can find out the correct keys by sleuthing the HTML of the login page (look into your browser’s “inspect element” feature and find the name attribute on the username and password fields).

AND/OR in Python?

For the updated question, you can replace what you want with something like:

someList = filter(lambda x: x not in ("a", "á", "à", "ã", "â"), someList)

filter evaluates every element of the list by passing it to the lambda provided. In this lambda we check if the element is not one of the characters provided, because these should stay in the list.

Alternatively, if the items in someList should be unique, you can make someList a set and do something like this:

someList = list(set(someList)-set(("a", "á", "à", "ã", "â")))

This essentially takes the difference between the sets, which does what you want, but also makes sure every element occurs only once, which is different from a list. Note you could store someList as a set from the beginning in this case, it will optimize things a bit.

Removing single-quote from a string in php

Using your current str_replace method:

$FileName = str_replace("'", "", $UserInput);

While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.

With str_replace, you could even have an array of strings you want to remove entirely:

$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example

$FileName = str_replace( $remove, "", $UserInput );

"Eliminate render-blocking CSS in above-the-fold content"

Hi For jQuery You can only use like this

Use async and type="text/javascript" only

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

How to remove files that are listed in the .gitignore but still on the repository?

I can't say it's an appropriate solution but you can try this.

Steps

  • I am hoping that you have already cloned your repo.
  • Now copy the file somewhere outside of your project.
  • Add that filename with a location in gitigonre file.
  • Remove that file from your local project.
  • Push your code to remote origin.
  • And now add that copied file into your project it'll be ignored.

This is just a hack solution if you want to maintain the history and don't to create mass in it.

If you don't want to use this solution please kindly ignore and try to avoid devote it. Because I am really trying to increase my score on this side

How to return an array from a function?

Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.

So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:

int *gnabber(){
  static int foo[] = {1,2,3}
  return foo;
}

How do I run Google Chrome as root?

STEP 1: cd /opt/google/chrome

STEP 2: edit google-chrome file. gedit google-chrome

STEP 3: find this line: exec -a "$0" "$HERE/chrome" "$@".

Mostly this line is in the end of google-chrome file.

Comment it out like this : #exec -a "$0" "$HERE/chrome" "$@"

STEP 4:add a new line at the same place.

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir

STEP 5: save google-chrome file and quit. And then you can use chrome as root user. Enjoy it!

JQuery create new select option

If you need to make single element you can use this construction:

$('<option/>', {
    'class': this.dataID,
    'text': this.s_dataValue
}).appendTo('.subCategory');

But if you need to print many elements you can use this construction:

function printOptions(arr){
    jQuery.each(arr, function(){
        $('<option/>', {
            'value': this.dataID,
            'text': this.s_dataValue
        }).appendTo('.subCategory');
    });
}

Convert a date format in epoch

tl;dr

ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" , 
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" ) 
                    )
              .toInstant()
              .toEpochMilli()

1055545912454

java.time

This Answer expands on the Answer by Lockni.

DateTimeFormatter

First define a formatting pattern to match your input string by creating a DateTimeFormatter object.

String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime

Parse the string as a ZonedDateTime. You can think of that class as: ( Instant + ZoneId ).

ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

Table of types of date-time classes in modern java.time versus legacy.

Count-from-epoch

I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).

But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00) through the Instant class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.

Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Pandas: Looking up the list of sheets in an excel file

I have tried xlrd, pandas, openpyxl and other such libraries and all of them seem to take exponential time as the file size increase as it reads the entire file. The other solutions mentioned above where they used 'on_demand' did not work for me. If you just want to get the sheet names initially, the following function works for xlsx files.

def get_sheet_details(file_path):
    sheets = []
    file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
    # Make a temporary directory with the file name
    directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
    os.mkdir(directory_to_extract_to)

    # Extract the xlsx file as it is just a zip file
    zip_ref = zipfile.ZipFile(file_path, 'r')
    zip_ref.extractall(directory_to_extract_to)
    zip_ref.close()

    # Open the workbook.xml which is very light and only has meta data, get sheets from it
    path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
    with open(path_to_workbook, 'r') as f:
        xml = f.read()
        dictionary = xmltodict.parse(xml)
        for sheet in dictionary['workbook']['sheets']['sheet']:
            sheet_details = {
                'id': sheet['@sheetId'],
                'name': sheet['@name']
            }
            sheets.append(sheet_details)

    # Delete the extracted files directory
    shutil.rmtree(directory_to_extract_to)
    return sheets

Since all xlsx are basically zipped files, we extract the underlying xml data and read sheet names from the workbook directly which takes a fraction of a second as compared to the library functions.

Benchmarking: (On a 6mb xlsx file with 4 sheets)
Pandas, xlrd: 12 seconds
openpyxl: 24 seconds
Proposed method: 0.4 seconds

Since my requirement was just reading the sheet names, the unnecessary overhead of reading the entire time was bugging me so I took this route instead.

IPC performance: Named Pipe vs Socket

I would suggest you take the easy path first, carefully isolating the IPC mechanism so that you can change from socket to pipe, but I would definitely go with socket first. You should be sure IPC performance is a problem before preemptively optimizing.

And if you get in trouble because of IPC speed, I think you should consider switching to shared memory rather than going to pipe.

If you want to do some transfer speed testing, you should try socat, which is a very versatile program that allows you to create almost any kind of tunnel.

How to bind RadioButtons to an enum?

For UWP, it is not so simple: You must jump through an extra hoop to pass a field value as a parameter.

Example 1

Valid for both WPF and UWP.

<MyControl>
    <MyControl.MyProperty>
        <Binding Converter="{StaticResource EnumToBooleanConverter}" Path="AnotherProperty">
            <Binding.ConverterParameter>
                <MyLibrary:MyEnum>Field</MyLibrary:MyEnum>
            </Binding.ConverterParameter>
        </MyControl>
    </MyControl.MyProperty>
</MyControl>

Example 2

Valid for both WPF and UWP.

...
<MyLibrary:MyEnum x:Key="MyEnumField">Field</MyLibrary:MyEnum>
...

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={StaticResource MyEnumField}}"/>

Example 3

Valid only for WPF!

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static MyLibrary:MyEnum.Field}}"/>

UWP doesn't support x:Static so Example 3 is out of the question; assuming you go with Example 1, the result is more verbose code. Example 2 is slightly better, but still not ideal.

Solution

public abstract class EnumToBooleanConverter<TEnum> : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;

        if (Parameter == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(typeof(TEnum), value) == false)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;
        return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
    }
}

Then, for each type you wish to support, define a converter that boxes the enum type.

public class MyEnumToBooleanConverter : EnumToBooleanConverter<MyEnum>
{
    //Nothing to do!
}

The reason it must be boxed is because there's seemingly no way to reference the type in the ConvertBack method; the boxing takes care of that. If you go with either of the first two examples, you can just reference the parameter type, eliminating the need to inherit from a boxed class; if you wish to do it all in one line and with least verbosity possible, the latter solution is ideal.

Usage resembles Example 2, but is, in fact, less verbose.

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource MyEnumToBooleanConverter}, ConverterParameter=Field}"/>

The downside is you must define a converter for each type you wish to support.

Android WebView not loading an HTTPS URL

Remove the below code it will work

 super.onReceivedSslError(view, handler, error);

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

My solution would be to use a parameterised query, as the connectivity objects take care of formatting the data correctly (including ensuring the correct data-type, and escaping "dangerous" characters where applicable):

// Assuming "conn" is an open SqlConnection
using(SqlCommand cmd = new SqlCommand("INSERT INTO mssqltable(varbinarycolumn) VALUES (@binaryValue)", conn))
{
    // Replace 8000, below, with the correct size of the field
    cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary, 8000).Value = arraytoinsert;
    cmd.ExecuteNonQuery();
}

Edit: Added the wrapping "using" statement as suggested by John Saunders to correctly dispose of the SqlCommand after it is finished with

Add custom message to thrown exception while maintaining stack trace in Java

Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
        try{
            long ans=divide(0);
            System.out.println("answer="+ans);
        }
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());

        }

    }
    public static long divide(int num) throws Exception{
        long x=-1;
        try {
            x=5/num;
        }
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        }
        return x;
    }
}  

the last line return x will not run if error occurs somewhere in between.

Using a Loop to add objects to a list(python)

Auto-incrementing the index in a loop:

myArr[(len(myArr)+1)]={"key":"val"}

Xcode couldn't find any provisioning profiles matching

What fixed it for me was plugging my iPhone and allowing it as a simulator destination. Doing so required my to register my iPhone in Apple Dev account and once that was done and I ran my project from Xcode on my iPhone everything fixed itself.

  1. Connect your iPhone to your Mac
  2. Xcode>Window>Devices & Simulators
  3. Add new under Devices and make sure "show are run destination" is ticked
  4. Build project and run it on your iPhone

how to define variable in jquery

var name = 'john';
document.write(name);

it will write the variable you have declared upper

python: iterate a specific range in a list

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple. The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need.

Elements in a list are numerated from 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

find and replace:

utf8mb4_unicode_520_ci

with

utf8_general_ci

in whole sql file

Bridged networking not working in Virtualbox under Windows 10

Virtual Box gives a lot of issues when it comes to bridge adaptor. I had the same issue with Virtual Box for windows 10. I decided to create VirtualBox Host-Only Ethernet adapter. But I again got issues while creating the host-only ethernet adaptor. I decided to switch to vmware. Vmware did not give me any issues. After installing vmware (and after changing few settings in the BIOS) and installing ubuntu on it, it automatically connected to my host machine's internet. It was able to generate it's own IP address as well and could also ping the host machine (windows machine). Hence, for me virtual box created a lot of issues whereas, vmware worked smoothly for me.

How do I lowercase a string in Python?

With Python 2, this doesn't work for non-English words in UTF-8. In this case decode('utf-8') can help:

>>> s='????????'
>>> print s.lower()
????????
>>> print s.decode('utf-8').lower()
????????

Adding to an ArrayList Java

thanks for the help, I've solved my problem :) Here is the code if anyone else needs it :D

import java.util.*;

public class HelloWorld {


public static void main(String[] Args) {

Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(9);
list.add(11);
map.put(1,list);        

    int First = list.get(1);
    int Second = list.get(2);

    if (First < Second) {

        System.out.println("One or more of your items have been restocked. The current stock is: " + First);

        Random rn = new Random();
int answer = rn.nextInt(99) + 1;

System.out.println("You are buying " + answer + " New stock");

First = First + answer;
list.set(1, First);
System.out.println("There are now " + First + " in stock");
}     
}  
}

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

How to change default JRE for all Eclipse workspaces?

Open the Java > Installed JREs preference page. Check the box on the line for the JRE that you want to assign as the default JRE in your workbench. If the JRE you want to assign as the default does not appear in the list, you must add it. Click OK.

Source-http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-assign_default_jre.htm

Why does overflow:hidden not work in a <td>?

Well here is a solution for you but I don't really understand why it works:

<html><body>
  <div style="width: 200px; border: 1px solid red;">Test</div>
  <div style="width: 200px; border: 1px solid blue; overflow: hidden; height: 1.5em;">My hovercraft is full of eels.  These pretzels are making me thirsty.</div>
  <div style="width: 200px; border: 1px solid yellow; overflow: hidden; height: 1.5em;">
  This_is_a_terrible_example_of_thinking_outside_the_box.
  </div>
  <table style="border: 2px solid black; border-collapse: collapse; width: 200px;"><tr>
   <td style="width:200px; border: 1px solid green; overflow: hidden; height: 1.5em;"><div style="width: 200px; border: 1px solid yellow; overflow: hidden;">
    This_is_a_terrible_example_of_thinking_outside_the_box.
   </div></td>
  </tr></table>
</body></html>

Namely, wrapping the cell contents in a div.

Item frequency count in Python

If you don't want to use the standard dictionary method (looping through the list incrementing the proper dict. key), you can try this:

>>> from itertools import groupby
>>> myList = words.split() # ['apple', 'banana', 'apple', 'strawberry', 'banana', 'lemon']
>>> [(k, len(list(g))) for k, g in groupby(sorted(myList))]
[('apple', 2), ('banana', 2), ('lemon', 1), ('strawberry', 1)]

It runs in O(n log n) time.

Is it better to use "is" or "==" for number comparison in Python?

== is what you want, "is" just happens to work on your examples.

Assignment inside lambda expression in Python

The pythonic way to track state during iteration is with generators. The itertools way is quite hard to understand IMHO and trying to hack lambdas to do this is plain silly. I'd try:

def keep_last_empty(input):
    last = None
    for item in iter(input):
        if item.name: yield item
        else: last = item
    if last is not None: yield last

output = list(keep_last_empty(input))

Overall, readability trumps compactness every time.

Remove all HTMLtags in a string (with the jquery text() function)

If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""

You must either wrap the text in valid HTML:

$('<div>' + 'Hello world' + '</div>').text();

Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method

Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"

$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"

How to pause for specific amount of time? (Excel/VBA)

Wait and Sleep functions lock Excel and you can't do anything else until the delay finishes. On the other hand Loop delays doesn't give you an exact time to wait.

So, I've made this workaround joining a little bit of both concepts. It loops until the time is the time you want.

Private Sub Waste10Sec()
   target = (Now + TimeValue("0:00:10"))
   Do
       DoEvents 'keeps excel running other stuff
   Loop Until Now >= target
End Sub

You just need to call Waste10Sec where you need the delay

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

Drop Down Menu/Text Field in one

The modern solution is an input field of type "search"!

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search https://www.w3schools.com/tags/tag_datalist.asp

Somewhere in your HTML you define a datalist for later reference:

<datalist id="mylist">
   <option value="Option 1">
   <option value="Option 2">
   <option value="Option 3">
</datalist>

Then you can define your search input like this:

<input type="search" list="mylist">

Voilà. Very nice and easy.

Java: parse int value from a char

By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.

String str = "123";

int a=str.charAt(1)-'0';

Using JSON POST Request

An example using jQuery is below. Hope this helps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "https://example.com/api/",
        type: "POST",
        data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 

Firebug debug process

Firebug XHR debug process

Java Comparator class to sort arrays

Just tried this solution, we don't have to even write int.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);

This thing will also work, it automatically detects the type of string.

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

Cheap way to search a large text file for a string

I'm surprised no one mentioned mapping the file into memory: mmap

With this you can access the file as if it were already loaded into memory and the OS will take care of mapping it in and out as possible. Also, if you do this from 2 independent processes and they map the file "shared", they will share the underlying memory.

Once mapped, it will behave like a bytearray. You can use regular expressions, find or any of the other common methods.

Beware that this approach is a little OS specific. It will not be automatically portable.

MySQL Data - Best way to implement paging?

From the MySQL documentation:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

Split string in Lua?

If you just want to iterate over the tokens, this is pretty neat:

line = "one, two and 3!"

for token in string.gmatch(line, "[^%s]+") do
   print(token)
end

Output:

one,

two

and

3!

Short explanation: the "[^%s]+" pattern matches to every non-empty string in between space characters.

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

Using angular-google-maps

$scope.bounds = new google.maps.LatLngBounds();
for (var i = $scope.markers.length - 1; i >= 0; i--) {
    $scope.bounds.extend(new google.maps.LatLng($scope.markers[i].coords.latitude, $scope.markers[i].coords.longitude));
};    
$scope.control.getGMap().fitBounds($scope.bounds);
$scope.control.getGMap().setCenter($scope.bounds.getCenter());

Twitter bootstrap hide element on small devices

On small device : 4 columns x 3 (= 12) ==> col-sm-3

On extra small : 3 columns x 4 (= 12) ==> col-xs-4

 <footer class="row">
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 1</li>
            <li>Text 2</li>
            <li>Text 3</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 4</li>
            <li>Text 5</li>
            <li>Text 6</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 7</li>
            <li>Text 8</li>
            <li>Text 9</li>
            </ul>
        </nav>
        <nav class="hidden-xs col-sm-3">
            <ul class="list-unstyled">
            <li>Text 10</li>
            <li>Text 11</li>
            <li>Text 12</li>
            </ul>
        </nav>
    </footer>

As you say, hidden-xs is not enough, you have to combine xs and sm class.


Here is links to the official doc about available responsive classes and about the grid system.

Have in head :

  • 1 row = 12 cols
  • For XtraSmall device : col-xs-__
  • For SMall device : col-sm-__
  • For MeDium Device: col-md-__
  • For LarGe Device : col-lg-__
  • Make visible only (hidden on other) : visible-md (just visible in medium [not in lg xs or sm])
  • Make hidden only (visible on other) : hidden-xs (just hidden in XtraSmall)

Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here
    </script>
    

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>
    

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <html>
    <!-- ... -->
    <body>
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->
    </body>
    </html>
    

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    }_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

_x000D_
_x000D_
.found {_x000D_
    color: green;_x000D_
}
_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
        p.classList.add("found");_x000D_
    });_x000D_
</script>_x000D_
<p>Paragraph 2</p>
_x000D_
_x000D_
_x000D_

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

Iterating through a string word by word

This is one way to do it:

string = "this is a string"
ssplit = string.split()
for word in ssplit:
    print (word)

Output:

this
is
a
string

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

How to publish a website made by Node.js to Github Pages?

It's very simple steps to push your node js application from local to GitHub.

Steps:

  1. First create a new repository on GitHub
  2. Open Git CMD installed to your system (Install GitHub Desktop)
  3. Clone the repository to your system with the command: git clone repo-url
  4. Now copy all your application files to this cloned library if it's not there
  5. Get everything ready to commit: git add -A
  6. Commit the tracked changes and prepares them to be pushed to a remote repository: git commit -a -m "First Commit"
  7. Push the changes in your local repository to GitHub: git push origin master

How do I make an Event in the Usercontrol and have it handled in the Main Form?

Try mapping it. Try placing this code in your UserControl:

public event EventHandler ValueChanged {
  add { numericUpDown1.ValueChanged += value; }
  remove { numericUpDown1.ValueChanged -= value; }
}

then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

Avoid printStackTrace(); use a logger call instead

Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders. I think a better replacement could be log.error("errors happend in XXX", e) This will also print out whole information which is easy reading than e.printStackTrace()

apache redirect from non www to www

I've just have a same problem. But solved with this

RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

This rule redirecting non-www to www.

And this rule to redirecting www to non-www

RewriteEngine On RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC] RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]

Refer from http://dense13.com/blog/2008/02/27/redirecting-non-www-to-www-with-htaccess/

jquery disable form submit on enter

I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!

$j(':input:not(textarea)').keydown(function(event){
    var kc = event.witch || event.keyCode;
    if(kc == 13){
    event.preventDefault();
        $j(this).closest('form').attr('data-oldaction', function(){
            return $(this).attr('action');
        }).attr('action', 'javascript:;');

        alert('some_text_if_you_want');

        $j(this).closest('form').attr('action', function(){
            return $(this).attr('data-oldaction');
        });
        return false;
    }
});

Access Control Origin Header error using Axios in React Web throwing error in Chrome

npm i cors
const app = require('express')()
app.use(cors())

Above code worked for me.

Download data url file

Combining answers from @owencm and @Chazt3n, this function will allow download of text from IE11, Firefox, and Chrome. (Sorry, I don't have access to Safari or Opera, but please add a comment if you try and it works.)

initiate_user_download = function(file_name, mime_type, text) {
    // Anything but IE works here
    if (undefined === window.navigator.msSaveOrOpenBlob) {
        var e = document.createElement('a');
        var href = 'data:' + mime_type + ';charset=utf-8,' + encodeURIComponent(text);
        e.setAttribute('href', href);
        e.setAttribute('download', file_name);
        document.body.appendChild(e);
        e.click();
        document.body.removeChild(e);
    }
    // IE-specific code
    else {
        var charCodeArr = new Array(text.length);
        for (var i = 0; i < text.length; ++i) {
            var charCode = text.charCodeAt(i);
            charCodeArr[i] = charCode;
        }
        var blob = new Blob([new Uint8Array(charCodeArr)], {type: mime_type});
        window.navigator.msSaveOrOpenBlob(blob, file_name);
    }
}

// Example:
initiate_user_download('data.csv', 'text/csv', 'Sample,Data,Here\n1,2,3\n');

How to get progress from XMLHttpRequest

One of the most promising approaches seems to be opening a second communication channel back to the server to ask it how much of the transfer has been completed.

Google reCAPTCHA: How to get user response and validate in the server side?

A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.

Check the success field for true or false

private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
    JsonObject jsonObject = null;
    URLConnection connection = null;
    InputStream is = null;
    String charset = java.nio.charset.StandardCharsets.UTF_8.name();

    String url = "https://www.google.com/recaptcha/api/siteverify";
    try {            
        String query = String.format("secret=%s&response=%s&remoteip=%s", 
        URLEncoder.encode(secret, charset), 
        URLEncoder.encode(response, charset),
        URLEncoder.encode(remoteip, charset));

        connection = new URL(url + "?" + query).openConnection();
        is = connection.getInputStream();
        JsonReader rdr = Json.createReader(is);
        jsonObject = rdr.readObject();

    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }

        }
    }
    return jsonObject;
}

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

How to use if statements in LESS

LESS has guard expressions for mixins, not individual attributes.

So you'd create a mixin like this:

.debug(@debug) when (@debug = true) {
    header {
      background-color: yellow;
      #title {
          background-color: orange;
      }
    }

    article {
      background-color: red;
    }
}

And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

How can I get dictionary key as variable directly in Python (not by searching from value)?

Iterate over dictionary (i) will return the key, then using it (i) to get the value

for i in D:
    print "key: %s, value: %s" % (i, D[i])

How can I do an UPDATE statement with JOIN in SQL Server?

Syntax strictly depends on which SQL DBMS you're using. Here are some ways to do it in ANSI/ISO (aka should work on any SQL DBMS), MySQL, SQL Server, and Oracle. Be advised that my suggested ANSI/ISO method will typically be much slower than the other two methods, but if you're using a SQL DBMS other than MySQL, SQL Server, or Oracle, then it may be the only way to go (e.g. if your SQL DBMS doesn't support MERGE):

ANSI/ISO:

update ud 
     set assid = (
          select sale.assid 
          from sale 
          where sale.udid = ud.id
     )
 where exists (
      select * 
      from sale 
      where sale.udid = ud.id
 );

MySQL:

update ud u
inner join sale s on
    u.id = s.udid
set u.assid = s.assid

SQL Server:

update u
set u.assid = s.assid
from ud u
    inner join sale s on
        u.id = s.udid

PostgreSQL:

update ud
  set assid = s.assid
from sale s 
where ud.id = s.udid;

Note that the target table must not be repeated in the FROM clause for Postgres.

Oracle:

update
    (select
        u.assid as new_assid,
        s.assid as old_assid
    from ud u
        inner join sale s on
            u.id = s.udid) up
set up.new_assid = up.old_assid

SQLite:

update ud 
     set assid = (
          select sale.assid 
          from sale 
          where sale.udid = ud.id
     )
 where RowID in (
      select RowID 
      from ud 
      where sale.udid = ud.id
 );

Redirect to a page/URL after alert button is pressed

You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location.href = "index.php";';
echo '</script>';

For clarity, try leaving PHP tags for this:

?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php

NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.

What is the preferred Bash shebang?

#!/bin/sh

as most scripts do not need specific bash feature and should be written for sh.

Also, this makes scripts work on the BSDs, which do not have bash per default.

Java client certificates over HTTPS/SSL

For me, this is what worked using Apache HttpComponents ~ HttpClient 4.x:

    KeyStore keyStore  = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
    try {
        keyStore.load(instream, "helloworld".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, "helloworld".toCharArray())
        //.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) //custom trust store
        .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
    CloseableHttpClient httpclient = HttpClients.custom()
        .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
        .setSSLSocketFactory(sslsf)
        .build();
    try {

        HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

The P12 file contains the client certificate and client private key, created with BouncyCastle:

public static byte[] convertPEMToPKCS12(final String keyFile, final String cerFile,
    final String password)
    throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException,
    NoSuchProviderException
{
    // Get the private key
    FileReader reader = new FileReader(keyFile);

    PEMParser pem = new PEMParser(reader);
    PEMKeyPair pemKeyPair = ((PEMKeyPair)pem.readObject());
    JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter().setProvider("BC");
    KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);

    PrivateKey key = keyPair.getPrivate();

    pem.close();
    reader.close();

    // Get the certificate
    reader = new FileReader(cerFile);
    pem = new PEMParser(reader);

    X509CertificateHolder certHolder = (X509CertificateHolder) pem.readObject();
    java.security.cert.Certificate x509Certificate =
        new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate(certHolder);

    pem.close();
    reader.close();

    // Put them into a PKCS12 keystore and write it to a byte[]
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(null);
    ks.setKeyEntry("key-alias", (Key) key, password.toCharArray(),
        new java.security.cert.Certificate[]{x509Certificate});
    ks.store(bos, password.toCharArray());
    bos.close();
    return bos.toByteArray();
}

How to export MySQL database with triggers and procedures?

mysqldump will backup by default all the triggers but NOT the stored procedures/functions. There are 2 mysqldump parameters that control this behavior:

  • --routines – FALSE by default
  • --triggers – TRUE by default

so in mysqldump command , add --routines like :

mysqldump <other mysqldump options> --routines > outputfile.sql

See the MySQL documentation about mysqldump arguments.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci.certificateStatus = "";
    }
  }

And because dataToSend.naci cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:

  const naciStatus = dataToSend.naci?.statusNACI;
  if (typeof naciStatus != "undefined") {
    switch (naciStatus) {
      case "AP":
        dataToSend.naci!.certificateStatus = "FALSE";
        break;
      case "AS":
      case "WR":
        dataToSend.naci!.certificateStatus = "TRUE";
        break;
      default:
        dataToSend.naci!.certificateStatus = "";
    }
  }

invalid conversion from 'const char*' to 'char*'

Well, data.str().c_str() yields a char const* but your function Printfunc() wants to have char*s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be

void Printfunc(int a, char const* loc, char const* stream)

The alternative might be to turn the char const* into a char* but fixing the declaration is preferable:

Printfunc(num, addr, const_cast<char*>(data.str().c_str()));

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

CTRL+SHIFT+* is the de-facto standard key combination for showing/hiding whitespace characters in all Microsoft products that support this feature.

P.S: * refers to 8- * key, not to numeric keypad * key.

Presenting a UIAlertController properly on an iPad using iOS 8

For me I just needed to add the following:

if let popoverController = alertController.popoverPresentationController {
    popoverController.barButtonItem = navigationItem.rightBarButtonItem
}

How to load a UIView using a nib file created with Interface Builder

I had reason to do the same thing (programmatically loading a view from a XIB file), but I needed to do this entirely from the context of a subclass of a subclass of a UIView (i.e. without involving the view controller in any way). To do this I created this utility method:

+ (id) initWithNibName:(NSString *)nibName withSelf:(id)myself {

    NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:nibName
                                                    owner:myself options:nil];
    for (id object in bundle) {
        if ([object isKindOfClass:[myself class]]) {
            return object;
        }
    }  

    return nil;
} 

Then I call it from my subclass' initWithFrame method like so:

- (id)initWithFrame:(CGRect)frame {

    self = [Utilities initWithNibName:@"XIB1" withSelf:self];
    if (self) {
        // Initialization code.
    }
    return self;
}

Posted for general interest; if anyone sees any problems without doing it this way, please let me know.

Validating a Textbox field for only numeric input.

If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:

private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
            if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
            if (e.KeyChar == (char)13) btnSearch_Click(sender, e);  //Allow Enter            
        }

This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

This is worked for me, Hope to help someone (Using my own button not FB login button )

CallbackManager callbackManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    setContentView(R.layout.activity_sign_in_user);



     LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {


            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    try {
                        Log.i("RESAULTS : ", object.getString("email"));
                    }catch (Exception e){

                    }
                }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields", "email");
            request.setParameters(parameters);
            request.executeAsync();

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            Log.i("RESAULTS : ", error.getMessage());
        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}


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

public void signupwith_facebook(View view) {

    LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile","email"));
}
}

Forcing to download a file using PHP

This means that your browser can handle this file type.

If you don't like it, the easiest method would be offering ZIP files. Everyone can handle ZIP files, and they are downloadable by default.

PHP Pass variable to next page

Sessions would be the only good way, you could also use GET/POST but that would be potentially insecure.