Programs & Examples On #Fpmake

Adding simple legend to plot in R

Take a look at ?legend and try this:

legend('topright', names(a)[-1] , 
   lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)

enter image description here

How to call a method in another class of the same package?

You can either create a static method or use the other class as a member of your class calling the function in the constructor.

public class aClass {
      private SomeOtherClass oc;
      public class aClass( SomeOtherClass otherClass) {
         oc = otherClass;
      }

      public callOtherClassMethod() {
         oc.otherClassMethod();
       }
    }

File content into unix variable with newlines

Just if someone is interested in another option:

content=( $(cat test.txt) )

a=0
while [ $a -le ${#content[@]} ]
do
        echo ${content[$a]}
        a=$[a+1]
done

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No, it is not possible.

Consider a scenario where an ACBus is a derived class of base class Bus. ACBus has features like TurnOnAC and TurnOffAC which operate on a field named ACState. TurnOnAC sets ACState to on and TurnOffAC sets ACState to off. If you try to use TurnOnAC and TurnOffAC features on Bus, it makes no sense.

New Intent() starts new instance with Android: launchMode="singleTop"

What actually worked for me in the end was this:

Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);

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

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

PHP Remove elements from associative array

The way to do this to take your nested target array and copy it in single step to a non-nested array. Delete the key(s) and then assign the final trimmed array to the nested node of the earlier array. Here is a code to make it simple:

$temp_array = $list['resultset'][0];

unset($temp_array['badkey1']);
unset($temp_array['badkey2']);

$list['resultset'][0] = $temp_array;

How to know if docker is already logged in to a docker registry server

Use command like below:

docker info | grep 'name'

WARNING: No swap limit support
Username: <strong>jonasm2009</strong>

How to force remounting on React components?

What's probably happening is that React thinks that only one MyInput (unemployment-duration) is added between the renders. As such, the job-title never gets replaced with the unemployment-reason, which is also why the predefined values are swapped.

When React does the diff, it will determine which components are new and which are old based on their key property. If no such key is provided in the code, it will generate its own.

The reason why the last code snippet you provide works is because React essentially needs to change the hierarchy of all elements under the parent div and I believe that would trigger a re-render of all children (which is why it works). Had you added the span to the bottom instead of the top, the hierarchy of the preceding elements wouldn't change, and those element's wouldn't re-render (and the problem would persist).

Here's what the official React documentation says:

The situation gets more complicated when the children are shuffled around (as in search results) or if new components are added onto the front of the list (as in streams). In these cases where the identity and state of each child must be maintained across render passes, you can uniquely identify each child by assigning it a key.

When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).

You should be able to fix this by providing a unique key element yourself to either the parent div or to all MyInput elements.

For example:

render(){
    if (this.state.employed) {
        return (
            <div key="employed">
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div key="notEmployed">
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

OR

render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput key="title" ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <MyInput key="reason" ref="unemployment-reason" name="unemployment-reason" />
                <MyInput key="duration" ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

Now, when React does the diff, it will see that the divs are different and will re-render it including all of its' children (1st example). In the 2nd example, the diff will be a success on job-title and unemployment-reason since they now have different keys.

You can of course use any keys you want, as long as they are unique.


Update August 2017

For a better insight into how keys work in React, I strongly recommend reading my answer to Understanding unique keys in React.js.


Update November 2017

This update should've been posted a while ago, but using string literals in ref is now deprecated. For example ref="job-title" should now instead be ref={(el) => this.jobTitleRef = el} (for example). See my answer to Deprecation warning using this.refs for more info.

How to change MenuItem icon in ActionBar programmatically

to use in onMenuItemClick(MenuItem item) just do invalidateOptionsMenu(); item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_baseline_play_circle_outline_24px));

How to connect to remote Oracle DB with PL/SQL Developer?

I would recommend creating a TNSNAMES.ORA file. From your Oracle Client install directory, navigate to NETWORK\ADMIN. You may already have a file called TNSNAMES.ORA, if so edit it, else create it using your favorite text editor.

Next, simply add an entry like this:

MYDB =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521))
    (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED))
  )

You can change MYDB to whatever you like, this is the identifier that applications will will use to find the database using the info from TNSNAMES.

Finally, login with MYDB as your database in PL/SQL Developer. It should automatically find the connection string in the TNSNAMES.ORA.

If that does not work, hit Help->About then click the icon with an "i" in it in the upper-lefthand corner. The fourth tab is the "TNS Names" tab, check it to confirm that it is loading the proper TNSNAMES.ORA file. If it is not, you may have multiple Oracle installations on your computer, and you will need to find the one that is in use.

Reading e-mails from Outlook with Python through MAPI

I had the same issue. Combining various approaches from the internet (and above) come up with the following approach (checkEmails.py)

class CheckMailer:

        def __init__(self, filename="LOG1.txt", mailbox="Mailbox - Another User Mailbox", folderindex=3):
            self.f = FileWriter(filename)
            self.outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI").Folders(mailbox)
            self.inbox = self.outlook.Folders(folderindex)


        def check(self):                
        #===============================================================================
        # for i in xrange(1,100):                           #Uncomment this section if index 3 does not work for you
        #     try:
        #         self.inbox = self.outlook.Folders(i)     # "6" refers to the index of inbox for Default User Mailbox
        #         print "%i %s" % (i,self.inbox)            # "3" refers to the index of inbox for Another user's mailbox
        #     except:
        #         print "%i does not work"%i
        #===============================================================================

                self.f.pl(time.strftime("%H:%M:%S"))
                tot = 0                
                messages = self.inbox.Items
                message = messages.GetFirst()
                while message:
                    self.f.pl (message.Subject)
                    message = messages.GetNext()
                    tot += 1
                self.f.pl("Total Messages found: %i" % tot)
                self.f.pl("-" * 80)
                self.f.flush()

if __name__ == "__main__":
    mail = CheckMailer()
    for i in xrange(320):  # this is 10.6 hours approximately
            mail.check()
            time.sleep(120.00)

For concistency I include also the code for the FileWriter class (found in FileWrapper.py). I needed this because trying to pipe UTF8 to a file in windows did not work.

class FileWriter(object):
    '''
    convenient file wrapper for writing to files
    '''


    def __init__(self, filename):
        '''
        Constructor
        '''
        self.file = open(filename, "w")

    def pl(self, a_string):
        str_uni = a_string.encode('utf-8')
        self.file.write(str_uni)
        self.file.write("\n")

    def flush(self):
        self.file.flush()

How to upgrade pip3?

The Problem

You use pip (the Python 2 one). Now you want to upgrade pip (the Python 3 one). After that, pip is the Python 3 one.

The solution

Use pip2 and pip3. This way it is explicit.

If you want to use pip, just check where it is (which pip) and change the link. For example:

$ which pip
/usr/local/bin/pip

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

$ which pip2
/usr/local/bin/pip2

$ sudo rm /usr/local/bin/pip
$ sudo ln -s /usr/local/bin/pip2 /usr/local/bin/pip

$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

Set value of textbox using JQuery

1) you are calling it wrong way try:

$(input[name="searchBar"]).val('hi')

2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event

$(document).ready(function() {
  $(input[name="searchBar"]).val('hi');
});

How do I concatenate two strings in C?

#include <stdio.h>

int main(){
    char name[] =  "derp" "herp";
    printf("\"%s\"\n", name);//"derpherp"
    return 0;
}

cannot download, $GOPATH not set

I found easier to do it like this:

export GOROOT=$HOME/go
export GOPATH=$GOROOT/bin
export PATH=$PATH:$GOPATH

Set NOW() as Default Value for datetime datatype?

My solution

ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

os.walk without digging into directories below

You could use os.listdir() which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call os.stat() on each name.

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Swift - Split string over multiple lines

The following example depicts a multi-line continuation, using parenthesis as a simple workaround for the Swift bug as of Xcode 6.2 Beta, where it complains the expression is too complex to resolve in a reasonable amount time, and to consider breaking it down into smaller pieces:

    .
    .
    .
    return String(format:"\n" +
                    ("    part1:    %d\n"    +
                     "    part2:    %d\n"    +
                     "    part3:  \"%@\"\n"  +
                     "    part4:  \"%@\"\n"  +
                     "    part5:  \"%@\"\n"  +
                     "    part6:  \"%@\"\n") +
                    ("    part7:  \"%@\"\n"  +
                     "    part8:  \"%@\"\n"  +
                     "    part9:  \"%@\"\n"  +
                     "    part10: \"%@\"\n"  +
                     "    part12: \"%@\"\n") +
                     "    part13:  %f\n"     +
                     "    part14:  %f\n\n",
                    part1, part2, part3, part4, part5, part6, part7, part8, 
                    part9, part10, part11, part12, part13, part14)
    .
    .
    .

http://localhost/ not working on Windows 7. What's the problem?

you have to install the service, go to wamp->Apache->Service->Install service, then a command prompt window will pop up, then press enter, and after a few seconds go to the same route Services-> and click Start/Resume service, and you ready

How to Set the Background Color of a JButton on the Mac OS

Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose

Unable to copy a file from obj\Debug to bin\Debug

No matter what the cause of this problem is, the only working solution for me is the following:

Go to Your-Project-Properties -> Application tab(first tab) -> Change the Assembly name.

This way your app creates a new assembly file each time you change the assembly name.

Finally, after you finish to develop, you can delete all those extra assembly files and just keep the last one (main one). Non of the other solutions worked for me, except this one.

How can I know when an EditText loses focus?

Using Java 8 lambda expression:

editText.setOnFocusChangeListener((v, hasFocus) -> {
    if(!hasFocus) {
        String value = String.valueOf( editText.getText() );
    }        
});

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

What's the difference between emulation and simulation?

Please forgive me if I'm wrong. And I have to admit upfront that I haven't done any research on these 2 terms. Anyway...

Emulation is to mimic something with detailed known results, whatever the internal behaviors actually are. We only try to get things done and don't care much about what goes on inside.

Simulation, on the other hand, is to mimic something with some known behaviors to study something not being known yet.

my 2cents

Running AngularJS initialization code when view is loaded

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

Since your controller runs before ng-init, this also solves your second issue.

Fiddle


As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

See jsFiddle


If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

var init = function () {
    // do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                    if( newVal && newVal.length > 0) {
                        unwatch();
                        init();
                    }
                });

How to download folder from putty using ssh client

You cannot use PuTTY to download the files, but you can use PSCP from the PuTTY developers to get the files or dump any directory that you want.

Please see the following link on how to download a file/folder: https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

Horizontal line using HTML/CSS

This might be your problem:

height: .05em;

Chrome is a bit funky with decimals, so try a fixed-pixel height:

height: 2px;

How do I change an HTML selected option using JavaScript?

It's an old post, but if anyone is still looking for solution to this kind of problem, here is what I came up with:

<script>
  document.addEventListener("DOMContentLoaded", function(e) {
    document.forms['AddAndEdit'].elements['list'].value = 11;
  });
</script>

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

Your second question is easy, GET has a size limitation of 1-2 kilobytes on both the server and browser side, so any kind of larger amounts of data you'd have to send through POST.

Insert json file into mongodb

In MS Windows, the mongoimport command has to be run in a normal Windows command prompt, not from the mongodb command prompt.

Close window automatically after printing dialog closes

<!--- ON click print button, get print and on click close button of print window, get print window closed--->

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Print preview</title>

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
    $(function () {
        $("#testid").click(function () {
            var sWinHTML = document.getElementById('content_print').innerHTML;
            var winprint = window.open("", "");
            winprint.document.open();
            winprint.document.write('<html><head>');
            winprint.document.write('<title>Print</title>');
            winprint.document.write('</head><body onload="window.focus(); window.print(); window.close()">');
            winprint.document.write(sWinHTML);
            winprint.document.write('</body></html>');
            winprint.document.close();
            winprint.focus();
        })
    })
</script>
</head>
 <body>

  <form id="form-print">
    <div id="content_print">
    <h3>Hello world</h3>
    <table cellpadding="0" cellspacing="0" width="100%">
    <thead>
    <tr>
    <th style="text-align:left">S.N</th>
    <th style="text-align:left">Name</th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <td>1</td>
      <td>Bijen</td>
    </tr>
    <tr>
      <td>2</td>
      <td>BJ</td>
    </tr>
    </tbody>
    </table>
    </div>
    <button type="button" id="testid"/>Print</button>
</form>
</body>
</html>

Bootstrap 3 Carousel Not Working

There are just two minor things here.

The first is in the following carousel indicator list items:

<li data-target="carousel" data-slide-to="0"></li>

You need to pass the data-target attribute a selector which means the ID must be prefixed with #. So change them to the following:

<li data-target="#carousel" data-slide-to="0"></li>

Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active class. Like this:

<ol class="carousel-indicators">
    <li data-target="#carousel" data-slide-to="0" class="active"></li>
    <!-- Other Items -->
</ol>
<div class="carousel-inner">
    <div class="item active">
        <img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
    </div>
    <!-- Other Items -->
</div>

Working Demo in Fiddle

Check if my SSL Certificate is SHA1 or SHA2

You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.

In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)

Spring Data and Native Query with pagination

Removing \n#pageable\n from both query and count query worked for me. Springboot version : 2.1.5.RELEASE DB : Mysql

Display current time in 12 hour format with AM/PM

    //To get Filename + date and time


    SimpleDateFormat f = new SimpleDateFormat("MMM");
    SimpleDateFormat f1 = new SimpleDateFormat("dd");
    SimpleDateFormat f2 = new SimpleDateFormat("a");

    int h;
         if(Calendar.getInstance().get(Calendar.HOUR)==0)
            h=12;
         else
            h=Calendar.getInstance().get(Calendar.HOUR)

    String filename="TestReport"+f1.format(new Date())+f.format(new Date())+h+f2.format(new Date())+".txt";


The Output Like:TestReport27Apr3PM.txt

Java AES encryption and decryption

import javax.crypto.*;    
import java.security.*;  
public class Java {

private static SecretKey key = null;         
   private static Cipher cipher = null; 

   public static void main(String[] args) throws Exception
   {

      Security.addProvider(new com.sun.crypto.provider.SunJCE());

      KeyGenerator keyGenerator =
         KeyGenerator.getInstance("DESede");
      keyGenerator.init(168);
      SecretKey secretKey = keyGenerator.generateKey();
      cipher = Cipher.getInstance("DESede");

      String clearText = "I am an Employee";
      byte[] clearTextBytes = clearText.getBytes("UTF8");

      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      byte[] cipherBytes = cipher.doFinal(clearTextBytes);
      String cipherText = new String(cipherBytes, "UTF8");

      cipher.init(Cipher.DECRYPT_MODE, secretKey);
      byte[] decryptedBytes = cipher.doFinal(cipherBytes);
      String decryptedText = new String(decryptedBytes, "UTF8");

      System.out.println("Before encryption: " + clearText);
      System.out.println("After encryption: " + cipherText);
      System.out.println("After decryption: " + decryptedText);
   }
}


// Output

/*
Before encryption: I am an Employee  
After encryption: }????j6??m??Zyc????*????l#l??dV  
After decryption: I am an Employee  
*/

Foreign key constraints: When to use ON UPDATE and ON DELETE

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

We'll take an example, a company table with a user table containing people from theses company

CREATE TABLE COMPANY (
     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)
) ENGINE=INNODB;

CREATE TABLE USER (
     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;

Let's look at the ON UPDATE clause:

  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE NO ACTION : same as RESTRICT.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

And now on the ON DELETE side:

  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE NO ACTION : same as RESTRICT
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.

Edit

It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

==> See below the last edit, things are moving on this domain

Triggers are not activated by foreign key actions.

And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

12/2017-Updating this Edit about MySQL:

as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

How long will my session last?

If session.cookie_lifetime is 0, the session cookie lives until the browser is quit.

EDIT: Others have mentioned the session.gc_maxlifetime setting. When session garbage collection occurs, the garbage collector will delete any session data that has not been accessed in longer than session.gc_maxlifetime seconds. To set the time-to-live for the session cookie, call session_set_cookie_params() or define the session.cookie_lifetime PHP setting. If this setting is greater than session.gc_maxlifetime, you should increase session.gc_maxlifetime to a value greater than or equal to the cookie lifetime to ensure that your sessions won't expire.

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

The article previously mentioned is good. http://forums.oracle.com/forums/thread.jspa?threadID=191750 (as far as it goes)

If this is not something that runs frequently (don't do it on your home page), you can turn off connection pooling.

There is one other "gotcha" that is not mentioned in the article. If the first thing you try to do with the connection is call a stored procedure, ODP will HANG!!!! You will not get back an error condition to manage, just a full bore HANG! The only way to fix it is to turn OFF connection pooling. Once we did that, all issues went away.

Pooling is good in some situations, but at the cost of increased complexity around the first statement of every connection.

If the error handling approach is so good, why don't they make it an option for ODP to handle it for us????

Python Remove last char from string and return it

The precise wording of the question makes me think it's impossible.

return to me means you have a function, which you have passed a string as a parameter.

You cannot change this parameter. Assigning to it will only change the value of the parameter within the function, not the passed in string. E.g.

>>> def removeAndReturnLastCharacter(a):
        c = a[-1]
        a = a[:-1]
        return c

>>> b = "Hello, Gaukler!"
>>> removeAndReturnLastCharacter(b)
!

>>> b    # b has not been changed
Hello, Gaukler!

How to pass parameters to ThreadStart method in Thread?

In Additional

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

What are the differences between type() and isinstance()?

The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()'s second parameter may be a tuple:

if isinstance(b, (str, unicode)):
    do_something_else()

or, using the basestring abstract class:

if isinstance(b, basestring):
    do_something_else()

Get attribute name value of <input>

While there is no denying that jQuery is a powerful tool, it is a really bad idea to use it for such a trivial operation as "get an element's attribute value".

Judging by the current accepted answer, I am going to assume that you were able to add an ID attribute to your element and use that to select it.

With that in mind, here are two pieces of code. First, the code given to you in the Accepted Answer:

$("#ID").attr("name");

And second, the Vanilla JS version of it:

document.getElementById('ID').getAttribute("name");

My results:

  • jQuery: 300k operations / second
  • JavaScript: 11,000k operations / second

You can test for yourself here. The "plain JavaScript" vesion is over 35 times faster than the jQuery version.

Now, that's just for one operation, over time you will have more and more stuff going on in your code. Perhaps for something particularly advanced, the optimal "pure JavaScript" solution would take one second to run. The jQuery version might take 30 seconds to a whole minute! That's huge! People aren't going to sit around for that. Even the browser will get bored and offer you the option to kill the webpage for taking too long!

As I said, jQuery is a powerful tool, but it should not be considered the answer to everything.

How to check for changes on remote (origin) Git repository

You could git fetch origin to update the remote branch in your repository to point to the latest version. For a diff against the remote:

git diff origin/master

Yes, you can use caret notation as well.

If you want to accept the remote changes:

git merge origin/master

Checking for empty queryset in Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

Laravel PHP Command Not Found

type on terminal:

nano ~/.bash_profile 

then paste:

export PATH="/Users/yourusername/.composer/vendor/bin:$PATH"

then save (press ctrl+c, press Y, press enter)

now you are ready to use "laravel" on your terminal

Add two numbers and display result in textbox with Javascript

var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);

// This is because your method .getElementById has the letter 's': .getElement**s**ById

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

In Spring 5

@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam MultiValueMap body ) {

    // import org.springframework.util.MultiValueMap;

    String datax = (String) body .getFirst("datax");
}

LINQ query to return a Dictionary<string, string>

Use the ToDictionary method directly.

var result = 
  // as Jon Skeet pointed out, OrderBy is useless here, I just leave it 
  // show how to use OrderBy in a LINQ query
  myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
                   .ToDictionary(mc => mc.KeyProp.ToString(), 
                                 mc => mc.ValueProp.ToString(), 
                                 StringComparer.OrdinalIgnoreCase);

Eclipse add Tomcat 7 blank server name

After trying @Philipp Claßen steps, even if did not work then,

Change eclipse, workspace and tomcat directory. [tested only for Windows7]

I know somebody might say that is not correct, but that did work for me after @Phillipp's steps not worked for me.

It took me 4 hours to find this brute force method solution.

How to set scope property with ng-init?

HTML:

<body ng-app="App">
    <div ng-controller="testController" >
        <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
    </div>
    {{ testInput }}
</body>

JS:

angular.module('App', []);

testController = function ($scope) {
    console.log('test');
    $scope.$watch('testInput', testShow, true);
    function testShow() {
      console.log($scope.testInput);
    }
}

Fiddle

jquery stop child triggering parent event

Or, rather than having an extra event handler to prevent another handler, you can use the Event Object argument passed to your click event handler to determine whether a child was clicked. target will be the clicked element and currentTarget will be the .header div:

$(".header").click(function(e){
     //Do nothing if .header was not directly clicked
     if(e.target !== e.currentTarget) return;

     $(this).children(".children").toggle();
});

What's the difference between KeyDown and KeyPress in .NET?

KeyPress is a higher level of abstraction than KeyDown (and KeyUp). KeyDown and KeyUp are hardware related: the actual action of a key on the keyboard. KeyPress is more "I received a character from the keyboard".

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

multiple plot in one figure in Python

The OP states that each plot element overwrites the previous one rather than being combined into a single plot. This can happen even with one of the many suggestions made by other answers. If you select several lines and run them together, say:

plt.plot(<X>, <Y>)
plt.plot(<X>, <Z>)

the plot elements will typically be rendered together, one layer on top of the other. But if you execute the code line-by-line, each plot will overwrite the previous one.

This perhaps is what happened to the OP. It just happened to me: I had set up a new key binding to execute code by a single key press (on spyder), but my key binding was executing only the current line. The solution was to select lines by whole blocks or to run the whole file.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

Docker is installed but Docker Compose is not ? why?

The above solutions didn't work for me. But I found this that worked:

sudo apt-get update -y && sudo apt-get install -y python3-pip python3-dev
sudo apt-get remove docker docker-engine docker.io
curl -fsSL get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo pip3 install docker-compose
#sudo docker-compose -f docker-compose-profess.yml pull ofw
sudo usermod -a -G docker $USER
sudo reboot

Insert a new row into DataTable

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);

PostgreSQL, checking date relative to "today"

This should give you the current date minus 1 year:

select now() - interval '1 year';

File to byte[] in Java

Let me add another solution without using third-party libraries. It re-uses an exception handling pattern that was proposed by Scott (link). And I moved the ugly part into a separate message (I would hide in some FileUtils class ;) )

public void someMethod() {
    final byte[] buffer = read(new File("test.txt"));
}

private byte[] read(final File file) {
    if (file.isDirectory())
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is a directory");
    if (file.length() > Integer.MAX_VALUE)
        throw new RuntimeException("Unsupported operation, file "
                + file.getAbsolutePath() + " is too big");

    Throwable pending = null;
    FileInputStream in = null;
    final byte buffer[] = new byte[(int) file.length()];
    try {
        in = new FileInputStream(file);
        in.read(buffer);
    } catch (Exception e) {
        pending = new RuntimeException("Exception occured on reading file "
                + file.getAbsolutePath(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                if (pending == null) {
                    pending = new RuntimeException(
                        "Exception occured on closing file" 
                             + file.getAbsolutePath(), e);
                }
            }
        }
        if (pending != null) {
            throw new RuntimeException(pending);
        }
    }
    return buffer;
}

Strange "java.lang.NoClassDefFoundError" in Eclipse

I thought my problem and its solution could help.So i was getting this same error in my eclipse project.In my project i have couple of jar files and the NOCLASSDEFERROR was thrown for a file in the jar file.

My library files were part of a folder name "lib" in my project heirarchy.I changed my folders name to "libs" and voila it worked.

(I looked into the .classpath file and i had key-value pairs,and the entry for my jar file had key named "lib" and hence i thought probably changing from lib could help.)

Hiding a button in Javascript

If you are not using jQuery I would suggest using it. If you do, you would want to do something like:

$( 'button' ).on(
   'click'
   function (  )
   {
       $( this ).hide(  );
   }
);

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

How about using Xcode built-in code snippet library?

enter image description here

Update for Swift:

Many up votes inspired me to update this answer.

The build-in Xcode code snippet library has dispatch_after for only objective-c language. People can also create their own Custom Code Snippet for Swift.

Write this in Xcode.

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(<#delayInSeconds#> * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
        <#code to be executed after a specified delay#>
    })

Drag this code and drop it in the code snippet library area. enter image description here

Bottom of the code snippet list, there will be a new entity named My Code Snippet. Edit this for a title. For suggestion as you type in the Xcode fill in the Completion Shortcut.

For more info see CreatingaCustomCodeSnippet.

Update Swift 3

Drag this code and drop it in the code snippet library area.

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(<#delayInSeconds#>)) {
    <#code to be executed after a specified delay#>
}

Login to remote site with PHP cURL

I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.

define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);

//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case

//login form action url
$url="https://www.example.com/login/action"; 
$postinfo = "email=".$username."&password=".$password;

$cookie_file_path = $path."/cookie.txt";

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,
    "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

If you still have problem then please try this.

Build Settings -> User Defined -> Provisioning profile (Remove this.)

It will solved my issue.

Thanks

How to pass command line arguments to a shell alias?

An empty alias will execute its args:

alias DEBUG=

How to order a data frame by one descending and one ascending column?

    library(dplyr)
    library(tidyr)
    #supposing you want to arrange column 'c' in descending order and 'd' in ascending order. name of data frame is df
    ## first doing descending
    df<-arrange(df,desc(c))
    ## then the ascending order of col 'd;
    df <-arrange(df,d)

What's the fastest way to convert String to Number in JavaScript?

This is probably not that fast, but has the added benefit of making sure your number is at least a certain value (e.g. 0), or at most a certain value:

Math.max(input, 0);

If you need to ensure a minimum value, usually you'd do

var number = Number(input);
if (number < 0) number = 0;

Math.max(..., 0) saves you from writing two statements.

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

Round a floating-point number down to the nearest integer?

One of these should work:

import math
math.trunc(1.5)
> 1
math.trunc(-1.5)
> -1
math.floor(1.5)
> 1
math.floor(-1.5)
> -2

What is the "-->" operator in C/C++?

My compiler will print out 9876543210 when I run this code.

#include <iostream>
int main()
{
    int x = 10;

    while( x --> 0 ) // x goes to 0
    {
        std::cout << x;
    }
}

As expected. The while( x-- > 0 ) actually means while( x > 0). The x-- post decrements x.

while( x > 0 ) 
{
    x--;
    std::cout << x;
}

is a different way of writing the same thing.

It is nice that the original looks like "while x goes to 0" though.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

You don't need to install Entity Framework in your Console application, you just need to add a reference to the assembly EntityFramework.SqlServer.dll. You can copy this assembly from the Class Library project that uses Entity Framework to a LIB folder and add a reference to it.

In summary:

  • Class Library application:
    • Install Entity Framework
    • Write your data layer code
    • app.config file has all the configuration related to Entity Framework except for the connection string.
  • Create a Console, web or desktop application:
    • Add a reference to the first project.
    • Add a reference to EntityFramework.SqlServer.dll.
    • app.config/web.config has the connection string (remember that the name of the configuration entry has to be the same as the name of the DbContext class.

I hope it helps.

javascript change background color on click

You can set the background color of an object using CSS.

You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.

_x000D_
_x000D_
body {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
_x000D_
_x000D_
_x000D_

Select folder dialog WPF

I wrote about it on my blog a long time ago, WPF's support for common file dialogs is really bad (or at least is was in 3.5 I didn't check in version 4) - but it's easy to work around it.

You need to add the correct manifest to your application - that will give you a modern style message boxes and folder browser (WinForms FolderBrowserDialog) but not WPF file open/save dialogs, this is described in those 3 posts (if you don't care about the explanation and only want the solution go directly to the 3rd):

Fortunately, the open/save dialogs are very thin wrappers around the Win32 API that is easy to call with the right flags to get the Vista/7 style (after setting the manifest)

How can I delete a newline if it is the last character in a file?

Yet another answer FTR (and my favourite!): echo/cat the thing you want to strip and capture the output through backticks. The final newline will be stripped. For example:

# Sadly, outputs newline, and we have to feed the newline to sed to be portable
echo thingy | sed -e 's/thing/sill/'

# No newline! Happy.
out=`echo thingy | sed -e 's/thing/sill/'`
printf %s "$out"

# Similarly for files:
file=`cat file_ending_in_newline`
printf %s "$file" > file_no_newline

Checking if a list is empty with LINQ

The second option is much quicker if you have multiple items.

  • Any() returns as soon as 1 item is found.
  • Count() has to keep going through the entire list.

For instance suppose the enumeration had 1000 items.

  • Any() would check the first one, then return true.
  • Count() would return 1000 after traversing the entire enumeration.

This is potentially worse if you use one of the predicate overrides - Count() still has to check every single item, even it there is only one match.

You get used to using the Any one - it does make sense and is readable.

One caveat - if you have a List, rather than just an IEnumerable then use that list's Count property.

Intellij idea cannot resolve anything in maven

I was getting this error because my project was not setup correctly. It had imported main and test folders as modules. When I deleted the 2 modules (but retained them as source and test folders), my code started compiling correctly.

What Vim command(s) can be used to quote/unquote words?

I don't know any builtin vim command for this, but using r"f'r" to change from ' to " and r'f"r' to change from " to ' works if you stand on the first ' or ". The command r' replaces whatever character is under your cursor with ', and f" moves you forward to the next ".

Extracting text OpenCV

You can detect text by finding close edge elements (inspired from a LPD):

#include "opencv2/opencv.hpp"

std::vector<cv::Rect> detectLetters(cv::Mat img)
{
    std::vector<cv::Rect> boundRect;
    cv::Mat img_gray, img_sobel, img_threshold, element;
    cvtColor(img, img_gray, CV_BGR2GRAY);
    cv::Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3, 1, 0, cv::BORDER_DEFAULT);
    cv::threshold(img_sobel, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY);
    element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) );
    cv::morphologyEx(img_threshold, img_threshold, CV_MOP_CLOSE, element); //Does the trick
    std::vector< std::vector< cv::Point> > contours;
    cv::findContours(img_threshold, contours, 0, 1); 
    std::vector<std::vector<cv::Point> > contours_poly( contours.size() );
    for( int i = 0; i < contours.size(); i++ )
        if (contours[i].size()>100)
        { 
            cv::approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 3, true );
            cv::Rect appRect( boundingRect( cv::Mat(contours_poly[i]) ));
            if (appRect.width>appRect.height) 
                boundRect.push_back(appRect);
        }
    return boundRect;
}

Usage:

int main(int argc,char** argv)
{
    //Read
    cv::Mat img1=cv::imread("side_1.jpg");
    cv::Mat img2=cv::imread("side_2.jpg");
    //Detect
    std::vector<cv::Rect> letterBBoxes1=detectLetters(img1);
    std::vector<cv::Rect> letterBBoxes2=detectLetters(img2);
    //Display
    for(int i=0; i< letterBBoxes1.size(); i++)
        cv::rectangle(img1,letterBBoxes1[i],cv::Scalar(0,255,0),3,8,0);
    cv::imwrite( "imgOut1.jpg", img1);  
    for(int i=0; i< letterBBoxes2.size(); i++)
        cv::rectangle(img2,letterBBoxes2[i],cv::Scalar(0,255,0),3,8,0);
    cv::imwrite( "imgOut2.jpg", img2);  
    return 0;
}

Results:

a. element = getStructuringElement(cv::MORPH_RECT, cv::Size(17, 3) ); imgOut1 imgOut2

b. element = getStructuringElement(cv::MORPH_RECT, cv::Size(30, 30) ); imgOut1 imgOut2

Results are similar for the other image mentioned.

Convert String To date in PHP

Try this:

$new_date=date('d-m-Y', strtotime($date));

How do I vertically align text in a paragraph?

If you use Bootstrap, try to assign margin-bottom 0 to the paragraph and after assign the property align-items-center to container, for example, like this:

<div class="row align-items-center">
     <p class="col-sm-1 mb-0">
          ....
     </p>
</div>

Bootstrap by default assign a calculate margin bottom, so mb-0 disabled this.

I hope it helps

How to send a POST request from node.js Express?

As described here for a post request :

var http = require('http');

var options = {
  host: 'www.host.com',
  path: '/',
  port: '80',
  method: 'POST'
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("data");
req.end();

What is a "cache-friendly" code?

It needs to be clarified that not only data should be cache-friendly, it is just as important for the code. This is in addition to branch predicition, instruction reordering, avoiding actual divisions and other techniques.

Typically the denser the code, the fewer cache lines will be required to store it. This results in more cache lines being available for data.

The code should not call functions all over the place as they typically will require one or more cache lines of their own, resulting in fewer cache lines for data.

A function should begin at a cache line-alignment-friendly address. Though there are (gcc) compiler switches for this be aware that if the the functions are very short it might be wasteful for each one to occupy an entire cache line. For example, if three of the most often used functions fit inside one 64 byte cache line, this is less wasteful than if each one has its own line and results in two cache lines less available for other usage. A typical alignment value could be 32 or 16.

So spend some extra time to make the code dense. Test different constructs, compile and review the generated code size and profile.

calculate the mean for each column of a matrix in R

You can use 'apply' to run a function or the rows or columns of a matrix or numerical data frame:

cluster1 <- data.frame(a=1:5, b=11:15, c=21:25, d=31:35)

apply(cluster1,2,mean)  # applies function 'mean' to 2nd dimension (columns)

apply(cluster1,1,mean)  # applies function to 1st dimension (rows)

sapply(cluster1, mean)  # also takes mean of columns, treating data frame like list of vectors

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to apply an XSLT Stylesheet in C#

This might help you

public static string TransformDocument(string doc, string stylesheetPath)
{
    Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         return xmlDocument;
     };

    try
    {
        var document = GetXmlDocument(doc);
        var style = GetXmlDocument(File.ReadAllText(stylesheetPath));

        System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
        transform.Load(style); // compiled stylesheet
        System.IO.StringWriter writer = new System.IO.StringWriter();
        XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
        transform.Transform(xmlReadB, null, writer);
        return writer.ToString();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}   

jQuery: Best practice to populate drop down?

Andreas Grech was pretty close... it's actually this (note the reference to this instead of the item in the loop):

var $dropdown = $("#dropdown");
$.each(result, function() {
    $dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});

Convert json to a C# array?

Old question but worth adding an answer if using .NET Core 3.0 or later. JSON serialization/deserialization is built into the framework (System.Text.Json), so you don't have to use third party libraries any more. Here's an example based off the top answer given by @Icarus

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{\"Name\":\"John Smith\", \"Age\":35}, {\"Name\":\"Pablo Perez\", \"Age\":34}]";

            // use the built in Json deserializer to convert the string to a list of Person objects
            var people = System.Text.Json.JsonSerializer.Deserialize<List<Person>>(json);

            foreach (var person in people)
            {
                Console.WriteLine(person.Name + " is " + person.Age + " years old.");
            }
        }

        public class Person
        {
            public int Age { get; set; }
            public string Name { get; set; }
        }
    }
}

How to subtract hours from a date in Oracle so it affects the day also

sysdate-(2/11)

A day consists of 24 hours. So, to subtract 2 hours from a day you need to divide it by 24:

DATE_value - 2/24

Using interval for the same:

DATE_value - interval '2' hour

Where does Hive store files in HDFS?

In Hive, tables are actually stored in a few places. Specifically, if you use partitions (which you should, if your tables are very large or growing) then each partition can have its own storage.

To show the default location where table data or partitions will be created if you create them through default HIVE commands: (insert overwrite ... partition ... and such):

describe formatted dbname.tablename

To show the actual location of a particular partition within a HIVE table, instead do this:

describe formatted dbname.tablename partition (name=value)

If you look in your filesystem where a table "should" live, and you find no files there, it's very likely that the table is created (usually incrementally) by creating a new partition and pointing that partition at some other location. This is a great way of building tables from things like daily imports from third parties and such, which avoids having to copy the files around or storing them more than once in different places.

How to load image (and other assets) in Angular an project?

It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).

Example A:

src
|__assests
   |__images
      |__myimage.png
|__yourmodule
   |__yourpage.html

As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:

<img class="img-responsive" src="../assests/images/myimage.png">

Example B:

src
|__assests
   |__images
      |__myimage.png
|__yourmodule
   |__yoursubmodule
      |__yourpage.html

Here you have to go u in the tree by 2 folders:

<img class="img-responsive" src="../../assests/images/myimage.png">

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Taking DWins example.

What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".

E.g.

clab = 1.5
cmain = 2
caxis = 1.2

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=clab,    
           col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis) 

You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:

which you then call with setwd("") source("plotcolours.r")

in a file say called plotcolours.r you then store all the e.g. colour or size variables

clab = 1.5
cmain = 2
caxis = 1.2 

for colours could use

darkred<-rgb(113,28,47,maxColorValue=255)

as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.

plot(1,1,col=darkred) 

Javascript: How to loop through ALL DOM elements on a page?

Was looking for same. Well, not exactly. I only wanted to list all DOM Nodes.

var currentNode,
    ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);

while(currentNode = ni.nextNode()) {
    console.log(currentNode.nodeName);
}

To get elements with a specific class, we can use filter function.

var currentNode,
    ni = document.createNodeIterator(
                     document.documentElement, 
                     NodeFilter.SHOW_ELEMENT,
                     function(node){
                         return node.classList.contains('toggleable') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
                     }
         );

while(currentNode = ni.nextNode()) {
    console.log(currentNode.nodeName);
}

Found solution on MDN

What is lazy loading in Hibernate?

In layman's language, it is like you are making a cake and you will need 5-10 ingredients from fridge. You have two options, get all ingredients from fridge and put it on your kitchen platform, or bring the item you want when you need.

Similarly, in eager loading, you fetch all information about bean and its related classes (not child or is-a relation but has a relationship, i.e. cake has flour, has milk, has cream etc), and in case of lazy loading, first you bring only its identifier and values that are coming from same table (necessary ingredients that first you will need in your bowl in case of cake). All information that is coming from other tables will be fetched as and when required/used.

Entity Framework. Delete all rows in table

I came across this question when I had to deal with a particular case: fully updating of content in a "leaf" table (no FKs pointing to it). This involved removing all rows and putting new rows information and it should be done transactionally (I do not want to end up with an empty table, if inserts fails for whatever reason).

I have tried the public static void Clear<T>(this DbSet<T> dbSet) approach, but new rows are not inserted. Another disadvante is that the whole process is slow, as rows are deleted one by one.

So, I have switched to TRUNCATE approach, since it is much faster and it is also ROLLBACKable. It also resets the identity.

Example using repository pattern:

public class Repository<T> : IRepository<T> where T : class, new()
{
    private readonly IEfDbContext _context;

    public void BulkInsert(IEnumerable<T> entities)
    {
        _context.BulkInsert(entities);
    }

    public void Truncate()
    {
        _context.Database.ExecuteSqlCommand($"TRUNCATE TABLE {typeof(T).Name}");
    }
 }

 // usage 
 DataAccess.TheRepository.Truncate();
 var toAddBulk = new List<EnvironmentXImportingSystem>();

 // fill toAddBulk from source system
 // ...

 DataAccess.TheRepository.BulkInsert(toAddBulk);
 DataAccess.SaveChanges();

Of course, as already mentioned, this solution cannot be used by tables referenced by foreign keys (TRUNCATE fails).

Regular expression: find spaces (tabs/space) but not newlines

Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000) is not included in \s for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000 with \u0020), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000].

If you're using Perl or PCRE, you have the option of using the \h shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.

However, this \h shorthand has not been implemented for .NET and C#, as best I've been able to tell.

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

How to move div vertically down using CSS

You could make your blue div position: relative and then give the div.title position:absolute; and bottom: 0px

Here is a working demo.. http://jsfiddle.net/gLaG6/

Shortcut for changing font size

In the Macros explorer under samples/accessibility there is an IncreaseTextEditorFontSize and a DecreaseTextEditorFontSize. Bind those to some keyboard shortcuts.

How to install pip3 on Windows?

On Windows pip3 should be in the Scripts path of your Python installation:

C:\path\to\python\Scripts\pip3

Use:

where python

to find out where your Python executable(s) is/are located. The result should look like this:

C:\path\to\python\python.exe

or:

C:\path\to\python\python3.exe

You can check if pip3 works with this absolute path:

C:\path\to\python\Scripts\pip3

if yes, add C:\path\to\python\Scripts to your environmental variable PATH .

How to make a launcher

Just develop a normal app and then add a couple of lines to the app's manifest file.

First you need to add the following attribute to your activity:

            android:launchMode="singleTask"

Then add two categories to the intent filter :

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />

The result could look something like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dummy.app"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="11"
            android:targetSdkVersion="19" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.dummy.app.MainActivity"
                android:launchMode="singleTask"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                    <category android:name="android.intent.category.DEFAULT" />
                    <category android:name="android.intent.category.HOME" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

It's that simple!

Oracle: how to set user password unexpire?

If you create a user using a profile like this:

CREATE PROFILE my_profile LIMIT
       PASSWORD_LIFE_TIME 30;
ALTER USER scott PROFILE my_profile;

then you can change the password lifetime like this:

ALTER PROFILE my_profile LIMIT
  PASSWORD_LIFE_TIME UNLIMITED;

I hope that helps.

Getting new Twitter API consumer and secret keys

step 1.Go to https://dev.twitter.com/apps


step 2.Create app(fill up the form)


step 3.Change permissions if necessary(depending if you want to just read,write or execute)


step 4.Go To API keys section and click generate ACCESS TOKEN.


5 years late to answer :)

Now you have these tokens which is all you need.

'oauth_access_token' => Access token
'oauth_access_token_secret' => Access token secret
'consumer_key' => API key
'consumer_secret' => API secret

UIView background color in Swift

Try This, It worked like a charm! for me,

The simplest way to add backgroundColor programmatically by using ColorLiteral.

You need to add the property ColorLiteral, Xcode will prompt you with a whole list of colors in which you can choose any color. The advantage of doing this is we use lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard.

Follow steps ,

1) Add below line of code in viewDidLoad() ,

self.view.backgroundColor = ColorLiteral

and clicked on enter button .

2) Display square box next to =

enter image description here

3) When Clicked on Square Box Xcode will prompt you with a whole list of colors which you can choose any colors also you can set HEX values or RGB

enter image description here

4) You can successfully set the colors .

enter image description here

Hope this will help some one to set backgroundColor in different ways.

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

Actually you have a code compiled targeting a higher JDK (JDK 1.8 in your case) but at runtime you are supplying a lower JRE(JRE 7 or below).

you can fix this problem by adding target parameter while compilation
e.g. if your runtime target is 1.7, you should use 1.7 or below

javac -target 1.7 *.java

if you are using eclipse, you can sent this parameter at Window -> Preferences -> Java -> Compiler -> set "Compiler compliance level" = choose your runtime jre version or lower.

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Suppose you face this issue while running your go binary with in alpine container. Export the following variable before building your bin

# CGO has to be disabled for alpine
export CGO_ENABLED=0

Then go build

How to Determine the Screen Height and Width in Flutter

Getting width is easy but height can be tricky, following are the ways to deal with height

// Full screen width and height
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;

// Height (without SafeArea)
var padding = MediaQuery.of(context).padding;
double height1 = height - padding.top - padding.bottom;

// Height (without status bar)
double height2 = height - padding.top;

// Height (without status and toolbar)
double height3 = height - padding.top - kToolbarHeight;

Git workflow and rebase vs merge questions

TL;DR

A git rebase workflow does not protect you from people who are bad at conflict resolution or people who are used to a SVN workflow, like suggested in Avoiding Git Disasters: A Gory Story. It only makes conflict resolution more tedious for them and makes it harder to recover from bad conflict resolution. Instead, use diff3 so that it's not so difficult in the first place.


Rebase workflow is not better for conflict resolution!

I am very pro-rebase for cleaning up history. However if I ever hit a conflict, I immediately abort the rebase and do a merge instead! It really kills me that people are recommending a rebase workflow as a better alternative to a merge workflow for conflict resolution (which is exactly what this question was about).

If it goes "all to hell" during a merge, it will go "all to hell" during a rebase, and potentially a lot more hell too! Here's why:

Reason #1: Resolve conflicts once, instead of once for each commit

When you rebase instead of merge, you will have to perform conflict resolution up to as many times as you have commits to rebase, for the same conflict!

Real scenario

I branch off of master to refactor a complicated method in a branch. My refactoring work is comprised of 15 commits total as I work to refactor it and get code reviews. Part of my refactoring involves fixing the mixed tabs and spaces that were present in master before. This is necessary, but unfortunately it will conflict with any change made afterward to this method in master. Sure enough, while I'm working on this method, someone makes a simple, legitimate change to the same method in the master branch that should be merged in with my changes.

When it's time to merge my branch back with master, I have two options:

git merge: I get a conflict. I see the change they made to master and merge it in with (the final product of) my branch. Done.

git rebase: I get a conflict with my first commit. I resolve the conflict and continue the rebase. I get a conflict with my second commit. I resolve the conflict and continue the rebase. I get a conflict with my third commit. I resolve the conflict and continue the rebase. I get a conflict with my fourth commit. I resolve the conflict and continue the rebase. I get a conflict with my fifth commit. I resolve the conflict and continue the rebase. I get a conflict with my sixth commit. I resolve the conflict and continue the rebase. I get a conflict with my seventh commit. I resolve the conflict and continue the rebase. I get a conflict with my eighth commit. I resolve the conflict and continue the rebase. I get a conflict with my ninth commit. I resolve the conflict and continue the rebase. I get a conflict with my tenth commit. I resolve the conflict and continue the rebase. I get a conflict with my eleventh commit. I resolve the conflict and continue the rebase. I get a conflict with my twelfth commit. I resolve the conflict and continue the rebase. I get a conflict with my thirteenth commit. I resolve the conflict and continue the rebase. I get a conflict with my fourteenth commit. I resolve the conflict and continue the rebase. I get a conflict with my fifteenth commit. I resolve the conflict and continue the rebase.

You have got to be kidding me if this is your preferred workflow. All it takes is a whitespace fix that conflicts with one change made on master, and every commit will conflict and must be resolved. And this is a simple scenario with only a whitespace conflict. Heaven forbid you have a real conflict involving major code changes across files and have to resolve that multiple times.

With all the extra conflict resolution you need to do, it just increases the possibility that you will make a mistake. But mistakes are fine in git since you can undo, right? Except of course...

Reason #2: With rebase, there is no undo!

I think we can all agree that conflict resolution can be difficult, and also that some people are very bad at it. It can be very prone to mistakes, which why it's so great that git makes it easy to undo!

When you merge a branch, git creates a merge commit that can be discarded or amended if the conflict resolution goes poorly. Even if you have already pushed the bad merge commit to the public/authoritative repo, you can use git revert to undo the changes introduced by the merge and redo the merge correctly in a new merge commit.

When you rebase a branch, in the likely event that conflict resolution is done wrong, you're screwed. Every commit now contains the bad merge, and you can't just redo the rebase*. At best, you have to go back and amend each of the affected commits. Not fun.

After a rebase, it's impossible to determine what was originally part of the commits and what was introduced as a result of bad conflict resolution.

*It can be possible to undo a rebase if you can dig the old refs out of git's internal logs, or if you create a third branch that points to the last commit before rebasing.

Take the hell out of conflict resolution: use diff3

Take this conflict for example:

<<<<<<< HEAD
TextMessage.send(:include_timestamp => true)
=======
EmailMessage.send(:include_timestamp => false)
>>>>>>> feature-branch

Looking at the conflict, it's impossible to tell what each branch changed or what its intent was. This is the biggest reason in my opinion why conflict resolution is confusing and hard.

diff3 to the rescue!

git config --global merge.conflictstyle diff3

When you use the diff3, each new conflict will have a 3rd section, the merged common ancestor.

<<<<<<< HEAD
TextMessage.send(:include_timestamp => true)
||||||| merged common ancestor
EmailMessage.send(:include_timestamp => true)
=======
EmailMessage.send(:include_timestamp => false)
>>>>>>> feature-branch

First examine the merged common ancestor. Then compare each side to determine each branch's intent. You can see that HEAD changed EmailMessage to TextMessage. Its intent is to change the class used to TextMessage, passing the same parameters. You can also see that feature-branch's intent is to pass false instead of true for the :include_timestamp option. To merge these changes, combine the intent of both:

TextMessage.send(:include_timestamp => false)

In general:

  1. Compare the common ancestor with each branch, and determine which branch has the simplest change
  2. Apply that simple change to the other branch's version of the code, so that it contains both the simpler and the more complex change
  3. Remove all the sections of conflict code other than the one that you just merged the changes together into

Alternate: Resolve by manually applying the branch's changes

Finally, some conflicts are terrible to understand even with diff3. This happens especially when diff finds lines in common that are not semantically common (eg. both branches happened to have a blank line at the same place!). For example, one branch changes the indentation of the body of a class or reorders similar methods. In these cases, a better resolution strategy can be to examine the change from either side of the merge and manually apply the diff to the other file.

Let's look at how we might resolve a conflict in a scenario where merging origin/feature1 where lib/message.rb conflicts.

  1. Decide whether our currently checked out branch (HEAD, or --ours) or the branch we're merging (origin/feature1, or --theirs) is a simpler change to apply. Using diff with triple dot (git diff a...b) shows the changes that happened on b since its last divergence from a, or in other words, compare the common ancestor of a and b with b.

    git diff HEAD...origin/feature1 -- lib/message.rb # show the change in feature1
    git diff origin/feature1...HEAD -- lib/message.rb # show the change in our branch
    
  2. Check out the more complicated version of the file. This will remove all conflict markers and use the side you choose.

    git checkout --ours -- lib/message.rb   # if our branch's change is more complicated
    git checkout --theirs -- lib/message.rb # if origin/feature1's change is more complicated
    
  3. With the complicated change checked out, pull up the diff of the simpler change (see step 1). Apply each change from this diff to the conflicting file.

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

How to examine processes in OS X's Terminal?

You can just use top It will display everything running on your OSX

Entity Framework Refresh context?

Use the Refresh method:

context.Refresh(RefreshMode.StoreWins, yourEntity);

or in alternative dispose your current context and create a new one.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

You can use function closures as data in larger expressions as well, as in this method of determining browser support for some of the html5 objects.

   navigator.html5={
     canvas: (function(){
      var dc= document.createElement('canvas');
      if(!dc.getContext) return 0;
      var c= dc.getContext('2d');
      return typeof c.fillText== 'function'? 2: 1;
     })(),
     localStorage: (function(){
      return !!window.localStorage;
     })(),
     webworkers: (function(){
      return !!window.Worker;
     })(),
     offline: (function(){
      return !!window.applicationCache;
     })()
    }

How do I ALTER a PostgreSQL table and make a column unique?

I figured it out from the PostgreSQL docs, the exact syntax is:

ALTER TABLE the_table ADD CONSTRAINT constraint_name UNIQUE (thecolumn);

Thanks Fred.

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Named capturing groups in JavaScript regex?

There is a node.js library called named-regexp that you could use in your node.js projects (on in the browser by packaging the library with browserify or other packaging scripts). However, the library cannot be used with regular expressions that contain non-named capturing groups.

If you count the opening capturing braces in your regular expression you can create a mapping between named capturing groups and the numbered capturing groups in your regex and can mix and match freely. You just have to remove the group names before using the regex. I've written three functions that demonstrate that. See this gist: https://gist.github.com/gbirke/2cc2370135b665eee3ef

How do I find out my python path using python?

import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')

How do you check that a number is NaN in JavaScript?

It seems that isNaN() is not supported in Node.js out of the box.
I worked around with

var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);

Android: Access child views from a ListView

A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

Found it here

force browsers to get latest js and css files in asp.net application

I use a similar way to do the same you are doing without modifying each page. Added a PreRender event is master file. It keeps my logic at one place and applicable to both js and css files.

protected void Page_PreRender(object sender, EventArgs e)
    {
        HtmlLink link = null;
        LiteralControl script = null;


        foreach (Control c in Header.Controls)
        {
            //StyleSheet add version
            if (c is HtmlLink)
            {
                link = c as HtmlLink;


                if (link.Href.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase))
                {
                    link.Href += string.Format("?v={0}", ConfigurationManager.AppSettings["agVersion"]);
                }

            }

            //Js add version
            if (c is LiteralControl)
            {
                script = c as LiteralControl;

                if (script.Text.Contains(".js"))
                {
                    var foundIndexes = new List<int>();


                    for (int i = script.Text.IndexOf(".js\""); i > -1; i = script.Text.IndexOf(".js\"", i + 1))
                    {

                        foundIndexes.Add(i);
                    }

                    for (int i = foundIndexes.Count - 1; i >= 0; i--)
                    {

                        script.Text = script.Text.Insert(foundIndexes[i] + 3, string.Format("?v={0}", ConfigurationManager.AppSettings["agVersion"]));
                    }
                }

            }

        }
    }

List of zeros in python

Here is the xrange way:

list(0 for i in xrange(0,5)) 

What is the difference between a generative and a discriminative algorithm?

All previous answers are great, and I'd like to plug in one more point.

From generative algorithm models, we can derive any distribution; while we can only obtain the conditional distribution P(Y|X) from the discriminative algorithm models(or we can say they are only useful for discriminating Y’s label), and that's why it is called discriminative model. The discriminative model doesn't assume that the X's are independent given the Y($X_i \perp X_{-i} | Y$) and hence is usually more powerful for calculating that conditional distribution.

What does the "+=" operator do in Java?

Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like

  • XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
  • If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
  • Swapping values without using temporary variable
  • Finding missing number in the range 1 to n
  • Basic validation of data sent over the network.

Lot many such tricks can be done using bit wise operators, interesting topic to explore.

Uploading an Excel sheet and importing the data into SQL Server database

using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;

protected void Button1_Click(object sender, EventArgs e)

{

    //Upload and save the file

    string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);

    FileUpload1.SaveAs(excelPath);



    string conString = string.Empty;

    string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);

    switch (extension)

    {

        case ".xls": //Excel 97-03

            conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;

            break;

        case ".xlsx": //Excel 07 or higher

            conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;

            break;



    }

    conString = string.Format(conString, excelPath);

    using (OleDbConnection excel_con = new OleDbConnection(conString))

    {

        excel_con.Open();

        string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();

        DataTable dtExcelData = new DataTable();



        //[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.

        dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),

            new DataColumn("Name", typeof(string)) });



        using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))

        {

            oda.Fill(dtExcelData);

        }

        excel_con.Close();



        string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;

        using (SqlConnection con = new SqlConnection(consString))

        {

            using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))

            {

                //Set the database table name

                sqlBulkCopy.DestinationTableName = "dbo.Table1";



                //[OPTIONAL]: Map the Excel columns with that of the database table

                sqlBulkCopy.ColumnMappings.Add("Sl", "Id");

                sqlBulkCopy.ColumnMappings.Add("Name", "Name");

                con.Open();

                sqlBulkCopy.WriteToServer(dtExcelData);

                con.Close();

            }

        }

    }

}

Copy this in web config

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>

you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html

What does "The APR based Apache Tomcat Native library was not found" mean?

Had this problem as well. If you do have the libraries, but still have this error, it may be a configuration error. Your server.xml may be missing the following line:

 <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />

(Alternatively, it may be commented out). This <Listener>, like other listeners is a child of the top-level <Server>.

Without the <Listener> line, there's no attempt to load the APR library, so LD_LIBRARY_PATH and -Djava.library.path= settings are ignored.

Create a list from two object lists with linq

This can easily be done by using the Linq extension method Union. For example:

var mergedList = list1.Union(list2).ToList();

This will return a List in which the two lists are merged and doubles are removed. If you don't specify a comparer in the Union extension method like in my example, it will use the default Equals and GetHashCode methods in your Person class. If you for example want to compare persons by comparing their Name property, you must override these methods to perform the comparison yourself. Check the following code sample to accomplish that. You must add this code to your Person class.

/// <summary>
/// Checks if the provided object is equal to the current Person
/// </summary>
/// <param name="obj">Object to compare to the current Person</param>
/// <returns>True if equal, false if not</returns>
public override bool Equals(object obj)
{        
    // Try to cast the object to compare to to be a Person
    var person = obj as Person;

    return Equals(person);
}

/// <summary>
/// Returns an identifier for this instance
/// </summary>
public override int GetHashCode()
{
    return Name.GetHashCode();
}

/// <summary>
/// Checks if the provided Person is equal to the current Person
/// </summary>
/// <param name="personToCompareTo">Person to compare to the current person</param>
/// <returns>True if equal, false if not</returns>
public bool Equals(Person personToCompareTo)
{
    // Check if person is being compared to a non person. In that case always return false.
    if (personToCompareTo == null) return false;

    // If the person to compare to does not have a Name assigned yet, we can't define if it's the same. Return false.
    if (string.IsNullOrEmpty(personToCompareTo.Name) return false;

    // Check if both person objects contain the same Name. In that case they're assumed equal.
    return Name.Equals(personToCompareTo.Name);
}

If you don't want to set the default Equals method of your Person class to always use the Name to compare two objects, you can also write a comparer class which uses the IEqualityComparer interface. You can then provide this comparer as the second parameter in the Linq extension Union method. More information on how to write such a comparer method can be found on http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx

How to delete columns in a CSV file?

import csv
with open("source","rb") as source:
    rdr= csv.reader( source )
    with open("result","wb") as result:
        wtr= csv.writer( result )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[3], r[4]) )

BTW, the for loop can be removed, but not really simplified.

        in_iter= ( (r[0], r[1], r[3], r[4]) for r in rdr )
        wtr.writerows( in_iter )

Also, you can stick in a hyper-literal way to the requirements to delete a column. I find this to be a bad policy in general because it doesn't apply to removing more than one column. When you try to remove the second, you discover that the positions have all shifted and the resulting row isn't obvious. But for one column only, this works.

            del r[2]
            wtr.writerow( r )

Inline style to act as :hover in CSS

I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.

I should mention that technically you should be able to do it according to the CSS spec, but most browsers don't support it

Edit: I just did a quick test with this:

<a href="test.html" style="{color: blue; background: white} 
            :visited {color: green}
            :hover {background: yellow}
            :visited:hover {color: purple}">Test</a>

And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?

Split string with PowerShell and do something with each token

"Once upon a time there were three little pigs".Split(" ") | ForEach {
    "$_ is a token"
 }

The key is $_, which stands for the current variable in the pipeline.

About the code you found online:

% is an alias for ForEach-Object. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.

$_.Split(" ") is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach.

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

Use lock_guard unless you need to be able to manually unlock the mutex in between without destroying the lock.

In particular, condition_variable unlocks its mutex when going to sleep upon calls to wait. That is why a lock_guard is not sufficient here.

If you're already on C++17 or later, consider using scoped_lock as a slightly improved version of lock_guard, with the same essential capabilities.

Django: Calling .update() on a single model instance retrieved by .get()?

As @Nils mentionned, you can use the update_fields keyword argument of the save() method to manually specify the fields to update.

obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2

obj_instance.save(update_fields=['field', 'field2'])

The update_fields value should be a list of the fields to update as strings.

See https://docs.djangoproject.com/en/2.1/ref/models/instances/#specifying-which-fields-to-save

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

I also faced the same problem. Then I found a solution after a lot of searching .

The problem was that when we get the datetime object from model or form it is offset aware and if we get the time by system it is offset naive.

So what I did is I got the current time using timezone.now() and import the timezone by from django.utils import timezone and put the USE_TZ = True in your project settings file.

Check file size before upload

Client side Upload Canceling

On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE, can be tampered with so always use server side validation.

<form method="post" enctype="multipart/form-data" action="upload.php">
    <input type="file" name="file" id="file" />
    <input type="submit" name="submit" value="Submit" />
</form>

<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('file').files[0];

    if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);
</script>

Server Side Upload Canceling

On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.

PHP Validation

On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES array to find out the upload size. (Docs on the contents of $_FILES can be found below the MAX_FILE_SIZE docs)

upload.php

<?php
if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}

SyntaxError: Cannot use import statement outside a module

Step 1

yarn add esm

or

npm i esm --save

Step 2

package.json

  "scripts": {
    "start": "node -r esm src/index.js",
  }

Step 3

nodemon --exec npm start

Javascript Thousand Separator / string format

I use this:

function numberWithCommas(number) {
    return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

source: link

http to https through .htaccess

I try all of above code but any code is not working for my website.then i try this code and This code is running perfect for my website. You can use the following Rule in htaccess :

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

//Redirect http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

//Redirect non-www to www
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

</IfModule>

Change example.com with your domain name and sorry for my poor english.

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

Pythonic way to print list items

To display each content, I use:

mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):     
    print(mylist[indexval])
    indexval += 1

Example of using in a function:

def showAll(listname, startat):
   indexval = startat
   try:
      for i in range(len(mylist)):
         print(mylist[indexval])
         indexval = indexval + 1
   except IndexError:
      print('That index value you gave is out of range.')

Hope I helped.

How to bind RadioButtons to an enum?

You could use a more generic converter

public class EnumBooleanConverter : IValueConverter
{
  #region IValueConverter Members
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
      return DependencyProperty.UnsetValue;

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

    object parameterValue = Enum.Parse(value.GetType(), parameterString);

    return parameterValue.Equals(value);
  }

  public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  {
    string parameterString = parameter as string;
    if (parameterString == null)
        return DependencyProperty.UnsetValue;

    return Enum.Parse(targetType, parameterString);
  }
  #endregion
}

And in the XAML-Part you use:

<Grid>
    <Grid.Resources>
      <l:EnumBooleanConverter x:Key="enumBooleanConverter" />
    </Grid.Resources>
    <StackPanel >
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
      <RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
    </StackPanel>
</Grid>

Set specific precision of a BigDecimal

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

Some examples in Clojure.

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

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

You can easily increase the scale:

(.setScale 0.00123M 7) ; 0.0012300M

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

(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary

You'll need to pass a rounding mode too:

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

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

It is easy to decrease the precision:

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

But it is not obvious how to increase the precision:

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

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

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

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

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

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

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

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

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

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

These steps, as Clojure code:

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

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

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

How to remove an element slowly with jQuery?

target.fadeOut(300, function(){ $(this).remove();});

or

$('#target_id').fadeOut(300, function(){ $(this).remove();});

Duplicate: How to "fadeOut" & "remove" a div in jQuery?

String.Replace ignoring case

Using @Georgy Batalov solution I had a problem when using the following example

string original = "blah,DC=bleh,DC=blih,DC=bloh,DC=com"; string replaced = original.ReplaceIgnoreCase(",DC=", ".")

Below is how I rewrote his extension

public static string ReplaceIgnoreCase(this string source, string oldVale, 
string newVale)
    {
        if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
            return source;

        var stringBuilder = new StringBuilder();
        string result = source;

        int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
        bool initialRun = true;

        while (index >= 0)
        {
            string substr = result.Substring(0, index);
            substr = substr + newVale;
            result = result.Remove(0, index);
            result = result.Remove(0, oldVale.Length);

            stringBuilder.Append(substr);

            index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
        }

        if (result.Length > 0)
        {
            stringBuilder.Append(result);
        }

        return stringBuilder.ToString();
    }

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I recently had this problem and it ended up being a port issue. My production SQL Server was set up at to be port 1427 instead 1433.

Just change the connection string to be

...data source=MySQLServerName,1427;initial catalog=MyDBName...

Hope this helps anyone who might be seeing this same issue.

Unfortunately MyApp has stopped. How can I solve this?

You can also get this error message on its own, without any stack trace or any further error message.

In this case you need to make sure your Android manifest is configured correctly (including any manifest merging happening from a library and any activity that would come from a library), and pay particular attention to the first activity displayed in your application in your manifest files.

Transpose a range in VBA

Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-

How to sort an associative array by its values in Javascript?

Instead of correcting you on the semantics of an 'associative array', I think this is what you want:

function getSortedKeys(obj) {
    var keys = keys = Object.keys(obj);
    return keys.sort(function(a,b){return obj[b]-obj[a]});
}

for really old browsers, use this instead:

function getSortedKeys(obj) {
    var keys = []; for(var key in obj) keys.push(key);
    return keys.sort(function(a,b){return obj[b]-obj[a]});
}

You dump in an object (like yours) and get an array of the keys - eh properties - back, sorted descending by the (numerical) value of the, eh, values of the, eh, object.

This only works if your values are numerical. Tweek the little function(a,b) in there to change the sorting mechanism to work ascending, or work for string values (for example). Left as an exercise for the reader.

How to render a DateTime in a specific format in ASP.NET MVC 3?

@{
  string datein = Convert.ToDateTime(item.InDate).ToString("dd/MM/yyyy");        
  @datein
}

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

A note about 64bit Windows which seems to trip up a few folks. If your app is running under 64bit Windows, you likely have to set the DWORD under [HKLM\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION] instead.

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

How to open standard Google Map application from my application?

Sometimes if there's no any application associated with geo: protocal , you could use try-catch to get the ActivityNotFoundException to handle it.

It happens when you use some emulator like androVM which is not installed google map by default.

How do I print to the debug output window in a Win32 app?

You can use OutputDebugString. OutputDebugString is a macro that depending on your build options either maps to OutputDebugStringA(char const*) or OutputDebugStringW(wchar_t const*). In the later case you will have to supply a wide character string to the function. To create a wide character literal you can use the L prefix:

OutputDebugStringW(L"My output string.");

Normally you will use the macro version together with the _T macro like this:

OutputDebugString(_T("My output string."));

If you project is configured to build for UNICODE it will expand into:

OutputDebugStringW(L"My output string.");

If you are not building for UNICODE it will expand into:

OutputDebugStringA("My output string.");

Problems installing the devtools package

CentOS 7:

I tried solutions in this post

sudo yum -y install libcurl libcurl-devel
sudo yum -y install openssl-devel

but wasn't enough.

Checking R error in Console gave me the anwser. In my case it was lacking libxml-2.0 below (and Console printed an explanation with package name to different Linux versions and other possible R configs)

sudo yum -y install libxml2-devel

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

JavaScript/jQuery - How to check if a string contain specific words

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6

How do I print bytes as hexadecimal?

If you want to use C++ streams rather than C functions, you can do the following:

int ar[] = { 20, 30, 40, 50, 60, 70, 80, 90 };
const int siz_ar = sizeof(ar) / sizeof(int);

for (int i = 0; i < siz_ar; ++i)
    cout << ar[i] << " ";
cout << endl;

for (int i = 0; i < siz_ar; ++i)
    cout << hex << setfill('0') << setw(2) << ar[i] << " ";
cout << endl;

Very simple.

Output:

20 30 40 50 60 70 80 90
14 1e 28 32 3c 46 50 5a 

How to convert String into Hashmap in java

String value = "{first_name = naresh,last_name = kumar,gender = male}"

Let's start

  1. Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
  2. Split the String from ,>> array of 3 element
  3. Now you have an array with 3 element
  4. Iterate the array and split each element by =
  5. Create a Map<String,String> put each part separated by =. first part as Key and second part as Value

Android Emulator Error Message: "PANIC: Missing emulator engine program for 'x86' CPUS."

Try the following work-around to start emulator-x86:

export LD_LIBRARY_PATH=$SDK/tools/lib:$LD_LIBRARY_PATH
$SDK/tools/emulator-x86 <your-other-options>

Where $SDK is the path to your SDK installation. That's in a nutshell what 'emulator' tries to do. You might want to start emulator64-x86 instead of emulator-x86 if the former exists though.

Nth max salary in Oracle

select * FROM (
select EmployeeID, Salary
, dense_rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = N;

dense_rank() is used for the salary has to be same.So it give the proper output instead of using rank().

Java variable number or arguments for a method

For different types of arguments, there is 3-dots :

public void foo(Object... x) {
    String myVar1  = x.length > 0 ? (String)x[0]  : "Hello";
    int myVar2     = x.length > 1 ? Integer.parseInt((String) x[1]) : 888;
} 

Then call it

foo("Hii"); 
foo("Hii", 146); 

for security, use like this:
if (!(x[0] instanceof String)) { throw new IllegalArgumentException("..."); }

The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Please, see more variations .

get the titles of all open windows

Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show.

using System.Runtime.InteropServices;
using HWND = System.IntPtr;

/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
  /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
  /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
  public static IDictionary<HWND, string> GetOpenWindows()
  {
    HWND shellWindow = GetShellWindow();
    Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

    EnumWindows(delegate(HWND hWnd, int lParam)
    {
      if (hWnd == shellWindow) return true;
      if (!IsWindowVisible(hWnd)) return true;

      int length = GetWindowTextLength(hWnd);
      if (length == 0) return true;

      StringBuilder builder = new StringBuilder(length);
      GetWindowText(hWnd, builder, length + 1);

      windows[hWnd] = builder.ToString();
      return true;

    }, 0);

    return windows;
  }

  private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

  [DllImport("USER32.DLL")]
  private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowTextLength(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern bool IsWindowVisible(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern IntPtr GetShellWindow();
}

And here’s some code that uses it:

foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
  IntPtr handle = window.Key;
  string title = window.Value;

  Console.WriteLine("{0}: {1}", handle, title);
}

Credit: http://www.tcx.be/blog/2006/list-open-windows/

CSS: borders between table columns only

I know this is an old question, but there is a simple, one line solution which works consistently for Chrome, Firefox, etc., as well as IE8 and above (and, for the most part, works on IE7 too - see http://www.quirksmode.org/css/selectors/ for details):

table td + td { border-left:2px solid red; }


The output is something like this:

Col1 | Col2 | Col3

What is making this work is that you are defining a border only on table cells which are adjacent to another table cell. In other words, you're applying the CSS to all cells in a row except the first one.

By applying a left border to the second through the last child, it gives the appearance of the line being "between" the cells.

How to create a link to another PHP page

Just try like this:

HTML in PHP :

$link_address1 = 'index.php';
echo "<a href='".$link_address1."'>Index Page</a>";

$link_address2 = 'page2.php';
echo "<a href='".$link_address2."'>Page 2</a>";

Easiest way

$link_address1 = 'index.php';
echo "<a href='$link_address1'>Index Page</a>";

$link_address2 = 'page2.php';
echo "<a href='$link_address2'>Page 2</a>";

CSS3 Transparency + Gradient

I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)

.grad {
    background-color: #F07575; /* fallback color if gradients are not supported */
    background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
    background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
    background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
    background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}

from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

get UTC timestamp in python with datetime

I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.

The most important thing to understand when dealing with time is that time is relative!

  • 2017-08-30 13:23:00: (a naive datetime), represents a local time somewhere in the world, but note that 2017-08-30 13:23:00 in London is NOT THE SAME TIME as 2017-08-30 13:23:00 in San Francisco.

Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.

A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00 at GMT timezone +00:00 offset).

Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.

This makes it possible to order events in time.

Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.

What are the types of time used in computer system?

  • naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.

  • UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to 2017-08-30T18:55:24Z, or 2017-08-30T17:55:24-0100 or also 2017-08-30T10:55:24-0800. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.

  • ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.

When to use which? or rather when do you need to care about timezones?

  • If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.

  • To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.

Timezone offset in a date string:

Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800 says the offset -0800 or 8 hours back, doesn't mean that it will always be!

In the summer it may well be in daylight saving time, and it would be -0700

What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)

America/Los_Angeles timezone is a place in the world, but it turns into PST (Pacific Standard Time) timezone offset notation in the winter, and PDT (Pacific Daylight Time) in the summer.

So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.

Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT timezone designation in West Africa, is UTC+0100 just like CET timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)

So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!

how to remove the dotted line around the clicked a element in html

Like @Lo Juego said, read the article

a, a:active, a:focus {
   outline: none;
}

How to run Pip commands from CMD

Little side note for anyone new to Python who didn't figure it out by theirself: this should be automatic when installing Python, but just in case, note that to run Python using the python command in Windows' CMD you must first add it to the PATH environment variable, as explained here.


To execute Pip, first of all make sure you have it installed, so type in your CMD:

> python
>>> import pip
>>>

And it should proceed with no error. Otherwise, if this fails, you can look here to see how to install it. Now that you are sure you've got Pip, you can run it from CMD with Python using the -m (module) parameter, like this:

> python -m pip <command> <args>

Where <command> is any Pip command you want to run, and <args> are its relative arguments, separated by spaces.

For example, to install a package:

> python -m pip install <package-name>

How to set the font size in Emacs?

Aquamacs:

(set-face-attribute 'default nil :font "Monaco-16" )

From the Emacs Wiki Globally Change the Default Font, it says you can use either of these:

(set-face-attribute 'default nil :font FONT )

(set-frame-font FONT nil t)

Where FONT is something like "Monaco-16", e.g.:

(set-face-attribute 'default nil :font "Monaco-16" )

There was an extra closing parenthesis in the first suggestion on the wiki, which caused an error on startup. I finally noticed the extra closing parenthesis, and I subsequently corrected the suggestion on the wiki. Then both of the suggestions worked for me.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long and long int are identical. So are long long and long long int. In both cases, the int is optional.

As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that long long is at least as wide as long.

The controlling parts of the standard (C++11, but this has been around for a long time) are, for one, 3.9.1 Fundamental types, section 2 (a later section gives similar rules for the unsigned integral types):

There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.

There's also a table 9 in 7.1.6.2 Simple type specifiers, which shows the "mappings" of the specifiers to actual types (showing that the int is optional), a section of which is shown below:

Specifier(s)         Type
-------------    -------------
long long int    long long int
long long        long long int
long int         long int
long             long int

Note the distinction there between the specifier and the type. The specifier is how you tell the compiler what the type is but you can use different specifiers to end up at the same type.

Hence long on its own is neither a type nor a modifier as your question posits, it's simply a specifier for the long int type. Ditto for long long being a specifier for the long long int type.

Although the C++ standard itself doesn't specify the minimum ranges of integral types, it does cite C99, in 1.2 Normative references, as applying. Hence the minimal ranges as set out in C99 5.2.4.2.1 Sizes of integer types <limits.h> are applicable.


In terms of long double, that's actually a floating point value rather than an integer. Similarly to the integral types, it's required to have at least as much precision as a double and to provide a superset of values over that type (meaning at least those values, not necessarily more values).

Python "extend" for a dictionary

In case you need it as a Class, you can extend it with dict and use update method:

Class a(dict):
  # some stuff
  self.update(b)

Import file size limit in PHPMyAdmin

C:\xampp\php\php.ini in my case or it could be C:\php\php.ini if the Apache / PHP / MySQL are stand alone

upload_max_filesize = 2M by default

so it can be changed as desired. And in my case upload_max_filesize = 20M

post_max_size = 8M by default it should be changed to post_max_size = 20M as well

memory_limit=128M is by default and it is not necessary to change to increase the max 2056kb or 2mb .sql file upload limit. But it only means that a script can consume up to 128 memory when you run apache and sql server , and if you change memory_limit=128M to higher and run any malfunctioned script then it may cause you trouble. So its up to you.

Iterating over all the keys of a map

This is also an option

 for key, element := range myMap{
    fmt.Println("Key:", key, "Element:", element)
 }

Make selected block of text uppercase

The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above).

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

[
 {
    "key": "ctrl+shift+u",
    "command": "editor.action.transformToUppercase",
    "when": "editorTextFocus"
 },
 {
    "key": "ctrl+shift+l",
    "command": "editor.action.transformToLowercase",
    "when": "editorTextFocus"
 }
]

Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.

These commands are built into VS Code, and no extensions are required to make them work.

Server configuration by allow_url_fopen=0 in

If you do not have the ability to modify your php.ini file, use cURL: PHP Curl And Cookies

Here is an example function I created:

function get_web_page( $url, $cookiesIn = '' ){
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => true,     //return headers in addition to content
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLINFO_HEADER_OUT    => true,
            CURLOPT_SSL_VERIFYPEER => true,     // Validate SSL Cert
            CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
            CURLOPT_COOKIE         => $cookiesIn
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $rough_content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header_content = substr($rough_content, 0, $header['header_size']);
        $body_content = trim(str_replace($header_content, '', $rough_content));
        $pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m"; 
        preg_match_all($pattern, $header_content, $matches); 
        $cookiesOut = implode("; ", $matches['cookie']);

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['headers']  = $header_content;
        $header['content'] = $body_content;
        $header['cookies'] = $cookiesOut;
    return $header;
}

NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

Bootstrap: add margin/padding space between columns

You may use the padding and margin shorthand Bootstrap 4 classes as follows:

For extra small devices i.e. xs

{property}{sides}-{size}

For other devices/viewports (small, medium, large and extra large)

{property}{sides}-{breakpoint}-{size}

Where:

property = m for margin and p for padding

Following are sides shorthand meanings:

l = defines the left-margin or left-padding
r = defines the right-margin or right-padding
t = defines the top-margin or top-padding
b = defines the bottom-margin or right-padding
x = For setting left and right padding and margins by the single call
y = For setting top and bottom margins
blank = margin and padding for all sides

The breakpoint = sm, md, lg, and xl.

Combining all the above, the left padding complete code can be (for example):

For left padding in extra small devices

pl-2

or for medium to extra large

pl-md-2

Face recognition Library

You can try open MVG library, It can be used for multiple interfaces too.

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Here is the perfect method:

Please note that Environment.NewLine works on on Microsoft platforms.

In addition to the above, you need to add \r and \n in a separate function!

Here is the code which will support whether you type on Linux, Windows, or Mac:

var stringTest = "\r Test\nThe Quick\r\n brown fox";

Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");

stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);

Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();

Git: Could not resolve host github.com error while cloning remote repository in git

I guess my case was very rare, but GitHub was out down. Check their webpage to see if it loads properly.

GitHub

pandas groupby sort descending order

This kind of operation is covered under hierarchical indexing. Check out the examples here

When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.

It turns out if you pass a tuple corresponding to the exact column you want sorted on.

Try this:

# generate toy data 
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])

# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique. 
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))

This will output a df sorted by the AUC-mean column only.

C - function inside struct

As others have noted, embedding function pointers directly inside your structure is usually reserved for special purposes, like a callback function.

What you probably want is something more like a virtual method table.

typedef struct client_ops_t client_ops_t;
typedef struct client_t client_t, *pno;

struct client_t {
    /* ... */
    client_ops_t *ops;
};

struct client_ops_t {
    pno (*AddClient)(client_t *);
    pno (*RemoveClient)(client_t *);
};

pno AddClient (client_t *client) { return client->ops->AddClient(client); }
pno RemoveClient (client_t *client) { return client->ops->RemoveClient(client); }

Now, adding more operations does not change the size of the client_t structure. Now, this kind of flexibility is only useful if you need to define many kinds of clients, or want to allow users of your client_t interface to be able to augment how the operations behave.

This kind of structure does appear in real code. The OpenSSL BIO layer looks similar to this, and also UNIX device driver interfaces have a layer like this.

How do I bind a WPF DataGrid to a variable number of columns?

Made a version of the accepted answer that handles unsubscription.

public class DataGridColumnsBehavior
{
    public static readonly DependencyProperty BindableColumnsProperty =
        DependencyProperty.RegisterAttached("BindableColumns",
                                            typeof(ObservableCollection<DataGridColumn>),
                                            typeof(DataGridColumnsBehavior),
                                            new UIPropertyMetadata(null, BindableColumnsPropertyChanged));

    /// <summary>Collection to store collection change handlers - to be able to unsubscribe later.</summary>
    private static readonly Dictionary<DataGrid, NotifyCollectionChangedEventHandler> _handlers;

    static DataGridColumnsBehavior()
    {
        _handlers = new Dictionary<DataGrid, NotifyCollectionChangedEventHandler>();
    }

    private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        DataGrid dataGrid = source as DataGrid;

        ObservableCollection<DataGridColumn> oldColumns = e.OldValue as ObservableCollection<DataGridColumn>;
        if (oldColumns != null)
        {
            // Remove all columns.
            dataGrid.Columns.Clear();

            // Unsubscribe from old collection.
            NotifyCollectionChangedEventHandler h;
            if (_handlers.TryGetValue(dataGrid, out h))
            {
                oldColumns.CollectionChanged -= h;
                _handlers.Remove(dataGrid);
            }
        }

        ObservableCollection<DataGridColumn> newColumns = e.NewValue as ObservableCollection<DataGridColumn>;
        dataGrid.Columns.Clear();
        if (newColumns != null)
        {
            // Add columns from this source.
            foreach (DataGridColumn column in newColumns)
                dataGrid.Columns.Add(column);

            // Subscribe to future changes.
            NotifyCollectionChangedEventHandler h = (_, ne) => OnCollectionChanged(ne, dataGrid);
            _handlers[dataGrid] = h;
            newColumns.CollectionChanged += h;
        }
    }

    static void OnCollectionChanged(NotifyCollectionChangedEventArgs ne, DataGrid dataGrid)
    {
        switch (ne.Action)
        {
            case NotifyCollectionChangedAction.Reset:
                dataGrid.Columns.Clear();
                foreach (DataGridColumn column in ne.NewItems)
                    dataGrid.Columns.Add(column);
                break;
            case NotifyCollectionChangedAction.Add:
                foreach (DataGridColumn column in ne.NewItems)
                    dataGrid.Columns.Add(column);
                break;
            case NotifyCollectionChangedAction.Move:
                dataGrid.Columns.Move(ne.OldStartingIndex, ne.NewStartingIndex);
                break;
            case NotifyCollectionChangedAction.Remove:
                foreach (DataGridColumn column in ne.OldItems)
                    dataGrid.Columns.Remove(column);
                break;
            case NotifyCollectionChangedAction.Replace:
                dataGrid.Columns[ne.NewStartingIndex] = ne.NewItems[0] as DataGridColumn;
                break;
        }
    }

    public static void SetBindableColumns(DependencyObject element, ObservableCollection<DataGridColumn> value)
    {
        element.SetValue(BindableColumnsProperty, value);
    }

    public static ObservableCollection<DataGridColumn> GetBindableColumns(DependencyObject element)
    {
        return (ObservableCollection<DataGridColumn>)element.GetValue(BindableColumnsProperty);
    }
}

How can I change the value of the elements in a vector?

Well, you could always run a transform over the vector:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

List method to delete last element in list as well as all elements

To delete the last element from the list just do this.

a = [1,2,3,4,5]
a = a[:-1]
#Output [1,2,3,4] 

How to get the current date/time in Java

Current Date using java 8: First, let's use java.time.LocalDate to get the current system date:

LocalDate localDate = LocalDate.now();

To get the date in any other timezone we can use LocalDate.now(ZoneId):

LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));

We can also use java.time.LocalDateTime to get an instance of LocalDate:

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();

Use LINQ to get items in one List<>, that are not in another List<>

Once you write a generic FuncEqualityComparer you can use it everywhere.

peopleList2.Except(peopleList1, new FuncEqualityComparer<Person>((p, q) => p.ID == q.ID));

public class FuncEqualityComparer<T> : IEqualityComparer<T>
{
    private readonly Func<T, T, bool> comparer;
    private readonly Func<T, int> hash;

    public FuncEqualityComparer(Func<T, T, bool> comparer)
    {
        this.comparer = comparer;
        if (typeof(T).GetMethod(nameof(object.GetHashCode)).DeclaringType == typeof(object))
            hash = (_) => 0;
        else
            hash = t => t.GetHashCode(); 
    }

    public bool Equals(T x, T y) => comparer(x, y);
    public int GetHashCode(T obj) => hash(obj);
}

Using "like" wildcard in prepared statement

Code it like this:

PreparedStatement pstmt = con.prepareStatement(
    "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`

Make sure that you DO NOT include the quotes ' ' like below as they will cause an exception.

pstmt.setString(1,"'%"+ notes + "%'");

How do I fit an image (img) inside a div and keep the aspect ratio?

Using CSS only:

div > img {
  width: auto;
  height : auto;
  max-height: 100%;
  max-width: 100%;
}

How to open a Bootstrap modal window using jQuery?

<script type="text/javascript">
    $(function () {
        $("mybtn").click(function () {
            $("#my-modal").modal("show");
        });
    });
</script>

How to decode JWT Token?

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(string token)
    {
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;
    }

Write to file, but overwrite it if it exists

If you have output that can have errors, you may want to use an ampersand and a greater than, as follows:

my_task &> 'Users/Name/Desktop/task_output.log' this will redirect both stderr and stdout to the log file (instead of stdout only).

Capturing URL parameters in request.GET

Using GET

request.GET["id"]

Using POST

request.POST["id"]

How to get absolute path to file in /resources folder of your project

Create the classLoader instance of the class you need, then you can access the files or resources easily. now you access path using getPath() method of that class.

 ClassLoader classLoader = getClass().getClassLoader();
 String path  = classLoader.getResource("chromedriver.exe").getPath();
 System.out.println(path);

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

Try this one:

$('body').tooltip({
    selector: '[rel=tooltip]'
});

IE11 prevents ActiveX from running

There is no solution to this problem. As of IE11 on Windows 8, Microsoft no longer allows ActiveX plugins to run in its browser space. There is absolutely nothing that a third party developer can do about it.

A similar thing has recently happened with the Chrome browser which no longer supports NPAPI plugins. Instead Chrome only supports PPAPI plugins which are useless for system level tasks once performed by NPAPI plugins.

So developers needing browser support for system interactive plugins can only recommend either the Firefox browser or the ASPS web browser.