Programs & Examples On #Defaultifempty

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

LEFT JOIN in LINQ to entities?

You can use this not only in entities but also store procedure or other data source:

var customer = (from cus in _billingCommonservice.BillingUnit.CustomerRepository.GetAll()  
                          join man in _billingCommonservice.BillingUnit.FunctionRepository.ManagersCustomerValue()  
                          on cus.CustomerID equals man.CustomerID  
                          // start left join  
                          into a  
                          from b in a.DefaultIfEmpty(new DJBL_uspGetAllManagerCustomer_Result() )  
                          select new { cus.MobileNo1,b.ActiveStatus });  

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

Checking Count() before the WHERE clause solved my problem. It is cheaper than ToList()

if (authUserList != null && _list.Count() > 0)
    _list = _list.Where(l => authUserList.Contains(l.CreateUserId));

LINQ Join with Multiple Conditions in On Clause

You just need to name the anonymous property the same on both sides

on new { t1.ProjectID, SecondProperty = true } equals 
   new { t2.ProjectID, SecondProperty = t2.Completed } into j1

Based on the comments of @svick, here is another implementation that might make more sense:

from t1 in Projects
from t2 in Tasks.Where(x => t1.ProjectID == x.ProjectID && x.Completed == true)
                .DefaultIfEmpty()
select new { t1.ProjectName, t2.TaskName }

LINQ - Full Outer Join

I like sehe's answer, but it does not use deferred execution (the input sequences are eagerly enumerated by the calls to ToLookup). So after looking at the .NET sources for LINQ-to-objects, I came up with this:

public static class LinqExtensions
{
    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> left,
        IEnumerable<TRight> right,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TKey, TResult> resultSelector,
        IEqualityComparer<TKey> comparator = null,
        TLeft defaultLeft = default(TLeft),
        TRight defaultRight = default(TRight))
    {
        if (left == null) throw new ArgumentNullException("left");
        if (right == null) throw new ArgumentNullException("right");
        if (leftKeySelector == null) throw new ArgumentNullException("leftKeySelector");
        if (rightKeySelector == null) throw new ArgumentNullException("rightKeySelector");
        if (resultSelector == null) throw new ArgumentNullException("resultSelector");

        comparator = comparator ?? EqualityComparer<TKey>.Default;
        return FullOuterJoinIterator(left, right, leftKeySelector, rightKeySelector, resultSelector, comparator, defaultLeft, defaultRight);
    }

    internal static IEnumerable<TResult> FullOuterJoinIterator<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> left,
        IEnumerable<TRight> right,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TKey, TResult> resultSelector,
        IEqualityComparer<TKey> comparator,
        TLeft defaultLeft,
        TRight defaultRight)
    {
        var leftLookup = left.ToLookup(leftKeySelector, comparator);
        var rightLookup = right.ToLookup(rightKeySelector, comparator);
        var keys = leftLookup.Select(g => g.Key).Union(rightLookup.Select(g => g.Key), comparator);

        foreach (var key in keys)
            foreach (var leftValue in leftLookup[key].DefaultIfEmpty(defaultLeft))
                foreach (var rightValue in rightLookup[key].DefaultIfEmpty(defaultRight))
                    yield return resultSelector(leftValue, rightValue, key);
    }
}

This implementation has the following important properties:

  • Deferred execution, input sequences will not be enumerated before the output sequence is enumerated.
  • Only enumerates the input sequences once each.
  • Preserves order of input sequences, in the sense that it will yield tuples in the order of the left sequence and then the right (for the keys not present in left sequence).

These properties are important, because they are what someone new to FullOuterJoin but experienced with LINQ will expect.

LINQ to SQL - Left Outer Join with multiple join conditions

Another valid option is to spread the joins across multiple LINQ clauses, as follows:

public static IEnumerable<Announcementboard> GetSiteContent(string pageName, DateTime date)
{
    IEnumerable<Announcementboard> content = null;
    IEnumerable<Announcementboard> addMoreContent = null;
        try
        {
            content = from c in DB.Announcementboards
              // Can be displayed beginning on this date
              where c.Displayondate > date.AddDays(-1)
              // Doesn't Expire or Expires at future date
              && (c.Displaythrudate == null || c.Displaythrudate > date)
              // Content is NOT draft, and IS published
              && c.Isdraft == "N" && c.Publishedon != null
              orderby c.Sortorder ascending, c.Heading ascending
              select c;

            // Get the content specific to page names
            if (!string.IsNullOrEmpty(pageName))
            {
              addMoreContent = from c in content
                  join p in DB.Announceonpages on c.Announcementid equals p.Announcementid
                  join s in DB.Apppagenames on p.Apppagenameid equals s.Apppagenameid
                  where s.Apppageref.ToLower() == pageName.ToLower()
                  select c;
            }

            // Add the specified content using UNION
            content = content.Union(addMoreContent);

            // Exclude the duplicates using DISTINCT
            content = content.Distinct();

            return content;
        }
    catch (MyLovelyException ex)
    {
        // Add your exception handling here
        throw ex;
    }
}

LINQ - Left Join, Group By, and Count

While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

Here's my solution:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }

Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

How do you perform a left outer join using linq extension methods

You can create extension method like:

public static IEnumerable<TResult> LeftOuterJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source, IEnumerable<TInner> other, Func<TSource, TKey> func, Func<TInner, TKey> innerkey, Func<TSource, TInner, TResult> res)
    {
        return from f in source
               join b in other on func.Invoke(f) equals innerkey.Invoke(b) into g
               from result in g.DefaultIfEmpty()
               select res.Invoke(f, result);
    }

Equivalent of SQL ISNULL in LINQ?

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

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

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

How do I make an attributed string using Swift?

I would highly recommend using a library for attributed strings. It makes it much easier when you want, for example, one string with four different colors and four different fonts. Here is my favorite. It is called SwiftyAttributes

If you wanted to make a string with four different colors and different fonts using SwiftyAttributes:

let magenta = "Hello ".withAttributes([
    .textColor(.magenta),
    .font(.systemFont(ofSize: 15.0))
    ])
let cyan = "Sir ".withAttributes([
    .textColor(.cyan),
    .font(.boldSystemFont(ofSize: 15.0))
    ])
let green = "Lancelot".withAttributes([
    .textColor(.green),
    .font(.italicSystemFont(ofSize: 15.0))

    ])
let blue = "!".withAttributes([
    .textColor(.blue),
    .font(.preferredFont(forTextStyle: UIFontTextStyle.headline))

    ])
let finalString = magenta + cyan + green + blue

finalString would show as

Shows as image

CURRENT_TIMESTAMP in milliseconds

For MySQL (5.6+) you can do this:

SELECT ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000)

Which will return (e.g.):

1420998416685 --milliseconds

How to increase Maximum Upload size in cPanel?

In my case it was wp-admin/.user.ini:

post_max_size = 33M
upload_max_filesize = 32M

Using Java 8's Optional with Stream::flatMap

What about that?

private static List<String> extractString(List<Optional<String>> list) {
    List<String> result = new ArrayList<>();
    list.forEach(element -> element.ifPresent(result::add));
    return result;
}

https://stackoverflow.com/a/58281000/3477539

Fastest way to convert Image to Byte array

The fastest way i could find out is this :

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

Hope to be useful

The number of method references in a .dex file cannot exceed 64k API 17

Just a side comment, Before adding support for multidex - make sure you are not adding unnecessary dependencies.

For example In the official Facebook analytics guide

They clearly state that you should add the following dependency:

implementation 'com.facebook.android:facebook-android-sdk:[4,5)'

which is actually the entire FacebookSDK - so if you need for example just the Analytics you need to replace it with:

implementation 'com.facebook.android:facebook-core:5.+'

Facebook partial SDK options

How can I convert a string to an int in Python?

Don't use str() method directly in html instead use with y=x|string()

<div class="row">
    {% for x in range(photo_upload_count) %}
        {% with y=x|string() %}

    <div col-md-4 >
        <div class="col-md-12">
            <div class="card card-primary "  style="border:1px solid #000">
                <div class="card-body">
                    {% if data['profile_photo']!= None: %}
                        <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                    {% else: %}
                        <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                    {% endif %}
                </div>
                <div class="card-footer text-center">
                    <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}
</div>

What is an NP-complete in computer science?

What is NP?

NP is the set of all decision problems (questions with a yes-or-no answer) for which the 'yes'-answers can be verified in polynomial time (O(nk) where n is the problem size, and k is a constant) by a deterministic Turing machine. Polynomial time is sometimes used as the definition of fast or quickly.

What is P?

P is the set of all decision problems which can be solved in polynomial time by a deterministic Turing machine. Since they can be solved in polynomial time, they can also be verified in polynomial time. Therefore P is a subset of NP.

What is NP-Complete?

A problem x that is in NP is also in NP-Complete if and only if every other problem in NP can be quickly (ie. in polynomial time) transformed into x.

In other words:

  1. x is in NP, and
  2. Every problem in NP is reducible to x

So, what makes NP-Complete so interesting is that if any one of the NP-Complete problems was to be solved quickly, then all NP problems can be solved quickly.

See also the post What's "P=NP?", and why is it such a famous question?

What is NP-Hard?

NP-Hard are problems that are at least as hard as the hardest problems in NP. Note that NP-Complete problems are also NP-hard. However not all NP-hard problems are NP (or even a decision problem), despite having NP as a prefix. That is the NP in NP-hard does not mean non-deterministic polynomial time. Yes, this is confusing, but its usage is entrenched and unlikely to change.

What does <value optimized out> mean in gdb?

Minimal runnable example with disassembly analysis

As usual, I like to see some disassembly to get a better understanding of what is going on.

In this case, the insight we obtain is that if a variable is optimized to be stored only in a register rather than the stack, and then the register it was in gets overwritten, then it shows as <optimized out> as mentioned by R..

Of course, this can only happen if the variable in question is not needed anymore, otherwise the program would lose its value. Therefore it tends to happen that at the start of the function you can see the variable value, but then at the end it becomes <optimized out>.

One typical case which we often are interested in of this is that of the function arguments themselves, since these are:

  • always defined at the start of the function
  • may not get used towards the end of the function as more intermediate values are calculated.
  • tend to get overwritten by further function subcalls which must setup the exact same registers to satisfy the calling convention

This understanding actually has a concrete application: when using reverse debugging, you might be able to recover the value of variables of interest simply by stepping back to their last point of usage: How do I view the value of an <optimized out> variable in C++?

main.c

#include <stdio.h>

int __attribute__((noinline)) f3(int i) {
    return i + 1;
}

int __attribute__((noinline)) f2(int i) {
    return f3(i) + 1;
}

int __attribute__((noinline)) f1(int i) {
    int j = 1, k = 2, l = 3;
    i += 1;
    j += f2(i);
    k += f2(j);
    l += f2(k);
    return l;
}

int main(int argc, char *argv[]) {
    printf("%d\n", f1(argc));
    return 0;
}

Compile and run:

gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
gdb -q -nh main.out

Then inside GDB, we have the following session:

Breakpoint 1, f1 (i=1) at main.c:13
13          i += 1;
(gdb) disas
Dump of assembler code for function f1:
=> 0x00005555555546c0 <+0>:     add    $0x1,%edi
   0x00005555555546c3 <+3>:     callq  0x5555555546b0 <f2>
   0x00005555555546c8 <+8>:     lea    0x1(%rax),%edi
   0x00005555555546cb <+11>:    callq  0x5555555546b0 <f2>
   0x00005555555546d0 <+16>:    lea    0x2(%rax),%edi
   0x00005555555546d3 <+19>:    callq  0x5555555546b0 <f2>
   0x00005555555546d8 <+24>:    add    $0x3,%eax
   0x00005555555546db <+27>:    retq   
End of assembler dump.
(gdb) p i
$1 = 1
(gdb) p j
$2 = 1
(gdb) n
14          j += f2(i);
(gdb) disas
Dump of assembler code for function f1:
   0x00005555555546c0 <+0>:     add    $0x1,%edi
=> 0x00005555555546c3 <+3>:     callq  0x5555555546b0 <f2>
   0x00005555555546c8 <+8>:     lea    0x1(%rax),%edi
   0x00005555555546cb <+11>:    callq  0x5555555546b0 <f2>
   0x00005555555546d0 <+16>:    lea    0x2(%rax),%edi
   0x00005555555546d3 <+19>:    callq  0x5555555546b0 <f2>
   0x00005555555546d8 <+24>:    add    $0x3,%eax
   0x00005555555546db <+27>:    retq   
End of assembler dump.
(gdb) p i
$3 = 2
(gdb) p j
$4 = 1
(gdb) n
15          k += f2(j);
(gdb) disas
Dump of assembler code for function f1:
   0x00005555555546c0 <+0>:     add    $0x1,%edi
   0x00005555555546c3 <+3>:     callq  0x5555555546b0 <f2>
   0x00005555555546c8 <+8>:     lea    0x1(%rax),%edi
=> 0x00005555555546cb <+11>:    callq  0x5555555546b0 <f2>
   0x00005555555546d0 <+16>:    lea    0x2(%rax),%edi
   0x00005555555546d3 <+19>:    callq  0x5555555546b0 <f2>
   0x00005555555546d8 <+24>:    add    $0x3,%eax
   0x00005555555546db <+27>:    retq   
End of assembler dump.
(gdb) p i
$5 = <optimized out>
(gdb) p j
$6 = 5
(gdb) n
16          l += f2(k);
(gdb) disas
Dump of assembler code for function f1:
   0x00005555555546c0 <+0>:     add    $0x1,%edi
   0x00005555555546c3 <+3>:     callq  0x5555555546b0 <f2>
   0x00005555555546c8 <+8>:     lea    0x1(%rax),%edi
   0x00005555555546cb <+11>:    callq  0x5555555546b0 <f2>
   0x00005555555546d0 <+16>:    lea    0x2(%rax),%edi
=> 0x00005555555546d3 <+19>:    callq  0x5555555546b0 <f2>
   0x00005555555546d8 <+24>:    add    $0x3,%eax
   0x00005555555546db <+27>:    retq   
End of assembler dump.
(gdb) p i
$7 = <optimized out>
(gdb) p j
$8 = <optimized out>

To understand what is going on, remember from the x86 Linux calling convention: What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 you should know that:

  • RDI contains the first argument
  • RDI can get destroyed in function calls
  • RAX contains the return value

From this we deduce that:

add    $0x1,%edi

corresponds to the:

i += 1;

since i is the first argument of f1, and therefore stored in RDI.

Now, while we were at both:

i += 1;
j += f2(i);

the value of RDI hadn't been modified, and therefore GDB could just query it at anytime in those lines.

However, as soon as the f2 call is made:

  • the value of i is not needed anymore in the program
  • lea 0x1(%rax),%edi does EDI = j + RAX + 1, which both:
    • initializes j = 1
    • sets up the first argument of the next f2 call to RDI = j

Therefore, when the following line is reached:

k += f2(j);

both of the following instructions have/may have modified RDI, which is the only place i was being stored (f2 may use it as a scratch register, and lea definitely set it to RAX + 1):

   0x00005555555546c3 <+3>:     callq  0x5555555546b0 <f2>
   0x00005555555546c8 <+8>:     lea    0x1(%rax),%edi

and so RDI does not contain the value of i anymore. In fact, the value of i was completely lost! Therefore the only possible outcome is:

$3 = <optimized out>

A similar thing happens to the value of j, although j only becomes unnecessary one line later afer the call to k += f2(j);.

Thinking about j also gives us some insight on how smart GDB is. Notably, at i += 1;, the value of j had not yet materialized in any register or memory address, and GDB must have known it based solely on debug information metadata.

-O0 analysis

If we use -O0 instead of -O3 for compilation:

gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c

then the disassembly would look like:

11      int __attribute__((noinline)) f1(int i) {
=> 0x0000555555554673 <+0>:     55      push   %rbp
   0x0000555555554674 <+1>:     48 89 e5        mov    %rsp,%rbp
   0x0000555555554677 <+4>:     48 83 ec 18     sub    $0x18,%rsp
   0x000055555555467b <+8>:     89 7d ec        mov    %edi,-0x14(%rbp)

12          int j = 1, k = 2, l = 3;
   0x000055555555467e <+11>:    c7 45 f4 01 00 00 00    movl   $0x1,-0xc(%rbp)
   0x0000555555554685 <+18>:    c7 45 f8 02 00 00 00    movl   $0x2,-0x8(%rbp)
   0x000055555555468c <+25>:    c7 45 fc 03 00 00 00    movl   $0x3,-0x4(%rbp)

13          i += 1;
   0x0000555555554693 <+32>:    83 45 ec 01     addl   $0x1,-0x14(%rbp)

14          j += f2(i);
   0x0000555555554697 <+36>:    8b 45 ec        mov    -0x14(%rbp),%eax
   0x000055555555469a <+39>:    89 c7   mov    %eax,%edi
   0x000055555555469c <+41>:    e8 b8 ff ff ff  callq  0x555555554659 <f2>
   0x00005555555546a1 <+46>:    01 45 f4        add    %eax,-0xc(%rbp)

15          k += f2(j);
   0x00005555555546a4 <+49>:    8b 45 f4        mov    -0xc(%rbp),%eax
   0x00005555555546a7 <+52>:    89 c7   mov    %eax,%edi
   0x00005555555546a9 <+54>:    e8 ab ff ff ff  callq  0x555555554659 <f2>
   0x00005555555546ae <+59>:    01 45 f8        add    %eax,-0x8(%rbp)

16          l += f2(k);
   0x00005555555546b1 <+62>:    8b 45 f8        mov    -0x8(%rbp),%eax
   0x00005555555546b4 <+65>:    89 c7   mov    %eax,%edi
   0x00005555555546b6 <+67>:    e8 9e ff ff ff  callq  0x555555554659 <f2>
   0x00005555555546bb <+72>:    01 45 fc        add    %eax,-0x4(%rbp)

17          return l;
   0x00005555555546be <+75>:    8b 45 fc        mov    -0x4(%rbp),%eax

18      }
   0x00005555555546c1 <+78>:    c9      leaveq 
   0x00005555555546c2 <+79>:    c3      retq 

From this horrendous disassembly, we see that the value of RDI is moved to the stack at the very start of program execution at:

mov    %edi,-0x14(%rbp)

and it then gets retrieved from memory into registers whenever needed, e.g. at:

14          j += f2(i);
   0x0000555555554697 <+36>:    8b 45 ec        mov    -0x14(%rbp),%eax
   0x000055555555469a <+39>:    89 c7   mov    %eax,%edi
   0x000055555555469c <+41>:    e8 b8 ff ff ff  callq  0x555555554659 <f2>
   0x00005555555546a1 <+46>:    01 45 f4        add    %eax,-0xc(%rbp)

The same basically happens to j which gets immediately pushed to the stack when when it is initialized:

   0x000055555555467e <+11>:    c7 45 f4 01 00 00 00    movl   $0x1,-0xc(%rbp)

Therefore, it is easy for GDB to find the values of those variables at any time: they are always present in memory!

This also gives us some insight on why it is not possible to avoid <optimized out> in optimized code: since the number of registers is limited, the only way to do that would be to actually push unneeded registers to memory, which would partly defeat the benefit of -O3.

Extend the lifetime of i

If we edited f1 to return l + i as in:

int __attribute__((noinline)) f1(int i) {
    int j = 1, k = 2, l = 3;
    i += 1;
    j += f2(i);
    k += f2(j);
    l += f2(k);
    return l + i;
}

then we observe that this effectively extends the visibility of i until the end of the function.

This is because with this we force GCC to use an extra variable to keep i around until the end:

   0x00005555555546c0 <+0>:     lea    0x1(%rdi),%edx
   0x00005555555546c3 <+3>:     mov    %edx,%edi
   0x00005555555546c5 <+5>:     callq  0x5555555546b0 <f2>
   0x00005555555546ca <+10>:    lea    0x1(%rax),%edi
   0x00005555555546cd <+13>:    callq  0x5555555546b0 <f2>
   0x00005555555546d2 <+18>:    lea    0x2(%rax),%edi
   0x00005555555546d5 <+21>:    callq  0x5555555546b0 <f2>
   0x00005555555546da <+26>:    lea    0x3(%rdx,%rax,1),%eax
   0x00005555555546de <+30>:    retq

which the compiler does by storing i += i in RDX at the very first instruction.

Tested in Ubuntu 18.04, GCC 7.4.0, GDB 8.1.0.

Taking pictures with camera on Android programmatically

You can use Magical Take Photo library.

1. try with compile in gradle

compile 'com.frosquivel:magicaltakephoto:1.0'

2. You need this permission in your manifest.xml

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

3. instance the class like this

// "this" is the current activity param

MagicalTakePhoto magicalTakePhoto =  new MagicalTakePhoto(this,ANY_INTEGER_0_TO_4000_FOR_QUALITY);

4. if you need to take picture use the method

magicalTakePhoto.takePhoto("my_photo_name");

5. if you need to select picture in device, try with the method:

magicalTakePhoto.selectedPicture("my_header_name");

6. You need to override the method onActivityResult of the activity or fragment like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     magicalTakePhoto.resultPhoto(requestCode, resultCode, data);

     // example to get photo
     // imageView.setImageBitmap(magicalTakePhoto.getMyPhoto());
}

Note: Only with this Library you can take and select picture in the device, this use a min API 15.

How to add a custom button to the toolbar that calls a JavaScript function?

This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal

There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.

How to download an entire directory and subdirectories using wget?

you can also use this command :

wget --mirror -pc --convert-links -P ./your-local-dir/ http://www.your-website.com

so that you get the exact mirror of the website you want to download

Get data from fs.readFile

Use the built in promisify library (Node 8+) to make these old callback functions more elegant.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

async function doStuff() {
  try {
    const content = await readFile(filePath, 'utf8');
    console.log(content);
  } catch (e) {
    console.error(e);
  }
}

Convert Iterable to Stream using Java 8 JDK

So as another answer mentioned Guava has support for this by using:

Streams.stream(iterable);

I want to highlight that the implementation does something slightly different than other answers suggested. If the Iterable is of type Collection they cast it.

public static <T> Stream<T> stream(Iterable<T> iterable) {
  return (iterable instanceof Collection)
    ? ((Collection<T>) iterable).stream()
    : StreamSupport.stream(iterable.spliterator(), false);
}

public static <T> Stream<T> stream(Iterator<T> iterator) {
  return StreamSupport.stream(
    Spliterators.spliteratorUnknownSize(iterator, 0),
    false
  );
}

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

Is there a job scheduler library for node.js?

I am the auhor of node-runnr . It have a very simple approach to create job. Also its very easy and clear to declare time and interval. For example, to execute a job at every 10min 20sec,

Runnr.addIntervalJob('10:20', function(){...}, 'myjob')

To do a job at 10am and 3pm daily,

Runnr.addDailyJob(['10:0:0', '15:0:0'], function(){...}, 'myjob')

Its that simple. For further detail: https://github.com/Saquib764/node-runnr

Add Header and Footer for PDF using iTextsharp

The answers to this question, while they are correct, are very unnecessarily complicated. It doesn't take that much code for text to show up in the header/footer. Here is a simple example of adding text to the header/footer.

The current version of iTextSharp works by implementing a callback class which is defined by the IPdfPageEvent interface. From what I understand, it's not a good idea to add things during the OnStartPage method, so instead I will be using the OnEndPage page method. The events are triggered depending on what is happening to the PdfWriter

First, create a class which implements IPdfPageEvent. In the:

public void OnEndPage(PdfWriter writer, Document document)

function, obtain the PdfContentByte object by calling

PdfContentByte cb = writer.DirectContent;

Now you can add text very easily:

ColumnText ct = new ColumnText(cb);

cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
//Note, (0,0) in this case is at the bottom of the document
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin); 
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();

So the full for the OnEndPage function will be:

public void OnEndPage(PdfWriter writer, Document document)
{
    PdfContentByte cb = writer.DirectContent;
    ColumnText ct = new ColumnText(cb);

    cb.BeginText();
    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
    cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
    cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
    cb.EndText();

}

This will show up at the bottom of your document. One last thing. Don't forget to assign the IPdfPageEvent like this:

writter.PageEvent = new PDFEvents();

To the PdfWriter writter object

For the header it is very similar. Just flip the SetTextMatrix y coordinate:

cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin);

Validate form field only on submit or user input

Use $dirty flag to show the error only after user interacted with the input:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

Then, if all that JS inside ng-showexpression looks too much for you, you can abstract it into a separate method:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

for loop in Python

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.

mylist = [1,2,3]
for item in mylist:
    print item

mydict  = {1:'one', 2:'two', 3:'three'}
for key in mydict:
    print key, mydict[key]

This is actually faster than using the above code with range(), and removes the extraneous i variable.

If you need to edit items of a list in-place, then you do need the index, but there's still a better way:

for i, item in enumerate(mylist):
    mylist[i] = item**2

Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.

Where can I download IntelliJ IDEA Color Schemes?

I know I'm late to the party but just wanted to mention that the Jumpout II theme really is amazing.. I have a lot of themes and this one really is great for a # of reasons..

  1. it handles glare very well (yes even pure black on matte screens can produce glare, unfortunately my new matte monitor - has a more "glary" coating than my old one).. this is a grayish-black background

  2. it has enough colors that you can easily see read even dense code - some themes that look nice at first use too much of one color and it makes dense code harder to digest

  3. the comments are all gray, this is even better than dark green which is my 2nd favorite choice.. it really helps the code pop out..

so basically this is a great anti-glare, anti-dense-code theme

honorable mentions (I think these all can be found on that same site, although I'm not sure I spelled all of them correctly)

  1. Dark Flash Builder (really great but at first the use of red can be confusing, but it is really one of its strengths. I had to modify it to make my error text highlighting different - I settled on some bright red underlined text)
  2. Gedit Original Oblivion
  3. Leone Dark II
  4. Visual Studio 2013
  5. Retta (very halloweeny)

and for white / beige / blue (in that order)

  1. Oughsumm (wow best white ever, possibly the most legible theme I've ever seen - however, white is too bright for me in my current office situation, although occasionally I do switch to this when I want to quickly review a lot of code before a commit), also it is comfortably legible at 1 point smaller than all dark themes I've used.
  2. humane-ist
  3. rubyblue

p.s. please note I change the font of all the themes I use to Consolas 11 or 12 depending on the monitor. Consolas I find to be the best programming font out there. It looks great, easy to read and very well suited to LCD anti-aliasing. I tried so many programming fonts but I always come back to this one quickly. And it is not too narrow.. I'm not in the narrow camp, I believe narrow font aficionados don't program with ultra wide monitors - maybe program on a macbook or something just as bad :)

p.p.s I know solarized is supposed to be some kind of ultimate, magical, life-enhancing nirvana-inducing theme but I just don't get it.. I tried but failed to find it anything but annoying

How to make android listview scrollable?

This is my working code. you may try with this.

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listEmployeeDetails"
        android:layout_height="match_parent" 
        android:layout_width="match_parent"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_gravity="center"
        android:background="#ffffff">

        <TextView android:id="@+id/tvEmpId"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.3"/>
            <TextView android:id="@+id/tvNameEmp"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"                     
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.5"/>
             <TextView
                    android:layout_height="wrap_content"
                    android:id="@+id/tvStatusEmp"
                    android:textSize="12sp"
                    android:padding="2dp"
                    android:layout_width="0dp"
                    android:layout_weight="0.2"/>               
</LinearLayout> 

details.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listEmployeeDetails"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/page_bg"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/lLayoutGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/page_bg"
        android:orientation="vertical" >

        ................... others components here............................

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alwaysDrawnWithCache="true"
            android:dividerHeight="1dp"
            android:horizontalSpacing="3dp"
            android:scrollingCache="true"
            android:smoothScrollbar="true"
            android:stretchMode="columnWidth"
            android:verticalSpacing="3dp" 
            android:layout_marginBottom="30dp">
        </ListView>
    </LinearLayout>
</RelativeLayout>

Adapter class :

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {
    private Context context;
    private List<EmployeeBean> employeeList; 

    publicListViewAdapter(Context context, List<EmployeeBean> employeeList) {
            this.context = context;
            this.employeeList = employeeList;
        }

    public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            EmployeeBeanHolder holder = null;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.row, parent, false);

            holder = new EmployeeBeanHolder();
            holder.employeeBean = employeeList.get(position);
            holder.tvEmpId = (TextView) row.findViewById(R.id.tvEmpId);
            holder.tvName = (TextView) row.findViewById(R.id.tvNameEmp);
            holder.tvStatus = (TextView) row.findViewById(R.id.tvStatusEmp);

            row.setTag(holder);
            holder.tvEmpId.setText(holder.employeeBean.getEmpId());
            holder.tvName.setText(holder.employeeBean.getName());
            holder.tvStatus.setText(holder.employeeBean.getStatus());

             if (position % 2 == 0) {
                    row.setBackgroundColor(Color.rgb(213, 229, 241));
                } else {                    
                    row.setBackgroundColor(Color.rgb(255, 255, 255));
                }        

            return row;
        }

   public static class EmployeeBeanHolder {
        EmployeeBean employeeBean;
        TextView tvEmpId;
        TextView tvName;
        TextView tvStatus;
    }

    @Override
    public int getCount() {
            return employeeList.size();
        }

    @Override
    public Object getItem(int position) {
            return null;
        }

    @Override
    public long getItemId(int position) {
            return 0;
    }
}

employee bean class:

public class EmployeeBean {
    private String empId;
    private String name;
    private String status;

    public EmployeeBean(){      
    }

    public EmployeeBean(String empId, String name, String status) {
        this.empId= empId;
        this.name = name;
        this.status = status;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId= empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status =status;
    }
}

in Activity class:

onCreate method:

public static List<EmployeeBean> EMPLOYEE_LIST = new ArrayList<EmployeeBean>();

//create emplyee data
for(int i=0;i<=10;i++) {
  EmployeeBean emplyee = new EmployeeBean("EmpId"+i,"Name "+i, "Active");
  EMPLOYEE_LIST .add(emplyee );
}

ListView listView;
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ListViewAdapter(this, EMPLOYEE_LIST));

jquery <a> tag click event

All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

You need to add icon.png through visual.

Resouces... / Dravable/ Add ///

onClick function of an input type="button" not working

When I try:

<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!"  />

It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.

Pls try:

<script type="text/javascript">
    function moreFields() {
        alert("The text will be show");
    }
</script>

<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!"  />

Hope it helped.

How do I execute a program from Python? os.system fails due to spaces in path

Here's a different way of doing it.

If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

filepath = 'textfile.txt'
import os
os.startfile(filepath)

Example:

import os
os.startfile('textfile.txt')

This will open textfile.txt with Notepad if Notepad is associated with .txt files.

Java - Get a list of all Classes loaded in the JVM

Well, what I did was simply listing all the files in the classpath. It may not be a glorious solution, but it works reliably and gives me everything I want, and more.

How to get a table creation script in MySQL Workbench?

Solution for MySQL Workbench 6.3E

  • On left panel, right click your table and selecct "Table Inspector"
  • On center panel, click DDL label

How to identify a strong vs weak relationship on ERD?

  1. Weak (Non-Identifying) Relationship

    • Entity is existence-independent of other enties

    • PK of Child doesn’t contain PK component of Parent Entity

  2. Strong (Identifying) Relationship

    • Child entity is existence-dependent on parent

    • PK of Child Entity contains PK component of Parent Entity

    • Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.

How to zoom div content using jquery?

@Gadde - your answer was very helpful. Thank you! I needed a "Maps"-like zoom for a div and was able to produce the feel I needed with your post. My criteria included the need to have the click repeat and continue to zoom out/in with each click. Below is my final result.

    var currentZoom = 1.0;

    $(document).ready(function () {
        $('#btn_ZoomIn').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom += .1 }, 'slow');
            })
        $('#btn_ZoomOut').click(
            function () {
                $('#divName').animate({ 'zoom': currentZoom -= .1 }, 'slow');
            })
        $('#btn_ZoomReset').click(
            function () {
                currentZoom = 1.0
                $('#divName').animate({ 'zoom': 1 }, 'slow');
            })
    });

BAT file to map to network drive without running as admin

Save below in a test.bat and It'll work for you:

@echo off

net use Z: \\server\SharedFolderName password /user:domain\Username /persistent:yes

/persistent:yes flag will tell the computer to automatically reconnect this share on logon. Otherwise, you need to run the script again during each boot to map the drive.

For Example:

net use Z: \\WindowsServer123\g$ P@ssw0rd /user:Mynetdomain\Sysadmin /persistent:yes

What is HTML5 ARIA?

ARIA stands for Accessible Rich Internet Applications.

WAI-ARIA is an incredibly powerful technology that allows developers to easily describe the purpose, state and other functionality of visually rich user interfaces - in a way that can be understood by Assistive Technology. WAI-ARIA has finally been integrated into the current working draft of the HTML 5 specification.

And if you are wondering what WAI-ARIA is, its the same thing.

Please note the terms WAI-ARIA and ARIA refer to the same thing. However, it is more correct to use WAI-ARIA to acknowledge its origins in WAI.

WAI = Web Accessibility Initiative

From the looks of it, ARIA is used for assistive technologies and mostly screen reading.

Most of your doubts will be cleared if you read this article

http://www.w3.org/TR/aria-in-html/

Check if a input box is empty

To auto check a checkbox if input field is not empty.

 <md-content>
            <md-checkbox ng-checked="myField.length"> Other </md-checkbox>
            <input  ng-model="myField" placeholder="Please Specify" type="text">
 </md-content>

How to apply CSS to iframe?

Edit: This does not work cross domain unless the appropriate CORS header is set.

There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:

<iframe name="iframe1" id="iframe1" src="empty.htm" 
        frameborder="0" border="0" cellspacing="0"
        style="border-style: none;width: 100%; height: 120px;"></iframe>

The style of the page embedded in the iframe must be either set by including it in the child page:

<link type="text/css" rel="Stylesheet" href="Style/simple.css" />

Or it can be loaded from the parent page with Javascript:

var cssLink = document.createElement("link");
cssLink.href = "style.css"; 
cssLink.rel = "stylesheet"; 
cssLink.type = "text/css"; 
frames['iframe1'].document.head.appendChild(cssLink);

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

How to load my app from Eclipse to my Android phone instead of AVD

I had the same problem, and have not been able to get Eclipse in Windows 7 to recognise the device. The device is correctly configured, Windows 7 recognises it on the USB port, and I edited the Run settings in Eclipse to prompt for a device, and it is just not there.

I ran it with the following steps:

  • Connect the device to the computer with USB.
  • Ensure the device is not locked (ie. timed out in the UI). I have to keep unlocking it while I'm working.
  • Wait for Windows to recognise the USB device, and when the autoplay menu comes up select Open device to view files. It should open up the file system in the device, in Explorer.
  • In Explorer go to the Eclipse workspace and find the apk file from the build (eg. MyFirstApp.apk)
  • Copy the apk file to the Downloads directory on the device
  • On the device, use the My Files app (or similar) to open the Downloads directory.
  • Click the downloaded file (My First App.apk) and Android offers to install it
  • Select install
  • The app is now in the installed Apps. Run it.

A second method is to mail the apk file to the device and then download and install it. (Credits to a post on SO which I can't find now).

A third method is to use DropBox. This requires installation of DropBox on the PC and on the device (from the play store) but once both are set up it runs very smoothly. Just share a DropBox folder between the two devices, and then drop the APK into that folder on the PC, and open it on the device. With this method you don't need a USB connection, and can also install the APK on multiple devices. It also assists the management of multiple development versions (by making a separate sub-folder for each version).

Can't draw Histogram, 'x' must be numeric

Use the dec argument to set "," as the decimal point by adding:

 ce <- read.table("file.txt", header = TRUE, dec = ",")

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

Key Shortcut for Eclipse Imports

For static import select the field and press Ctrl+Shift+M

java.lang.IllegalArgumentException: View not attached to window manager

I think your code is correct unlike the other answer suggested. onPostExecute will run on the UI thread. That's the whole point of AsyncTask - you don't have to worry about calling runOnUiThread or deal with handlers. Furthermore, according to the docs, dismiss() can be safely called from any thread (not sure they made this the exception).

Perhaps it's a timing issue where dialog.dismiss() is getting called after the activity is no longer displayed?

What about testing what happens if you comment out the setOnCancelListener and then exit the activity while the background task is running? Then your onPostExecute will try to dismiss an already dismissed dialog. If the app crashes you can probably just check if the dialog is open before dismissing it.

I'm having the exact same problem so I'm going to try it out in code.

Angular directives - when and how to use compile, controller, pre-link and post-link

What is the difference between a source template and an instance template?

The fact that Angular allows DOM manipulation means that the input markup into the compilation process sometimes differ from the output. Particularly, some input markup may be cloned a few times (like with ng-repeat) before being rendered to the DOM.

Angular terminology is a bit inconsistent, but it still distinguishes between two types of markups:

  • Source template - the markup to be cloned, if needed. If cloned, this markup will not be rendered to the DOM.
  • Instance template - the actual markup to be rendered to the DOM. If cloning is involved, each instance will be a clone.

The following markup demonstrates this:

<div ng-repeat="i in [0,1,2]">
    <my-directive>{{i}}</my-directive>
</div>

The source html defines

    <my-directive>{{i}}</my-directive>

which serves as the source template.

But as it is wrapped within an ng-repeat directive, this source template will be cloned (3 times in our case). These clones are instance template, each will appear in the DOM and be bound to the relevant scope.

iTunes Connect: How to choose a good SKU?

Might be answer is late but look at Simple Information of SKU (Stock keeping unit) number is, it's an unique tracking number (an arbi­trary num­ber) that are used in appStore for your application. You can put what­ever you want in there as long as it is unique among your appli­ca­tions. Try to fol­low a pat­tern for the SKU Num­ber of your apps so that you will be able to bet­ter orga­nize them. I sug­gest a com­bi­na­tion of the cur­rent year + month + ID for your app. So if you’re devel­op­ing your first appli­ca­tion on september 1991 (oh,, yah it's my b'day's month and year :D ), you could put your SKU Num­ber as “19910901”. Here, I am just suggesting you for this pattern but you can take/choose any pattern which easy for you.

Highlighting Text Color using Html.fromHtml() in Android?

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

Does file_get_contents() have a timeout setting?

Yes! By passing a stream context in the third parameter:

Here with a timeout of 1s:

file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));

Source in comment section of https://www.php.net/manual/en/function.file-get-contents.php

HTTP context options:

method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout

Other contexts: https://www.php.net/manual/en/context.php

'Source code does not match the bytecode' when debugging on a device

You can created AVD, select API Level equal your tagetApi andr compileApi, it works for me.

How to unpublish an app in Google Play Developer Console

  1. Go to your "play.google.com" dashboard
  2. Select your app
  3. In left menu item select "Store presence"
  4. Then, select "Pricing & distribution"
  5. Click "Unpublish" in "App Availability" section

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

How to suppress Pandas Future warning ?

@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.


For those who need to know why...

Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all'). With Pandas 0.23.4, you get the following:

>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)

  warnings.warn(d.msg, FutureWarning)

: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

  warnings.warn(d.msg, FutureWarning)

>>>

Following the @bdiamante's advice, you use the warnings library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In fact, disabling all warnings produces the same output:

>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)


: boolean
    use_inf_as_null had been deprecated and will be removed in a future
    version. Use `use_inf_as_na` instead.

>>>

In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn on the warning messages shows that the pandas warning system is implemented in core/config_init.py:

$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead

Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!

Does MySQL foreign_key_checks affect the entire database?

# will get you the current local (session based) state.
SHOW Variables WHERE Variable_name='foreign_key_checks';

If you didn't SET GLOBAL, only your session was affected.

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

JAXB: how to marshall map into <key>value</key>

I'm still working on a better solution but using MOXy JAXB, I've been able to handle the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <mapProperty>
      <map>
         <key>value</key>
         <key2>value2</key2>
      </map>
   </mapProperty>
</root>

You need to use an @XmlJavaTypeAdapter on your Map property:

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Map<String, String> mapProperty;

    public Root() {
        mapProperty = new HashMap<String, String>();
    }

    @XmlJavaTypeAdapter(MapAdapter.class)
    public Map<String, String> getMapProperty() {
        return mapProperty;
    }

    public void setMapProperty(Map<String, String> map) {
        this.mapProperty = map;
    }

}

The implementation of the XmlAdapter is as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {

    @Override
    public AdaptedMap marshal(Map<String, String> map) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Element rootElement = document.createElement("map");
        document.appendChild(rootElement);

        for(Entry<String,String> entry : map.entrySet()) {
            Element mapElement = document.createElement(entry.getKey());
            mapElement.setTextContent(entry.getValue());
            rootElement.appendChild(mapElement);
        }

        AdaptedMap adaptedMap = new AdaptedMap();
        adaptedMap.setValue(document);
        return adaptedMap;
    }

    @Override
    public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Element rootElement = (Element) adaptedMap.getValue();
        NodeList childNodes = rootElement.getChildNodes();
        for(int x=0,size=childNodes.getLength(); x<size; x++) {
            Node childNode = childNodes.item(x);
            if(childNode.getNodeType() == Node.ELEMENT_NODE) {
                map.put(childNode.getLocalName(), childNode.getTextContent());
            }
        }
        return map;
    }

}

The AdpatedMap class is where all the magic happens, we will use a DOM to represent the content. We will trick JAXB intro dealing with a DOM through the combination of @XmlAnyElement and a property of type Object:

import javax.xml.bind.annotation.XmlAnyElement;

public class AdaptedMap {

    private Object value;

    @XmlAnyElement
    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}

This solution requires the MOXy JAXB implementation. You can configure the JAXB runtime to use the MOXy implementation by adding a file named jaxb.properties in with your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

The following demo code can be used to verify the code:

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(new File("src/forum74/input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}

"Cannot allocate an object of abstract type" error

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

PowerShell Script to Find and Replace for all Files with a Specific Extension

This approach works well:

gci C:\Projects *.config -recurse | ForEach {
  (Get-Content $_ | ForEach {$_ -replace "old", "new"}) | Set-Content $_ 
}
  • Change "old" and "new" to their corresponding values (or use variables).
  • Don't forget the parenthesis -- without which you will receive an access error.

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

Visual Studio 2015 or 2017 does not discover unit tests

Disable Windows Defender Service. Turning this off immediately caused all of my unit tests to show up in Test Explorer.

How to use greater than operator with date?

Adding this since this was not mentioned.

SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');

Because that's what actually works for me. Adding date() function on both comparison values.

How to create Python egg file

For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.

python myapp.zip

Where myapp.zip is a zip containing a __main__.py file which is executed as the script file to be executed. Your package dependencies can also be included in the file:

__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py

You can also execute an egg, but the incantation is not as nice:

# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows 
set PYTHONPATH=myapp.egg
python -m myapp

This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:

myapp/__init__.py
myapp/somelibfile.py

And python will run __init__.py (you should check that __file__=='__main__' in your app for command line use).

Egg files are just zip files so you might be able to add __main__.py to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg instead of the above incantation where the PYTHONPATH environment variable is set.

More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.

How to format numbers by prepending 0 to single-digit numbers?

Improved version of previous answer

_x000D_
_x000D_
function atLeast2Digit(n){_x000D_
    n = parseInt(n); //ex. if already passed '05' it will be converted to number 5_x000D_
    var ret = n > 9 ? "" + n: "0" + n;_x000D_
    return ret;_x000D_
}_x000D_
_x000D_
alert(atLeast2Digit(5));
_x000D_
_x000D_
_x000D_

How to overlay one div over another div

Here is a simple example to bring an overlay effect with a loading icon over another div.

<style>
    #overlay {
        position: absolute;
        width: 100%;
        height: 100%;
        background: black url('icons/loading.gif') center center no-repeat; /* Make sure the path and a fine named 'loading.gif' is there */
        background-size: 50px;
        z-index: 1;
        opacity: .6;
    }
    .wraper{
        position: relative;
        width:400px;  /* Just for testing, remove width and height if you have content inside this div */
        height:500px; /* Remove this if you have content inside */
    }
</style>

<h2>The overlay tester</h2>
<div class="wraper">
    <div id="overlay"></div>
    <h3>Apply the overlay over this div</h3>
</div>

Try it here: http://jsbin.com/fotozolucu/edit?html,css,output

How can git be installed on CENTOS 5.5?

This worked for me on CentOS:

  1. Install dependencies:

    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    
  2. Get Git

    cd /usr/local/src
    wget http://code.google.com/p/git-core/downloads/detail?name=git-1.7.8.3.tar.gz
    tar xvzf git-1.7.8.3.tar.gz
    cd git-1.7.8.3
    
  3. Build Git

    ./configure
    make
    make install
    

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

How to set RelativeLayout layout params in code not in xml?

How about you just pull the layout params from the view itself if you created it.

$((RelativeLayout)findViewById(R.id.imageButton1)).getLayoutParams();

Activating Anaconda Environment in VsCode

Simply use

  1. shift + cmd + P
  2. Search Select Interpreter

pyhton : Select Interpreter

  1. Select it and it will show you the list of your virtual environment created via conda and other python versions

Activating conda virtual environment

  1. select the environment and you are ready to go.

Quoting the 'Select and activate an environment' docs

Selecting an interpreter from the list adds an entry for python.pythonPath with
the path to the interpreter inside your Workspace Settings.

Create a File object in memory from a string in Java

FileReader r = new FileReader(file);

Use a file reader load the file and then write its contents to a string buffer.

example

The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.

How to find a value in an array and remove it by using PHP array functions?

<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>

How do you display a Toast from a background thread on Android?

One approach that works from pretty much anywhere, including from places where you don't have an Activity or View, is to grab a Handler to the main thread and show the toast:

public void toast(final Context context, final String text) {
  Handler handler = new Handler(Looper.getMainLooper());
  handler.post(new Runnable() {
    public void run() {
      Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }
  });
}

The advantage of this approach is that it works with any Context, including Service and Application.

C++ auto keyword. Why is it magic?

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.

It can be very useful when we have to use the iterator. For e.g. for below code we can simply use the "auto" instead of writing the whole iterator syntax .

int main() 
{ 

// Initialize set 
set<int> s; 

s.insert(1); 
s.insert(4); 
s.insert(2); 
s.insert(5); 
s.insert(3); 

// iterator pointing to 
// position where 2 is 
auto pos = s.find(3); 

// prints the set elements 
cout << "The set elements after 3 are: "; 
for (auto it = pos; it != s.end(); it++) 
    cout << *it << " "; 

return 0; 
}

This is how we can use "auto" keyword

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

After failing with cleaning the Credentials from the Manager and clearing the VS cache, consider to repair Visual Studio from the Visual Studio Installer (VS2017). I personally found no other solution working.

How do I check the operating system in Python?

More detailed information are available in the platform module.

Install IPA with iTunes 11

For iTunes 11:

  1. open your iTunes "Side Bar" by going to View -> Show Side Bar
  2. drag the mobileprovision and ipa files to your iTunes "Apps" under LIBRARY
  3. open you device Apps from DEVICES and click install for the application and wait for iTunes to sync

How do I change the formatting of numbers on an axis with ggplot?

I find Jack Aidley's suggested answer a useful one.

I wanted to throw out another option. Suppose you have a series with many small numbers, and you want to ensure the axis labels write out the full decimal point (e.g. 5e-05 -> 0.0005), then:

NotFancy <- function(l) {
 l <- format(l, scientific = FALSE)
 parse(text=l)
}

ggplot(data = data.frame(x = 1:100, 
                         y = seq(from=0.00005,to = 0.0000000000001,length.out=100) + runif(n=100,-0.0000005,0.0000005)), 
       aes(x=x, y=y)) +
     geom_point() +
     scale_y_continuous(labels=NotFancy) 

How to view/delete local storage in Firefox?

To inspect your localStorage items you may type console.log(localStorage); in your javascript console (firebug for example or in new FF versions the shipped js console).

You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:

localStorage.clear();

TypeError: can't pickle _thread.lock objects

You need to change from queue import Queue to from multiprocessing import Queue.

The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.

For details, you can read some source code or contact me!

How do I truncate a .NET string?

I know there are a ton of answers here already, but this is the one I have gone with, which handles both null strings and the situation where the length passed in is negative:

public static string Truncate(this string s, int length)
{
    return string.IsNullOrEmpty(s) || s.Length <= length ? s 
        : length <= 0 ? string.Empty 
        : s.Substring(0, length);
}

ExecJS and could not find a JavaScript runtime

Ubuntu Users

I'm on Ubuntu 11.04 and had similar issues. Installing Node.js fixed it.

As of Ubuntu 13.04 x64 you only need to run:

sudo apt-get install nodejs

This will solve the problem.


CentOS/RedHat Users

sudo yum install nodejs

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

How can I start InternetExplorerDriver using Selenium WebDriver

1---Enable protected mode for all zones You need to enable protected mode for all zones from Internet Options -> Security tab. To enable protected mode for all zones

Open Internet Explorer browser.
Go to menu Tools -> Internet Options.
Click on Security tab.
Select Internet from "Select a zone to view or change security settings" and Select(check) check box "Enable Protected Mode" from In the "Security level for this zone" block .
Apply same thing for all other 3 zones -> Local Internet, Trusted Sites and Restricted Sites

This setting will resolve error related to "Protected Mode settings are not the same for all zones.

2-- Set IE browser's zoom level 100%

Open Internet Explorer browser.
Go to menu View -> Zoom -> Select 100%

Append TimeStamp to a File Name

Perhaps appending DateTime.Now.Ticks instead, is a tiny bit faster since you won't be creating 3 strings and the ticks value will always be unique also.

Android custom Row Item for ListView

Add this row.xml to your layout folder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Header"/>

<TextView 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text"/>
    
    
</LinearLayout>

make your main xml layout as this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

This is your adapter

class yourAdapter extends BaseAdapter {

    Context context;
    String[] data;
    private static LayoutInflater inflater = null;

    public yourAdapter(Context context, String[] data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView text = (TextView) vi.findViewById(R.id.text);
        text.setText(data[position]);
        return vi;
    }
}

Your java activity

public class StackActivity extends Activity {

    ListView listview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(new yourAdapter(this, new String[] { "data1",
                "data2" }));
    }
}

the results

enter image description here

jQuery remove options from select

When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)

$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list

concatenate char array in C

First copy the current string to a larger array with strcpy, then use strcat.

For example you can do:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

window.location (JS) vs header() (PHP) for redirection

The result is same for all options. Redirect.

<meta> in HTML:

  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Don't need JavaScript enabled.
  • Don't need PHP.

window.location in JS:

  • Javascript enabled needed.
  • Don't need PHP.
  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Redirect can be dependent on any conditions if (1 === 1) { window.location.href = 'http://example.com'; }.

header('Location:') in PHP:

  • Don't need JavaScript enabled.
  • PHP needed.
  • Redirect will be executed first, user never see what is after. header() must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

You are missing setter for salt property as indicated by the exception

Please add the setter as

 public void setSalt(long salt) {
      this.salt=salt;
 }

SQL, Postgres OIDs, What are they and why are they useful?

OID's are still in use for Postgres with large objects (though some people would argue large objects are not generally useful anyway). They are also used extensively by system tables. They are used for instance by TOAST which stores larger than 8KB BYTEA's (etc.) off to a separate storage area (transparently) which is used by default by all tables. Their direct use associated with "normal" user tables is basically deprecated.

The oid type is currently implemented as an unsigned four-byte integer. Therefore, it is not large enough to provide database-wide uniqueness in large databases, or even in large individual tables. So, using a user-created table's OID column as a primary key is discouraged. OIDs are best used only for references to system tables.

Apparently the OID sequence "does" wrap if it exceeds 4B 6. So in essence it's a global counter that can wrap. If it does wrap, some slowdown may start occurring when it's used and "searched" for unique values, etc.

See also https://wiki.postgresql.org/wiki/FAQ#What_is_an_OID.3F

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I had the same error. It is solved by following steps

Go to IIS -> find your site -> right click on the site -> Manage Website -> Advanced Setting -> Check your physical path is correct or not.

If it is wrong, locate the correct path. This will solve issue.

hadoop copy a local file system folder to HDFS

You could try:

hadoop fs -put /path/in/linux /hdfs/path

or even

hadoop fs -copyFromLocal /path/in/linux /hdfs/path

By default both put and copyFromLocal would upload directories recursively to HDFS.

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Send JSON data with jQuery

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

From the jQuery docs for $.ajax:

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

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

data: JSON.stringify(arr);

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

Selecting only first-level elements in jquery

I had some trouble with nested classes from any depth so I figured this out. It will select only the first level it encounters of a containing Jquery Object:

_x000D_
_x000D_
var $elementsAll = $("#container").find(".fooClass");4_x000D_
_x000D_
var $levelOneElements = $elementsAll.not($elementsAll.children().find($elementsAll));_x000D_
_x000D_
$levelOneElements.css({"color":"red"})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div class="fooClass" style="color:black">_x000D_
Container_x000D_
  <div id="container">_x000D_
    <div class="fooClass" style="color:black">_x000D_
      Level One_x000D_
      <div>_x000D_
        <div class="fooClass" style="color:black">_x000D_
             Level Two_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="fooClass" style="color:black">_x000D_
      Level One_x000D_
      <div>_x000D_
        <div class="fooClass" style="color:black">_x000D_
             Level Two_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ReflectionException: Class ClassName does not exist - Laravel

I had this problem and I could solve it by doing php artisan config:cache. The problem was that I had already run that command previously and later included some new seeder classes. The cached configurations didn't recognize the new classes. So running that command again worked.

If you see yourself making frequent changes to include new seeder classes then consider running php artisan config:clear. This will enable you to make as many changes as you'd like and then after testing you can run config:cache again to make things run optimally again.

Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.

In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.

It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.

Dynamic creation of table with DOM

var html = "";
    for (var i = 0; i < data.length; i++){
    html +="<tr>"+
            "<td>"+ (i+1) + "</td>"+
            "<td>"+ data[i].name + "</td>"+
            "<td>"+ data[i].number + "</td>"+
            "<td>"+ data[i].city + "</td>"+
            "<td>"+ data[i].hobby + "</td>"+
            "<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);

'dict' object has no attribute 'has_key'

Try:

if start not in graph:

For more info see ProgrammerSought

How to force file download with PHP

you can use download attribute to force download a file:

_x000D_
_x000D_
<a href="https://test.com/aaa.exe" download>click here to download</a>
_x000D_
_x000D_
_x000D_

How do I import a .sql file in mysql database using PHP?

Warning: mysql_* extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.

the answer from Raj is useful, but (because of file($filename)) it will fail if your mysql-dump not fits in memory

If you are on shared hosting and there are limitations like 30 MB and 12s Script runtime and you have to restore a x00MB mysql dump, you can use this script:

it will walk the dumpfile query for query, if the script execution deadline is near, it saves the current fileposition in a tmp file and a automatic browser reload will continue this process again and again ... If an error occurs, the reload will stop and an the error is shown ...

if you comeback from lunch your db will be restored ;-)

the noLimitDumpRestore.php:

// your config
$filename = 'yourGigaByteDump.sql';
$dbHost = 'localhost';
$dbUser = 'user';
$dbPass = '__pass__';
$dbName = 'dbname';
$maxRuntime = 8; // less then your max script execution limit


$deadline = time()+$maxRuntime; 
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro

mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());

($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);

// check for previous error
if( file_exists($errorFilename) ){
    die('<pre> previous error: '.file_get_contents($errorFilename));
}

// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';

// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
    $filePosition = file_get_contents($progressFilename);
    fseek($fp, $filePosition);
}

$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
    if(substr($line,0,2)=='--' OR trim($line)=='' ){
        continue;
    }

    $query .= $line;
    if( substr(trim($query),-1)==';' ){
        if( !mysql_query($query) ){
            $error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
            file_put_contents($errorFilename, $error."\n");
            exit;
        }
        $query = '';
        file_put_contents($progressFilename, ftell($fp)); // save the current file position for 
        $queryCount++;
    }
}

if( feof($fp) ){
    echo 'dump successfully restored!';
}else{
    echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
    echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}

push multiple elements to array

When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.

In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))

Built in Python hash() function

The response is absolutely no surprise: in fact

In [1]: -5768830964305142685L & 0xffffffff
Out[1]: 1934711907L

so if you want to get reliable responses on ASCII strings, just get the lower 32 bits as uint. The hash function for strings is 32-bit-safe and almost portable.

On the other side, you can't rely at all on getting the hash() of any object over which you haven't explicitly defined the __hash__ method to be invariant.

Over ASCII strings it works just because the hash is calculated on the single characters forming the string, like the following:

class string:
    def __hash__(self):
        if not self:
            return 0 # empty
        value = ord(self[0]) << 7
        for char in self:
            value = c_mul(1000003, value) ^ ord(char)
        value = value ^ len(self)
        if value == -1:
            value = -2
        return value

where the c_mul function is the "cyclic" multiplication (without overflow) as in C.

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

C# Return Different Types?

If there is no common base-type or interface, then public object GetAnything() {...} - but it would usually be preferable to have some kind of abstraction such as a common interface. For example if Hello, Computer and Radio all implemented IFoo, then it could return an IFoo.

Converting between java.time.LocalDateTime and java.util.Date

the following seems to work when converting from new API LocalDateTime into java.util.date:

Date.from(ZonedDateTime.of({time as LocalDateTime}, ZoneId.systemDefault()).toInstant());

the reverse conversion can be (hopefully) achieved similar way...

hope it helps...

How can I run a windows batch file but hide the command window?

Using C# it's very easy to start a batch command without having a window open. Have a look at the following code example:

        Process process = new Process();
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.FileName = "doSomeBatch.bat";
        process.Start();

Find duplicate records in a table using SQL Server

Try this

with T1 AS
(
SELECT LASTNAME, COUNT(1) AS 'COUNT' FROM Employees GROUP BY LastName HAVING  COUNT(1) > 1
)
SELECT E.*,T1.[COUNT] FROM Employees E INNER JOIN T1 ON T1.LastName = E.LastName

How to find out if an item is present in a std::vector?

If your vector is not ordered, use the approach MSN suggested:

if(std::find(vector.begin(), vector.end(), item)!=vector.end()){
      // Found the item
}

If your vector is ordered, use binary_search method Brian Neal suggested:

if(binary_search(vector.begin(), vector.end(), item)){
     // Found the item
}

binary search yields O(log n) worst-case performance, which is way more efficient than the first approach. In order to use binary search, you may use qsort to sort the vector first to guarantee it is ordered.

How to make a cross-module variable?

This sounds like modifying the __builtin__ name space. To do it:

import __builtin__
__builtin__.foo = 'some-value'

Do not use the __builtins__ directly (notice the extra "s") - apparently this can be a dictionary or a module. Thanks to ??O????? for pointing this out, more can be found here.

Now foo is available for use everywhere.

I don't recommend doing this generally, but the use of this is up to the programmer.

Assigning to it must be done as above, just setting foo = 'some-other-value' will only set it in the current namespace.

minimize app to system tray

At the click on the image in System tray, you can verify if the frame is visible and then you have to set Visible = true or false

Chrome: Uncaught SyntaxError: Unexpected end of input

In cases where your JavaScript code is minified to a single line, another cause for this error is using // instead of /**/ for your comments.

Bad (comments out everything after // including the closing } for your function)

function example() { //comment console.log('TEST'); }

Good (confines your comment)

function example() { /* comment */ console.log('TEST'); }

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

jQuery: If this HREF contains

$("a").each(function() {
    if (this.href.indexOf('?') != -1) {
        alert("Contains questionmark");
    }
});

Filtering Sharepoint Lists on a "Now" or "Today"

If you want to filter only items that are less than 7 days old then you just use

Filter

  • Created

  • is greater than or equal to

  • [Today]-7

Note - the screenshot is incorrect.

New items - created in last 7 days

[Today] is fully supported in view filters in 2007 and onwards (just keep the spaces out!) and you only need to muck around with calculated columns in 2003.

Arduino error: does not name a type?

The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!

Two notes from experience which might be helpful:

  1. You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.

  2. If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.

angular2: how to copy object into another object

As suggested before, the clean way of deep copying objects having nested objects inside is by using lodash's cloneDeep method.

For Angular, you can do it like this:

Install lodash with yarn add lodash or npm install lodash.

In your component, import cloneDeep and use it:

import * as cloneDeep from 'lodash/cloneDeep';
...
clonedObject = cloneDeep(originalObject);

It's only 18kb added to your build, well worth for the benefits.

I've also written an article here, if you need more insight on why using lodash's cloneDeep.

Submit form using a button outside the <form> tag

I used this way, and kind liked it , it validates the form before submit also is compatible with safari/google. no jquery n.n.

        <module-body>
            <form id="testform" method="post">
                <label>Input Title</label>
                <input name="named1" placeholder="Placeholder"  title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>

                <label>Input Title</label>
                <input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>

                <label>Input Title</label>
                <input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
                <alert>No Alerts!</alert>
            </form>
        </module-body>
        <module-footer>
            <input type="button" onclick='if (document.querySelector("#testform").reportValidity()) { document.querySelector("#testform").submit(); }' value="Submit">
            <input type="button" value="Reset">
        </module-footer>

mssql convert varchar to float

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED

above will return values

however below query wont work

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED

as @INPUT_1 actually has varchar in it.

So your output column must have a varchar in it.

PHP compare time

$ThatTime ="14:08:10";
if (time() >= strtotime($ThatTime)) {
  echo "ok";
}

A solution using DateTime (that also regards the timezone).

$dateTime = new DateTime($ThatTime);
if ($dateTime->diff(new DateTime)->format('%R') == '+') {
  echo "OK";
}

http://php.net/datetime.diff

How do I specify new lines on Python, when writing on files?

It depends on how correct you want to be. \n will usually do the job. If you really want to get it right, you look up the newline character in the os package. (It's actually called linesep.)

Note: when writing to files using the Python API, do not use the os.linesep. Just use \n; Python automatically translates that to the proper newline character for your platform.

How to use google maps without api key

this simple code work 100% all you need is changing 'lat','long' for address to show

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

Cancel a vanilla ECMAScript 6 Promise chain

Promise can be cancelled with the help of AbortController.

Is there a method for clearing then: yes you can reject the promise with AbortController object and then the promise will bypass all then blocks and go directly to the catch block.

Example:

import "abortcontroller-polyfill";

let controller = new window.AbortController();
let signal = controller.signal;
let elem = document.querySelector("#status")

let example = (signal) => {
    return new Promise((resolve, reject) => {
        let timeout = setTimeout(() => {
            elem.textContent = "Promise resolved";
            resolve("resolved")
        }, 2000);

        signal.addEventListener('abort', () => {
            elem.textContent = "Promise rejected";
            clearInterval(timeout);
            reject("Promise aborted")
        });
    });
}

function cancelPromise() {
    controller.abort()
    console.log(controller);
}

example(signal)
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log("Catch: ", error)
    });

document.getElementById('abort-btn').addEventListener('click', cancelPromise);

Html


    <button type="button" id="abort-btn" onclick="abort()">Abort</button>
    <div id="status"> </div>

Note: need to add polyfill, not supported in all browser.

Live Example

Edit elegant-lake-5jnh3

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

Getting full URL of action in ASP.NET MVC

As Paddy mentioned: if you use an overload of UrlHelper.Action() that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.

I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:

/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
    string actionName, string controllerName, object routeValues = null)
{
    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

    return url.Action(actionName, controllerName, routeValues, scheme);
}

You can then simply use it like that in your view:

@Url.AbsoluteAction("Action", "Controller")

What SOAP client libraries exist for Python, and where is the documentation for them?

Update (2016):

If you only need SOAP client, there is well maintained library called zeep. It supports both Python 2 and 3 :)


Update:

Additionally to what is mentioned above, I will refer to Python WebServices page which is always up-to-date with all actively maintained and recommended modules to SOAP and all other webservice types.


Unfortunately, at the moment, I don't think there is a "best" Python SOAP library. Each of the mainstream ones available has its own pros and cons.

Older libraries:

  • SOAPy: Was the "best," but no longer maintained. Does not work on Python 2.5+

  • ZSI: Very painful to use, and development is slow. Has a module called "SOAPpy", which is different than SOAPy (above).

"Newer" libraries:

  • SUDS: Very Pythonic, and easy to create WSDL-consuming SOAP clients. Creating SOAP servers is a little bit more difficult. (This package does not work with Python3. For Python3 see SUDS-py3)

  • SUDS-py3: The Python3 version of SUDS

  • spyne: Creating servers is easy, creating clients a little bit more challenging. Documentation is somewhat lacking.

  • ladon: Creating servers is much like in soaplib (using a decorator). Ladon exposes more interfaces than SOAP at the same time without extra user code needed.

  • pysimplesoap: very lightweight but useful for both client and server - includes a web2py server integration that ships with web2py.

  • SOAPpy: Distinct from the abandoned SOAPpy that's hosted at the ZSI link above, this version was actually maintained until 2011, now it seems to be abandoned too.
  • soaplib: Easy to use python library for writing and calling soap web services. Webservices written with soaplib are simple, lightweight, work well with other SOAP implementations, and can be deployed as WSGI applications.
  • osa: A fast/slim easy to use SOAP python client library.

Of the above, I've only used SUDS personally, and I liked it a lot.

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

How to update/upgrade a package using pip?

The way is

pip install [package_name] --upgrade

or in short

pip install [package_name] -U

Using sudo will ask to enter your root password to confirm the action, but although common, is considered unsafe.

If you do not have a root password (if you are not the admin) you should probably work with virtualenv.

You can also use the user flag to install it on this user only.

pip install [package_name] --upgrade --user

How do I calculate someone's age in Java?

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.Period;

public class AgeCalculator1 {

    public static void main(String args[]) {
        LocalDate start = LocalDate.of(1970, 2, 23);
        LocalDate end = LocalDate.now(ZoneId.systemDefault());

        Period p = Period.between(start, end);
        //The output of the program is :
        //45 years 6 months and 6 days.
        System.out.print(p.getYears() + " year" + (p.getYears() > 1 ? "s " : " ") );
        System.out.print(p.getMonths() + " month" + (p.getMonths() > 1 ? "s and " : " and ") );
        System.out.print(p.getDays() + " day" + (p.getDays() > 1 ? "s.\n" : ".\n") );
    }//method main ends here.
}

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

SIMPLE SOLUTION

  1. Create a new blank project and save it
  2. using NOTEPAD open the .VBP of the new project and copy the MSCOMCTL line
  3. using NOTEPAD open the .VBP file of your project
  4. replace the MSCOMCTL line and save it

DONE

good luck

Get checkbox value in jQuery

Use the following code:

$('input[name^=CheckBoxInput]').val();

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How to pause in C?

you can put

getchar();

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.

Line break in HTML with '\n'

As per your question, it can be done by various ways: - For example you can use:

If you want to insert a new line in text area , you can try this:-

&#10; Line Feed and &#13;Carriage return

<textarea>Hello &#10;&#13;Stackoverflow</textarea>

You can also <pre>---</pre> Preformatted text.

<pre>
     This is Line1
     This is Line2
     This is Line3
</pre>

Or,you can use <p>----</p> Paragraph

<p>This is Line1</p>

<p>This is Line2</p>

<p>This is Line3</p>

Note: if you want to use \n you need to install a server like Xampp or Apache to support server side language

How can I debug a HTTP POST in Chrome?

You can filter for HTTP POST requests with the Chrome DevTools. Just do the following:

  1. Open Chrome DevTools (Cmd+Opt+I on Mac, Ctrl+Shift+I or F12 on Windows) and click on the "Network" tab
  2. Click on the "Filter" icon
  3. Enter your filter method: method:POST
  4. Select the request you want to debug
  5. View the details of the request you want to debug

Screenshot

Chrome DevTools

Tested with Chrome Version 53.

How to check if a string contains text from an array of substrings in JavaScript?

You can check like this:

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
         var list = ["bad", "words", "include"] 
         var sentence = $("#comments_text").val()

         $.each(list, function( index, value ) {
           if (sentence.indexOf(value) > -1) {
                console.log(value)
            }
         });
         });
      </script>
   </head>
   <body>
      <input id="comments_text" value="This is a bad, with include test"> 
   </body>
</html>

Google Maps: Auto close open InfoWindows?

How about -

google.maps.event.addListener(yourMarker, 'mouseover', function () {
        yourInfoWindow.open(yourMap, yourMarker);

    });

google.maps.event.addListener(yourMarker, 'mouseout', function () {
        yourInfoWindow.open(yourMap, yourMarker);

    });

Then you can just hover over it and it will close itself.

VB.NET: how to prevent user input in a ComboBox

this is the most simple way but it works for me with a ComboBox1 name

SOLUTION on 3 Basic STEPS:

step 1.

Declare a variable at the beginning of your form which will hold the original text value of the ComboBox. Example:

     Dim xCurrentTextValue as string

step 2.

Create the event combobox1 key down and Assign to xCurrentTextValue variable the current text of the combobox if any key diferrent than "ENTER" is pressed the combobox text value keeps the original text value

Example:

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyDown

    xCurrentTextValue = ComboBox1.Text

    If e.KeyCode <> Keys.Enter Then
        Me.ComboBox1.Text = xCmbItem
    End If

End Sub

step 3.

Validate the when the combo text is changed if len(xcurrenttextvalue)> 0 or is different than nothing then the combobox1 takes the xcurrenttextvalue variable value

Private Sub ComboBox1_TextChanged(sender As Object, e As EventArgs) Handles ComboBox1.TextChanged
    If Len(xCurrentTextValue) > 0 Then
        Me.ComboBox1.Text = xCurrentTextValue

    End If
End Sub

========================================================== that's it,

Originally I only tried the step number 2, but I have problems when you press the DEL key and DOWN arrow key, also for some reason it didn't validate the keydown event unless I display any message box


!Sorry, this is a correction on step number 2, I forgot to change the variable xCmbItem to xCurrentTextValue, xCmbItem it was used for my personal use

THIS IS THE CORRECT CODE

xCurrentTextValue = ComboBox1.Text

If e.KeyCode <> Keys.Enter Then
    Me.ComboBox1.Text = xCurrentTextValue
End If

How can I add a help method to a shell script?

The first argument to a shell script is available as the variable $1, so the simplest implementation would be

if [ "$1" == "-h" ]; then
  echo "Usage: `basename $0` [somestuff]"
  exit 0
fi

But what anubhava said.

How do I make the text box bigger in HTML/CSS?

If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>).

Text areas are resizable by default. If you want to disable that, just use the resize css rule:

#signin textarea {
    resize: none;
}

A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input> tags as well.

<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>

This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.

Create component to specific module with Angular-CLI

To create a component as part of a module you should

  1. ng g module newModule to generate a module,
  2. cd newModule to change directory into the newModule folder
  3. ng g component newComponent to create a component as a child of the module.

UPDATE: Angular 9

Now it doesn't matter what folder you are in when generating the component.

  1. ng g module NewMoudle to generate a module.
  2. ng g component new-module/new-component to create NewComponent.

Note: When the Angular CLI sees new-module/new-component, it understands and translates the case to match new-module -> NewModule and new-component -> NewComponent. It can get confusing in the beginning, so easy way is to match the names in #2 with the folder names for the module and component.

Number of processors/cores in command line

I think the method you give is the most portable on Linux. Instead of spawning unnecessary cat and wc processes, you can shorten it a bit:

$ grep --count ^processor /proc/cpuinfo
2

jquery change class name

So you want to change it WHEN it's clicked...let me go through the whole process. Let's assume that your "External DOM Object" is an input, like a select:

Let's start with this HTML:

<body>
  <div>
    <select id="test">
      <option>Bob</option>
      <option>Sam</option>
      <option>Sue</option>
      <option>Jen</option>
    </select>
  </div>

  <table id="theTable">
    <tr><td id="cellToChange">Bob</td><td>Sam</td></tr>
    <tr><td>Sue</td><td>Jen</td></tr>
  </table>
</body>

Some very basic CSS:

?#theTable td {
    border:1px solid #555;
}
.activeCell {
    background-color:#F00;
}

And set up a jQuery event:

function highlightCell(useVal){
  $("#theTable td").removeClass("activeCell")
      .filter(":contains('"+useVal+"')").addClass("activeCell");
}

$(document).ready(function(){
    $("#test").change(function(e){highlightCell($(this).val())});
});

Now, whenever you pick something from the select, it will automatically find a cell with the matching text, allowing you to subvert the whole id-based process. Of course, if you wanted to do it that way, you could easily modify the script to use IDs rather than values by saying

.filter("#"+useVal)

and make sure to add the ids appropriately. Hope this helps!

Generate Json schema from XML schema (XSD)

True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).

Get month name from Date

It is now possible to do this with the ECMAScript Internationalization API:

_x000D_
_x000D_
const date = new Date(2009, 10, 10);  // 2009-11-10_x000D_
const month = date.toLocaleString('default', { month: 'long' });_x000D_
console.log(month);
_x000D_
_x000D_
_x000D_

'long' uses the full name of the month, 'short' for the short name, and 'narrow' for a more minimal version, such as the first letter in alphabetical languages.

You can change the locale from browser's 'default' to any that you please (e.g. 'en-us'), and it will use the right name for that language/country.

With toLocaleStringapi you have to pass in the locale and options each time. If you are going do use the same locale info and formatting options on multiple different dates, you can use Intl.DateTimeFormat instead:

_x000D_
_x000D_
const formatter = new Intl.DateTimeFormat('fr', { month: 'short' });_x000D_
const month1 = formatter.format(new Date());_x000D_
const month2 = formatter.format(new Date(2003, 5, 12));_x000D_
console.log(`${month1} and ${month2}`); // current month in French and "juin".
_x000D_
_x000D_
_x000D_

For more information see my blog post on the Internationalization API.

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

How to easily consume a web service from PHP

This article explains how you can use PHP SoapClient to call a api web service.

How to get history on react-router v4?

This works! https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);

TypeError: Can't convert 'int' object to str implicitly

You cannot concatenate a string with an int. You would need to convert your int to a string using the str function, or use formatting to format your output.

Change: -

print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")

to: -

print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))

or: -

print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")

or as per the comment, use , to pass different strings to your print function, rather than concatenating using +: -

print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")

How to use export with Python on Linux

Not that simple:

python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty

But:

python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

You can get your custom GMT time from this function from here

  public static String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd hh:mm a zzz");
        Date date = new Date();
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+6:00"));
        return sdf.format(date);
    }

How do I split a multi-line string into multiple lines?

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

How can I make a JPA OneToOne relation lazy

First off, some clarifications to KLE's answer:

  1. Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. Here's a more detailed explanation.

  2. many-to-one associations (and one-to-many, obviously) do not suffer from this issue. Owner entity can easily check its own FK (and in case of one-to-many, empty collection proxy is created initially and populated on demand), so the association can be lazy.

  3. Replacing one-to-one with one-to-many is pretty much never a good idea. You can replace it with unique many-to-one but there are other (possibly better) options.

Rob H. has a valid point, however you may not be able to implement it depending on your model (e.g. if your one-to-one association is nullable).

Now, as far as original question goes:

A) @ManyToOne(fetch=FetchType.LAZY) should work just fine. Are you sure it's not being overwritten in the query itself? It's possible to specify join fetch in HQL and / or explicitly set fetch mode via Criteria API which would take precedence over class annotation. If that's not the case and you're still having problems, please post your classes, query and resulting SQL for more to-the-point conversation.

B) @OneToOne is trickier. If it's definitely not nullable, go with Rob H.'s suggestion and specify it as such:

@OneToOne(optional = false, fetch = FetchType.LAZY)

Otherwise, if you can change your database (add a foreign key column to owner table), do so and map it as "joined":

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="other_entity_fk")
public OtherEntity getOther()

and in OtherEntity:

@OneToOne(mappedBy = "other")
public OwnerEntity getOwner()

If you can't do that (and can't live with eager fetching) bytecode instrumentation is your only option. I have to agree with CPerkins, however - if you have 80!!! joins due to eager OneToOne associations, you've got bigger problems then this :-)

What is the difference between fastcgi and fpm?

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable

whereas

PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments

However, there are pros and cons to both and one should choose as per their specific use case.

I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.

converting json to string in python

json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

But the dumps() would convert None into null making a valid JSON string that can be loaded:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

scrollable div inside container

The simplest way is as this example:

<div>
   <div style=' height:300px;'>
     SOME LOGO OR CONTENT HERE
   </div>
   <div style='overflow-x: hidden;overflow-y: scroll;'> 
      THIS IS SOME TEXT
   </DIV>

You can see the test cases on: https://www.w3schools.com/css/css_overflow.asp

Downcasting in Java

Using your example, you could do:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();
}

Better way to represent array in java properties file

Actually all answers are wrong

Easy: foo.[0]filename

"Parser Error Message: Could not load type" in Global.asax

My app was built in an older version of VS, and didn't have a bin folder. I had upgraded it to a newer version, and had a nightmare getting it to deploy. I finally tracked this error down to the Project > Properties > Application. The Target Framework was set to 2.0; changing it on the server to match in the IIS Manager/App Pool solved the issue for me.

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

get the margin size of an element with jquery

The CSS tag 'margin' is actually a shorthand for the four separate margin values, top/left/bottom/right. Use css('marginTop'), etc. - note they will have 'px' on the end if you have specified them that way.

Use parseInt() around the result to turn it in to the number value.

NB. As noted by Omaty, the order of the shorthand 'margin' tag is: top right bottom left - the above list was not written in a way intended to be the list order, just a list of that specified in the tag.

How to add style from code behind?

try this

 lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";

How do I install PHP cURL on Linux Debian?

Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version and see the versions.

Here's what I did to get the latest curl version installed in Ubuntu:

  1. sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
  2. sudo apt-get update
  3. sudo apt-get install curl

How to initialize an array in angular2 and typescript

You can use this construct:

export class AppComponent {

    title:string;
    myHero:string;
    heroes: any[];

    constructor() {
       this.title = 'Tour of Heros';
       this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
       this.myHero = this.heroes[0];
    }
}

400 BAD request HTTP error code meaning?

Selecting a HTTP response code is quite an easy task and can be described by simple rules. The only tricky part which is often forgotten is paragraph 6.5 from RFC 7231:

Except when responding to a HEAD request, the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.

Rules are as following:

  1. If request was successful, then return 2xx code (3xx for redirect). If there was an internal logic error on a server, then return 5xx. If there is anything wrong in client request, then return 4xx code.
  2. Look through available response code from selected category. If one of them has a name which matches well to your situation, you can use it. Otherwise just fallback to x00 code (200, 400, 500). If you doubt, fallback to x00 code.
  3. Return error description in response body. For 4xx codes it must contain enough information for client developer to understand the reason and fix the client. For 5xx because of security reasons no details must be revealed.
  4. If client needs to distinguish different errors and have different reaction depending on it, define a machine readable and extendible error format and use it everywhere in your API. It is good practice to make that from very beginning.
  5. Keep in mind that client developer may do strange things and try to parse strings which you return as human readable description. And by changing the strings you will break such badly written clients. So always provide machine readable description and try to avoid reporting additional information in text.

So in your case I'd returned 400 error and something like this if "Roman" is obtained from user input and client must have specific reaction:

{
    "error_type" : "unsupported_resource",
    "error_description" : "\"Roman\" is not supported"
}

or a more generic error, if such situation is a bad logic error in a client and is not expected, unless developer made something wrong:

{
    "error_type" : "malformed_json",
    "error_description" : "\"Roman\" is not supported for \"requestedResource\" field"
}

vertical align middle in <div>

Use the translateY CSS property to vertically center your text in it's container

<style>
.centertext{

    position: relative;
    top: 50%;
    transform: translateY(40%);

}
</style>

And then apply it to your containing DIV

  <div class="centertext">
        <font style="color:white; font-size:20px;">   Your Text Here </font>
  </div>

Adjust the translateY percentage to suit your needs. Hope this helps

MySQL: determine which database is selected?

SELECT DATABASE() worked in PHPMyAdmin.

What is InputStream & Output Stream? Why and when do we use them?

OutputStream is an abstract class that represents writing output. There are many different OutputStream classes, and they write out to certain things (like the screen, or Files, or byte arrays, or network connections, or etc). InputStream classes access the same things, but they read data in from them.

Here is a good basic example of using FileOutputStream and FileInputStream to write data to a file, then read it back in.

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Insert HTML with React Variable Statements (JSX)

To avoid linter errors, I use it like this:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

Classpath including JAR within a JAR

Extracting into an Uber-dir works for me as we s should all be using root:\java and have outlets code in packages with versioning. Ie ca.tecreations-1.0.0. Signing is okay because the jars are intact from their downloaded location. 3rd party signatures intact, extract to c:\java. There’s my project dir. run from launcher so java -cp c:\java Launcher

Flutter plugin not installed error;. When running flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[?] Flutter (Channel beta, v0.9.4, on Linux, locale en_IN)
[?] Android toolchain - develop for Android devices (Android SDK 28.0.1)
[?] Android Studio (version 3.1)
    ? Flutter plugin not installed; this adds Flutter specific functionality.
    ? Dart plugin not installed; this adds Dart specific functionality.
[!] Connected devices
    ! No devices available

Solution that worked for me:

  1. Just install plugins.
    Studio>>File>Settings>Plugins>Browse Repositories
  2. Search for flutter.
  3. Tap on Install (a dialog will pop regarding dart dependency. click Yes).
  4. Once the installation is finished restart android studio.

enter image description here

Now run flutter doctor.

Doctor summary (to see all details, run flutter doctor -v):
[?] Flutter (Channel beta, v0.9.4, on Linux, locale en_IN)
[?] Android toolchain - develop for Android devices (Android SDK 28.0.1)
[?] Android Studio (version 3.1)
[!] Connected devices
    ! No devices available

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

MySQL Workbench Edit Table Data is read only

1.)You have to make the primary key unique, then you should be able to edit.

right click on you table in the "blue" schemas ->ALTER TABLE, look for your primert key (PK), then just check the check-box, UN, the AI should already be checked. After that just apply and you should be able to edit the table data.

2.)You also need to include the primery key I your select statement

Nr 1 is not really necessary, but a good practice.

Why am I getting AttributeError: Object has no attribute

I got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.

Call a Vue.js component method from outside the component

Sometimes you want to keep these things contained within your component. Depending on DOM state (the elements you're listening on must exist in DOM when your Vue component is instantiated), you can listen to events on elements outside of your component from within your Vue component. Let's say there is an element outside of your component, and when the user clicks it, you want your component to respond.

In html you have:

<a href="#" id="outsideLink">Launch the component</a>
...
<my-component></my-component>

In your Vue component:

    methods() {
      doSomething() {
        // do something
      }
    },
    created() {
       document.getElementById('outsideLink').addEventListener('click', evt => 
       {
          this.doSomething();
       });
    }
    

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

Push commits to another branch

_x000D_
_x000D_
git init _x000D_
#git remote remove origin_x000D_
git remote add origin  <http://...git>_x000D_
echo "This is for demo" >> README.md _x000D_
git add README.md_x000D_
git commit -m "Initail Commit" _x000D_
git checkout -b branch1 _x000D_
git branch --list_x000D_
****add files***_x000D_
git add -A_x000D_
git status_x000D_
git commit -m "Initial - branch1"_x000D_
git push --set-upstream origin branch1_x000D_
#git push origin --delete  branch1_x000D_
#git branch --unset-upstream  
_x000D_
_x000D_
_x000D_

How to define an optional field in protobuf 3

To expand on @cybersnoopy 's suggestion here

if you had a .proto file with a message like so:

message Request {
    oneof option {
        int64 option_value = 1;
    }
}

You can make use of the case options provided (java generated code):

So we can now write some code as follows:

Request.OptionCase optionCase = request.getOptionCase();
OptionCase optionNotSet = OPTION_NOT_SET;

if (optionNotSet.equals(optionCase)){
    // value not set
} else {
    // value set
}

How to output MySQL query results in CSV format?

From http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Using this command columns names will not be exported.

Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

Set cURL to use local virtual hosts

Actually, curl has an option explicitly for this: --resolve

Instead of curl -H 'Host: yada.com' http://127.0.0.1/something

use curl --resolve 'yada.com:80:127.0.0.1' http://yada.com/something

What's the difference, you ask?

Among others, this works with HTTPS. Assuming your local server has a certificate for yada.com, the first example above will fail because the yada.com certificate doesn't match the 127.0.0.1 hostname in the URL.

The second example works correctly with HTTPS.

In essence, passing a "Host" header via -H does hack your Host into the header set, but bypasses all of curl's host-specific intelligence. Using --resolve leverages all of the normal logic that applies, but simply pretends the DNS lookup returned the data in your command-line option. It works just like /etc/hosts should.

Note --resolve takes a port number, so for HTTPS you would use

curl --resolve 'yada.com:443:127.0.0.1' https://yada.com/something

Converting string to tuple without splitting characters

See:

'Quattro TT'

is a string.

Since string is a list of characters, this is the same as

['Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T']

Now...

['Quattro TT']

is a list with a string in the first position.

Also...

a = 'Quattro TT'

list(a)

is a string converted into a list.

Again, since string is a list of characters, there is not much change.

Another information...

tuple(something)

This convert something into tuple.

Understanding all of this, I think you can conclude that nothing fails.

"OverflowError: Python int too large to convert to C long" on windows but not mac

Could anyone help explain why

In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.

The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.

or give a solution for the code on windows? Thanks so much!

Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64

Gson library in Android Studio

Add following dependency or download Gson jar file

implementation 'com.google.code.gson:gson:2.8.6'

Follow github repo for documentation and more.

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

Setting the correct PATH for Eclipse

For me none worked. I compared my existing eclipse.ini with a new one and started removing options and testing if eclipse worked.

The only option that prevented eclipse from starting was -XX:+UseParallelGC, so I removed it and voilá!

Pure CSS animation visibility with delay

You are correct in thinking that display is not animatable. It won't work, and you shouldn't bother including it in keyframe animations.

visibility is technically animatable, but in a round about way. You need to hold the property for as long as needed, then snap to the new value. visibility doesn't tween between keyframes, it just steps harshly.

_x000D_
_x000D_
.ele {_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  _x000D_
  background-color: #ff6699;_x000D_
  animation: 1s fadeIn;_x000D_
  animation-fill-mode: forwards;_x000D_
  _x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
  background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
  99% {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
  100% {_x000D_
    visibility: visible;_x000D_
  }_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
_x000D_
_x000D_

If you want to fade, you use opacity. If you include a delay, you'll need visibility as well, to stop the user from interacting with the element while it's not visible.

_x000D_
_x000D_
.ele {_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  _x000D_
  background-color: #ff6699;_x000D_
  animation: 1s fadeIn;_x000D_
  animation-fill-mode: forwards;_x000D_
  _x000D_
  visibility: hidden;_x000D_
}_x000D_
_x000D_
.ele:hover {_x000D_
  background-color: #123;_x000D_
}_x000D_
_x000D_
@keyframes fadeIn {_x000D_
  0% {_x000D_
    opacity: 0;_x000D_
  }_x000D_
  100% {_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
  }_x000D_
}
_x000D_
<div class="ele"></div>
_x000D_
_x000D_
_x000D_

Both examples use animation-fill-mode, which can hold an element's visual state after an animation ends.

XAMPP Apache Webserver localhost not working on MAC OS

To be able to do this, you will have to stop apache from your terminal.

sudo apachectl stop

After you've done this, your apache server will be be up and running again!

Hope this helps

Bootstrap datepicker disabling past dates without current date

Please refer to the fiddle http://jsfiddle.net/Ritwika/gsvh83ry/

**With three fields having date greater than the **
<input type="text" type="text" class="form-control datepickstart" />
<input type="text" type="text" class="form-control datepickend" />
<input type="text" type="text" class="form-control datepickthird" />

var date = new Date();
 date.setDate(date.getDate()-1);
$('.datepickstart').datepicker({
 autoclose: true,
 todayHighlight: true,
 format: 'dd/mm/yyyy',
  startDate: date
});
$('.datepickstart').datepicker().on('changeDate', function() {
    var temp = $(this).datepicker('getDate');
    var d = new Date(temp);
  d.setDate(d.getDate() + 1);
  $('.datepickend').datepicker({
 autoclose: true,
 format: 'dd/mm/yyyy',
 startDate: d
}).on('changeDate', function() {
    var temp1 = $(this).datepicker('getDate');
    var d1 = new Date(temp1);
   d1.setDate(d1.getDate() + 1);
  $('.datepickthird').datepicker({
 autoclose: true,
 format: 'dd/mm/yyyy',
 startDate: d1
});
});
});

Count immediate child div elements using jQuery

I recommend using $('#foo').children().size() for better performance.

I've created a jsperf test to see the speed difference and the children() method beaten the child selector (#foo > div) approach by at least 60% in Chrome (canary build v15) 20-30% in Firefox (v4).

By the way, needless to say, these two approaches produce same results (in this case, 1000).

[Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: length usage is slightly faster (2%) than size())

[Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both $("#foo > div").length & $('#foo').children().length resulted the same (jsfiddle). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance

What's the best strategy for unit-testing database-driven applications?

I have been asking this question for a long time, but I think there is no silver bullet for that.

What I currently do is mocking the DAO objects and keeping a in memory representation of a good collection of objects that represent interesting cases of data that could live on the database.

The main problem I see with that approach is that you're covering only the code that interacts with your DAO layer, but never testing the DAO itself, and in my experience I see that a lot of errors happen on that layer as well. I also keep a few unit tests that run against the database (for the sake of using TDD or quick testing locally), but those tests are never run on my continuous integration server, since we don't keep a database for that purpose and I think tests that run on CI server should be self-contained.

Another approach I find very interesting, but not always worth since is a little time consuming, is to create the same schema you use for production on an embedded database that just runs within the unit testing.

Even though there's no question this approach improves your coverage, there are a few drawbacks, since you have to be as close as possible to ANSI SQL to make it work both with your current DBMS and the embedded replacement.

No matter what you think is more relevant for your code, there are a few projects out there that may make it easier, like DbUnit.

How to efficiently concatenate strings in go

I just benchmarked the top answer posted above in my own code (a recursive tree walk) and the simple concat operator is actually faster than the BufferString.

func (r *record) String() string {
    buffer := bytes.NewBufferString("");
    fmt.Fprint(buffer,"(",r.name,"[")
    for i := 0; i < len(r.subs); i++ {
        fmt.Fprint(buffer,"\t",r.subs[i])
    }
    fmt.Fprint(buffer,"]",r.size,")\n")
    return buffer.String()
}

This took 0.81 seconds, whereas the following code:

func (r *record) String() string {
    s := "(\"" + r.name + "\" ["
    for i := 0; i < len(r.subs); i++ {
        s += r.subs[i].String()
    }
    s += "] " + strconv.FormatInt(r.size,10) + ")\n"
    return s
} 

only took 0.61 seconds. This is probably due to the overhead of creating the new BufferString.

Update: I also benchmarked the join function and it ran in 0.54 seconds.

func (r *record) String() string {
    var parts []string
    parts = append(parts, "(\"", r.name, "\" [" )
    for i := 0; i < len(r.subs); i++ {
        parts = append(parts, r.subs[i].String())
    }
    parts = append(parts, strconv.FormatInt(r.size,10), ")\n")
    return strings.Join(parts,"")
}

POST data to a URL in PHP

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

How to get config parameters in Symfony2 Twig Templates

You can use parameter substitution in the twig globals section of the config:

Parameter config:

parameters:
    app.version: 0.1.0

Twig config:

twig:
    globals:
        version: '%app.version%'

Twig template:

{{ version }}

This method provides the benefit of allowing you to use the parameter in ContainerAware classes as well, using:

$container->getParameter('app.version');

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Fragment pressing back button

you can use this one in onCreateView, you can use transaction or replace

 OnBackPressedCallback callback = new OnBackPressedCallback(true) {
                @Override
                public void handleOnBackPressed() {
                    //what you want to do 
                }
            };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

Is there a way to pass javascript variables in url?

Try this:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";

To put a variable in a string enclose the variable in quotes and addition signs like this:

var myname = "BOB";
var mystring = "Hi there "+myname+"!"; 

Just remember that one rule!