Programs & Examples On #Istream

In C++ std::istream is the base class for input streams.

Using C++ filestreams (fstream), how can you determine the size of a file?

You can seek until the end, then compute the difference:

std::streampos fileSize( const char* filePath ){

    std::streampos fsize = 0;
    std::ifstream file( filePath, std::ios::binary );

    fsize = file.tellg();
    file.seekg( 0, std::ios::end );
    fsize = file.tellg() - fsize;
    file.close();

    return fsize;
}

Can't subtract offset-naive and offset-aware datetimes

I know some people use Django specifically as an interface to abstract this type of database interaction. Django provides utilities that can be used for this:

from django.utils import timezone
now_aware = timezone.now()

You do need to set up a basic Django settings infrastructure, even if you are just using this type of interface (in settings, you need to include USE_TZ=True to get an aware datetime).

By itself, this is probably nowhere near enough to motivate you to use Django as an interface, but there are many other perks. On the other hand, if you stumbled here because you were mangling your Django app (as I did), then perhaps this helps...

Send mail via Gmail with PowerShell V2's Send-MailMessage

I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):

# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)

Enjoy!

C++ floating point to integer type conversions

Normal way is to:

float f = 3.4;
int n = static_cast<int>(f);

How to iterate through property names of Javascript object?

Use for...in loop:

for (var key in obj) {
   console.log(' name=' + key + ' value=' + obj[key]);

   // do some more stuff with obj[key]
}

Free space in a CMD shell

df.exe

Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.

You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.

df -h will show all your drive's used and available disk space. For example:

M:\>df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/cygwin/bin   932G   78G  855G   9% /usr/bin
C:/cygwin/lib   932G   78G  855G   9% /usr/lib
C:/cygwin       932G   78G  855G   9% /
C:              932G   78G  855G   9% /cygdrive/c
E:              1.9T  1.3T  621G  67% /cygdrive/e
F:              1.9T  201G  1.7T  11% /cygdrive/f
H:              1.5T  524G  938G  36% /cygdrive/h
M:              1.5T  524G  938G  36% /cygdrive/m
P:               98G   67G   31G  69% /cygdrive/p
R:               98G   14G   84G  15% /cygdrive/r

Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:

M:\>df -h | grep M: | awk '{print $4}'

How to loop an object in React?

You can use it in a more compact way as:

var tifs = {1: 'Joe', 2: 'Jane'};
...

return (
   <select id="tif" name="tif" onChange={this.handleChange}>  
      { Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }          
   </select>
)

And another slightly different flavour:

 Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)  

How to debug Lock wait timeout exceeded on MySQL?

For the record, the lock wait timeout exception happens also when there is a deadlock and MySQL cannot detect it, so it just times out. Another reason might be an extremely long running query, which is easier to solve/repair, however, and I will not describe this case here.

MySQL is usually able to deal with deadlocks if they are constructed "properly" within two transactions. MySQL then just kills/rollback the one transaction that owns fewer locks (is less important as it will impact less rows) and lets the other one finish.

Now, let's suppose there are two processes A and B and 3 transactions:

Process A Transaction 1: Locks X
Process B Transaction 2: Locks Y
Process A Transaction 3: Needs Y => Waits for Y
Process B Transaction 2: Needs X => Waits for X
Process A Transaction 1: Waits for Transaction 3 to finish

(see the last two paragraph below to specify the terms in more detail)

=> deadlock 

This is a very unfortunate setup because MySQL cannot see there is a deadlock (spanned within 3 transactions). So what MySQL does is ... nothing! It just waits, since it does not know what to do. It waits until the first acquired lock exceeds the timeout (Process A Transaction 1: Locks X), then this will unblock the Lock X, which unlocks Transaction 2 etc.

The art is to find out what (which query) causes the first lock (Lock X). You will be able to see easily (show engine innodb status) that Transaction 3 waits for Transaction 2, but you will not see which transaction Transaction 2 is waiting for (Transaction 1). MySQL will not print any locks or query associated with Transaction 1. The only hint will be that at the very bottom of the transaction list (of the show engine innodb status printout), you will see Transaction 1 apparently doing nothing (but in fact waiting for Transaction 3 to finish).

The technique for how to find which SQL query causes the lock (Lock X) to be granted for a given transaction that is waiting is described here Tracking MySQL query history in long running transactions

If you are wondering what the process and the transaction is exactly in the example. The process is a PHP process. Transaction is a transaction as defined by innodb-trx-table. In my case, I had two PHP processes, in each I started a transaction manually. The interesting part was that even though I started one transaction in a process, MySQL used internally in fact two separate transactions (I don't have a clue why, maybe some MySQL dev can explain).

MySQL is managing its own transactions internally and decided (in my case) to use two transactions to handle all the SQL requests coming from the PHP process (Process A). The statement that Transaction 1 is waiting for Transaction 3 to finish is an internal MySQL thing. MySQL "knew" the Transaction 1 and Transaction 3 were actually instantiated as part of one "transaction" request (from Process A). Now the whole "transaction" was blocked because Transaction 3 (a subpart of "transaction") was blocked. Because "transaction" was not able to finish the Transaction 1 (also a subpart of the "transaction") was marked as not finished as well. This is what I meant by "Transaction 1 waits for Transaction 3 to finish".

set height of imageview as matchparent programmatically

You can use the MATCH_PARENT constant or its numeric value -1.

Compare two files in Visual Studio

Basically you can't.

Version 1.52.1 none of the above worked.

how to find seconds since 1970 in java

java.time

Using the java.time framework built into Java 8 and later.

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

int year = 2011;
int month = 10;
int day = 1;
int date = LocalDate.of(year, month, day);

date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond; # Long = 1317427200

How to install packages offline?

Let me go through the process step by step:

  1. On a computer connected to the internet, create a folder.
   $ mkdir packages
   $ cd packages
  1. open up a command prompt or shell and execute the following command:

    Suppose the package you want is tensorflow

    $ pip download tensorflow

  2. Now, on the target computer, copy the packages folder and apply the following command

  $ cd packages
  $ pip install 'tensorflow-xyz.whl' --no-index --find-links '.'

Note that the tensorflow-xyz.whl must be replaced by the original name of the required package.

Search for executable files using find command

find . -executable -type f

does not really guarantee that the file is executable it will find files with the execution bit set. If you do

chmod a+x image.jpg

the above find will think image.jpg is an executable even if it is really a jpeg image with the execution bit set.

I generally work around the issue with this:

find . -type f -executable -exec file {} \; | grep -wE "executable|shared object|ELF|script|a\.out|ASCII text"

If you want the find to actually print dome information about executable files you can do something like this:

find . -type f -executable -printf "%i.%D %s %m %U %G %C@ %p" 2>/dev/null |while read LINE
do
  NAME=$(awk '{print $NF}' <<< $LINE)
  file -b $NAME |grep -qEw "executable|shared object|ELF|script|a\.out|ASCII text" && echo $LINE
done

In the above example the file's full pathname is in the last field and must reflect where you look for it with awk "NAME=$(awk '{print $NF}' <<< $LINE)" if the file name was elsewhere in the find output string you need to replace "NF" with the correct numerical position. If your separator is not space you also need to tell awk what your separator is.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

How to read Excel cell having Date with Apache POI?

You can use CellDateFormatter to fetch the Date in the same format as in excel cell. See the following code:

CellValue cv = formulaEv.evaluate(cell);
double dv = cv.getNumberValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = HSSFDateUtil.getJavaDate(dv);

    String df = cell.getCellStyle().getDataFormatString();

    strValue = new CellDateFormatter(df).format(date); 
}

PowerShell: Run command from script's directory

There are answers with big number of votes, but when I read your question, I thought you wanted to know the directory where the script is, not that where the script is running. You can get the information with powershell's auto variables

$PSScriptRoot - the directory where the script exists, not the target directory the script is running in
$PSCommandPath - the full path of the script

For example, I have $profile script that finds visual studio solution file and start it. I wanted to store the full path, once a solution file is started. But I wanted to save the file where the original script exists. So I used $PsScriptRoot.

Select all text inside EditText when it gets focus

You can also add an OnClick Method to the editText after

_editText.setSelectAllOnFocus(true);

and in that:

_editText.clearFocus();
_editText.requestFocus();

As soon as you click the editText the whole text is selected.

How to get EditText value and display it on screen through TextView?

in "String.xml" you can notice any String or value you want to use, here are two examples:

<string name="app_name">My Calculator App
    </string>
<color name="color_menu_home">#ffcccccc</color>

Used for the layout.xml: android:text="@string/app_name"

The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file

Do you recommend using semicolons after every statement in JavaScript?

I'd say consistency is more important than saving a few bytes. I always include semicolons.

On the other hand, I'd like to point out there are many places where the semicolon is not syntactically required, even if a compressor is nuking all available whitespace. e.g. at then end of a block.

if (a) { b() }

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

How do I read a specified line in a text file?

Tried and tested. It's as simple as follows:

string line = File.ReadLines(filePath).ElementAt(actualLineNumber - 1);

As long as you have a text file, this should work. Later, depending upon what data you expect to read, you can cast the string accordingly and use it.

Convert string to ASCII value python

If you want your result concatenated, as you show in your question, you could try something like:

>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In my case, this error happened because my HTML had a trailing linebreak.

var myHtml = '<p>\
    This should work.\
    But does not.\
</p>\
';

jQuery('.something').append(myHtml); // this causes the error

To avoid the error, you just need to trim the HTML.

jQuery('.something').append(jQuery.trim(myHtml)); // this works

How to change font size in html?

Or add styles inline:

<p style="font-size:18px">Paragraph 1</p>
<p style="font-size:16px">Paragraph 2</p>

Could not find default endpoint element

Do not put service client declaration line as class field, instead of this, create instance at each method that used in. So problem will be fixed. If you create service client instance as class field, then design time error occurs !

How to create a sticky navigation bar that becomes fixed to the top after scrolling

Note (2015): Both question and the answer below apply to the old, deprecated version 2.x of Twitter Bootstrap.

This feature of making and element "sticky" is built into the Twitter's Bootstrap and it is called Affix. All you have to do is to add:

<div data-spy="affix" data-offset-top="121">
  ... your navbar ...
</div>

around your tag and do not forget to load the Bootstrap's JS files as described in the manual. Data attribute offset-top tells how many pixels the page is scrolled (from the top) to fix you menu component. Usually it is just the space to the top of the page.

Note: You will have to take care of the missing space when the menu will be fixed. Fixing means cutting it off out of your page layer and pasting in different layer that does not scroll. I am doing the following:

<div style="height: 77px;">
  <div data-spy="affix" data-offset-top="121">
    <div style="position: relative; height: 0; width: 100%;">
      <div style="position: absolute; top: 0; left: 0;">
        ... my menu ...
      </div>
    </div>
  </div>
</div>

where 77px is the height of my affixed component.

Xcode source automatic formatting

Consider buying yourself a license for AppCode, an intelligent Objective-C IDE that helps iOS/OS X developers. AppCode is fully compatible with Xcode, but goes beyond Xcode in adding powerful features.

AppCode an Objective-C variant of the Intellij IDEA IDE from JetBrains. They are also authors of popular ReSharper extension to Visual Studio, which main purpose from here seems like a desperate attempt to bring a touch of IDEA experience to a Microsoft product.

AppCode is using its own code analyser which gives close-to-perfect refactoring and code navigation support. There is an ability to re-indent and completely reformat code also (although I still keep missing a couple of formatting settings in hard cases, but mostly it works well).

You might try the trial version, of course.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

I found this answer quite simple and did the trick for what I needed: https://stackoverflow.com/a/12956348/652519

A summary from the link, use this query:

EXEC sp_fkeys 'TableName'

Quick and simple. I was able to locate all the foreign key tables, respective columns and foreign key names of 15 tables pretty quickly.

As @mdisibio noted below, here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql

jQuery: Setting select list 'selected' based on text, failing strangely

When an <option> isn't given a value="", the text becomes its value, so you can just use .val() on the <select> to set by value, like this:

var text1 = 'Monkey';
$("#mySelect1").val(text1);

var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);

You can test it out here, if the example is not what you're after and they actually have a value, use the <option> element's .text property to .filter(), like this:

var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
    return this.text == text1; 
}).attr('selected', true);

var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
    return this.text == text2; 
}).attr('selected', true);?

You can test that version here.

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • Squaring all elements in a list

    array = [1,2,3,4,5]
    def square(array):
        result = map(lambda x: x * x,array)
        return list(result)
    print(square(array))
    

    How to remove focus from input field in jQuery?

    If you have readonly attribute, blur by itself would not work. Contraption below should do the job.

    $('#myInputID').removeAttr('readonly').trigger('blur').attr('readonly','readonly');
    

    How can I selectively escape percent (%) in Python strings?

    You can't selectively escape %, as % always has a special meaning depending on the following character.

    In the documentation of Python, at the bottem of the second table in that section, it states:

    '%'        No argument is converted, results in a '%' character in the result.
    

    Therefore you should use:

    selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
    

    (please note the expicit change to tuple as argument to %)

    Without knowing about the above, I would have done:

    selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
    

    with the knowledge you obviously already had.

    IIS7 Permissions Overview - ApplicationPoolIdentity

    Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).

    I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.

    What is LD_LIBRARY_PATH and how to use it?

    My error was also related to not finding the required .so file by a service. I used LD_LIBRARY_PATH variable to priorities the path picked up by the linker to search the required lib.

    I copied both service and .so file in a folder and fed it to LD_LIBRARY_PATH variable as

    LD_LIBRARY_PATH=. ./service
    

    being in the same folder I have given the above command and it worked.

    Reload parent window from child window

    You can use window.opener, window.parent, or window.top to reference the window in question. From there, you just call the reload method (e.g.: window.parent.location.reload()).

    However, as a caveat, you might have problems with window.opener if you need to navigate away from the originally opened page since the reference will be lost.

    How to get thread id from a thread pool?

    If you are using logging then thread names will be helpful. A thread factory helps with this:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadFactory;
    
    public class Main {
    
        static Logger LOG = LoggerFactory.getLogger(Main.class);
    
        static class MyTask implements Runnable {
            public void run() {
                LOG.info("A pool thread is doing this task");
            }
        }
    
        public static void main(String[] args) {
            ExecutorService taskExecutor = Executors.newFixedThreadPool(5, new MyThreadFactory());
            taskExecutor.execute(new MyTask());
            taskExecutor.shutdown();
        }
    }
    
    class MyThreadFactory implements ThreadFactory {
        private int counter;
        public Thread newThread(Runnable r) {
            return new Thread(r, "My thread # " + counter++);
        }
    }
    

    Output:

    [   My thread # 0] Main         INFO  A pool thread is doing this task
    

    Generate a UUID on iOS from Swift

    For Swift 4;

    let uuid = NSUUID().uuidString.lowercased()
    

    How do I parse JSON with Objective-C?

    Don't reinvent the wheel. Use json-framework or something similar.

    If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:

    SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
    // assuming jsonString is your JSON string...
    NSDictionary* myDict = [parser objectWithString:jsonString];
    
    // now you can grab data out of the dictionary using objectForKey or another dictionary method
    

    Load resources from relative path using local html in uiwebview

    I crammed everything into one line (bad I know) and had no troubles with it:

    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" 
                                                                                                             ofType:@"html"]
                                                                 isDirectory:NO]]];         
    

    join list of lists in python

    Or a recursive operation:

    def flatten(input):
        ret = []
        if not isinstance(input, (list, tuple)):
            return [input]
        for i in input:
            if isinstance(i, (list, tuple)):
                ret.extend(flatten(i))
            else:
                ret.append(i)
        return ret
    

    What’s the best RESTful method to return total number of items in an object?

    You could return the count as a custom HTTP header in response to a HEAD request. This way, if a client only wants the count, you don't need to return the actual list, and there's no need for an additional URL.

    (Or, if you're in a controlled environment from endpoint to endpoint, you could use a custom HTTP verb such as COUNT.)

    'dict' object has no attribute 'has_key'

    The whole code in the document will be:

    graph = {'A': ['B', 'C'],
                 'B': ['C', 'D'],
                 'C': ['D'],
                 'D': ['C'],
                 'E': ['F'],
                 'F': ['C']}
    def find_path(graph, start, end, path=[]):
            path = path + [start]
            if start == end:
                return path
            if start not in graph:
                return None
            for node in graph[start]:
                if node not in path:
                    newpath = find_path(graph, node, end, path)
                    if newpath: return newpath
            return None
    

    After writing it, save the document and press F 5

    After that, the code you will run in the Python IDLE shell will be:

    find_path(graph, 'A','D')

    The answer you should receive in IDLE is

    ['A', 'B', 'C', 'D'] 
    

    How to pass arguments from command line to gradle

    There's a great example here:

    https://kb.novaordis.com/index.php/Gradle_Pass_Configuration_on_Command_Line

    Which details that you can pass parameters and then provide a default in an ext variable like so:

    gradle -Dmy_app.color=blue
    

    and then reference in Gradle as:

    ext {
       color = System.getProperty("my_app.color", "red");
    }
    

    And then anywhere in your build script you can reference it as course anywhere you can reference it as project.ext.color

    More tips here: https://kb.novaordis.com/index.php/Gradle_Variables_and_Properties

    How many threads can a Java VM support?

    After reading Charlie Martin's post, I was curious about whether the heap size makes any difference in the number of threads you can create, and I was totally dumbfounded by the result.

    Using JDK 1.6.0_11 on Vista Home Premium SP1, I executed Charlie's test application with different heap sizes, between 2 MB and 1024 MB.

    For example, to create a 2 MB heap, I'd invoke the JVM with the arguments -Xms2m -Xmx2m.

    Here are my results:

    2 mb --> 5744 threads
    4 mb --> 5743 threads
    8 mb --> 5735 threads
    12 mb --> 5724 threads
    16 mb --> 5712 threads
    24 mb --> 5687 threads
    32 mb --> 5662 threads
    48 mb --> 5610 threads
    64 mb --> 5561 threads
    96 mb --> 5457 threads
    128 mb --> 5357 threads
    192 mb --> 5190 threads
    256 mb --> 5014 threads
    384 mb --> 4606 threads
    512 mb --> 4202 threads
    768 mb --> 3388 threads
    1024 mb --> 2583 threads
    

    So, yeah, the heap size definitely matters. But the relationship between heap size and maximum thread count is INVERSELY proportional.

    Which is weird.

    No shadow by default on Toolbar?

    You can't use the elevation attribute before API 21 (Android Lollipop). You can however add the shadow programmatically, for example using a custom view placed below the Toolbar.

    @layout/toolbar

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/blue"
        android:minHeight="?attr/actionBarSize"
        app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />
    
    <View
        android:id="@+id/toolbar_shadow"
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:background="@drawable/toolbar_dropshadow" />
    

    @drawable/toolbar_dropshadow

    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <gradient
            android:startColor="@android:color/transparent"
            android:endColor="#88333333"
            android:angle="90"/> </shape>
    

    in your activity layout <include layout="@layout/toolbar" />

    enter image description here

    Quick Way to Implement Dictionary in C

    For ease of implementation, it's hard to beat naively searching through an array. Aside from some error checking, this is a complete implementation (untested).

    typedef struct dict_entry_s {
        const char *key;
        int value;
    } dict_entry_s;
    
    typedef struct dict_s {
        int len;
        int cap;
        dict_entry_s *entry;
    } dict_s, *dict_t;
    
    int dict_find_index(dict_t dict, const char *key) {
        for (int i = 0; i < dict->len; i++) {
            if (!strcmp(dict->entry[i], key)) {
                return i;
            }
        }
        return -1;
    }
    
    int dict_find(dict_t dict, const char *key, int def) {
        int idx = dict_find_index(dict, key);
        return idx == -1 ? def : dict->entry[idx].value;
    }
    
    void dict_add(dict_t dict, const char *key, int value) {
       int idx = dict_find_index(dict, key);
       if (idx != -1) {
           dict->entry[idx].value = value;
           return;
       }
       if (dict->len == dict->cap) {
           dict->cap *= 2;
           dict->entry = realloc(dict->entry, dict->cap * sizeof(dict_entry_s));
       }
       dict->entry[dict->len].key = strdup(key);
       dict->entry[dict->len].value = value;
       dict->len++;
    }
    
    dict_t dict_new(void) {
        dict_s proto = {0, 10, malloc(10 * sizeof(dict_entry_s))};
        dict_t d = malloc(sizeof(dict_s));
        *d = proto;
        return d;
    }
    
    void dict_free(dict_t dict) {
        for (int i = 0; i < dict->len; i++) {
            free(dict->entry[i].key);
        }
        free(dict->entry);
        free(dict);
    }
    

    Multiple queries executed in java in single statement

    Hint: If you have more than one connection property then separate them with:

    &amp;
    

    To give you somthing like:

    url="jdbc:mysql://localhost/glyndwr?autoReconnect=true&amp;allowMultiQueries=true"
    

    I hope this helps some one.

    Regards,

    Glyn

    FCM getting MismatchSenderId

    I had big trouble figuring out why I was getting a "MismatchSenderId" status. I added the gms dependency in the root build.gradle but my error was actually not applying the gms plugin in the app build.gradle.

    If you have don't have this line in the app build.gradle, this could be the reason why the notification are not working: apply plugin: 'com.google.gms.google-services'

    How to scroll the window using JQuery $.scrollTo() function

    Actually something like

    function scrollTo(prop){
        $('html,body').animate({scrollTop: $("#"+prop).offset().top +
     parseInt($("#"+prop).css('padding-top'),10) },'slow');
    }
    

    will work nicely and support padding. You can also support margins easily - for completion see below

    function scrollTo(prop){
        $('html,body').animate({scrollTop: $("#"+prop).offset().top 
    + parseInt($("#"+prop).css('padding-top'),10) 
    + parseInt($("#"+prop).css('margin-top'),10) +},'slow');
    }
    

    Media Queries: How to target desktop, tablet, and mobile?

    If you want to target a device then just write min-device-width. For example:

    For iPhone

    @media only screen and (min-device-width: 480px){}
    

    For tablets

    @media only screen and (min-device-width: 768px){}
    

    Here are some good articles:

    include external .js file in node.js app

    To place an emphasis on what everyone else has been saying var foo in top level does not create a global variable. If you want a global variable then write global.foo. but we all know globals are evil.

    If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).

    // Declare application
    var app = require('express').createServer();
    
    // Declare usefull stuff for DB purposes
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var ObjectId = Schema.ObjectId;
    
    require('./models/car.js').make(Schema, mongoose);
    

    in car.js

    function make(Schema, mongoose) {
        // Define Car model
        CarSchema = new Schema({
          brand        : String,
          type : String
        });
        mongoose.model('Car', CarSchema);
    }
    
    module.exports.make = make;
    

    Execute a file with arguments in Python shell

    Actually, wouldn't we want to do this?

    import sys
    sys.argv = ['abc.py','arg1', 'arg2']
    execfile('abc.py')
    

    Print directly from browser without print popup window

    IE9 no longer supports triggering the Print() VBScript by calling window.print() like IE7 and IE8 do, and thus window.print() will now always trigger the print dialog in IE9.

    The fix is pretty simple. You just need to call Print() itself, instead of window.print() in the onclick event.

    I've described the fix in more detail in an answer to another question, with a working code example sporting slightly updated HTML syntax (as much as possible while still tested as working code).

    You can find that sample code here:

    Bypass Printdialog in IE9

    Distinct by property of class with LINQ

    You can implement an IEqualityComparer and use that in your Distinct extension.

    class CarEqualityComparer : IEqualityComparer<Car>
    {
        #region IEqualityComparer<Car> Members
    
        public bool Equals(Car x, Car y)
        {
            return x.CarCode.Equals(y.CarCode);
        }
    
        public int GetHashCode(Car obj)
        {
            return obj.CarCode.GetHashCode();
        }
    
        #endregion
    }
    

    And then

    var uniqueCars = cars.Distinct(new CarEqualityComparer());
    

    adb uninstall failed

    In my case I often get this issue when I first complise a app in debug mode and later try to install the google signed app.

    That is because both apps have the same package name but diffent signatures. Since I upgraded to Android lollypop I sometimes even get this error if I uninstall the app via the settings\Apps. If you have this problem check if the app is installed in a other User profile and uninstall it in all user accounts.

    How can I read input from the console using the Scanner class in Java?

    You can use the Scanner class in Java

    Scanner scan = new Scanner(System.in);
    String s = scan.nextLine();
    System.out.println("String: " + s);
    

    Resolve Javascript Promise outside function scope

    Just another solution to resolve Promise from the outside

     class Lock {
            #lock;  // Promise to be resolved (on  release)
            release;  // Release lock
            id;  // Id of lock
            constructor(id) {
                this.id = id
                this.#lock = new Promise((resolve) => {
                    this.release = () => {
                        if (resolve) {
                            resolve()
                        } else {
                            Promise.resolve()
                        }
                    }
                })
            }
            get() { return this.#lock }
        }
    

    Usage

    let lock = new Lock(... some id ...);
    ...
    lock.get().then(()=>{console.log('resolved/released')})
    lock.release()  // Excpected 'resolved/released'
    

    How to get current time and date in C++?

    You could use boost:

    #include <boost/date_time/gregorian/gregorian.hpp>
    #include <iostream>
    using namespace boost::gregorian;
    
    int main()
    {
        date d = day_clock::universal_day();
        std::cout << d.day() << " " << d.month() << " " << d.year();
    }
    

    Use 'import module' or 'from module import'?

    import package
    import module
    

    With import, the token must be a module (a file containing Python commands) or a package (a folder in the sys.path containing a file __init__.py.)

    When there are subpackages:

    import package1.package2.package
    import package1.package2.module
    

    the requirements for folder (package) or file (module) are the same, but the folder or file must be inside package2 which must be inside package1, and both package1 and package2 must contain __init__.py files. https://docs.python.org/2/tutorial/modules.html

    With the from style of import:

    from package1.package2 import package
    from package1.package2 import module
    

    the package or module enters the namespace of the file containing the import statement as module (or package) instead of package1.package2.module. You can always bind to a more convenient name:

    a = big_package_name.subpackage.even_longer_subpackage_name.function
    

    Only the from style of import permits you to name a particular function or variable:

    from package3.module import some_function
    

    is allowed, but

    import package3.module.some_function 
    

    is not allowed.

    Count the number occurrences of a character in a string

    I am a fan of the pandas library, in particular the value_counts() method. You could use it to count the occurrence of each character in your string:

    >>> import pandas as pd
    >>> phrase = "I love the pandas library and its `value_counts()` method"
    >>> pd.Series(list(phrase)).value_counts()
         8
    a    5
    e    4
    t    4
    o    3
    n    3
    s    3
    d    3
    l    3
    u    2
    i    2
    r    2
    v    2
    `    2
    h    2
    p    1
    b    1
    I    1
    m    1
    (    1
    y    1
    _    1
    )    1
    c    1
    dtype: int64
    

    How to run a class from Jar which is not the Main-Class in its Manifest file

    You can execute any class which has a public final static main method from a JAR file, even if the jar file has a Main-Class defined.

    Execute Main-Class:

    java -jar MyJar.jar  // will execute the Main-Class
    

    Execute another class with a public static void main method:

    java -cp MyJar.jar com.mycomp.myproj.AnotherClassWithMainMethod
    

    Note: the first uses -jar, the second uses -cp.

    Split function in oracle to comma separated values with automatic sequence

    Here is how you could create such a table:

     SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
       FROM dual
    CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;
    

    With a little bit of tweaking (i.e., replacing the , in [^,] with a variable) you could write such a function to return a table.

    Overlay a background-image with an rgba background-color

    The solution by PeterVR has the disadvantage that the additional color displays on top of the entire HTML block - meaning that it also shows up on top of div content, not just on top of the background image. This is fine if your div is empty, but if it is not using a linear gradient might be a better solution:

    <div class="the-div">Red text</div>
    
    <style type="text/css">
      .the-div
      {
        background-image: url("the-image.png");
        color: #f00;
        margin: 10px;
        width: 200px;
        height: 80px;
      }
      .the-div:hover
      {
        background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
        background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
        background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
        background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
        background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.1))), url("the-image.png");
        background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
      }
    </style>
    

    See fiddle. Too bad that gradient specifications are currently a mess. See compatibility table, the code above should work in any browser with a noteworthy market share - with the exception of MSIE 9.0 and older.

    Edit (March 2017): The state of the web got far less messy by now. So the linear-gradient (supported by Firefox and Internet Explorer) and -webkit-linear-gradient (supported by Chrome, Opera and Safari) lines are sufficient, additional prefixed versions are no longer necessary.

    java: HashMap<String, int> not working

    You can't use primitive types as generic arguments in Java. Use instead:

    Map<String, Integer> myMap = new HashMap<String, Integer>();
    

    With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:

    myMap.put("foo", 3);
    

    instead of:

    myMap.put("foo", new Integer(3));
    

    Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

    int i = myMap.get("foo");
    

    instead of:

    int i = myMap.get("foo").intValue();
    

    The implicit call to intValue() means if the key isn't found it will generate a NullPointerException, for example:

    int i = myMap.get("bar"); // NullPointerException
    

    The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:

    Integer i = (Integer)myMap.get("foo");
    

    To give you an example, this code is perfectly legal:

    Map<String, Integer> myMap = new HashMap<String, Integer>();
    Map<Integer, String> map2 = (Map<Integer, String>)myMap;
    map2.put(3, "foo");
    

    Is there a way to avoid null check before the for-each loop iteration starts?

    How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.

    I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

    Django: Display Choice Value

    For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

    In Views

    person = Person.objects.filter(to_be_listed=True)
    context['gender'] = person.get_gender_display()
    

    In Template

    {{ person.get_gender_display }}
    

    Documentation of get_FOO_display()

    How to declare an array in Python?

    Python calls them lists. You can write a list literal with square brackets and commas:

    >>> [6,28,496,8128]
    [6, 28, 496, 8128]
    

    WiX tricks and tips

    Create a UI that has a custom action that will set a variable and the UI will disable/enable the next button (or similar) based upon the variable set in the custom action.

    Not as straight-forward as you would think, not too difficult just not documented anywhere!

    Wix Interactions with Conditions, Properties & Custom Actions

    How using try catch for exception handling is best practice

    Sometimes you need to treat exceptions which say nothing to users.

    My way is:

    • To catch uncaughted exceptions on application level (ie. in global.asax) for critical exceptions (application can not be useful). These exeptions I am not catching on the place. Just log them on app level and let system do its job.
    • Catch "on place" and show some useful info to user (entered wrong number, can't parse).
    • Catch on place and do nothing on marginal problems like "I will check for update info on the background, but the service is not running".

    It definitely does not have to be best practice. ;-)

    How to update TypeScript to latest version with npm?

    Try npm install -g typescript@latest. You can also use npm update instead of install, without the latest modifier.

    Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?

    Arrow functions => best ES6 feature so far. They are a tremendously powerful addition to ES6, that I use constantly.

    Wait, you can't use arrow function everywhere in your code, its not going to work in all cases like this where arrow functions are not usable. Without a doubt, the arrow function is a great addition it brings code simplicity.

    But you can’t use an arrow function when a dynamic context is required: defining methods, create objects with constructors, get the target from this when handling events.

    Arrow functions should NOT be used because:

    1. They do not have this

      It uses “lexical scoping” to figure out what the value of “this” should be. In simple word lexical scoping it uses “this” from the inside the function’s body.

    2. They do not have arguments

      Arrow functions don’t have an arguments object. But the same functionality can be achieved using rest parameters.

      let sum = (...args) => args.reduce((x, y) => x + y, 0) sum(3, 3, 1) // output - 7 `

    3. They cannot be used with new

      Arrow functions can't be construtors because they do not have a prototype property.

    When to use arrow function and when not:

    1. Don't use to add function as a property in object literal because we can not access this.
    2. Function expressions are best for object methods. Arrow functions are best for callbacks or methods like map, reduce, or forEach.
    3. Use function declarations for functions you’d call by name (because they’re hoisted).
    4. Use arrow functions for callbacks (because they tend to be terser).

    AWS S3 CLI - Could not connect to the endpoint URL

    first you use 'aws configure' then input the access key, and secret key, and the region. the region you input would be important for this problem. try to input something like 's3.us-east-1', not 's3.us-east-1a'. it will solve the issue.

    What is the difference between varchar and nvarchar?

    nvarchar stores data as Unicode, so, if you're going to store multilingual data (more than one language) in a data column you need the N variant.

    How To Create Table with Identity Column

    CREATE TABLE [dbo].[History](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [RequestID] [int] NOT NULL,
        [EmployeeID] [varchar](50) NOT NULL,
        [DateStamp] [datetime] NOT NULL,
     CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
    ) ON [PRIMARY]
    

    Collections.emptyList() returns a List<Object>?

    the emptyList method has this signature:

    public static final <T> List<T> emptyList()
    

    That <T> before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:

    List<String> stringList = Collections.emptyList();
    

    The return value is then referenced explicitly by a variable of type List<String>, so the compiler can figure it out. In this case:

    setList(Collections.emptyList());
    

    There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object.

    How can I change a button's color on hover?

    a.button a:hover means "a link that's being hovered over that is a child of a link with the class button".

    Go instead for a.button:hover.

    How to get access to raw resources that I put in res folder?

    InputStream raw = context.getAssets().open("filename.ext");
    
    Reader is = new BufferedReader(new InputStreamReader(raw, "UTF8"));
    

    Convert PDF to image with high resolution

    It appears that the following works:

    convert           \
       -verbose       \
       -density 150   \
       -trim          \
        test.pdf      \
       -quality 100   \
       -flatten       \
       -sharpen 0x1.0 \
        24-18.jpg
    

    It results in the left image. Compare this to the result of my original command (the image on the right):

      

    (To really see and appreciate the differences between the two, right-click on each and select "Open Image in New Tab...".)

    Also keep the following facts in mind:

    • The worse, blurry image on the right has a file size of 1.941.702 Bytes (1.85 MByte). Its resolution is 3060x3960 pixels, using 16-bit RGB color space.
    • The better, sharp image on the left has a file size of 337.879 Bytes (330 kByte). Its resolution is 758x996 pixels, using 8-bit Gray color space.

    So, no need to resize; add the -density flag. The density value 150 is weird -- trying a range of values results in a worse looking image in both directions!

    How to find an object in an ArrayList by property

    Here is a solution using Guava

    private User findUserByName(List<User> userList, final String name) {
        Optional<User> userOptional =
                FluentIterable.from(userList).firstMatch(new Predicate<User>() {
                    @Override
                    public boolean apply(@Nullable User input) {
                        return input.getName().equals(name);
                    }
                });
        return userOptional.isPresent() ? userOptional.get() : null; // return user if found otherwise return null if user name don't exist in user list
    }
    

    Writing String to Stream and reading it back does not work

    You're using message.Length which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:

    byte[] messageBytes = uniEncoding.GetBytes(message);
    stringAsStream.Write(messageBytes, 0, messageBytes.Length);
    

    You're then reading a single byte and expecting to get a character from it just by casting to char. UnicodeEncoding will use two bytes per character.

    As Justin says you're also not seeking back to the beginning of the stream.

    Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter to write and then a StreamReader to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.

    How to create global variables accessible in all views using Express / Node.JS?

    With the differents answers, I implemented this code to use an external file JSON loaded in "app.locals"

    Parameters

    {
        "web": {
            "title" : "Le titre de ma Page",
            "cssFile" : "20200608_1018.css"
        }
    }
    

    Application

    var express     = require('express');
    var appli       = express();
    var serveur     = require('http').Server(appli);
    
    var myParams    = require('./include/my_params.json');
    var myFonctions = require('./include/my_fonctions.js');
    
    appli.locals = myParams;
    

    EJS Page

    <!DOCTYPE html>
    <html lang="fr">
    <head>
        <meta charset="UTF-8">
        <title><%= web.title %></title>
        <link rel="stylesheet" type="text/css" href="/css/<%= web.cssFile %>">
    </head>
    
    </body>
    </html>
    

    Hoping it will help

    Converting data frame column from character to numeric

    If we need only one column to be numeric

    yyz$b <- as.numeric(as.character(yyz$b))
    

    But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

    yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
    

    Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


    Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

    lapply(yyz, class)
    

    Or

    sapply(yyz, class)
    

    Or check

    str(yyz)
    

    How to plot a function curve in R

    I did some searching on the web, and this are some ways that I found:

    The easiest way is using curve without predefined function

    curve(x^2, from=1, to=50, , xlab="x", ylab="y")
    

    enter image description here

    You can also use curve when you have a predfined function

    eq = function(x){x*x}
    curve(eq, from=1, to=50, xlab="x", ylab="y")
    

    enter image description here

    If you want to use ggplot,

    library("ggplot2")
    eq = function(x){x*x}
    ggplot(data.frame(x=c(1, 50)), aes(x=x)) + 
      stat_function(fun=eq)
    

    enter image description here

    Align an element to bottom with flexbox

    When setting your display to flex, you could simply use the flex property to mark which content can grow and which content cannot.

    Flex property

    _x000D_
    _x000D_
    div.content {_x000D_
     height: 300px;_x000D_
     display: flex;_x000D_
     flex-direction: column;_x000D_
    }_x000D_
    _x000D_
    div.up {_x000D_
      flex: 1;_x000D_
    }_x000D_
    _x000D_
    div.down {_x000D_
      flex: none;_x000D_
    }
    _x000D_
    <div class="content">_x000D_
      <div class="up">_x000D_
        <h1>heading 1</h1>_x000D_
        <h2>heading 2</h2>_x000D_
        <p>Some more or less text</p>_x000D_
      </div>_x000D_
    _x000D_
      <div class="down">_x000D_
        <a href="/" class="button">Click me</a>_x000D_
      </div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to perform update operations on columns of type JSONB in Postgres 9.4

    Maybe: UPDATE test SET data = '"my-other-name"'::json WHERE id = 1;

    It worked with my case, where data is a json type

    Pandas How to filter a Series

    A fast way of doing this is to reconstruct using numpy to slice the underlying arrays. See timings below.

    mask = s.values != 1
    pd.Series(s.values[mask], s.index[mask])
    
    0
    383    3.000000
    737    9.000000
    833    8.166667
    dtype: float64
    

    naive timing

    enter image description here

    Find Java classes implementing an interface

    In full generality, this functionality is impossible. The Java ClassLoader mechanism guarantees only the ability to ask for a class with a specific name (including pacakge), and the ClassLoader can supply a class, or it can state that it does not know that class.

    Classes can be (and frequently are) loaded from remote servers, and they can even be constructed on the fly; it is not difficult at all to write a ClassLoader that returns a valid class that implements a given interface for any name you ask from it; a List of the classes that implement that interface would then be infinite in length.

    In practice, the most common case is an URLClassLoader that looks for classes in a list of filesystem directories and JAR files. So what you need is to get the URLClassLoader, then iterate through those directories and archives, and for each class file you find in them, request the corresponding Class object and look through the return of its getInterfaces() method.

    select the TOP N rows from a table

    In MySql, you can get 10 rows starting from row 20 using:

    SELECT * FROM Reflow  
    WHERE ReflowProcessID = somenumber
    ORDER BY ID DESC
    LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10
    

    dplyr mutate with conditional values

    Try this:

    myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))
    

    giving:

      V1 V2 V3 V4 V5
    1  1  2  3  5  1
    2  2  4  4  1  2
    3  1  4  1  1  0
    4  4  5  1  3  0
    5  5  5  5  4  0
    

    or this:

    myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))
    

    giving:

      V1 V2 V3 V4 V5
    1  1  2  3  5  1
    2  2  4  4  1  2
    3  1  4  1  1  0
    4  4  5  1  3  0
    5  5  5  5  4  0
    

    Note

    Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

    Above used this input:

    myfile <- 
    structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
    5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
    )), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5"))
    

    Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

    Update 2 dplyr now has case_when which provides another solution:

    myfile %>% 
           mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                                 V2 == 4 & V3 != 1 ~ 2,
                                 TRUE ~ 0))
    

    C# convert int to string with padding zeros?

    .NET has an easy function to do that in the String class. Just use:

    .ToString().PadLeft(4, '0')  // that will fill your number with 0 on the left, up to 4 length
    
    int i = 1; 
    i.toString().PadLeft(4,'0')  // will return "0001"  
    

    How to extract svg as file from web page

    Based on a web search, I just found a Chrome plugin called SVG Export.

    using c# .net libraries to check for IMAP messages from gmail servers

    As the author of the above project i can say that yes it does support SSL.

    I am currently working on a new version of the library that will be completely asynchronous to increase the speed with which it can interact with IMAP servers.

    That code, while not complete, can be downloaded, along with the original synchronous library (which also supports SSL), from the code plex site linked to above.

    Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

    Drezus - you solved it for me. Thanks so much.

    In your AccountController, login should look like this:

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
    

    Counting inversions in an array

    Another Python solution, short one. Makes use of builtin bisect module, which provides functions to insert element into its place in sorted array and to find index of element in sorted array.

    The idea is to store elements left of n-th in such array, which would allow us to easily find the number of them greater than n-th.

    import bisect
    def solution(A):
        sorted_left = []
        res = 0
        for i in xrange(1, len(A)):
            bisect.insort_left(sorted_left, A[i-1])
            # i is also the length of sorted_left
            res += (i - bisect.bisect(sorted_left, A[i]))
        return res
    

    Android get Current UTC time

    see my answer here:

    How can I get the current date and time in UTC or GMT in Java?

    I've fully tested it by changing the timezones on the emulator

    Opening a remote machine's Windows C drive

    By default, Windows makes the root of each drive available (provided you've got Administrator privileges) as (e.g.) \\server\c$. These are known as Administrative Shares.

    Remove multiple objects with rm()

    An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

    How to get response using cURL in PHP

    Just use the below piece of code to get the response from restful web service url, I use social mention url.

    $response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
    $resArr = array();
    $resArr = json_decode($response);
    echo "<pre>"; print_r($resArr); echo "</pre>";
    
    function get_web_page($url) {
        $options = array(
            CURLOPT_RETURNTRANSFER => true,   // return web page
            CURLOPT_HEADER         => false,  // don't return headers
            CURLOPT_FOLLOWLOCATION => true,   // follow redirects
            CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects
            CURLOPT_ENCODING       => "",     // handle compressed
            CURLOPT_USERAGENT      => "test", // name of client
            CURLOPT_AUTOREFERER    => true,   // set referrer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect
            CURLOPT_TIMEOUT        => 120,    // time-out on response
        ); 
    
        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
    
        $content  = curl_exec($ch);
    
        curl_close($ch);
    
        return $content;
    }
    

    python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

    While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.

    The error message indirectly tells you what character set Python was trying to use:

      File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
    

    This means the charset is cp850.

    You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).

    It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)

    But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:

    >>> '\u2013'.encode('cp850')
    UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
    >>> '\u2013'.encode('cp850', errors='replace')
    b'?'
    

    So, how do you print a string that won't print on your console?

    You can replace every print function with something like this:

    >>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
    ?
    

    … but that's going to get pretty tedious pretty fast.

    The simple thing to do is to just set the error handler on sys.stdout:

    >>> sys.stdout.errors = 'replace'
    >>> print(r['body'])
    ?
    

    For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:

    with open('path', 'w', encoding='cp850') as f:
    

    Do this:

    with open('path', 'w', encoding='cp850', errors='replace') as f:
    

    … Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:

    with open('path', 'w', encoding='utf-8') as f:
    

    Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

    Why controllers are needed

    The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

    From the docs:

    Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

    Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

    In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

    Moreover, if such a controller is not found, an error will be raised.

    Why use link at all

    There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

    However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

    What is offsetHeight, clientHeight, scrollHeight?

    * offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

    * clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

    * scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

    Same is the case for all of these with width instead of height.

    Jquery - Uncaught TypeError: Cannot use 'in' operator to search for '324' in

    Use getJSON

    $.getJSON(
    'index.php?r=admin/post/ajax',
    {"parentCatId":parentCatId},
    function(data){                     
        $.each(data, function(key, value){
            console.log(key + ":" + value)
        })
    });
    

    Detail look here http://api.jquery.com/jQuery.getJSON/

    Switch statement fallthrough in C#?

    To add to the answers here, I think it's worth considering the opposite question in conjunction with this, viz. why did C allow fall-through in the first place?

    Any programming language of course serves two goals:

    1. Provide instructions to the computer.
    2. Leave a record of the intentions of the programmer.

    The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.

    Conversely, the more the language expresses the intention of the programmer, rather than the means taken to that end, the more understandable the program both when writing and during maintenance.

    Now, switch could always have been compiled by converting it into the equivalent chain of if-else blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn switch into the equivalent if-else, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).

    In this case there are two good reasons for allowing fall-through:

    1. It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the switch-using C into jump-table–using machine code.

    2. Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit break when necessary was "natural" for the coder too.

    At the time therefore, it was a reasonable attempt to balance the two goals of a computer language as it relates to both the produced machine code, and the expressiveness of the source code.

    Four decades later though, things are not quite the same, for a few reasons:

    1. Coders in C today may have little or no assembly experience. Coders in many other C-style languages are even less likely to (especially Javascript!). Any concept of "what people are used to from assembly" is no longer relevant.
    2. Improvements in optimisations mean that the likelihood of switch either being turned into if-else because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was.
    3. Experience has shown that fall-through tends to be the minority case rather than the norm (a study of Sun's compiler found 3% of switch blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common.
    4. Experience has shown that fall-through tends to be the source of problems both in cases where it is accidentally done, and also in cases where correct fall-through is missed by someone maintaining the code. This latter is a subtle addition to the bugs associated with fall-through, because even if your code is perfectly bug-free, your fall-through can still cause problems.

    Related to those last two points, consider the following quote from the current edition of K&R:

    Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.

    As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary. Some day when another case gets added at the end, this bit of defensive programming will save you.

    So, from the horse's mouth, fall-through in C is problematic. It's considered good practice to always document fall-throughs with comments, which is an application of the general principle that one should document where one does something unusual, because that's what will trip later examination of the code and/or make your code look like it has a novice's bug in it when it is in fact correct.

    And when you think about it, code like this:

    switch(x)
    {
      case 1:
       foo();
       /* FALLTHRU */
      case 2:
        bar();
        break;
    }
    

    Is adding something to make the fall-through explicit in the code, it's just not something that can be detected (or whose absence can be detected) by the compiler.

    As such, the fact that on has to be explicit with fall-through in C# doesn't add any penalty to people who wrote well in other C-style languages anyway, since they would already be explicit in their fall-throughs.†

    Finally, the use of goto here is already a norm from C and other such languages:

    switch(x)
    {
      case 0:
      case 1:
      case 2:
        foo();
        goto below_six;
      case 3:
        bar();
        goto below_six;
      case 4:
        baz();
        /* FALLTHRU */
      case 5:
      below_six:
        qux();
        break;
      default:
        quux();
    }
    

    In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use goto. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a switch, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the case as a label in C#. In C# we can get rid of the below_six label and use goto case 5 which is clearer as to what we are doing. (We'd also have to add break for the default, which I left out just to make the above C code clearly not C# code).

    In summary therefore:

    1. C# no longer relates to unoptimised compiler output as directly as C code did 40 years ago (nor does C these days), which makes one of the inspirations of fall-through irrelevant.
    2. C# remains compatible with C in not just having implicit break, for easier learning of the language by those familiar with similar languages, and easier porting.
    3. C# removes a possible source of bugs or misunderstood code that has been well-documented as causing problems for the last four decades.
    4. C# makes existing best-practice with C (document fall through) enforceable by the compiler.
    5. C# makes the unusual case the one with more explicit code, the usual case the one with the code one just writes automatically.
    6. C# uses the same goto-based approach for hitting the same block from different case labels as is used in C. It just generalises it to some other cases.
    7. C# makes that goto-based approach more convenient, and clearer, than it is in C, by allowing case statements to act as labels.

    All in all, a pretty reasonable design decision


    *Some forms of BASIC would allow one to do the likes of GOTO (x AND 7) * 50 + 240 which while brittle and hence a particularly persuasive case for banning goto, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of nop fillers.

    †Duff's Device comes up here again, as a reasonable exception. The fact that with that and similar patterns there's a repetition of operations serves to make the use of fall-through relatively clear even without an explicit comment to that effect.

    How to Debug Variables in Smarty like in PHP var_dump()

    You can use {php} tags

    Method 1 (won't work in Smarty 3.1 or later):

    {php}
    
    $var =
    $this->get_template_vars('var');
    var_dump($var);
    
    {/php}
    

    Method 2:

    {$var|@print_r}
    

    Method 3:

    {$var|@var_dump}
    

    How to get all checked checkboxes

    Get all the checked checkbox value in an array - one liner

    _x000D_
    _x000D_
    const data = [...document.querySelectorAll('.inp:checked')].map(e => e.value);_x000D_
    console.log(data);
    _x000D_
    <div class="row">_x000D_
        <input class="custom-control-input inp"type="checkbox" id="inlineCheckbox1" Checked value="option1"> _x000D_
        <label class="custom-control-label" for="inlineCheckbox1">Option1</label>_x000D_
        <input class="custom-control-input inp"  type="checkbox" id="inlineCheckbox1" value="option2"> _x000D_
        <label class="custom-control-label" for="inlineCheckbox1">Option2</label>_x000D_
        <input class="custom-control-input inp" Checked  type="checkbox" id="inlineCheckbox1" value="option3"> _x000D_
        <label class="custom-control-label" for="inlineCheckbox1">Option3</label>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    How to convert interface{} to string?

    To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

    Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.

    How to get a web page's source code from Java

    URL yahoo = new URL("http://www.yahoo.com/");
    BufferedReader in = new BufferedReader(
                new InputStreamReader(
                yahoo.openStream()));
    
    String inputLine;
    
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    
    in.close();
    

    Where in an Eclipse workspace is the list of projects stored?

    In Eclipse 3.3:

    It's installed under your Eclipse workspace. Something like:

    .metadata\.plugins\org.eclipse.core.resources\.projects\
    

    within your workspace folder.

    Under that folder is one folder per project. There's a file in there called .location, but it's binary.

    So it looks like you can't do what you want, without interacting w/ Eclipse programmatically.

    How to check java bit version on Linux?

    Why don't you examine System.getProperty("os.arch") value in your code?

    python NameError: name 'file' is not defined

    It seems that your project is written in Python < 3. This is because the file() builtin function is removed in Python 3. Try using Python 2to3 tool or edit the erroneous file yourself.

    EDIT: BTW, the project page clearly mentions that

    Gunicorn requires Python 2.x >= 2.5. Python 3.x support is planned.

    Is there a way to retrieve the view definition from a SQL Server using plain ADO?

    You can get table/view details through below query.

    For table :sp_help table_name For View :sp_help view_name

    How to open standard Google Map application from my application?

    You should create an Intent object with a geo-URI:

    String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    context.startActivity(intent);
    

    If you want to specify an address, you should use another form of geo-URI: geo:0,0?q=address.

    reference : https://developer.android.com/guide/components/intents-common.html#Maps

    Python convert object to float

    • You can use pandas.Series.astype
    • You can do something like this :

      weather["Temp"] = weather.Temp.astype(float)
      
    • You can also use pd.to_numeric that will convert the column from object to float

    • For details on how to use it checkout this link :http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html
    • Example :

      s = pd.Series(['apple', '1.0', '2', -3])
      print(pd.to_numeric(s, errors='ignore'))
      print("=========================")
      print(pd.to_numeric(s, errors='coerce'))
      
    • Output:

      0    apple
      1      1.0
      2        2
      3       -3
      =========================
      dtype: object
      0    NaN
      1    1.0
      2    2.0
      3   -3.0
      dtype: float64
      
    • In your case you can do something like this:

      weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
      
    • Other option is to use convert_objects
    • Example is as follows

      >> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
      
      0     1
      1     2
      2     3
      3     4
      4   NaN
      dtype: float64
      
    • You can use this as follows:

      weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
      
    • I have showed you examples because if any of your column won't have a number then it will be converted to NaN... so be careful while using it.

    How do I get a UTC Timestamp in JavaScript?

    I actually think Date values in js are far better than say the C# DateTime objects. The C# DateTime objects have a Kind property, but no strict underlying time zone as such, and time zone conversions are difficult to track if you are converting between two non UTC and non local times. In js, all Date values have an underlying UTC value which is passed around and known regardless of the offest or time zone conversions that you do. My biggest complaint about the Date object is the amount of undefined behaviour that browser implementers have chosen to include, which can confuse people who attack dates in js with trial and error than reading the spec. Using something like iso8601.js solves this varying behaviour by defining a single implementation of the Date object.

    By default, the spec says you can create dates with an extended ISO 8601 date format like

    var someDate = new Date('2010-12-12T12:00Z');
    

    So you can infer the exact UTC time this way.

    When you want to pass the Date value back to the server you would call

    someDate.toISOString();
    

    or if you would rather work with a millisecond timestamp (number of milliseconds from the 1st January 1970 UTC)

    someDate.getTime();
    

    ISO 8601 is a standard. You can't be confused about what a date string means if you include the date offset. What this means for you as a developer is that you never have to deal with local time conversions yourself. The local time values exist purely for the benefit of the user, and date values by default display in their local time. All the local time manipulations allow you to display something sensible to the user and to convert strings from user input. It's good practice to convert to UTC as soon as you can, and the js Date object makes this fairly trivial.

    On the downside there is not a lot of scope for forcing the time zone or locale for the client (that I am aware of), which can be annoying for website-specific settings, but I guess the reasoning behind this is that it's a user configuration that shouldn't be touched.

    So, in short, the reason there isn't a lot of native support for time zone manipulation is because you simply don't want to be doing it.

    Checking if type == list in python

    This seems to work for me:

    >>>a = ['x', 'y', 'z']
    >>>type(a)
    <class 'list'>
    >>>isinstance(a, list)
    True
    

    "Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

    This worked for me with phpmyadmin under Ubuntu 16.04:

    I edited /etc/phpmyadmin/config.inc.php and changed the following 2 lines:

    $cfg['Servers'][$i]['controluser'] = 'root'; 
    $cfg['Servers'][$i]['controlpass'] = 'thepasswordgiventoroot'; 
    

    C# - insert values from file into two arrays

    string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

    C++ Get name of type in template

    typeid(uint8_t).name() is nice, but it returns "unsigned char" while you may expect "uint8_t".

    This piece of code will return you the appropriate type

    #define DECLARE_SET_FORMAT_FOR(type) \
        if ( typeid(type) == typeid(T) ) \
            formatStr = #type;
    
    template<typename T>
    static std::string GetFormatName()
    {
        std::string formatStr;
    
        DECLARE_SET_FORMAT_FOR( uint8_t ) 
        DECLARE_SET_FORMAT_FOR( int8_t ) 
    
        DECLARE_SET_FORMAT_FOR( uint16_t )
        DECLARE_SET_FORMAT_FOR( int16_t )
    
        DECLARE_SET_FORMAT_FOR( uint32_t )
        DECLARE_SET_FORMAT_FOR( int32_t )
    
        DECLARE_SET_FORMAT_FOR( float )
    
        // .. to be exptended with other standard types you want to be displayed smartly
    
        if ( formatStr.empty() )
        {
            assert( false );
            formatStr = typeid(T).name();
        }
    
        return formatStr;
    }
    

    http://localhost:50070 does not work HADOOP

    If you can open the http://localhost:8088/cluster but can't open http://localhost:50070/. Maybe datanode didn't start-up or namenode didn't formate.

    Hadoop version 2.6.4

    • step 1:

    check whether your namenode has been formated, if not type:

    $ stop-all.sh
    $ /path/to/hdfs namenode -format
    $ start-all.sh
    
    • step 2:

    check your namenode tmp file path, to see in /tmp, if the namenode directory is in /tmp, you need set tmp path in core-site.xml, because every time when you reboot or start your machine, the files in /tmp will be removed, you need set a tmp dir path.

    add the following to it.

    <property>
        <name>hadoop.tmp.dir</name>
        <value>/path/to/hadoop/tmp</value>
    </property>
    
    • step 3:

    check step 2, stop hadoop and remove the namenode tmp dir in /tmp, then type /path/to/hdfs namenode -format, and start the hadoop. The is also a tmp dir in $HADOOP_HOME

    If all the above don't help, please comment below!

    How to select rows from a DataFrame based on column values

    For selecting only specific columns out of multiple columns for a given value in Pandas:

    select col_name1, col_name2 from table where column_name = some_value.
    

    Options:

    df.loc[df['column_name'] == some_value][[col_name1, col_name2]]
    

    or

    df.query['column_name' == 'some_value'][[col_name1, col_name2]]
    

    Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

    I was looking for a listing of macOS but found nothing, maybe this helps someone.

    Output on macOS Catalina (10.15.7) using net5.0

    # SpecialFolders (Only with value)
    SpecialFolder.ApplicationData: /Users/$USER/.config
    SpecialFolder.CommonApplicationData: /usr/share
    SpecialFolder.Desktop: /Users/$USER/Desktop
    SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
    SpecialFolder.Favorites: /Users/$USER/Library/Favorites
    SpecialFolder.Fonts: /Users/$USER/Library/Fonts
    SpecialFolder.InternetCache: /Users/$USER/Library/Caches
    SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
    SpecialFolder.MyDocuments: /Users/$USER
    SpecialFolder.MyMusic: /Users/$USER/Music
    SpecialFolder.MyPictures: /Users/$USER/Pictures
    SpecialFolder.ProgramFiles: /Applications
    SpecialFolder.System: /System
    SpecialFolder.UserProfile: /Users/$USER
    
    # SpecialFolders (All)
    SpecialFolder.AdminTools: 
    SpecialFolder.ApplicationData: /Users/$USER/.config
    SpecialFolder.CDBurning: 
    SpecialFolder.CommonAdminTools: 
    SpecialFolder.CommonApplicationData: /usr/share
    SpecialFolder.CommonDesktopDirectory: 
    SpecialFolder.CommonDocuments: 
    SpecialFolder.CommonMusic: 
    SpecialFolder.CommonOemLinks: 
    SpecialFolder.CommonPictures: 
    SpecialFolder.CommonProgramFiles: 
    SpecialFolder.CommonProgramFilesX86: 
    SpecialFolder.CommonPrograms: 
    SpecialFolder.CommonStartMenu: 
    SpecialFolder.CommonStartup: 
    SpecialFolder.CommonTemplates: 
    SpecialFolder.CommonVideos: 
    SpecialFolder.Cookies: 
    SpecialFolder.Desktop: /Users/$USER/Desktop
    SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
    SpecialFolder.Favorites: /Users/$USER/Library/Favorites
    SpecialFolder.Fonts: /Users/$USER/Library/Fonts
    SpecialFolder.History: 
    SpecialFolder.InternetCache: /Users/$USER/Library/Caches
    SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
    SpecialFolder.LocalizedResources: 
    SpecialFolder.MyComputer: 
    SpecialFolder.MyDocuments: /Users/$USER
    SpecialFolder.MyMusic: /Users/$USER/Music
    SpecialFolder.MyPictures: /Users/$USER/Pictures
    SpecialFolder.MyVideos: 
    SpecialFolder.NetworkShortcuts: 
    SpecialFolder.PrinterShortcuts: 
    SpecialFolder.ProgramFiles: /Applications
    SpecialFolder.ProgramFilesX86: 
    SpecialFolder.Programs: 
    SpecialFolder.Recent: 
    SpecialFolder.Resources: 
    SpecialFolder.SendTo: 
    SpecialFolder.StartMenu: 
    SpecialFolder.Startup: 
    SpecialFolder.System: /System
    SpecialFolder.SystemX86: 
    SpecialFolder.Templates: 
    SpecialFolder.UserProfile: /Users/$USER
    SpecialFolder.Windows: 
    

    I have replaced my username with $USER.

    Code Snippet from pogosama.

    foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
    {
        string commonAppData = Environment.GetFolderPath(f);
        Console.WriteLine("{0}: {1}", f, commonAppData);
    }
    Console.ReadLine();
    

    Negate if condition in bash script

    You can choose:

    if [[ $? -ne 0 ]]; then       # -ne: not equal
    
    if ! [[ $? -eq 0 ]]; then     # -eq: equal
    
    if [[ ! $? -eq 0 ]]; then
    

    ! inverts the return of the following expression, respectively.

    What to do with branch after merge

    I prefer RENAME rather than DELETE

    All my branches are named in the form of

    • Fix/fix-<somedescription> or
    • Ftr/ftr-<somedescription> or
    • etc.

    Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
    Once I am done with a branch, I rename them to Done/...-<description>.

    That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

    How to use C++ in Go

    You're walking on uncharted territory here. Here is the Go example for calling C code, perhaps you can do something like that after reading up on C++ name mangling and calling conventions, and lots of trial and error.

    If you still feel like trying it, good luck.

    internet explorer 10 - how to apply grayscale filter?

    IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

    However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

    img.grayscale:hover {
        filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
    }
    
    svg {
        background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
    }
    

    (from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

    Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

    More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

    What is the C++ function to raise a number to a power?

    pow(2.0,1.0)
    pow(2.0,2.0)
    pow(2.0,3.0)
    

    Your original question title is misleading. To just square, use 2*2.

    Add column to SQL query results

    Manually add it when you build the query:

    SELECT 'Site1' AS SiteName, t1.column, t1.column2
    FROM t1
    
    UNION ALL
    SELECT 'Site2' AS SiteName, t2.column, t2.column2
    FROM t2
    
    UNION ALL
    ...
    

    EXAMPLE:

    DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
    DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
    
    INSERT INTO @t1
    SELECT 1, 'a'
    UNION SELECT 2, 'b'
    
    INSERT INTO @t2
    SELECT 3, 'c'
    UNION SELECT 4, 'd'
    
    
    SELECT 'Site1' AS SiteName, t1.column1, t1.column2
    FROM @t1 t1
    
    UNION ALL
    SELECT 'Site2' AS SiteName, t2.column1, t2.column2
    FROM @t2 t2
    

    RESULT:

    SiteName  column1  column2
    Site1       1      a
    Site1       2      b
    Site2       3      c
    Site2       4      d
    

    elasticsearch bool query combine must with OR

    $filterQuery = $this->queryFactory->create(QueryInterface::TYPE_BOOL, ['must' => $queries,'should'=>$queriesGeo]);
    

    In must you need to add the query condition array which you want to work with AND and in should you need to add the query condition which you want to work with OR.

    You can check this: https://github.com/Smile-SA/elasticsuite/issues/972

    Cmake is not able to find Python-libraries

    You can fix the errors by appending to the cmake command the -DPYTHON_LIBRARY and -DPYTHON_INCLUDE_DIR flags filled with the respective folders.

    Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):

    $ cmake .. \
    -DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
    -DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")
    

    If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ... can be used instead of python -c ....

    In case that the error persists, you may need to update the cmake to a higher version as stated by @pdpcosta and repeat the process again.

    How to workaround 'FB is not defined'?

    You were very close with your original example. You could either use @jAndy's suggestion or:

    if (typeof FB != 'undefined')
    

    Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

    Adding this as a second reference because I had a similar problem..
    I had to explicitly add '.aar' as a registered file type under the 'Archives' category in AS settings.

    Check/Uncheck a checkbox on datagridview

    You can use this code on your grid CellClick event for check or unchecked cell checkbox :

    private void Grid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = (Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? true : (!(bool)Grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value));
            }
        }
    

    Checking if a number is a prime number in Python

    def is_prime(x):
        n = 2
        if x < n:
            return False
        else:    
            while n < x:
               print n
                if x % n == 0:
                    return False
                    break
                n = n + 1
            else:
                return True
    

    Sending XML data using HTTP POST with PHP

    Another option would be file_get_contents():

    // $xml_str = your xml
    // $url = target url
    
    $post_data = array('xml' => $xml_str);
    $stream_options = array(
        'http' => array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
            'content' =>  http_build_query($post_data)));
    
    $context  = stream_context_create($stream_options);
    $response = file_get_contents($url, null, $context);
    

    I can't delete a remote master branch on git

    As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.

    You need to go to the GitHub page for your forked repository, and click on the “Settings” button.

    Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.

    From there, select placeholder (where placeholder is the dummy name for your new default branch).

    Confirm that you want to change your default branch.

    Now you can do (from the command line):

    git push origin :master
    

    Or, since 2012, you can delete that same branch directly on GitHub:

    GitHub deletion

    That was announced in Sept. 2013, a year after I initially wrote that answer.

    For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.


    Note: for BitBucket, Tum reports in the comments:

    About the same for Bitbucket

    Repo -> Settings -> Repository details -> Main branch
    

    What datatype should be used for storing phone numbers in SQL Server 2005?

    using varchar is pretty inefficient. use the money type and create a user declared type "phonenumber" out of it, and create a rule to only allow positive numbers.

    if you declare it as (19,4) you can even store a 4 digit extension and be big enough for international numbers, and only takes 9 bytes of storage. Also, indexes are speedy.

    How to sort the letters in a string alphabetically in Python

    Python functionsorted returns ASCII based result for string.

    INCORRECT: In the example below, e and d is behind H and W due it's to ASCII value.

    >>>a = "Hello World!"
    >>>"".join(sorted(a))
    ' !!HWdellloor'
    

    CORRECT: In order to write the sorted string without changing the case of letter. Use the code:

    >>> a = "Hello World!"
    >>> "".join(sorted(a,key=lambda x:x.lower()))
    ' !deHllloorW'
    

    If you want to remove all punctuation and numbers. Use the code:

    >>> a = "Hello World!"
    >>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
    'deHllloorW'
    

    Spring Boot application can't resolve the org.springframework.boot package

    Mine worked by adding

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>2.1.3.RELEASE</version>
    </dependency>
    

    instead of directly using other main dependencies, I have no idea why.

    PHP: get the value of TEXTBOX then pass it to a VARIABLE

    You are posting the data, so it should be $_POST. But 'name' is not the best name to use.

    name = "name"
    

    will only cause confusion IMO.

    Where does npm install packages?

    The command npm root will tell you the effective installation directory of your npm packages.

    If your current working directory is a node package or a sub-directory of a node package, npm root will tell you the local installation directory. npm root -g will show the global installation root regardless of current working directory.

    Example:

    $ npm root -g
    /usr/local/lib/node_modules
    

    See the documentation.

    How do I convert from a money datatype in SQL server?

    This looks like a formating issue to me.
    As far as SQL Server's money type is concerned 0 == 0.00

    If you're trying to display 0 in say c# rather then 0.00 you should convert it to a string, and format it as you want. (or truncate it.)

    Disable back button in android

    You can do this simple way Don't call super.onBackPressed()

    Note:- Don't do this unless and until you have strong reason to do it.

    @Override
    public void onBackPressed() {
    // super.onBackPressed();
    // Not calling **super**, disables back button in current screen.
    }
    

    Shell script to set environment variables

    Run the script as source= to run in debug mode as well.

    source= ./myscript.sh
    

    Which characters need to be escaped when using Bash?

    format that can be reused as shell input

    Edit february 2021: ${var@Q}

    Under bash, you could store your variable content with Parameter Expansion's @ command for Parameter transformation:

    ${parameter@operator}
           Parameter transformation.  The expansion is either a transforma-
           tion of the value of parameter or  information  about  parameter
           itself,  depending on the value of operator.  Each operator is a
           single letter:
    
           Q      The expansion is a string that is the value of  parameter
                  quoted in a format that can be reused as input.
    ...
           A      The  expansion  is  a string in the form of an assignment
                  statement or declare command  that,  if  evaluated,  will
                  recreate parameter with its attributes and value.
    

    Sample:

    $ var=$'Hello\nGood world.\n'
    $ echo "$var"
    Hello
    Good world.
    
    $ echo "${var@Q}"
    $'Hello\nGood world.\n'
    
    $ echo "${var@A}"
    var=$'Hello\nGood world.\n'
    

    Old answer

    There is a special printf format directive (%q) built for this kind of request:

    printf [-v var] format [arguments]

     %q     causes printf to output the corresponding argument
            in a format that can be reused as shell input.
    

    Some samples:

    read foo
    Hello world
    printf "%q\n" "$foo"
    Hello\ world
    
    printf "%q\n" $'Hello world!\n'
    $'Hello world!\n'
    

    This could be used through variables too:

    printf -v var "%q" "$foo
    "
    echo "$var"
    $'Hello world\n'
    

    Quick check with all (128) ascii bytes:

    Note that all bytes from 128 to 255 have to be escaped.

    for i in {0..127} ;do
        printf -v var \\%o $i
        printf -v var $var
        printf -v res "%q" "$var"
        esc=E
        [ "$var" = "$res" ] && esc=-
        printf "%02X %s %-7s\n" $i $esc "$res"
    done |
        column
    

    This must render something like:

    00 E ''         1A E $'\032'    34 - 4          4E - N          68 - h      
    01 E $'\001'    1B E $'\E'      35 - 5          4F - O          69 - i      
    02 E $'\002'    1C E $'\034'    36 - 6          50 - P          6A - j      
    03 E $'\003'    1D E $'\035'    37 - 7          51 - Q          6B - k      
    04 E $'\004'    1E E $'\036'    38 - 8          52 - R          6C - l      
    05 E $'\005'    1F E $'\037'    39 - 9          53 - S          6D - m      
    06 E $'\006'    20 E \          3A - :          54 - T          6E - n      
    07 E $'\a'      21 E \!         3B E \;         55 - U          6F - o      
    08 E $'\b'      22 E \"         3C E \<         56 - V          70 - p      
    09 E $'\t'      23 E \#         3D - =          57 - W          71 - q      
    0A E $'\n'      24 E \$         3E E \>         58 - X          72 - r      
    0B E $'\v'      25 - %          3F E \?         59 - Y          73 - s      
    0C E $'\f'      26 E \&         40 - @          5A - Z          74 - t      
    0D E $'\r'      27 E \'         41 - A          5B E \[         75 - u      
    0E E $'\016'    28 E \(         42 - B          5C E \\         76 - v      
    0F E $'\017'    29 E \)         43 - C          5D E \]         77 - w      
    10 E $'\020'    2A E \*         44 - D          5E E \^         78 - x      
    11 E $'\021'    2B - +          45 - E          5F - _          79 - y      
    12 E $'\022'    2C E \,         46 - F          60 E \`         7A - z      
    13 E $'\023'    2D - -          47 - G          61 - a          7B E \{     
    14 E $'\024'    2E - .          48 - H          62 - b          7C E \|     
    15 E $'\025'    2F - /          49 - I          63 - c          7D E \}     
    16 E $'\026'    30 - 0          4A - J          64 - d          7E E \~     
    17 E $'\027'    31 - 1          4B - K          65 - e          7F E $'\177'
    18 E $'\030'    32 - 2          4C - L          66 - f      
    19 E $'\031'    33 - 3          4D - M          67 - g      
    

    Where first field is hexa value of byte, second contain E if character need to be escaped and third field show escaped presentation of character.

    Why ,?

    You could see some characters that don't always need to be escaped, like ,, } and {.

    So not always but sometime:

    echo test 1, 2, 3 and 4,5.
    test 1, 2, 3 and 4,5.
    

    or

    echo test { 1, 2, 3 }
    test { 1, 2, 3 }
    

    but care:

    echo test{1,2,3}
    test1 test2 test3
    
    echo test\ {1,2,3}
    test 1 test 2 test 3
    
    echo test\ {\ 1,\ 2,\ 3\ }
    test  1 test  2 test  3
    
    echo test\ {\ 1\,\ 2,\ 3\ }
    test  1, 2 test  3 
    

    jQuery plugin returning "Cannot read property of undefined"

    The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:

    var len = menuitems.length;
    for (var i = 0; i < len; i++){
        (function(i) {
          $('<li/>',{
              'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
              'click':function(){
                  menuitems[i].action();
              },
              'class':o.itemClass
          }).appendTo('.'+o.listClass);
        })(i);
    }
    

    In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.

    The condition has length > 1 and only the first element will be used

    Like sgibb said it was an if problem, it had nothing to do with | or ||.

    Here is another way to solve your problem:

    for (i in 1:nrow(trip)) {
      if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
        trip[i, 'mutType'] <- "G:C to T:A"
      }
      else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
        trip[i, 'mutType'] <- "G:C to C:G"
      }
      else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
        trip[i, 'mutType'] <- "G:C to A:T"
      }
      else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
        trip[i, 'mutType'] <- "A:T to T:A"
      }
      else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
        trip[i, 'mutType'] <- "A:T to G:C"
      }
      else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
        trip[i, 'mutType'] <- "A:T to C:G"
      }
    }
    

    Replace non-ASCII characters with a single space

    What about this one?

    def replace_trash(unicode_string):
         for i in range(0, len(unicode_string)):
             try:
                 unicode_string[i].encode("ascii")
             except:
                  #means it's non-ASCII
                  unicode_string=unicode_string[i].replace(" ") #replacing it with a single space
         return unicode_string
    

    Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

    While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.

    git still shows files as modified after adding to .gitignore

    In my case, the .gitignore file is somehow corrupted. It sometimes shows up OK but sometimes is gibberish. I guess the encoding might be to blame but cannot be sure. To solve the issue, I deleted the file (previously created through echo > .gitgore in VS Code commandline) and created a new one manually in the file system (Explorer), then added my ignore rules. After the new .ignore was in place, everything works fine.

    string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

    It says it all IsNullOrEmpty() does not include white spacing while IsNullOrWhiteSpace() does!

    IsNullOrEmpty() If string is:
    -Null
    -Empty

    IsNullOrWhiteSpace() If string is:
    -Null
    -Empty
    -Contains White Spaces Only

    Merge two objects with ES6

    Another aproach is:

    let result = { ...item, location : { ...response } }
    

    But Object spread isn't yet standardized.

    May also be helpful: https://stackoverflow.com/a/32926019/5341953

    CSS div 100% height

    try setting the body style to:

    body { position:relative;}
    

    it worked for me

    Type safety: Unchecked cast

    The solution to avoid the unchecked warning:

    class MyMap extends HashMap<String, String> {};
    someMap = (MyMap)getApplicationContext().getBean("someMap");
    

    What's the best way to break from nested loops in JavaScript?

    Quite simple:

    var a = [1, 2, 3];
    var b = [4, 5, 6];
    var breakCheck1 = false;
    
    for (var i in a) {
        for (var j in b) {
            breakCheck1 = true;
            break;
        }
        if (breakCheck1) break;
    }
    

    Dropping Unique constraint from MySQL table

    The constraint could be removed with syntax:

    ALTER TABLE

    As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name: ALTER TABLE tbl_name DROP CONSTRAINT symbol;

    Example:

    CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));
    
    -- checking constraint name if autogenerated
    SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';
    
    -- dropping constraint
    ALTER TABLE tab DROP CONSTRAINT unq_tab_id;
    

    db<>fiddle demo

    Getting DOM elements by classname

    DOMDocument is slow to type and phpQuery has bad memory leak issues. I ended up using:

    https://github.com/wasinger/htmlpagedom

    To select a class:

    include 'includes/simple_html_dom.php';
    
    $doc = str_get_html($html);
    $href = $doc->find('.lastPage')[0]->href;
    

    I hope this helps someone else as well

    CSS center content inside div

    The problem is that you assigned a fixed width to your .wrap DIV. The DIV itself is centered (you can see that when you add a border to it) but the DIV is just too wide. In other words the content does not fill the whole width of the DIV.

    To solve the problem you have to make sure, that the .wrap DIV is only as wide as it's content.

    To achieve that you have to remove the floating in the content elements and set the display property of the block levels elements to inline:

    #partners .wrap {
     display: inline;
    } 
    
    .wrap { margin: 0 auto; position: relative;}
    
    #partners h2 {
    color: #A6A5A5;
    font-weight: normal;
    margin: 2px 15px 0 0;
    display: inline;
    }
    
    #partners ul {
    display: inline;
    }
    
    #partners li {display: inline}
    
    ul { list-style-position: outside; list-style-type: none; }
    

    Installing PHP Zip Extension

    I tried changing the repository list with:

    http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe

    But none of them seem to work, but I finally found a repository that works running the following command

    add-apt-repository ppa:ondrej/php

    And then updating and installing normally the package using apt-get

    As you can see it's installed at last.

    Cannot make Project Lombok work on Eclipse

    It was little frustrating. But finally it got resolved for me with following solution.

    The issue seems to be where "-javaagent:lombok.jar" is placed in your ini file. When i installed it through lombok installation. This line got added towards last parameters after -vmargs. When i moved it up next to -vmargs. the issue got resolved.

    Pausing a batch file for amount of time

    If choice is available, use this:

    choice /C X /T 10 /D X > nul
    

    where /T 10 is the number of seconds to delay. Note the syntax can vary depending on your Windows version, so use CHOICE /? to be sure.

    AttributeError: 'dict' object has no attribute 'predictors'

    The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

    >>> d = {'hello': 34, 'world': 2999}
    >>> for key, value in d.items():
    ...   print key, value
    ...
    world 2999
    hello 34
    

    The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

    Update Fragment from ViewPager

    i had 4 Fragments in the ViewPager, but i wanted to update just one Fragment "FavoriteFragment" at the position 0 of the viewPager, every time the user click on this fragment. but none of the codes above helped me reload just the one Fragment i want. so i tried this and it works for me:

    in my FavoriteFragment i overrided onResume()

    @Override
        public void onResume() {
            super.onResume();
            updateUI(); // code to update the UI in the fragment
        }
    

    in the Activity hosting the viewPager override addOnPageChangeListener() and add this code

    mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
    
                    if(position == 0) { // 0 = the first fragment in the ViewPager, in this case, the fragment i want to refresh its UI
                        FavoritesFragment fragment = (FavoritesFragment) mViewPager.getAdapter().instantiateItem(mViewPager, position); 
                        fragment.onResume(); // here i call the onResume of the fragment, where i have the method updateUI() to update its UI
                        mViewPager.getAdapter().notifyDataSetChanged();
                    }
                }
            });
    

    and it works perfect for me, to refresh/reload just the one fragment i want.

    grunt: command not found when running from terminal

    My fix for this on Mountain Lion was: -

    npm install -g grunt-cli 
    

    Saw it on http://gruntjs.com/getting-started

    What version of Python is on my Mac?

    You could have multiple Python versions on your macOS.

    You may check that by command, type or which command, like:

    which -a python python2 python2.7 python3 python3.6
    

    Or type python in Terminal and hit Tab few times for auto completion, which is equivalent to:

    compgen -c python
    

    By default python/pip commands points to the first binary found in PATH environment variable depending what's actually installed. So before installing Python packages with Homebrew, the default Python is installed in /usr/bin which is shipped with your macOS (e.g. Python 2.7.10 on High Sierra). Any versions found in /usr/local (such as /usr/local/bin) are provided by external packages.

    It is generally advised, that when working with multiple versions, for Python 2 you may use python2/pip2 command, respectively for Python 3 you can use python3/pip3, but it depends on your configuration which commands are available.

    It is also worth to mention, that since release of Homebrew 1.5.0+ (on 19 January 2018), the python formula has been upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7. Before, python formula was pointing to Python 2.

    For instance, if you've installed different version via Homebrew, try the following command:

    brew list python python3
    

    or:

    brew list | grep ^python
    

    it'll show you all Python files installed with the package.

    Alternatively you may use apropos or locate python command to locate more Python related files.

    To check any environment variables related to Python, run:

    env | grep ^PYTHON
    

    To address your issues:

    • Error: No such keg: /usr/local/Cellar/python

      Means you don't have Python installed via Homebrew. However double check by specifying only one package at a time (like brew list python python2 python3).

    • The locate database (/var/db/locate.database) does not exist.

      Follow the advice and run:

      sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
      

      After the database is rebuild, you can use locate command.

    glm rotate usage in Opengl

    You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).

    All you need to do is (see here)

    Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
    

    Note that to convert from degrees to radians, use glm::radians(degrees)

    That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.

    note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6

    Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
    

    Tomcat Servlet: Error 404 - The requested resource is not available

    You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like

    @WebServlet(name="helloServlet", urlPatterns={"/hello"})
    public class HelloWorld extends HttpServlet {
         //rest of the class
    

    Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like

    <servlet>
        <servlet-name>helloServlet</servlet-name>
        <servlet-class>crunch.HelloWorld</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    

    Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

    Another simple way to solve this problem is to edit your build.gradle (app):

    1. Go to android tag and change compileSdkVersion 26 to compileSdkVersion 27
    2. Go to defaultConfig tag and change targetSdkVersion 26 to targetSdkVersion 27
    3. Got to dependencies tag and change implementation 'com.android.support:appcompat-v7:26.1.0' to implementation 'com.android.support:appcompat-v7:27.1.1'

    How to convert signed to unsigned integer in python

    just use abs for converting unsigned to signed in python

     a=-12
    b=abs(a)
    print(b)
    

    Output: 12

    Freely convert between List<T> and IEnumerable<T>

    A List<T> is already an IEnumerable<T>, so you can run LINQ statements directly on your List<T> variable.

    If you don't see the LINQ extension methods like OrderBy() I'm guessing it's because you don't have a using System.Linq directive in your source file.

    You do need to convert the LINQ expression result back to a List<T> explicitly, though:

    List<Customer> list = ...
    list = list.OrderBy(customer => customer.Name).ToList()
    

    Polynomial time and exponential time

    Polynomial time.

    A polynomial is a sum of terms that look like Constant * x^k Exponential means something like Constant * k^x

    (in both cases, k is a constant and x is a variable).

    The execution time of exponential algorithms grows much faster than that of polynomial ones.

    How to format DateTime in Flutter , How to get current time in flutter?

    You can also use this syntax. For YYYY-MM-JJ HH-MM:

    var now = DateTime.now();
    var month = now.month.toString().padLeft(2, '0');
    var day = now.day.toString().padLeft(2, '0');
    var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';
    

    Java: Finding the highest value in an array

    If you are looking for the quickest and simplest way to perform various actions in regards to arrays, the use of the Collections class is extremely helpful (documentation available from https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html), actions ranges from finding the maximum, minimum, sorting, reverse order, etc.

    A simple way to find the maximum value from the array with the use of Collections:

    Double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4, 8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2, 3.5, 3.0, 1.1, 6.5, 5.1, -1.2, -5.1, 2.0, 5.2, 2.1};
    List<Double> a = new ArrayList<Double>(Arrays.asList(decMax));
    System.out.println("The highest maximum for the December is: " + Collections.max(a));
    

    If you are interested in finding the minimum value, similar to finding maximum:

    System.out.println(Collections.min(a));
    

    The simplest line to sort the list:

    Collections.sort(a);
    

    Or alternatively the use of the Arrays class to sort an array:

    Arrays.sort(decMax);
    

    However the Arrays class does not have a method that refers to the maximum value directly, sorting it and referring to the last index is the maximum value, however keep in mind sorting by the above 2 methods has a complexity of O(n log n).

    How to create a new branch from a tag?

    An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )

    git fetch upstream --tags
    

    Give me

    From https://github.com/keycloak/keycloak
       90b29b0e31..0ba9055d28  stage      -> upstream/stage
     * [new tag]    11.0.0     -> 11.0.0
    

    Then I can create a new branch from this tag and checkout on it

    git checkout -b tags/<name> <newbranch>

    git checkout tags/11.0.0 -b v11.0.0
    

    bootstrap 4 responsive utilities visible / hidden xs sm lg not working

    Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

    How to count string occurrence in string?

    function countInstances(string, word) {
       return string.split(word).length - 1;
    }
    

    The container 'Maven Dependencies' references non existing library - STS

    Today I had this same problem with another jar. I tried multiple things people said on Stackoverflow, but nothing worked. Eventually I did this:

    1. Close eclipse and any project-app that is running.
    2. Delete the .m2 folder (Users --> [your_username] --> .m2). It's an invisible folder, make sure you are able to view invisible folders.
    3. Restarted Eclipse (I guess it works in other IDE too) and updated my project.

    Now it works again for me. Perhaps this solves the problem for someone else too.

    How does the compilation/linking process work?

    This topic is discussed at CProgramming.com:
    https://www.cprogramming.com/compilingandlinking.html

    Here is what the author there wrote:

    Compiling isn't quite the same as creating an executable file! Instead, creating an executable is a multistage process divided into two components: compilation and linking. In reality, even if a program "compiles fine" it might not actually work because of errors during the linking phase. The total process of going from source code files to an executable might better be referred to as a build.

    Compilation

    Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name .o or .obj (the extension will depend on your compiler). Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use. That's where the linker comes in.

    Linking

    Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.

    You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)

    To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled. (You could, of course, just recompile every file that has a timestamp greater than the timestamp of the corresponding object file.) If you're working with an integrated development environment (IDE) it may already take care of this for you. If you're using command line tools, there's a nifty utility called make that comes with most *nix distributions. Along with conditional compilation, it has several other nice features for programming, such as allowing different compilations of your program -- for instance, if you have a version producing verbose output for debugging.

    Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. Linking errors usually have to do with missing or multiple definitions. If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.

    Get Date Object In UTC format in Java

    final Date currentTime = new Date();
    final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println("UTC time: " + sdf.format(currentTime));
    

    JavaScript module pattern with example

    Here https://toddmotto.com/mastering-the-module-pattern you can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/

    C++ correct way to return pointer to array from function

    A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:

    #include <assert.h>
    
    int main() {
      int a[] = {1, 2, 3, 4, 5}; 
    
      int* pArr = a;
      int* pFirstElem = &(a[0]);
    
      assert(a == pArr);
      assert(a == pFirstElem);
    
      return 0;
    }
    

    This also means that passing an array to a function should be done via pointer (and not via int in[5]), and possibly along with the length of the array:

    int* test(int* in, int len) {
        int* out = in;
        return out;
    }
    

    That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:

    #include <iostream>
    
    using namespace std;
    
    int main() {
      int* pArr = 0;
      {
        int a[] = {1, 2, 3, 4, 5};
        pArr = a; // or test(a) if you wish
      }
      // a[] went out of scope here, but pArr holds a pointer to it
    
      // all bets are off, this can output "1", output 1st chapter
      // of "Romeo and Juliet", crash the program or destroy the
      // universe
      cout << pArr[0] << endl; // WRONG!
    
      return 0;
    }
    

    So if you don't feel competent enough, just use std::vector.

    [answer to the updated question]

    The correct way to write your test function is either this:

    void test(int* a, int* b, int* c, int len) {
      for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
    }
    ...
    int main() {
       int a[5] = {...}, b[5] = {...}, c[5] = {};
       test(a, b, c, 5);
       // c now holds the result
    }
    

    Or this (using std::vector):

    #include <vector>
    
    vector<int> test(const vector<int>& a, const vector<int>& b) {
      vector<int> result(a.size());
      for (int i = 0; i < a.size(); ++i) {
        result[i] = a[i] + b[i];
      }
      return result; // copy will be elided
    }
    

    Bootstrap button drop-down inside responsive table not visible because of scroll

    For reference, it's 2018 and I'm using BS4.1

    Try adding data-boundary="viewport" to the button that toggles the dropdown (the one with the class dropdown-toggle). See https://getbootstrap.com/docs/4.1/components/dropdowns/#options

    How to run a program automatically as admin on Windows 7 at startup?

    You should also consider the security implications of running a process as an administrator level user or as Service. If any input is not being validated properly, such as if it is listening on a network interface. If the parser for this input doesn't validate properly, it can be abused, and possibly lead to an exploit that could run code as the elevated user. in abatishchev's example it shouldn't be much of a problem, but if it were to be deployed in an enterprise environment, do a security assessment prior to wide scale deployment.

    How do I enter a multi-line comment in Perl?

    I found it. Perl has multi-line comments:

    #!/usr/bin/perl
    
    use strict;
    
    use warnings;
    
    =for comment
    
    Example of multiline comment.
    
    Example of multiline comment.
    
    =cut
    
    print "Multi Line Comment Example \n";
    

    What are bitwise shift (bit-shift) operators and how do they work?

    The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.

    The Operators

    • >> is the arithmetic (or signed) right shift operator.
    • >>> is the logical (or unsigned) right shift operator.
    • << is the left shift operator, and meets the needs of both logical and arithmetic shifts.

    All of these operators can be applied to integer values (int, long, possibly short and byte or char). In some languages, applying the shift operators to any datatype smaller than int automatically resizes the operand to be an int.

    Note that <<< is not an operator, because it would be redundant.

    Also note that C and C++ do not distinguish between the right shift operators. They provide only the >> operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.

    (In all mainstream C and C++ implementations including GCC and Clang/LLVM, >> on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not undefined, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers is undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)


    Left shift (<<)

    Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int would be:

    00000000 00000000 00000000 00000110
    

    Shifting this bit pattern to the left one position (6 << 1) would result in the number 12:

    00000000 00000000 00000000 00001100
    

    As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So 6 << 1 is equivalent to 6 * 2, and 6 << 3 is equivalent to 6 * 8. A good optimizing compiler will replace multiplications with shifts when possible.

    Non-circular shifting

    Please note that these are not circular shifts. Shifting this value to the left by one position (3,758,096,384 << 1):

    11100000 00000000 00000000 00000000
    

    results in 3,221,225,472:

    11000000 00000000 00000000 00000000
    

    The digit that gets shifted "off the end" is lost. It does not wrap around.


    Logical right shift (>>>)

    A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:

    00000000 00000000 00000000 00001100
    

    to the right by one position (12 >>> 1) will get back our original 6:

    00000000 00000000 00000000 00000110
    

    So we see that shifting to the right is equivalent to division by powers of 2.

    Lost bits are gone

    However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:

    00111000 00000000 00000000 00000110
    

    to the left 4 positions (939,524,102 << 4), we get 2,147,483,744:

    10000000 00000000 00000000 01100000
    

    and then shifting back ((939,524,102 << 4) >>> 4) we get 134,217,734:

    00001000 00000000 00000000 00000110
    

    We cannot get back our original value once we have lost bits.


    Arithmetic right shift (>>)

    The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the sign bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.

    For example, if we interpret this bit pattern as a negative number:

    10000000 00000000 00000000 01100000
    

    we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:

    11111000 00000000 00000000 00000110
    

    or the number -134,217,722.

    So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.

    How to make VS Code to treat other file extensions as certain language?

    This, for example, will make files ending in .variables and .overrides being treated just like any other LESS file. In terms of code coloring, in terms of (auto) formatting. Define in user settings or project settings, as you like.

    (Semantic UI uses these weird extensions, in case you wonder)

    How to reset par(mfrow) in R

    You can reset the mfrow parameter

    par(mfrow=c(1,1))
    

    How to set index.html as root file in Nginx?

    The answer is to place the root dir to the location directives:

    root   /srv/www/ducklington.org/public_html;
    

    Set a form's action attribute when submitting?

    Attach to the submit button click event and change the action attribute in the event handler.

    WCF, Service attribute value in the ServiceHost directive could not be found

    Building the solution before adding the service reference solved my problem.

    How to enter ssh password using bash?

    Create a new keypair: (go with the defaults)

    ssh-keygen
    

    Copy the public key to the server: (password for the last time)

    ssh-copy-id [email protected]
    

    From now on the server should recognize your key and not ask you for the password anymore:

    ssh [email protected]
    

    OAuth 2.0 Authorization Header

    For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:

    Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
    

    How do I run a spring boot executable jar in a Production environment?

    You can use the application called Supervisor. In supervisor config you can define multiple services and ways to execute the same.

    For Java and Spring boot applications the command would be java -jar springbootapp.jar.

    Options can be provided to keep the application running always.So if the EC2 restart then Supervisor will restart you application

    I found Supervisor easy to use compared to putting startup scripts in /etc/init.d/.The startup scripts would hang or go into waiting state in case of errors .

    Cannot find reference 'xxx' in __init__.py - Python / Pycharm

    You should first take a look at this. This explains what happens when you import a package. For convenience:

    The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package.

    So PyCharm respects this by showing a warning message, so that the author can decide which of the modules get imported when * from the package is imported. Thus this seems to be useful feature of PyCharm (and in no way can it be called a bug, I presume). You can easily remove this warning by adding the names of the modules to be imported when your package is imported in the __all__ variable which is list, like this

    __init__.py

    from . import MyModule1, MyModule2, MyModule3
    __all__ = [MyModule1, MyModule2, MyModule3]
    

    After you add this, you can ctrl+click on these module names used in any other part of your project to directly jump to the declaration, which I often find very useful.

    How do I write the 'cd' command in a makefile?

    Like this:

    target:
        $(shell cd ....); \
        # ... commands execution in this directory
        # ... no need to go back (using "cd -" or so)
        # ... next target will be automatically in prev dir
    

    Good luck!

    Disabling Chrome Autofill

    The autocomplete feature has successfully disabled via this trick. It Works!

    [HTML]

    <div id="login_screen" style="min-height: 45px;">
       <input id="password_1" type="text" name="password">
    </div>
    

    [JQuery]

    $("#login_screen").on('keyup keydown mousedown', '#password_1', function (e) {
        let elem = $(this);
    
        if (elem.val().length > 0 && elem.attr("type") === "text") {
            elem.attr("type", "password");
        } else {
            setTimeout(function () {
                if (elem.val().length === 0) {
                    elem.attr("type", "text");
                    elem.hide();
                    setTimeout(function () {
                        elem.show().focus();
                    }, 1);
                }
            }, 1);
        }
    
        if (elem.val() === "" && e.type === "mousedown") {
            elem.hide();
            setTimeout(function () {
                elem.show().focus();
            }, 1);
        }
    
    });
    

    Expected response code 220 but got code "", with message "" in Laravel

    i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).

    How to return JSon object

    You only have one row to serialize. Try something like this :

    List<results> resultRows = new List<results>
    
    resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
    resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});
    
    string json = JavaScriptSerializer.Serialize(new { results = resultRows});
    
    • Edit to match OP's original json output

    ** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

    {"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}
    

    The 'packages' element is not declared

    Taken from this answer.

    1. Close your packages.config file.
    2. Build
    3. Warning is gone!

    This is the first time I see ignoring a problem actually makes it go away...

    Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can

    Pandas dataframe groupby plot

    Similar to Julien's answer above, I had success with the following:

    fig, ax = plt.subplots(figsize=(10,4))
    for key, grp in df.groupby(['ticker']):
        ax.plot(grp['Date'], grp['adj_close'], label=key)
    
    ax.legend()
    plt.show()
    

    This solution might be more relevant if you want more control in matlab.

    Solution inspired by: https://stackoverflow.com/a/52526454/10521959

    Python pandas: fill a dataframe row by row

    df['y'] will set a column

    since you want to set a row, use .loc

    Note that .ix is equivalent here, yours failed because you tried to assign a dictionary to each element of the row y probably not what you want; converting to a Series tells pandas that you want to align the input (for example you then don't have to to specify all of the elements)

    In [7]: df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])
    
    In [8]: df.loc['y'] = pandas.Series({'a':1, 'b':5, 'c':2, 'd':3})
    
    In [9]: df
    Out[9]: 
         a    b    c    d
    x  NaN  NaN  NaN  NaN
    y    1    5    2    3
    z  NaN  NaN  NaN  NaN