Programs & Examples On #Longest prefix

Cannot find mysql.sock

This solved my problem

mysql_config --socket

UPDATE

mysql_config can tell us where the file mysql.sock should be, but in my case the file didn't exist. So, I've deleted my.cnf:

sudo rm -rf /etc/my.cnf

And then restarted mysql:

brew services restart mysql

The file was created and mysql is now running well.

Print text instead of value from C enum

I know I am late to the party, but how about this?

const char* dayNames[] = { [Sunday] = "Sunday", [Monday] = "Monday", /*and so on*/ };
printf("%s", dayNames[Sunday]); // prints "Sunday"

This way, you do not have to manually keep the enum and the char* array in sync. If you are like me, chances are that you will later change the enum, and the char* array will print invalid strings. This may not be a feature universally supported. But afaik, most of the mordern day C compilers support this designated initialier style.

You can read more about designated initializers here.

Maven error "Failure to transfer..."

This worked for me in Windows as well.

  1. Locate the {user}/.m2/repository (Using Juno /Win7 here)
  2. In the Search field in upper right of window, type ".lastupdated". Windows will look through all subfolders for these files in the directory. (I did not look through cache.)
  3. Remove them by Right-click > Delete (I kept all of the lastupdated.properties).
  4. Then go back into Eclipse, Right-click on the project and select Maven > Update Project. I selected to "Force Update of Snapshots/Releases". Click Ok and the dependencies finally resolved correctly.

Getting unix timestamp from Date()

In java 8, it's convenient to use the new date lib and getEpochSecond method to get the timestamp (it's in second)

Instant.now().getEpochSecond();

How to create a directory in Java?

if you want to be sure its created then this:

final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
    final boolean logsDirExists = logsDir.exists();
    assertThat(logsDirExists).isTrue();
}

beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...

mkDir() returns only true if mkDir() creates it. If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.

assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.

How to create exe of a console application

The following steps are necessary to create .exe i.e. executable files which are as 1) Open visual studio framework 2) Then, create a new project or application 3) Build or execute your application by pressing F5

How to append to a file in Node?

My approach is rather special. I basically use the WriteStream solution but without actually 'closing' the fd by using stream.end(). Instead I use cork/uncork. This got the benefit of low RAM usage (if that matters to anyone) and I believe it's more safe to use for logging/recording (my original use case).

Following is a pretty simple example. Notice I just added a pseudo for loop for showcase -- in production code I am waiting for websocket messages.

var stream = fs.createWriteStream("log.txt", {flags:'a'});
for(true) {
  stream.cork();
  stream.write("some content to log");
  process.nextTick(() => stream.uncork());
}

uncork will flush the data to the file in the next tick.

In my scenario there are peaks of up to ~200 writes per second in various sizes. During night time however only a handful writes per minute are needed. The code is working super reliable even during peak times.

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

MySQL: How to allow remote connection to mysql

some times need to use name of pc on windows

first step) put in config file of mysql:

mysqld.cnf SET bind-address= 0.0.0.0

(to let recibe connections over tcp/ip)

second step) make user in mysql, table users, with name of pc on windows propierties, NOT ip

enter image description here

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

How can I scale an entire web page with CSS?

Scale is not the best option

It will need some other adjustments, like margins paddings etc ..

but the right option is

zoom: 75%

How do I use a custom Serializer with Jackson?

I tried doing this too, and there is a mistake in the example code on the Jackson web page that fails to include the type (.class) in the call to addSerializer() method, which should read like this:

simpleModule.addSerializer(Item.class, new ItemSerializer());

In other words, these are the lines that instantiate the simpleModule and add the serializer (with the prior incorrect line commented out):

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", 
                                          new Version(1,0,0,null));
// simpleModule.addSerializer(new ItemSerializer());
simpleModule.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(simpleModule);

FYI: Here is the reference for the correct example code: http://wiki.fasterxml.com/JacksonFeatureModules

Read text from response

The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there's a new way to do this in .NET 4.5.

To perform an HTTP GET and read the response text, do the following.

.NET 1.1 - 4.0

public static string GetResponseText(string address)
{
    var request = (HttpWebRequest)WebRequest.Create(address);

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        var encoding = Encoding.GetEncoding(response.CharacterSet);

        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream, encoding))
            return reader.ReadToEnd();
    }
}

.NET 4.5

private static readonly HttpClient httpClient = new HttpClient();

public static async Task<string> GetResponseText(string address)
{
    return await httpClient.GetStringAsync(address);
}

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

Count number of columns in a table row

It's a bad idea to count the td elements to get the number of columns in your table, because td elements can span multiple columns with colspan.

Here's a simple solution using jquery:

_x000D_
_x000D_
var length = 0;_x000D_
$("tr:first").find("td,th").each(function(){_x000D_
 var colspan = $(this).attr("colspan");_x000D_
  if(typeof colspan !== "undefined" && colspan > 0){_x000D_
   length += parseInt(colspan);_x000D_
  }else{_x000D_
        length += 1;_x000D_
  }_x000D_
});_x000D_
_x000D_
$("div").html("number of columns: "+length);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
  <td>single</td>_x000D_
  <td colspan="2">double</td>_x000D_
  <td>single</td>_x000D_
  <td>single</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

For a plain Javascript solution, see Emilio's answer.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

You need to add sudo . I did the following to get it installed :

sudo apt-get install libsm6 libxrender1 libfontconfig1

and then did that (optional! maybe you won't need it)

sudo python3 -m pip install opencv-contrib-python

FINALLY got it done !

Read file from resources folder in Spring Boot

For me, the bug had two fixes.

  1. Xml file which was named as SAMPLE.XML which was causing even the below solution to fail when deployed to aws ec2. The fix was to rename it to new_sample.xml and apply the solution given below.
  2. Solution approach https://medium.com/@jonathan.henrique.smtp/reading-files-in-resource-path-from-jar-artifact-459ce00d2130

I was using Spring boot as jar and deployed to aws ec2 Java variant of the solution is as below :

package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;


public class XmlReader {

    private static Logger LOGGER = LoggerFactory.getLogger(XmlReader.class);

  public static void main(String[] args) {


      String fileLocation = "classpath:cbs_response.xml";
      String reponseXML = null;
      try (ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext()){

        Resource resource = appContext.getResource(fileLocation);
        if (resource.isReadable()) {
          BufferedReader reader =
              new BufferedReader(new InputStreamReader(resource.getInputStream()));
          Stream<String> lines = reader.lines();
          reponseXML = lines.collect(Collectors.joining("\n"));

        }      
      } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
      }
  }
}

Why is "npm install" really slow?

I had similar problems. I was also confused by some solutions leaving me with different versions displaying for different users. If you have any problems at all, I would first check every account your using any implementation of node

Finally, this solution appears to solve this issue 100%, giving me the confidence that my versions were universal no matter what user privileges I wanted to use:

    sudo yum update

    sudo yum install build-essential checkinstall libssl-dev

    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

    (sudo) nvm --version

    (sudo) nvm ls-remote

    (sudo) nvm install [version.number] 

1

If you're still having a problem, next try looking inside your /usr/local/bin directory. If you find either a large binary document named node or a folder named npm, delete them.

    rm /usr/local/bin/node

    rm -r /usr/local/bin/npm

Personally, before I deleted those, two of my user accounts were using the latest version of node/npm installed correctly via nvm, while a third account of mine remained stubborn by still using a far older installation of both node and npm apparently located inside my /usr/local/bin/ directory. As soon as I deleted both of them with the two above commands, that problematic user account implicitly began running the correct installation, having all three accounts mutually the intended versions.

(Implemented while using Centos 7 Blank x64. Some source code used above was originally supplied by 'phoenixNAP Global IT services' 1)

problem with php mail 'From' header

Edit: I just noted that you are trying to use a gmail address as the from value. This is not going to work, and the ISP is right in overwriting it. If you want to redirect the replies to your outgoing messages, use reply-to.

A workaround for valid addresses that works with many ISPs:

try adding a fifth parameter to your mail() command:

mail($to,$subject,$message,$headers,"-f [email protected]");

Can I export a variable to the environment from a bash script without sourcing it?

Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

Quick answer: No.

But there are several possible workarounds.

The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:

$ cat set-vars1.sh 
export FOO=BAR
$ . set-vars1.sh 
$ echo $FOO
BAR

Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:

$ cat set-vars2.sh
#!/bin/bash
echo export FOO=BAR
$ eval "$(./set-vars2.sh)"
$ echo "$FOO"
BAR

A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:

$ cat set-vars3.sh
#!/bin/bash
export FOO=BAR
exec "$@"
$ ./set-vars3.sh printenv | grep FOO
FOO=BAR

This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I got the same error when using policy as below, although i have "s3:ListBucket" for s3:ListObjects operation.

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "s3:ListBucket",
            "s3:GetObject",
            "s3:GetObjectAcl"
        ],
        "Resource": [
            "arn:aws:s3:::<bucketname>/*",
            "arn:aws:s3:::*-bucket/*"
        ],
        "Effect": "Allow"
    }
  ]
 }

Then i fixed it by adding one line "arn:aws:s3:::bucketname"

{
"Version": "2012-10-17",
"Statement": [
    {
        "Action": [
            "s3:ListBucket",
            "s3:GetObject",
            "s3:GetObjectAcl"
        ],
        "Resource": [
             "arn:aws:s3:::<bucketname>",
            "arn:aws:s3:::<bucketname>/*",
            "arn:aws:s3:::*-bucket/*"
        ],
        "Effect": "Allow"
    }
 ]
}

Why doesn't "System.out.println" work in Android?

There is no place on your phone that you can read the System.out.println();

Instead, if you want to see the result of something either look at your logcat/console window or make a Toast or a Snackbar (if you're on a newer device) appear on the device's screen with the message :) That's what i do when i have to check for example where it goes in a switch case code! Have fun coding! :)

How to update UI from another thread running in another class

You're right that you should use the Dispatcher to update controls on the UI thread, and also right that long-running processes should not run on the UI thread. Even if you run the long-running process asynchronously on the UI thread, it can still cause performance issues.

It should be noted that Dispatcher.CurrentDispatcher will return the dispatcher for the current thread, not necessarily the UI thread. I think you can use Application.Current.Dispatcher to get a reference to the UI thread's dispatcher if that's available to you, but if not you'll have to pass the UI dispatcher in to your background thread.

Typically I use the Task Parallel Library for threading operations instead of a BackgroundWorker. I just find it easier to use.

For example,

Task.Factory.StartNew(() => 
    SomeObject.RunLongProcess(someDataObject));

where

void RunLongProcess(SomeViewModel someDataObject)
{
    for (int i = 0; i <= 1000; i++)
    {
        Thread.Sleep(10);

        // Update every 10 executions
        if (i % 10 == 0)
        {
            // Send message to UI thread
            Application.Current.Dispatcher.BeginInvoke(
                DispatcherPriority.Normal,
                (Action)(() => someDataObject.ProgressValue = (i / 1000)));
        }
    }
}

Wait for a void async method

do a AutoResetEvent, call the function then wait on AutoResetEvent and then set it inside async void when you know it is done.

You can also wait on a Task that returns from your void async

Adding CSRFToken to Ajax request

The answer above didn't work for me.

I added the following code before my ajax request:

function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
            var csrftoken = getCookie('csrftoken');

            function csrfSafeMethod(method) {
                // these HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });

            $.ajax({
                     type: 'POST',
                     url: '/url/',
            });

time delayed redirect?

You can easily create timed redirections with JavaScript. But I suggest you to use location.replace('url') instead of location.href. It prevents to browser to push the site into the history. I found this JavaScript redirect tool. I think you could use this.

Example code (with 5 secs delay):

<!-- Pleace this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="5;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.com/";
    var delay = "5000";
    window.onload = function ()
    {
        setTimeout(GoToURL, delay);
    }
    function GoToURL()
    {
        if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
        {
            var referLink = document.createElement("a");
            referLink.href = url;
            document.body.appendChild(referLink);
            referLink.click();
        }
        else { window.location.replace(url); } // All other browsers
    }
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

How do I merge a specific commit from one branch into another in Git?

If BranchA has not been pushed to a remote then you can reorder the commits using rebase and then simply merge. It's preferable to use merge over rebase when possible because it doesn't create duplicate commits.

git checkout BranchA
git rebase -i HEAD~113
... reorder the commits so the 10 you want are first ...
git checkout BranchB
git merge [the 10th commit]

How do I 'foreach' through a two-dimensional array?

string[][] languages = new string[2][];
            languages[0] = new string[2];
            languages[1] = new string[3];
// inserting data into double dimensional arrays.
            for (int i = 0; i < 2; i++)
            {
                languages[0][i] = "Jagged"+i.ToString();
            }
            for (int j = 0; j < 3; j++)
            {
                languages[1][j] = "Jag"+j.ToString();
            }

// doing foreach through 2 dimensional arrays.
foreach (string[] s in languages)
            {
                foreach (string a in s)
                {
                    Console.WriteLine(a);
                }
            }

Show which git tag you are on?

When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.

It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:

$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

How to convert strings into integers in Python?

Instead of putting int( ), put float( ) which will let you use decimals along with integers.

Is it possible to install both 32bit and 64bit Java on Windows 7?

Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

In fact, i have such a setup myself.

Python Threading String Arguments

I hope to provide more background knowledge here.

First, constructor signature of the of method threading::Thread:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

args is the argument tuple for the target invocation. Defaults to ().

Second, A quirk in Python about tuple:

Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).

On the other hand, a string is a sequence of characters, like 'abc'[1] == 'b'. So if send a string to args, even in parentheses (still a sting), each character will be treated as a single parameter.

However, Python is so integrated and is not like JavaScript where extra arguments can be tolerated. Instead, it throws an TypeError to complain.

Is optimisation level -O3 dangerous in g++?

Recently I experienced a problem using optimization with g++. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:

unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
    pciMemory[ 0 ] = someCommand[ i ];

The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ] into pciMemory, omitting all preceding writes.

In conclusion: be accurate and attentive with optimization.

How to return a table from a Stored Procedure?

In SQL Server 2008 you can use

http://www.sommarskog.se/share_data.html#tableparam

or else simple and same as common execution

CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS

SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
     JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

I hopes its help to you

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Google brought me here but... The examples provided work if the dropdown menu is overlaping (at least by 1px) with its parent when show. If not, it loses focus and nothing works as intended.

Here is a working solution with jQuery and Bootstrap 4.5.2 :

$('li.nav-item').mouseenter(function (e) {

        e.stopImmediatePropagation();

        if ($(this).hasClass('dropdown')) {

            // target element containing dropdowns, show it
            $(this).addClass('show');
            $(this).find('.dropdown-menu').addClass('show');

            // Close dropdown on mouseleave
            $('.dropdown-menu').mouseleave(function (e) {
                e.stopImmediatePropagation();
                $(this).removeClass('show');
            });

            // If you have a prenav above, this clears open dropdowns (since you probably will hover the nav-item going up and it will reopen its dropdown otherwise)
            $('#prenav').off().mouseenter(function (e) {
                e.stopImmediatePropagation();
                $('.dropdown-menu').removeClass('show');
            });

        } else {
            // unset open dropdowns if hover is on simple nav element
            $('.dropdown-menu').removeClass('show');
        }
    });

How to easily map c++ enums to strings

If you want the enum names themselves as strings, see this post. Otherwise, a std::map<MyEnum, char const*> will work nicely. (No point in copying your string literals to std::strings in the map)

For extra syntactic sugar, here's how to write a map_init class. The goal is to allow

std::map<MyEnum, const char*> MyMap;
map_init(MyMap)
    (eValue1, "A")
    (eValue2, "B")
    (eValue3, "C")
;

The function template <typename T> map_init(T&) returns a map_init_helper<T>. map_init_helper<T> stores a T&, and defines the trivial map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&). (Returning *this from operator() allows the chaining of operator(), like operator<< on std::ostreams)

template<typename T> struct map_init_helper
{
    T& data;
    map_init_helper(T& d) : data(d) {}
    map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value)
    {
        data[key] = value;
        return *this;
    }
};

template<typename T> map_init_helper<T> map_init(T& item)
{
    return map_init_helper<T>(item);
}

Since the function and helper class are templated, you can use them for any map, or map-like structure. I.e. it can also add entries to std::unordered_map

If you don't like writing these helpers, boost::assign offers the same functionality out of the box.

Indirectly referenced from required .class file

Add spring-tx jar file and it should settle it.

encrypt and decrypt md5

As already stated, you cannot decrypt MD5 without attempting something like brute force hacking which is extremely resource intensive, not practical, and unethical.

However you could use something like this to encrypt / decrypt passwords/etc safely:

$input = "SmackFactory";

$encrypted = encryptIt( $input );
$decrypted = decryptIt( $encrypted );

echo $encrypted . '<br />' . $decrypted;

function encryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
    return( $qEncoded );
}

function decryptIt( $q ) {
    $cryptKey  = 'qJB0rGtIn5UB1xG03efyCp';
    $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "\0");
    return( $qDecoded );
}

Using a encypted method with a salt would be even safer, but this would be a good next step past just using a MD5 hash.

What is the difference between match_parent and fill_parent?

match_parent and fill_parent are same property, used to define width or height of a view in full screen horizontally or vertically.

These properties are used in android xml files like this.

 android:layout_width="match_parent"
 android:layout_height="fill_parent"

or

 android:layout_width="fill_parent"
 android:layout_height="match_parent"

fill_parent was used in previous versions, but now it has been deprecated and replaced by match_parent. I hope it'll help you.

How to detect orientation change in layout in Android?

For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView in onConfigurationChanged method.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.yourxmlinlayout-land);
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        setContentView(R.layout.yourxmlinlayoutfolder);
    }
}

If you have only one layout then no necessary to make setContentView in This method. simply

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

What is a PDB file?

I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.

Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace string. I included the PDB file in the executable folder and now all is fine.

What's the easiest way to call a function every 5 seconds in jQuery?

Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:

my_function(){};
setInterval(my_function,10000);

How to limit the maximum files chosen when using multiple file input

On change of the input track how many files are selected:

_x000D_
_x000D_
$("#image").on("change", function() {_x000D_
    if ($("#image")[0].files.length > 2) {_x000D_
        alert("You can select only 2 images");_x000D_
    } else {_x000D_
        $("#imageUploadForm").submit();_x000D_
    }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<strong>On change of the input track how many files are selected:</strong>_x000D_
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >
_x000D_
_x000D_
_x000D_

Java regex to extract text between tags

Try this:

Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);

For example:

String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
   Log.e("Regex"," Regex result: " + m.group())       
}

Output:

10 Ene

3.08%

Finding sum of elements in Swift array

This is the easiest/shortest method I can find.

Swift 3 and Swift 4:

let multiples = [...]
let sum = multiples.reduce(0, +)
print("Sum of Array is : ", sum)

Swift 2:

let multiples = [...]
sum = multiples.reduce(0, combine: +)

Some more info:

This uses Array's reduce method (documentation here), which allows you to "reduce a collection of elements down to a single value by recursively applying the provided closure". We give it 0 as the initial value, and then, essentially, the closure { $0 + $1 }. Of course, we can simplify that to a single plus sign, because that's how Swift rolls.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

Node.js project naming conventions for files & folders

There are no conventions. There are some logical structure.

The only one thing that I can say: Never use camelCase file and directory names. Why? It works but on Mac and Windows there are no different between someAction and some action. I met this problem, and not once. I require'd a file like this:

var isHidden = require('./lib/isHidden');

But sadly I created a file with full of lowercase: lib/ishidden.js. It worked for me on mac. It worked fine on mac of my co-worker. Tests run without errors. After deploy we got a huge error:

Error: Cannot find module './lib/isHidden'

Oh yeah. It's a linux box. So camelCase directory structure could be dangerous. It's enough for a colleague who is developing on Windows or Mac.

So use underscore (_) or dash (-) separator if you need.

T-SQL How to create tables dynamically in stored procedures?

You are using a table variable i.e. you should declare the table. This is not a temporary table.

You create a temp table like so:

CREATE TABLE #customer
(
     Name varchar(32) not null
)

You declare a table variable like so:

DECLARE @Customer TABLE
(
      Name varchar(32) not null
)

Notice that a temp table is declared using # and a table variable is declared using a @. Go read about the difference between table variables and temp tables.

UPDATE:

Based on your comment below you are actually trying to create tables in a stored procedure. For this you would need to use dynamic SQL. Basically dynamic SQL allows you to construct a SQL Statement in the form of a string and then execute it. This is the ONLY way you will be able to create a table in a stored procedure. I am going to show you how and then discuss why this is not generally a good idea.

Now for a simple example (I have not tested this code but it should give you a good indication of how to do it):

CREATE PROCEDURE sproc_BuildTable 
    @TableName NVARCHAR(128)
   ,@Column1Name NVARCHAR(32)
   ,@Column1DataType NVARCHAR(32)
   ,@Column1Nullable NVARCHAR(32)
AS

   DECLARE @SQLString NVARCHAR(MAX)
   SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY '

   EXEC (@SQLString)
   GO

This stored procedure can be executed like this:

sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'

There are some major problems with this type of stored procedure.

Its going to be difficult to cater for complex tables. Imagine the following table structure:

CREATE TABLE [dbo].[Customers] (
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerName] [nvarchar](64) NOT NULL,
    [CustomerSUrname] [nvarchar](64) NOT NULL,
    [CustomerDateOfBirth] [datetime] NOT NULL,
    [CustomerApprovedDiscount] [decimal](3, 2) NOT NULL,
    [CustomerActive] [bit] NOT NULL,
    CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED 
    (
        [CustomerID] ASC
    ) WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Customers] ADD CONSTRAINT [DF_Customers_CustomerApprovedDiscount] DEFAULT ((0.00)) FOR [CustomerApprovedDiscount]
GO 

This table is a little more complex than the first example, but not a lot. The stored procedure will be much, much more complex to deal with. So while this approach might work for small tables it is quickly going to be unmanageable.

Creating tables require planning. When you create tables they should be placed strategically on different filegroups. This is to ensure that you don't cause disk I/O contention. How will you address scalability if everything is created on the primary file group?

Could you clarify why you need tables to be created dynamically?

UPDATE 2:

Delayed update due to workload. I read your comment about needing to create a table for each shop and I think you should look at doing it like the example I am about to give you.

In this example I make the following assumptions:

  1. It's an e-commerce site that has many shops
  2. A shop can have many items (goods) to sell.
  3. A particular item (good) can be sold at many shops
  4. A shop will charge different prices for different items (goods)
  5. All prices are in $ (USD)

Let say this e-commerce site sells gaming consoles (i.e. Wii, PS3, XBOX360).

Looking at my assumptions I see a classical many-to-many relationship. A shop can sell many items (goods) and items (goods) can be sold at many shops. Let's break this down into tables.

First I would need a shop table to store all the information about the shop.

A simple shop table might look like this:

CREATE TABLE [dbo].[Shop](
    [ShopID] [int] IDENTITY(1,1) NOT NULL,
    [ShopName] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_Shop] PRIMARY KEY CLUSTERED 
    (
      [ShopID] ASC
    ) WITH (
              PAD_INDEX  = OFF
              , STATISTICS_NORECOMPUTE  = OFF
              , IGNORE_DUP_KEY = OFF
              , ALLOW_ROW_LOCKS  = ON
              , ALLOW_PAGE_LOCKS  = ON
    ) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

Let's insert three shops into the database to use during our example. The following code will insert three shops:

INSERT INTO Shop
SELECT 'American Games R US'
UNION
SELECT 'Europe Gaming Experience'
UNION
SELECT 'Asian Games Emporium'

If you execute a SELECT * FROM Shop you will probably see the following:

ShopID  ShopName
1           American Games R US
2           Asian Games Emporium
3           Europe Gaming Experience

Right, so now let's move onto the Items (goods) table. Since the items/goods are products of various companies I am going to call the table product. You can execute the following code to create a simple Product table.

CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [ProductDescription] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
 (
     [ProductID] ASC
 )WITH (PAD_INDEX  = OFF
        , STATISTICS_NORECOMPUTE  = OFF
        , IGNORE_DUP_KEY = OFF
        ,     ALLOW_ROW_LOCKS  = ON
         , ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

GO

Let's populate the products table with some products. Execute the following code to insert some products:

INSERT INTO Product
SELECT 'Wii'
UNION 
SELECT 'PS3'
UNION 
SELECT 'XBOX360'

If you execute SELECT * FROM Product you will probably see the following:

ProductID   ProductDescription
1           PS3
2           Wii
3           XBOX360

OK, at this point you have both product and shop information. So how do you bring them together? Well we know we can identify the shop by its ShopID primary key column and we know we can identify a product by its ProductID primary key column. Also, since each shop has a different price for each product we need to store the price the shop charges for the product.

So we have a table that maps the Shop to the product. We will call this table ShopProduct. A simple version of this table might look like this:

CREATE TABLE [dbo].[ShopProduct](
[ShopID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Price] [money] NOT NULL,
CONSTRAINT [PK_ShopProduct] PRIMARY KEY CLUSTERED 
 (
     [ShopID] ASC,
      [ProductID] ASC
 )WITH (PAD_INDEX  = OFF,
     STATISTICS_NORECOMPUTE  = OFF, 
     IGNORE_DUP_KEY = OFF, 
     ALLOW_ROW_LOCKS  = ON,
     ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

 GO

So let's assume the American Games R Us shop only sells American consoles, the Europe Gaming Experience sells all consoles and the Asian Games Emporium sells only Asian consoles. We would need to map the primary keys from the shop and product tables into the ShopProduct table.

Here is how we are going to do the mapping. In my example the American Games R Us has a ShopID value of 1 (this is the primary key value) and I can see that the XBOX360 has a value of 3 and the shop has listed the XBOX360 for $159.99

By executing the following code you would complete the mapping:

INSERT INTO ShopProduct VALUES(1,3,159.99)

Now we want to add all product to the Europe Gaming Experience shop. In this example we know that the Europe Gaming Experience shop has a ShopID of 3 and since it sells all consoles we will need to insert the ProductID 1, 2 and 3 into the mapping table. Let's assume the prices for the consoles (products) at the Europe Gaming Experience shop are as follows: 1- The PS3 sells for $259.99 , 2- The Wii sells for $159.99 , 3- The XBOX360 sells for $199.99.

To get this mapping done you would need to execute the following code:

INSERT INTO ShopProduct VALUES(3,2,159.99) --This will insert the WII console into the mapping table for the Europe Gaming Experience Shop with a price of 159.99
INSERT INTO ShopProduct VALUES(3,1,259.99) --This will insert the PS3 console into the mapping table for the Europe Gaming Experience Shop with a price of 259.99
INSERT INTO ShopProduct VALUES(3,3,199.99) --This will insert the XBOX360 console into the mapping table for the Europe Gaming Experience Shop with a price of 199.99

At this point you have mapped two shops and their products into the mapping table. OK, so now how do I bring this all together to show a user browsing the website? Let's say you want to show all the product for the European Gaming Experience to a user on a web page – you would need to execute the following query:

SELECT      Shop.*
        , ShopProduct.*
        , Product.*
FROM         Shop 
INNER JOIN  ShopProduct ON Shop.ShopID = ShopProduct.ShopID 
INNER JOIN  Product ON ShopProduct.ProductID = Product.ProductID
WHERE       Shop.ShopID=3

You will probably see the following results:

ShopID     ShopName                 ShopID  ProductID   Price   ProductID   ProductDescription
3          Europe Gaming Experience   3         1       259.99  1           PS3
3          Europe Gaming Experience   3         2       159.99  2           Wii
3          Europe Gaming Experience   3         3       199.99  3           XBOX360

Now for one last example, let's assume that your website has a feature which finds the cheapest price for a console. A user asks to find the cheapest prices for XBOX360.

You can execute the following query:

 SELECT     Shop.*
        , ShopProduct.*
        , Product.*
 FROM         Shop 
 INNER JOIN  ShopProduct ON Shop.ShopID = ShopProduct.ShopID 
 INNER JOIN  Product ON ShopProduct.ProductID = Product.ProductID
 WHERE      Product.ProductID =3  -- You can also use Product.ProductDescription = 'XBOX360'
 ORDER BY    Price ASC

This query will return a list of all shops which sells the XBOX360 with the cheapest shop first and so on.

You will notice that I have not added the Asian Games shop. As an exercise, add the Asian games shop to the mapping table with the following products: the Asian Games Emporium sells the Wii games console for $99.99 and the PS3 console for $159.99. If you work through this example you should now understand how to model a many-to-many relationship.

I hope this helps you in your travels with database design.

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

You're mixing up HTML with XHTML.

Usually a <!DOCTYPE> declaration is used to distinguish between versions of HTMLish languages (in this case, HTML or XHTML).

Different markup languages will behave differently. My favorite example is height:100%. Look at the following in a browser:

XHTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

... and compare it to the following: (note the conspicuous lack of a <!DOCTYPE> declaration)

HTML (quirks mode)

<html>
<head>
  <style type="text/css">
    table { height:100%;background:yellow; }
  </style>
</head>
<body>
  <table>
    <tbody>
      <tr><td>How tall is this?</td></tr>
    </tbody>
  </table>
</body>
</html>

You'll notice that the height of the table is drastically different, and the only difference between the 2 documents is the type of markup!

That's nice... now, what does <html xmlns="http://www.w3.org/1999/xhtml"> do?

That doesn't answer your question though. Technically, the xmlns attribute is used by the root element of an XHTML document: (according to Wikipedia)

The root element of an XHTML document must be html, and must contain an xmlns attribute to associate it with the XHTML namespace.

You see, it's important to understand that XHTML isn't HTML but XML - a very different creature. (ok, a kind of different creature) The xmlns attribute is just one of those things the document needs to be valid XML. Why? Because someone working on the standard said so ;) (you can read more about XML namespaces on Wikipedia but I'm omitting that info 'cause it's not actually relevant to your question!)

But then why is <html xmlns="http://www.w3.org/1999/xhtml"> fixing the CSS?

If structuring your document like so... (as you suggest in your comment)

<html xmlns="http://www.w3.org/1999/xhtml">
<!DOCTYPE html>
<html>
<head>
[...]

... is fixing your document, it leads me to believe that you don't know that much about CSS and HTML (no offense!) and that the truth is that without <html xmlns="http://www.w3.org/1999/xhtml"> it's behaving normally and with <html xmlns="http://www.w3.org/1999/xhtml"> it's not - and you just think it is, because you're used to writing invalid HTML and thus working in quirks mode.

The above example I provided is an example of that same problem; most people think height:100% should result in the height of the <table> being the whole window, and that the DOCTYPE is actually breaking their CSS... but that's not really the case; rather, they just don't understand that they need to add a html, body { height:100%; } CSS rule to achieve their desired effect.

Error handling in AngularJS http get then construct

Try this

function sendRequest(method, url, payload, done){

        var datatype = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: datatype,
                data: payload || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(res){
                done(null, res.data); // server response
            },
            function(res){
                responseHandler(res, done);
            }
        );

    }
    function responseHandler(res, done){
        switch(res.status){
            default: done(res.status + ": " + res.statusText);
        }
    }

JavaScript loop through json array?

A bit late but i hope i may help others :D

your json needs to look like something Niklas already said. And then here you go:

for(var key in currentObject){
        if(currentObject.hasOwnProperty(key)) {
          console.info(key + ': ' + currentObject[key]);
        }
   }

if you have an Multidimensional array, this is your code:

for (var i = 0; i < multiDimensionalArray.length; i++) {
    var currentObject = multiDimensionalArray[i]
    for(var key in currentObject){
            if(currentObject.hasOwnProperty(key)) {
              console.info(key + ': ' + currentObject[key]);
            }
       }
}

How to Logout of an Application Where I Used OAuth2 To Login With Google?

I hope we can achieve this by storing the token in session while logging in and access the token when he clicked on logout.

    String _accessToken=(String)session.getAttribute("ACCESS_TOKEN");
    if(_accessToken!=null)
    {
        StringBuffer path=httpRequest.getRequestURL();
        reDirectPage="https://www.google.com/accounts/Logout?
        continue=https://appengine.google.com/_ah/logout?
        continue="+path;
    }
    response.sendRedirect(reDirectPage);

Convert from lowercase to uppercase all values in all character variables in dataframe

Alternatively, if you just want to convert one particular row to uppercase, use the code below:

df[[1]] <- toupper(df[[1]])

Only variable references should be returned by reference - Codeigniter

this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015

How to handle change text of span

Span does not have 'change' event by default. But you can add this event manually.

Listen to the change event of span.

$("#span1").on('change',function(){
     //Do calculation and change value of other span2,span3 here
     $("#span2").text('calculated value');
});

And wherever you change the text in span1. Trigger the change event manually.

$("#span1").text('test').trigger('change'); 

Javascript dynamic array of strings

As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.

var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9,10,11


var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray);  // Gives 1,2,3,4,5,6,7,8,9

You can even add elements like

var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30

you can even change the values

myArray[2] = 40

Printing Order

If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.

Page Submission

If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.

How to change the style of a DatePicker in android?

(I'm using React Native; targetSdkVersion 22). I'm trying to change the look of a calendar date picker dialog. The accepted answer didn't work for me, but this did. Hope this snippet helps some of you.

<style name="CalendarDatePickerDialog"  parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">#6bf442</item>
    <item name="android:textColorPrimary">#6bf442</item>
</style>

Webpack not excluding node_modules

This worked for me:

exclude: [/bower_components/, /node_modules/]

module.loaders

A array of automatically applied loaders.

Each item can have these properties:

test: A condition that must be met

exclude: A condition that must not be met

include: A condition that must be met

loader: A string of "!" separated loaders

loaders: A array of loaders as string

A condition can be a RegExp, an absolute path start, or an array of one of these combined with "and".

See http://webpack.github.io/docs/configuration.html#module-loaders

'mvn' is not recognized as an internal or external command, operable program or batch file

I prefer adding path to ~/.bashrc.

vim ~/.bashrc, then add these lines:

export M2_HOME=/usr/local/apache-maven-your_maven_path&version
export M2=$M2_HOME/bin

How does one set up the Visual Studio Code compiler/debugger to GCC?

For Windows:

  1. Install MinGW or Dev C++
  2. Open Environment Variables
  3. In System Variable select Path -> Edit -> New
  4. Copy this C:\Program Files (x86)\Dev-Cpp\MinGW64\bin to the New window. (If you have MinGW installed copy its /bin path).
  5. To check if you have added it successfully: Open CMD -> Type "gcc" and it should return: gcc: fatal error: no input files compilation terminated.
  6. Install C/C++ for Visual Studio Code && C/C++ Compile Run || Code Runner
  7. If you installed only C/C++ Compile Run extension you can compile your program using F6/F7
  8. If you installed the second extension you can compile your program using the button in the top bar.

Screenshot: Hello World compiled in VS Code

"Items collection must be empty before using ItemsSource."

I had this same error for a while in a slightly different scenario. I had

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGridTextColumn 
        Header="Account Name" 
        Binding="{Binding Path=AccountName}" />
</wpftoolkit:DataGrid>

which I fixed to be

<wpftoolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding Path=Accounts}" >
    <wpftoolkit:DataGrid.Columns>
        <wpftoolkit:DataGridTextColumn 
            Header="Account Name" 
            Binding="{Binding Path=AccountName}" />
    </wpftoolkit:DataGrid.Columns>
</wpftoolkit:DataGrid>

Underline text in UIlabel

An enhanced version of the code of Kovpas (color and line size)

@implementation UILabelUnderlined

- (void)drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    const CGFloat* colors = CGColorGetComponents(self.textColor.CGColor);

    CGContextSetRGBStrokeColor(ctx, colors[0], colors[1], colors[2], 1.0); // RGBA

    CGContextSetLineWidth(ctx, 1.0f);

    CGSize tmpSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(200, 9999)];

    CGContextMoveToPoint(ctx, 0, self.bounds.size.height - 1);
    CGContextAddLineToPoint(ctx, tmpSize.width, self.bounds.size.height - 1);

    CGContextStrokePath(ctx);

    [super drawRect:rect];  
}

@end

Matplotlib scatter plot with different text at each data point

Python 3.6+:

coordinates = [('a',1,2), ('b',3,4), ('c',5,6)]
for x in coordinates: plt.annotate(x[0], (x[1], x[2]))

Using floats with sprintf() in embedded C

use the %f modifier:

sprintf (str, "adc_read = %f\n", adc_read);

For instance:

#include <stdio.h>

int main (void) 
{
    float x = 2.5;
    char y[200];

    sprintf(y, "x = %f\n", x);
    printf(y);
    return 0;
}

Yields this:

x = 2.500000

What is the difference between float and double?

Huge difference.

As the name implies, a double has 2x the precision of float[1]. In general a double has 15 decimal digits of precision, while float has 7.

Here's how the number of digits are calculated:

double has 52 mantissa bits + 1 hidden bit: log(253)÷log(10) = 15.95 digits

float has 23 mantissa bits + 1 hidden bit: log(224)÷log(10) = 7.22 digits

This precision loss could lead to greater truncation errors being accumulated when repeated calculations are done, e.g.

float a = 1.f / 81;
float b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.7g\n", b); // prints 9.000023

while

double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i)
    b += a;
printf("%.15g\n", b); // prints 8.99999999999996

Also, the maximum value of float is about 3e38, but double is about 1.7e308, so using float can hit "infinity" (i.e. a special floating-point number) much more easily than double for something simple, e.g. computing the factorial of 60.

During testing, maybe a few test cases contain these huge numbers, which may cause your programs to fail if you use floats.


Of course, sometimes, even double isn't accurate enough, hence we sometimes have long double[1] (the above example gives 9.000000000000000066 on Mac), but all floating point types suffer from round-off errors, so if precision is very important (e.g. money processing) you should use int or a fraction class.


Furthermore, don't use += to sum lots of floating point numbers, as the errors accumulate quickly. If you're using Python, use fsum. Otherwise, try to implement the Kahan summation algorithm.


[1]: The C and C++ standards do not specify the representation of float, double and long double. It is possible that all three are implemented as IEEE double-precision. Nevertheless, for most architectures (gcc, MSVC; x86, x64, ARM) float is indeed a IEEE single-precision floating point number (binary32), and double is a IEEE double-precision floating point number (binary64).

Cannot call getSupportFragmentManager() from activity

Simply Use

 FragmentManager fm = getActivity().getSupportFragmentManager();

Remember always when accessing fragment inflating in MainLayout use Casting or getActivity().

Error - Unable to access the IIS metabase

Create a new WebSite, after error go to folder where you created a project, in a txt app open the .csproj file, find this tag "<UseIIS>" and change "false" to "true", in lines bellow find the tag "<IISUrl>" then put the iis url(find url in iis), your tags must be like this:

<WebProjectProperties>
      <UseIIS>True</UseIIS>
      <AutoAssignPort>True</AutoAssignPort>
      <DevelopmentServerPort>0</DevelopmentServerPort>
      <DevelopmentServerVPath>/</DevelopmentServerVPath>
      <IISUrl>http://localhost/yourIISAppAlias
      </IISUrl>
      <NTLMAuthentication>False</NTLMAuthentication>
      <UseCustomServer>False</UseCustomServer>
      <CustomServerUrl>
      </CustomServerUrl>
      <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
    </WebProjectProperties>

Extract column values of Dataframe as List in Apache Spark

List<String> whatever_list = df.toJavaRDD().map(new Function<Row, String>() {
    public String call(Row row) {
        return row.getAs("column_name").toString();
    }
}).collect();

logger.info(String.format("list is %s",whatever_list)); //verification

Since no one has given any solution in java(Real Programming Language) Can thank me later

getDate with Jquery Datepicker

I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle

$(document).ready(function(){
    // Datepicker
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();                 
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;             
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
            $('#page_output').html(str_output);
        }
    });
});

Get Base64 encode file-data from Input Form

I used FileReader to display image on click of the file upload button not using any Ajax requests. Following is the code hope it might help some one.

$(document).ready(function($) {
    $.extend( true, jQuery.fn, {        
        imagePreview: function( options ){          
            var defaults = {};
            if( options ){
                $.extend( true, defaults, options );
            }
            $.each( this, function(){
                var $this = $( this );              
                $this.bind( 'change', function( evt ){

                    var files = evt.target.files; // FileList object
                    // Loop through the FileList and render image files as thumbnails.
                    for (var i = 0, f; f = files[i]; i++) {
                        // Only process image files.
                        if (!f.type.match('image.*')) {
                        continue;
                        }
                        var reader = new FileReader();
                        // Closure to capture the file information.
                        reader.onload = (function(theFile) {
                            return function(e) {
                                // Render thumbnail.
                                    $('#imageURL').attr('src',e.target.result);                         
                            };
                        })(f);
                        // Read in the image file as a data URL.
                        reader.readAsDataURL(f);
                    }

                });
            });
        }   
    });
    $( '#fileinput' ).imagePreview();
});

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

The ENABLEDELAYEDEXPANSION part is REQUIRED in certain programs that use delayed expansion, that is, that takes the value of variables that were modified inside IF or FOR commands by enclosing their names in exclamation-marks.

If you enable this expansion in a script that does not require it, the script behaves different only if it contains names enclosed in exclamation-marks !LIKE! !THESE!. Usually the name is just erased, but if a variable with the same name exist by chance, then the result is unpredictable and depends on the value of such variable and the place where it appears.

The SETLOCAL part is REQUIRED in just a few specialized (recursive) programs, but is commonly used when you want to be sure to not modify any existent variable with the same name by chance or if you want to automatically delete all the variables used in your program. However, because there is not a separate command to enable the delayed expansion, programs that require this must also include the SETLOCAL part.

jQuery access input hidden value

There is nothing special about <input type="hidden">:

$('input[type="hidden"]').val()

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

List last updated on December 1, 2020:

As of November 30, 2020, AWS now has EC2 Mac instances:

We previously used and had good experiences with:

Here are some other sites that I am aware of:

When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).

In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.

How to uncommit my last commit in Git

git reset --soft HEAD^ Will keep the modified changes in your working tree.

git reset --hard HEAD^ WILL THROW AWAY THE CHANGES YOU MADE !!!

Full width image with fixed height

<div id="container">
    <img style="width: 100%; height: 40%;" id="image" src="...">
</div>

I hope this will serve your purpose.

How do I refresh the page in ASP.NET? (Let it reload itself by code)

Use javascript's location.reload() method.

<script type="text/javascript">
  function reloadPage()
  {
    window.location.reload()
  }
</script>

How to use enums as flags in C++?

The C++ standard explicitly talks about this, see section "17.5.2.1.3 Bitmask types":

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf

Given this "template" you get:

enum AnimalFlags : unsigned int
{
    HasClaws = 1,
    CanFly = 2,
    EatsFish = 4,
    Endangered = 8
};

constexpr AnimalFlags operator|(AnimalFlags X, AnimalFlags Y) {
    return static_cast<AnimalFlags>(
        static_cast<unsigned int>(X) | static_cast<unsigned int>(Y));
}

AnimalFlags& operator|=(AnimalFlags& X, AnimalFlags Y) {
    X = X | Y; return X;
}

And similar for the other operators. Also note the "constexpr", it is needed if you want the compiler to be able to execute the operators compile time.

If you are using C++/CLI and want to able assign to enum members of ref classes you need to use tracking references instead:

AnimalFlags% operator|=(AnimalFlags% X, AnimalFlags Y) {
    X = X | Y; return X;
}

NOTE: This sample is not complete, see section "17.5.2.1.3 Bitmask types" for a complete set of operators.

How to lock orientation of one view controller to portrait mode only in Swift

Best Solution for lock and change orientation on portrait and landscape:

Watch this video on YouTube:

https://m.youtube.com/watch?v=4vRrHdBowyo

This tutorial is best and simple.

or use below code:

See this picture

// 1- in second viewcontroller we set landscapeleft and in first viewcontroller we set portrat:

// 2- if you use NavigationController, you should add extension

import UIKit

class SecondViewController: UIViewController {


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
    }

    override open var shouldAutorotate: Bool {
        return false
    }

    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeLeft
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeLeft
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
    }

//write The rest of your code in here


}

//if you use NavigationController, you should add this extension

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .allButUpsideDown
    
    }
}

Convert a string to an enum in C#

Not sure when this was added but on the Enum class there is now a

Parse<TEnum>(stringValue)

Used like so with example in question:

var MyStatus = Enum.Parse<StatusEnum >("Active")

or ignoring casing by:

var MyStatus = Enum.Parse<StatusEnum >("active", true)

Here is the decompiled methods this uses:

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct
    {
      return Enum.Parse<TEnum>(value, false);
    }

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct
    {
      TEnum result;
      Enum.TryParse<TEnum>(value, ignoreCase, true, out result);
      return result;
    }

Git merge two local branches

For merging first branch to second one:

on first branch: git merge secondBranch

on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch

What's the "average" requests per second for a production web application?

Not sure anyone is still interested, but this information was posted about Twitter (and here too):

The Stats

  • Over 350,000 users. The actual numbers are as always, very super super top secret.
  • 600 requests per second.
  • Average 200-300 connections per second. Spiking to 800 connections per second.
  • MySQL handled 2,400 requests per second.
  • 180 Rails instances. Uses Mongrel as the "web" server.
  • 1 MySQL Server (one big 8 core box) and 1 slave. Slave is read only for statistics and reporting.
  • 30+ processes for handling odd jobs.
  • 8 Sun X4100s.
  • Process a request in 200 milliseconds in Rails.
  • Average time spent in the database is 50-100 milliseconds.
  • Over 16 GB of memcached.

Find TODO tags in Eclipse

Is there an easy way to view all methods which contain this comment? Some sort of menu option?

Yes, choose one of the following:

  1. Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.

  2. As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.

  3. If you just want the // TODO Auto-generated method stub messages (rather than all // TODO messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)

Context.startForegroundService() did not then call Service.startForeground()

From Google's docs on Android 8.0 behavior changes:

The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.

Solution: Call startForeground() in onCreate() for the Service which you use Context.startForegroundService()

See also: Background Execution Limits for Android 8.0 (Oreo)

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

JSON - Iterate through JSONArray

for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

You need to check for the type:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]

In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.

Find duplicate entries in a column

Try this query.. It uses the Analytic function SUM:

SELECT * FROM
(  
 SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
 FROM table1 a 
 WHERE s_ind ='Y'   
)
WHERE cnt > 2

Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1

How to get the selected value from drop down list in jsp?

I know that this is an old question, but as I was googling it was the first link in a results. So here is the jsp solution:

<form action="some.jsp">
  <select name="item">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
  <input type="submit" value="Submit">
</form>

in some.jsp

request.getParameter("item");

this line will return the selected option (from the example it is: 1, 2 or 3)

Remove everything after a certain character

You can also use the split() function. This seems to be the easiest one that comes to my mind :).

url.split('?')[0]

jsFiddle Demo

One advantage is this method will work even if there is no ? in the string - it will return the whole string.

Relative paths in Python

In the file that has the script, you want to do something like this:

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py
import os
print os.getcwd()
print __file__

#in the interactive interpreter
>>> import foo
/Users/jason
foo.py

#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'

However, this raises an exception on my Windows machine.

Find by key deep in a nested array

If you're already using Underscore, use _.find()

_.find(yourList, function (item) {
    return item.id === 1;
});

Use of for_each on map elements

Just an example:

template <class key, class value>
class insertIntoVec
{
public:
    insertIntoVec(std::vector<value>& vec_in):m_vec(vec_in)
    {}

    void operator () (const std::pair<key, value>& rhs)  
    {   
        m_vec.push_back(rhs.second);
    }

private:
    std::vector<value>& m_vec;
};

int main()
{
std::map<int, std::string> aMap;
aMap[1] = "test1";
aMap[2] = "test2";
aMap[3] = "test3";
aMap[4] = "test4";

std::vector<std::string> aVec;

aVec.reserve(aMap.size());
std::for_each(aMap.begin(), aMap.end(),
          insertIntoVec<int, std::string>(aVec) 
    );

}

How to retrieve images from MySQL database and display in an html tag

add $row = mysql_fetch_object($result); after your mysql_query();

your html <img src="<?php echo $row->dvdimage; ?>" width="175" height="200" />

How to get an object's properties in JavaScript / jQuery?

Scanning object for first intance of a determinated prop:

var obj = {a:'Saludos',
            b:{b_1:{b_1_1:'Como estas?',b_1_2:'Un gusto conocerte'}},
           d:'Hasta luego'
            }
function scan (element,list){
    var res;
    if (typeof(list) != 'undefined'){
        if (typeof(list) == 'object'){
            for(key in list){
               if (typeof(res) == 'undefined'){
                res = (key == element)?list[key]:scan(element,list[key]);
               }
            });
        }
    }
    return res;
}
console.log(scan('a',obj));

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Dynamically load JS inside JS

Here is a little lib to load javascript and CSS files dynamically:

https://github.com/todotresde/javascript-loader

I guess is usefull to load css and js files in order and dynamically.

Support to extend to load any lib you want, and not just the main file, you can use it to load custom files.

I.E.:

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="scripts/javascript-loader.js" type="text/javascript" charset="utf-8" ></script>    
    <script type="text/javascript">
        $(function() {

            registerLib("threejs", test);

            function test(){
                console.log(THREE);
            }

            registerLib("tinymce", draw);

            function draw(){
                tinymce.init({selector:'textarea'});
            }

        }); 
    </script>
</head>
<body>
    <textarea>Your content here.</textarea>
</body>

Help with packages in java - import does not work

Okay, just to clarify things that have already been posted.

You should have the directory com, containing the directory company, containing the directory example, containing the file MyClass.java.

From the folder containing com, run:

$ javac com\company\example\MyClass.java

Then:

$ java com.company.example.MyClass
Hello from MyClass!

These must both be done from the root of the source tree. Otherwise, javac and java won't be able to find any other packages (in fact, java wouldn't even be able to run MyClass).

A short example

I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:

package testpackage;

import testpackage2.MyClass;

public class TestPackageClass {
    public static void main(String[] args) {
        System.out.println("Hello from testpackage.TestPackageClass!");
        System.out.println("Now accessing " + MyClass.NAME);
    }
}

Inside testpackage2, I created MyClass.java containing the following code:

package testpackage2;
public class MyClass {
    public static String NAME = "testpackage2.MyClass";
}

From the directory containing the two new folders, I ran:

C:\examples>javac testpackage\*.java

C:\examples>javac testpackage2\*.java

Then:

C:\examples>java testpackage.TestPackageClass
Hello from testpackage.TestPackageClass!
Now accessing testpackage2.MyClass

Does that make things any clearer?

Convert number to month name in PHP

Use:

$name = jdmonthname(gregoriantojd($monthNumber, 1, 1), CAL_MONTH_GREGORIAN_LONG);

Detecting endianness programmatically in a C++ program

The C++ way has been to use boost, where preprocessor checks and casts are compartmentalized away inside very thoroughly-tested libraries.

The Predef Library (boost/predef.h) recognizes four different kinds of endianness.

The Endian Library was planned to be submitted to the C++ standard, and supports a wide variety of operations on endian-sensitive data.

As stated in answers above, Endianness will be a part of c++20.

How to get screen width without (minus) scrollbar?

Here are some examples which assume $element is a jQuery element:

// Element width including overflow (scrollbar)
$element[0].offsetWidth; // 1280 in your case

// Element width excluding overflow (scrollbar)
$element[0].clientWidth; // 1280 - scrollbarWidth

// Scrollbar width
$element[0].offsetWidth - $element[0].clientWidth; // 0 if no scrollbar

Convert ArrayList<String> to String[] array

An alternative in Java 8:

String[] strings = list.stream().toArray(String[]::new);

COALESCE Function in TSQL

I'm not sure why you think the documentation is vague.

It simply goes through all the parameters one by one, and returns the first that is NOT NULL.

COALESCE(NULL, NULL, NULL, 1, 2, 3)
=> 1


COALESCE(1, 2, 3, 4, 5, NULL)
=> 1


COALESCE(NULL, NULL, NULL, 3, 2, NULL)
=> 3


COALESCE(6, 5, 4, 3, 2, NULL)
=> 6


COALESCE(NULL, NULL, NULL, NULL, NULL, NULL)
=> NULL

It accepts pretty much any number of parameters, but they should be the same data-type. (If they're not the same data-type, they get implicitly cast to an appropriate data-type using data-type order of precedence.)

It's like ISNULL() but for multiple parameters, rather than just two.

It's also ANSI-SQL, where-as ISNULL() isn't.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

After upgrading from 4.6.1 framework to 4.7.2 we started getting this error:

"The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'." and ultimately the solution was to add the "netstandard" assembly reference mentioned above:

<compilation debug="true" targetFramework="4.7.1" >
    <assemblies>
      <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
            PublicKeyToken=cc7b13ffcd2ddd51"/>
    </assemblies>
  </compilation>

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I think there is MID() and maybe LEFT() and RIGHT() in Access.

How to create roles in ASP.NET Core and assign them to users?

Update in 2020. Here is another way if you prefer.

 IdentityResult res = new IdentityResult();
 var _role = new IdentityRole();
 _role.Name = role.RoleName;
  res = await _roleManager.CreateAsync(_role);
  if (!res.Succeeded)
  {
        foreach (IdentityError er in res.Errors)
        {
             ModelState.AddModelError(string.Empty, er.Description);
         }
         ViewBag.UserMessage = "Error Adding Role";
         return View();
  }
  else
  {
        ViewBag.UserMessage = "Role Added";
        return View();
   }

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).

enter image description here

I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.

I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.

If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.

Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.

Update 2: Same solution seems to be needed on iOS 13 beta builds as well.

How to evaluate a boolean variable in an if block in bash?

bash doesn't know boolean variables, nor does test (which is what gets called when you use [).

A solution would be:

if $myVar ; then ... ; fi

because true and false are commands that return 0 or 1 respectively which is what if expects.

Note that the values are "swapped". The command after if must return 0 on success while 0 means "false" in most programming languages.

SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /

How to create and download a csv file from php script?

Use the following,

echo "<script type='text/javascript'> window.location.href = '$file_name'; </script>";

Where do I put my php files to have Xampp parse them?

The default location to put all the web projects in ubuntu with LAMPP is :

 /var/www/

You may make symbolic link to public_html directory from this directory.Refered. Hope this is helpful.

Is there a WebSocket client implemented for Python?

Autobahn has a good websocket client implementation for Python as well as some good examples. I tested the following with a Tornado WebSocket server and it worked.

from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS


class EchoClientProtocol(WebSocketClientProtocol):

   def sendHello(self):
      self.sendMessage("Hello, world!")

   def onOpen(self):
      self.sendHello()

   def onMessage(self, msg, binary):
      print "Got echo: " + msg
      reactor.callLater(1, self.sendHello)


if __name__ == '__main__':

   factory = WebSocketClientFactory("ws://localhost:9000")
   factory.protocol = EchoClientProtocol
   connectWS(factory)
   reactor.run()

Looping through list items with jquery

You can use each for this:

$('#productList li').each(function(i, li) {
  var $product = $(li);  
  // your code goes here
});

That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?

Regex Until But Not Including

A lookahead regex syntax can help you to achieve your goal. Thus a regex for your example is

.*?quick.*?(?=z)

And it's important to notice the .*? lazy matching before the (?=z) lookahead: the expression matches a substring until a first occurrence of the z letter.

Here is C# code sample:

const string text = "The quick red fox jumped over the lazy brown dogz";

string lazy = new Regex(".*?quick.*?(?=z)").Match(text).Value;
Console.WriteLine(lazy); // The quick red fox jumped over the la

string greedy = new Regex(".*?quick.*(?=z)").Match(text).Value;
Console.WriteLine(greedy); // The quick red fox jumped over the lazy brown dog

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I really have the same problem, finally, i solved it.

its likey not the Swift Mail's problem. It's Yaml parser's problem. if your password only the digits, the password senmd to swift finally not the same one.

swiftmailer:
    transport:  smtp
    encryption: ssl
    auth_mode:  login
    host:       smtp.gmail.com
    username:   your_username
    password:   61548921

you need fix it with double quotes password: "61548921"

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

Two div blocks on same line

What I would first is make the following CSS code:

#bloc1 {
   float: left
}

This will make #bloc2 be inline with #bloc1.

To make it central, I would add #bloc1 and #bloc2 in a separate div. For example:

<style type="text/css">
    #wrapper { margin: 0 auto; }
</style>
<div id="wrapper">
    <div id="bloc1"> ... </div>
    <div id="bloc2"> ... </div>
</div>

Are table names in MySQL case sensitive?

It depends upon lower_case_table_names system variable:

show variables where Variable_name='lower_case_table_names'

There are three possible values for this:

  • 0 - lettercase specified in the CREATE TABLE or CREATE DATABASE statement. Name comparisons are case sensitive.
  • 1 - Table names are stored in lowercase on disk and name comparisons are not case sensitive.
  • 2 - lettercase specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup. Name comparisons are not case sensitive.

Documentation

com.android.build.transform.api.TransformException

I changed a couple of pngs and the build number in the gradle and now I get this. No amount of cleaning and restarting helped. Disabling Instant Run fixed it for me. YMMV

MIN and MAX in C

The maximum of two integers a and b is (int)(0.5((a+b)+abs(a-b))). This may also work with (double) and fabs(a-b) for doubles (similar for floats)

How can I add new item to the String array?

From arrays

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

enter image description here

So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.

String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...

So if your requirement is to add many objects, it's recommended that you use Lists like:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp"); 

How to send a POST request using volley with string body?

I created a function for a Volley Request. You just need to pass the arguments :

public void callvolly(final String username, final String password){
    RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
    String url = "http://your_url.com/abc.php"; // <----enter your post url here
    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //This code is executed if the server responds, whether or not the response contains data.
            //The String 'response' contains the server's response.
        }
    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
        @Override
        public void onErrorResponse(VolleyError error) {
            //This code is executed if there is an error.
        }
    }) {
        protected Map<String, String> getParams() {
            Map<String, String> MyData = new HashMap<String, String>();
            MyData.put("username", username);             
            MyData.put("password", password);                
            return MyData;
        }
    };


    MyRequestQueue.add(MyStringRequest);
}

Check if inputs form are empty jQuery

I'd suggest to add an class='denominationcomune' to all elements that you want to check and then use the following:

function are_elements_emtpy(class_name)
{
  return ($('.' + class_name).filter(function() { return $(this).val() == ''; }).length == 0)
}

Hide console window from Process.Start C#

I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:

Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process

less than 10 add 0 to number

$('#detect').html( toGeo(apX, screenX)  + latT +', '+ toGeo(apY, screenY) + lonT  );

function toGeo(d, max) {
   var c = '';

   var r = d/max * 180;
   var deg = Math.floor(r);
   if(deg < 10) deg = '0' + deg;
   c += deg + "° ";

   r = (r - deg) * 60;
   var min = Math.floor(r);
   if(min < 10) min = '0' + min;
   c += min + "' ";

   r = (r - min) * 60;
   var sec = Math.floor(r);
   if(sec < 10) sec = '0' + sec;
   c += sec + """;

   return c;
}

How do I get the current date and current time only respectively in Django?

Another way to get datetime UTC with milliseconds.

from datetime import datetime

datetime.utcnow().isoformat(sep='T', timespec='milliseconds') + 'Z'

2020-10-29T14:46:37.655Z

How to check existence of user-define table type in SQL Server 2008?

You can use also system table_types view

IF EXISTS (SELECT *
           FROM   [sys].[table_types]
           WHERE  user_type_id = Type_id(N'[dbo].[UdTableType]'))
  BEGIN
      PRINT 'EXISTS'
  END 

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

Bootstrap4 adding scrollbar to div

_x000D_
_x000D_
.Scroll {
  height:600px;
  overflow-y: scroll;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
</script>
</head>
<body>

<h1>Smooth Scroll</h1>

<div class="Scroll">
  <div class="main" id="section1">
    <h2>Section 1</h2>
    <p>Click on the link to see the "smooth" scrolling effect.</p>
    <p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
  </div>
  <div class="main" id="section2">
    <h2>Section 2</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section3">
    <h2>Section 3</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section4">
    <h2>Section 4</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>

  <div class="main" id="section5">
    <h2>Section 5</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
  <div class="main" id="section6">
    <h2>Section 6</h2>
    <p>Knowing how to write a paragraph is incredibly important. It’s a basic aspect of writing, and it is something that everyone should know how to do. There is a specific structure that you have to follow when you’re writing a paragraph. This structure helps make it easier for the reader to understand what is going on. Through writing good paragraphs, a person can communicate a lot better through their writing.</p>
  </div>
  <div class="main" id="section7">
    <h2>Section 7</h2>
    <a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
  </div>
</div>
</body>
</html>
_x000D_
_x000D_
_x000D_

Find Locked Table in SQL Server

sp_lock

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

SELECT object_name(16003073)

EDIT :

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

add title attribute from css

Can do, with jQuery:

$(document).ready(function() {
    $('.mandatory').each(function() {
        $(this).attr('title', $(this).attr('class'));
    });
});

Numeric for loop in Django templates

This method supports all the functionality of the standard range([start,] stop[, step]) function

<app>/templatetags/range.py

from django import template

register = template.Library()


@register.filter(name='range')
def _range(_min, args=None):
    _max, _step = None, None
    if args:
        if not isinstance(args, int):
            _max, _step = map(int, args.split(','))
        else:
            _max = args
    args = filter(None, (_min, _max, _step))
    return range(*args)

Usage:

{% load range %}

<p>stop 5
{% for value in 5|range %}
{{ value }}
{% endfor %}
</p>

<p>start 5 stop 10
{% for value in 5|range:10 %}
{{ value }}
{% endfor %}
</p>

<p>start 5 stop 10 step 2
{% for value in 5|range:"10,2" %}
{{ value }}
{% endfor %}
</p>

Output

<p>stop 5
0 1 2 3 4
</p>

<p>start 5 stop 10
5 6 7 8 9
</p>

<p>start 5 stop 10 step 2
5 7 9
</p>

How do I fire an event when a iframe has finished loading in jQuery?

I had to show a loader while pdf in iFrame is loading so what i come up with:

    loader({href:'loader.gif', onComplete: function(){
            $('#pd').html('<iframe onLoad="loader.close();" src="pdf" width="720px" height="600px" >Please wait... your report is loading..</iframe>');
    }
    });

I'm showing a loader. Once I'm sure that customer can see my loader, i'm calling onCompllet loaders method that loads an iframe. Iframe has an "onLoad" event. Once PDF is loaded it triggers onloat event where i'm hiding the loader :)

The important part:

iFrame has "onLoad" event where you can do what you need (hide loaders etc.)

Print a file's last modified date in Bash

Adding to @StevePenny answer, you might want to cut the not-so-human-readable part:

stat -c%y Localizable.strings | cut -d'.' -f1

How to enable CORS in flask

OK, I don't think the official snippet mentioned by galuszkak should be used everywhere, we should concern the case that some bug may be triggered during the handler such as hello_world function. Whether the response is correct or uncorrect, the Access-Control-Allow-Origin header is what we should concern. So, thing is very simple, just like bellow:

@blueprint.after_request # blueprint can also be app~~
def after_request(response):
    header = response.headers
    header['Access-Control-Allow-Origin'] = '*'
    return response

That is all~~

How do I rename a file using VBScript?

From what I understand, your context is to download from ALM. In this case, ALM saves the files under: C:/Users/user/AppData/Local/Temp/TD_80/ALM_VERSION/random_string/Attach/artefact_type/ID

where :

ALM_VERSION is the version of your alm installation, e.g 12.53.2.0_952

artefact_type is the type of the artefact, e.g : REQ

ID is the ID of the artefact

Herebelow a code sample which connects to an instance of ALM, domain 'DEFAUT', project 'MY_PROJECT', gets all the attachments from a REQ with id 6 and saves them in c:/tmp. It's ruby code, but it's easy to transcribe to VBSctript

require 'win32ole'
require 'fileutils'

# login to ALM and domain/project 
alm_server = ENV['CURRRENT_ALM_SERVER']
tdc = WIN32OLE.new('TDApiOle80.TDConnection')
tdc.InitConnectionEx(alm_server)
username, password = ENV['ALM_CREDENTIALS'].split(':')
tdc.Login(username, password)
tdc.Connect('DEFAULT', 'MY_PROJECT')

# get a handle for the Requirements 
reqFact = tdc.ReqFactory

# get Requirement with ID=6
req = reqFact.item(6)

# get a handle for the attachment of REQ 
att = req.Attachments

# get a handle for the list of attachements
attList = att.NewList("")

thePath= 'c:/tmp'

# for each attachment:
attList.each do |el|
  clientPath = nil

  # download the attachment to its default location
  el.Load true, clientPath

  baseName = File.basename(el.FileName)
  dirName = File.dirname(el.FileName)
  puts "file downloaded as : #{baseName}\n in Folder #{dirName}"  
  FileUtils.mkdir_p thePath
  puts "now moving #{baseName} to #{thePath}"  
  FileUtils.mv el.FileName, thePath
end

The output:

=> file downloaded as : REQ_6_20191112_143346.png

=> in Folder C:\Users\user\AppData\Local\Temp\TD_80\12.53.2.0_952\e68ab622\Attach\REQ\6

=> now moving REQ_6_20191112_143346.png to c:/tmp

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

GitHub Error Message - Permission denied (publickey)

I know about this problem. After add ssh key, add you ssh key to ssh agent too (from official docs)

ssh-agent -s
ssh-add ~/.ssh/id_rsa

After it all work fine, git can view proper key, before couldn't.

How to change the name of an iOS app?

Target>Build Setting>Product name

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

If this is a Magento related problem, you should turn off automatic re-indexing as this could be causing the socket to timeout (or expire). You can turn it back on once the script has finished its tasks. Increasing the default socket timeout in php.ini is also a good idea.

javascript regex - look behind alternative?

Let's suppose you want to find all int not preceded by unsigned:

With support for negative look-behind:

(?<!unsigned )int

Without support for negative look-behind:

((?!unsigned ).{9}|^.{0,8})int

Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).

So the regex in question:

(?<!filename)\.js$

would translate to:

((?!filename).{8}|^.{0,7})\.js$

You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

TimeSpan to DateTime conversion

You need a reference date for this to be useful.

An example from http://msdn.microsoft.com/en-us/library/system.datetime.add.aspx

// Calculate what day of the week is 36 days from this instant.  
System.DateTime today = System.DateTime.Now;  
System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);  
System.DateTime answer = today.Add(duration);  
System.Console.WriteLine("{0:dddd}", answer);  

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

C++ vector of char array

You cannot store arrays in vectors (or in any other standard library container). The things that standard library containers store must be copyable and assignable, and arrays are neither of these.

If you really need to put an array in a vector (and you probably don't - using a vector of vectors or a vector of strings is more likely what you need), then you can wrap the array in a struct:

struct S {
  char a[10];
};

and then create a vector of structs:

vector <S> v;
S s;
s.a[0] = 'x';
v.push_back( s );

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Maybe your project has not been as android project by android studio, please make sure that plugin 'android support' has been enabled(Android Studio Preferences -> Plugins -> Select Android Support)

Bash script to run php script

You just need to set :

/usr/bin/php path_to_your_php_file

in your crontab.

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

Laravel 5 route not defined, while it is?

The route() method, which is called when you do ['route' => 'someroute'] in a form opening, wants what's called a named route. You give a route a name like this:

Route::patch('/preferences/{id}',[
    'as' => 'user.preferences.update',
    'uses' => 'UserController@update'
]);

That is, you make the second argument of the route into an array, where you specify both the route name (the as), and also what to do when the route is hit (the uses).

Then, when you open the form, you call the route:

{!! Form::model(Auth::user(), [
    'method' => 'PATCH',
    'route' => ['user.preferences.update', Auth::user()->id]
]) !!}

Now, for a route without parameters, you could just do 'route' => 'routename', but since you have a parameter, you make an array instead and supply the parameters in order.

All that said, since you appear to be updating the current user's preferences, I would advise you to let the handling controller check the id of the currently logged-in user, and base the updating on that - there's no need to send in the id in the url and the route unless your users should need to update the preferences of other users as well. :)

Use stored procedure to insert some data into a table

if you want to populate a table in SQL SERVER you can use while statement as follows:

declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES 
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end

Hope it helps.

codeigniter, result() vs. result_array()

result_array() is faster, result() is easier

LINQ with groupby and count

After calling GroupBy, you get a series of groups IEnumerable<Grouping>, where each Grouping itself exposes the Key used to create the group and also is an IEnumerable<T> of whatever items are in your original data set. You just have to call Count() on that Grouping to get the subtotal.

foreach(var line in data.GroupBy(info => info.metric)
                        .Select(group => new { 
                             Metric = group.Key, 
                             Count = group.Count() 
                        })
                        .OrderBy(x => x.Metric))
{
     Console.WriteLine("{0} {1}", line.Metric, line.Count);
}

> This was a brilliantly quick reply but I'm having a bit of an issue with the first line, specifically "data.groupby(info=>info.metric)"

I'm assuming you already have a list/array of some class that looks like

class UserInfo {
    string name;
    int metric;
    ..etc..
} 
...
List<UserInfo> data = ..... ;

When you do data.GroupBy(x => x.metric), it means "for each element x in the IEnumerable defined by data, calculate it's .metric, then group all the elements with the same metric into a Grouping and return an IEnumerable of all the resulting groups. Given your example data set of

    <DATA>           | Grouping Key (x=>x.metric) |
joe  1 01/01/2011 5  | 1
jane 0 01/02/2011 9  | 0
john 2 01/03/2011 0  | 2
jim  3 01/04/2011 1  | 3
jean 1 01/05/2011 3  | 1
jill 2 01/06/2011 5  | 2
jeb  0 01/07/2011 3  | 0
jenn 0 01/08/2011 7  | 0

it would result in the following result after the groupby:

(Group 1): [joe  1 01/01/2011 5, jean 1 01/05/2011 3]
(Group 0): [jane 0 01/02/2011 9, jeb  0 01/07/2011 3, jenn 0 01/08/2011 7]
(Group 2): [john 2 01/03/2011 0, jill 2 01/06/2011 5]
(Group 3): [jim  3 01/04/2011 1]

Force uninstall of Visual Studio

So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).

I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.

To do this

  1. Uninstall any Windows 10 SDKs that me on the system (the naming schem for them looks like Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE) -> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!
  2. All that's left is to download the SDKs you want by Checking out the SDK Archive for all available SDKs and you should be good to go in developing for the UWP!

What is the best way to connect and use a sqlite database from C#

Mono comes with a wrapper, use theirs!

https://github.com/mono/mono/tree/master/mcs/class/Mono.Data.Sqlite/Mono.Data.Sqlite_2.0 gives code to wrap the actual SQLite dll ( http://www.sqlite.org/sqlite-shell-win32-x86-3071300.zip found on the download page http://www.sqlite.org/download.html/ ) in a .net friendly way. It works on Linux or Windows.

This seems the thinnest of all worlds, minimizing your dependence on third party libraries. If I had to do this project from scratch, this is the way I would do it.

What's the key difference between HTML 4 and HTML 5?

You'll want to check HTML5 Differences from HTML4: W3C Working Group Note 9 December 2014 for the complete differences. There are many new elements and element attributes. Some elements were removed and others have different semantic value than before.

There are also APIs defined, such as the use of canvas, to help build the next generation of web apps and make sure implementations are standardized.

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

While creating the matrix X and Y vector use values.

X=dataset.iloc[:,4].values
Y=dataset.iloc[:,0:4].values

It will definitely solve your problem.

Why are Python's 'private' methods not actually private?

Why are Python's 'private' methods not actually private?

As I understand it, they can't be private. How could privacy be enforced?

The obvious answer is "private members can only be accessed through self", but that wouldn't work - self is not special in Python, it is nothing more than a commonly-used name for the first parameter of a function.

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

If you change the property name in pubspect.yaml all your package in lib folder turn to red with the error Target of URI doesn't exist...

Convert char to int in C and C++

Use static_cast<int>:

int num = static_cast<int>(letter); // if letter='a', num=97

Edit: You probably should try to avoid to use (int)

int num = (int) letter;

check out Why use static_cast<int>(x) instead of (int)x? for more info.

How to resize array in C++?

You can do smth like this for 1D arrays. Here we use int*& because we want our pointer to be changeable.

#include<algorithm> // for copy

void resize(int*& a, size_t& n)
{
   size_t new_n = 2 * n;
   int* new_a = new int[new_n];
   copy(a, a + n, new_a);
   delete[] a;
   a = new_a;
   n = new_n;
}

For 2D arrays:

#include<algorithm> // for copy

void resize(int**& a, size_t& n)
{
   size_t new_n = 2 * n, i = 0;
   int** new_a = new int* [new_n];
   for (i = 0; i != new_n; ++i)
       new_a[i] = new int[100];
   for (i = 0; i != n; ++i)
   {
       copy(a[i], a[i] + 100, new_a[i]);
       delete[] a[i];
   }
   delete[] a;
   a = new_a;
   n = new_n;
}

Invoking of 1D array:

void myfn(int*& a, size_t& n)
{
   // do smth
   resize(a, n);
}

Invoking of 2D array:

void myfn(int**& a, size_t& n)
{
   // do smth
   resize(a, n);
}
  


   

Android Studio cannot resolve R in imported project?

check the build tools version in build.gradle(for module app). Then go to android sdk manager see if the version is installed if not install it or change the build tools version to the one which is installed like below.

    android {
          buildToolsVersion "22.0.1"
          ..
          ..
          ..
     }

Convert Iterable to Stream using Java 8 JDK

A very simple work-around for this issue is to create a Streamable<T> interface extending Iterable<T> that holds a default <T> stream() method.

interface Streamable<T> extends Iterable<T> {
    default Stream<T> stream() {
        return StreamSupport.stream(spliterator(), false);
    }
}

Now any of your Iterable<T>s can be trivially made streamable just by declaring them implements Streamable<T> instead of Iterable<T>.

Count the number of all words in a string

With stringr package, one can also write a simple script that could traverse a vector of strings for example through a for loop.

Let's say

df$text

contains a vector of strings that we are interested in analysing. First, we add additional columns to the existing dataframe df as below:

df$strings    = as.integer(NA)
df$characters = as.integer(NA)

Then we run a for-loop over the vector of strings as below:

for (i in 1:nrow(df)) 
{
   df$strings[i]    = str_count(df$text[i], '\\S+') # counts the strings
   df$characters[i] = str_count(df$text[i])         # counts the characters & spaces
}

The resulting columns: strings and character will contain the counts of words and characters and this will be achieved in one-go for a vector of strings.

Installing a dependency with Bower from URL and specify version

Try bower install git://github.com/urin/jquery.balloon.js.git#1.0.3 --save where 1.0.3 is the tag number which you can get by reading tag under releases. Also for URL replace by git:// in order for system to connect.

Grunt watch error - Waiting...Fatal error: watch ENOSPC

In my case I found that I have an aggressive plugin for Vim, just restarted it.

C# Java HashMap equivalent

Let me help you understand it with an example of "codaddict's algorithm"

'Dictionary in C#' is 'Hashmap in Java' in parallel universe.

Some implementations are different. See the example below to understand better.

Declaring Java HashMap:

Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

Declaring C# Dictionary:

Dictionary<int, int> Pairs = new Dictionary<int, int>();

Getting a value from a location:

pairs.get(input[i]); // in Java
Pairs[input[i]];     // in C#

Setting a value at location:

pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i];    // in C#

An Overall Example can be observed from below Codaddict's algorithm.

codaddict's algorithm in Java:

import java.util.HashMap;

public class ArrayPairSum {

    public static void printSumPairs(int[] input, int k)
    {
        Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

        for (int i = 0; i < input.length; i++)
        {
            if (pairs.containsKey(input[i]))
                System.out.println(input[i] + ", " + pairs.get(input[i]));
            else
                pairs.put(k - input[i], input[i]);
        }

    }

    public static void main(String[] args)
    {
        int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
        printSumPairs(a, 10);

    }
}

Codaddict's algorithm in C#

using System;
using System.Collections.Generic;

class Program
{
    static void checkPairs(int[] input, int k)
    {
        Dictionary<int, int> Pairs = new Dictionary<int, int>();

        for (int i = 0; i < input.Length; i++)
        {
            if (Pairs.ContainsKey(input[i]))
            {
                Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
            }
            else
            {
                Pairs[k - input[i]] = input[i];
            }
        }
    }
    static void Main(string[] args)
    {
        int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
        //method : codaddict's algorithm : O(n)
        checkPairs(a, 10);
        Console.Read();
    }
}

TabLayout tab selection

You can set TabLayout position using following functions

public void setTab(){
 tabLayout.setScrollPosition(YOUR_SCROLL_INDEX,0,true);
 tabLayout.setSelected(true);
}

Convert data.frame columns from factors to characters

If you would use data.table package for the operations on data.frame then the problem is not present.

library(data.table)
dt = data.table(col1 = c("a","b","c"), col2 = 1:3)
sapply(dt, class)
#       col1        col2 
#"character"   "integer" 

If you have a factor columns in you dataset already and you want to convert them to character you can do the following.

library(data.table)
dt = data.table(col1 = factor(c("a","b","c")), col2 = 1:3)
sapply(dt, class)
#     col1      col2 
# "factor" "integer" 
upd.cols = sapply(dt, is.factor)
dt[, names(dt)[upd.cols] := lapply(.SD, as.character), .SDcols = upd.cols]
sapply(dt, class)
#       col1        col2 
#"character"   "integer" 

Update Git branches from master

You have basically two options:

  1. You merge. That is actually quite simple, and a perfectly local operation:

    git checkout b1
    git merge master
    # repeat for b2 and b3
    

    This leaves the history exactly as it happened: You forked from master, you made changes to all branches, and finally you incorporated the changes from master into all three branches.

    git can handle this situation really well, it is designed for merges happening in all directions, at the same time. You can trust it be able to get all threads together correctly. It simply does not care whether branch b1 merges master, or master merges b1, the merge commit looks all the same to git. The only difference is, which branch ends up pointing to this merge commit.

  2. You rebase. People with an SVN, or similar background find this more intuitive. The commands are analogue to the merge case:

    git checkout b1
    git rebase master
    # repeat for b2 and b3
    

    People like this approach because it retains a linear history in all branches. However, this linear history is a lie, and you should be aware that it is. Consider this commit graph:

    A --- B --- C --- D <-- master
     \
      \-- E --- F --- G <-- b1
    

    The merge results in the true history:

    A --- B --- C --- D <-- master
     \                 \
      \-- E --- F --- G +-- H <-- b1
    

    The rebase, however, gives you this history:

    A --- B --- C --- D <-- master
                       \
                        \-- E' --- F' --- G' <-- b1
    

    The point is, that the commits E', F', and G' never truly existed, and have likely never been tested. They may not even compile. It is actually quite easy to create nonsensical commits via a rebase, especially when the changes in master are important to the development in b1.

    The consequence of this may be, that you can't distinguish which of the three commits E, F, and G actually introduced a regression, diminishing the value of git bisect.

    I am not saying that you shouldn't use git rebase. It has its uses. But whenever you do use it, you need to be aware of the fact that you are lying about history. And you should at least compile test the new commits.

postgresql: INSERT INTO ... (SELECT * ...)

insert into TABLENAMEA (A,B,C,D) 
select A::integer,B,C,D from TABLENAMEB

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

Assign null to a SqlParameter

if (_id_categoria_padre > 0)
{
    objComando.Parameters.Add("id_categoria_padre", SqlDbType.Int).Value = _id_categoria_padre;
}
else
{
    objComando.Parameters.Add("id_categoria_padre", DBNull.Value).Value = DBNull.Value;
}

Vue.js : How to set a unique ID for each component instance?

If you're using TypeScript, without any plugin, you could simply add a static id in your class component and increment it in the created() method. Each component will have a unique id (add a string prefix to avoid collision with another components which use the same tip)

<template>
  <div>
    <label :for="id">Label text for {{id}}</label>
    <input :id="id" type="text" />
  </div>
</template>

<script lang="ts">
  ...
  @Component
  export default class MyComponent extends Vue {
    private id!: string;
    private static componentId = 0;
    ...
    created() {
      MyComponent.componentId += 1;
      this.id = `my-component-${MyComponent.componentId}`;
    }
 </script>

Changing specific text's color using NSMutableAttributedString in Swift

This extension works well when configuring the text of a label with an already set default color.

public extension String {
    func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
        let range = (self as NSString).range(of: substring)
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        return attributedString
    }
}

For example

let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")

let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText

No mapping found for HTTP request with URI.... in DispatcherServlet with name

Make sure

<mvc:annotation-driven/>
<context:component-scan base-package="com.hireartists.web.controllers"/>

points to proper package that contains controllers.

Copy file or directories recursively in Python

I suggest you first call shutil.copytree, and if an exception is thrown, then retry with shutil.copy.

import shutil, errno

def copyanything(src, dst):
    try:
        shutil.copytree(src, dst)
    except OSError as exc: # python >2.5
        if exc.errno == errno.ENOTDIR:
            shutil.copy(src, dst)
        else: raise

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

How do I change the owner of a SQL Server database?

To change database owner:

ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa

As of SQL Server 2014 you can still use sp_changedbowner as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.

What is "X-Content-Type-Options=nosniff"?

The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.

Syntax :

X-Content-Type-Options: nosniff

Directives :

nosniff Blocks a request if the requested type is 1. "style" and the MIME type is not "text/css", or 2. "script" and the MIME type is not a JavaScript MIME type.

Note: nosniff only applies to "script" and "style" types. Also applying nosniff to images turned out to be incompatible with existing web sites.

Specification :

https://fetch.spec.whatwg.org/#x-content-type-options-header

What are the different types of keys in RDBMS?

Ólafur forgot the surrogate key:

A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data.

Adding an identity to an existing column

Right click on table name in Object Explorer. You will get some options. Click on 'Design'. A new tab will be opened for this table. You can add Identity constraint here in 'Column Properties'.

JavaScript object: access variable property by name as string

You don't need a function for it - simply use the bracket notation:

var side = columns['right'];

This is equal to dot notation, var side = columns.right;, except the fact that right could also come from a variable, function return value, etc., when using bracket notation.

If you NEED a function for it, here it is:

function read_prop(obj, prop) {
    return obj[prop];
}

To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:

var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};

you can access property x of c as follows:

var cx = foo['c']['x']

If a property is undefined, an attempt to reference it will return undefined (not null or false):

foo['c']['q'] === null
// returns false

foo['c']['q'] === false
// returns false

foo['c']['q'] === undefined
// returns true

Erasing elements from a vector

  1. You can iterate using the index access,

  2. To avoid O(n^2) complexity you can use two indices, i - current testing index, j - index to store next item and at the end of the cycle new size of the vector.

code:

void erase(std::vector<int>& v, int num)
{
  size_t j = 0;
  for (size_t i = 0; i < v.size(); ++i) {
    if (v[i] != num) v[j++] = v[i];
  }
  // trim vector to new size
  v.resize(j);
}

In such case you have no invalidating of iterators, complexity is O(n), and code is very concise and you don't need to write some helper classes, although in some case using helper classes can benefit in more flexible code.

This code does not use erase method, but solves your task.

Using pure stl you can do this in the following way (this is similar to the Motti's answer):

#include <algorithm>

void erase(std::vector<int>& v, int num) {
    vector<int>::iterator it = remove(v.begin(), v.end(), num);
    v.erase(it, v.end());
}

How to grep, excluding some patterns?

A bit old, but oh well...

The most up-voted solution from @houbysoft will not work as that will exclude any line with "gloom" in it, even if it has "loom". According to OP's expectations, we need to include lines with "loom", even if they also have "gloom" in them. This line needs to be in the output "Arty is slooming in a gloomy day.", but this will be excluded by a chained grep like

grep -n 'loom' ~/projects/**/trunk/src/**/*.@(h|cpp) | grep -v 'gloom'

Instead, the egrep regex example of Bentoy13 works better

egrep '(^|[^g])loom' ~/projects/**/trunk/src/**/*.@(h|cpp)

as it will include any line with "loom" in it, regardless of whether or not it has "gloom". On the other hand, if it only has gloom, it will not include it, which is precisely the behaviour OP wants.

Character reading from file in Python

There are a few points to consider.

A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:

>>> text = u'‘'
>>> print repr(text)
u'\u2018'

Now if you simply want to print the unicode string prettily, just use unicode's encode method:

>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this

To make sure that every line from any file would be read as unicode, you'd better use the codecs.open function instead of just open, which allows you to specify file's encoding:

>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this

What is the proper use of an EventEmitter?

There is no: nono and no: yesyes. The truth is in the middle And no reasons to be scared because of the next version of Angular.

From a logical point of view, if You have a Component and You want to inform other components that something happens, an event should be fired and this can be done in whatever way You (developer) think it should be done. I don't see the reason why to not use it and i don't see the reason why to use it at all costs. Also the EventEmitter name suggests to me an event happening. I usually use it for important events happening in the Component. I create the Service but create the Service file inside the Component Folder. So my Service file becomes a sort of Event Manager or an Event Interface, so I can figure out at glance to which event I can subscribe on the current component.

I know..Maybe I'm a bit an old fashioned developer. But this is not a part of Event Driven development pattern, this is part of the software architecture decisions of Your particular project.

Some other guys may think that use Observables directly is cool. In that case go ahead with Observables directly. You're not a serial killer doing this. Unless you're a psychopath developer, So far the Program works, do it.

How to add scroll bar to the Relative Layout?

Check the following sample layout file

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@color/white">
<RelativeLayout android:layout_height="fill_parent"
    android:layout_width="fill_parent">
    <ImageView android:id="@+id/image1"
        android:layout_width="wrap_content"  
                    android:layout_height="wrap_content"
        android:layout_marginLeft="15dip" android:layout_marginTop="15dip"
        android:src="@drawable/btn_blank" android:clickable="true" /> </RelativeLayout> </ScrollView>

What is the difference between atan and atan2 in C++?

Mehrwolf below is correct, but here is a heuristic which may help:

If you are working in a 2-dimensional coordinate system, which is often the case for programming the inverse tangent, you should use definitely use atan2. It will give the full 2 pi range of angles and take care of zeros in the x coordinate for you.

Another way of saying this is that atan(y/x) is virtually always wrong. Only use atan if the argument cannot be thought of as y/x.

The object 'DF__*' is dependent on column '*' - Changing int to double

This is the tsql way

 ALTER TABLE yourtable DROP CONSTRAINT constraint_name     -- DF_Movies_Rating__48CFD27E

For completeness, this just shows @Joe Taras's comment as an answer

LINQ order by null column where order is ascending and nulls should be last

I have another option in this situation. My list is objList, and I have to order but nulls must be in the end. my decision:

var newList = objList.Where(m=>m.Column != null)
                     .OrderBy(m => m.Column)
                     .Concat(objList.where(m=>m.Column == null));

How to call Stored Procedure in a View?

If you are using Sql Server 2005 you can use table valued functions. You can call these directly and pass paramters, whilst treating them as if they were tables.

For more info check out Table-Valued User-Defined Functions

Iterate through Nested JavaScript Objects

In typescript with object/generic way, it could be alse implemented:

export interface INestedIterator<T> {
    getChildren(): T[];
}

export class NestedIterator {
    private static forEach<T extends INestedIterator<T>>(obj: T, fn: ((obj: T) => void)): void {      
        fn(obj);    
        if (obj.getChildren().length) {
            for (const item of obj.getChildren()) {
                NestedIterator.forEach(item, fn);            
            };
        }
    }
}

than you can implement interface INestedIterator<T>:

class SomeNestedClass implements INestedIterator<SomeNestedClass>{
    items: SomeNestedClass[];
    getChildren() {
        return this.items;
    }
}

and then just call

NestedIterator.forEach(someNesteObject, (item) => {
    console.log(item);
})

if you don't want use interfaces and strongly typed classes, just remove types

export class NestedIterator {
    private static forEach(obj: any, fn: ((obj: any) => void)): void {      
        fn(obj);    
        if (obj.items && obj.items.length) {
            for (const item of obj.items) {
                NestedIterator.forEach(item, fn);            
            };
        }
    }
}

How to send a pdf file directly to the printer using JavaScript?

<?php

$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];

if($browser_ver['browser'] == 'IE') {
?>

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
    html { height:100%; }
</style>
<script>
    function printIt(id) {
        var pdf = document.getElementById("samplePDF");
        pdf.click();
        pdf.setActive();
        pdf.focus();
        pdf.print();
    }
</script>
</head>

<body style="margin:0; height:100%;">

<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>


</body>
</html>

<?php
} else {
?>
<HTML>
<script Language="javascript">

function printfile(id) { 
    window.frames[id].focus();
    window.frames[id].print();
} 

</script>
<BODY marginheight="0" marginwidth="0">

<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>

<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">

</BODY>
</HTML>
<?php
}
?>

Editing dictionary values in a foreach loop

You can't modify the collection, not even the values. You could save these cases and remove them later. It would end up like this:

Dictionary<string, int> colStates = new Dictionary<string, int>();
// ...
// Some code to populate colStates dictionary
// ...

int OtherCount = 0;
List<string> notRelevantKeys = new List<string>();

foreach (string key in colStates.Keys)
{

    double Percent = colStates[key] / colStates.Count;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        notRelevantKeys.Add(key);
    }
}

foreach (string key in notRelevantKeys)
{
    colStates[key] = 0;
}

colStates.Add("Other", OtherCount);

Android - Share on Facebook, Twitter, Mail, ecc

I think the following code will help....

public void btnShareClick(View v) {
    // shareBtnFlag = 1;
    Dialog d = new Dialog(DrawAppActivity.this);
    d.requestWindowFeature(d.getWindow().FEATURE_NO_TITLE);
    d.setCancelable(true);

    d.setContentView(R.layout.sharing);

    final Button btnFacebook = (Button) d.findViewById(R.id.btnFacebook);
    final Button btnEmail = (Button) d.findViewById(R.id.btnEmail);

    btnEmail.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnEmail.isSelected()) {
                btnEmail.setSelected(true);
            } else {
                btnEmail.setSelected(false);
            }
            saveBtnFlag = 1;
            // Check if email id is available-------------
            AccountManager manager = AccountManager
                    .get(DrawAppActivity.this);
            Account[] accounts = manager.getAccountsByType("com.google");
            Account account = CommonFunctions.getAccount(manager);
            if (account.name != null) {
                emailSendingTask eTask = new emailSendingTask();
                eTask.execute();
                if (CommonFunctions.createDirIfNotExists(getResources()
                        .getString(R.string.path)))

                {
                    tempImageSaving(
                            getResources().getString(R.string.path),
                            getCurrentImage());
                }

                Intent sendIntent;
                sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.setType("application/octet-stream");
                sendIntent.setType("image/jpeg");
                sendIntent.putExtra(Intent.EXTRA_EMAIL,
                        new String[] { account.name });
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Drawing App");
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Check This Image");
                sendIntent.putExtra(Intent.EXTRA_STREAM,
                        Uri.parse("file://" + tempPath.getPath()));

                List<ResolveInfo> list = getPackageManager()
                        .queryIntentActivities(sendIntent,
                                PackageManager.MATCH_DEFAULT_ONLY);

                if (list.size() != 0) {

                    startActivity(Intent.createChooser(sendIntent,
                            "Send Email Using:"));

                }

                else {
                    AlertDialog.Builder confirm = new AlertDialog.Builder(
                            DrawAppActivity.this);
                    confirm.setTitle(R.string.app_name);
                    confirm.setMessage("No Email Sending App Available");
                    confirm.setPositiveButton("Set Account",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    dialog.dismiss();
                                }
                            });
                    confirm.show();
                }
            } else {
                AlertDialog.Builder confirm = new AlertDialog.Builder(
                        DrawAppActivity.this);
                confirm.setTitle(R.string.app_name);
                confirm.setMessage("No Email Account Available!");
                confirm.setPositiveButton("Set Account",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent i = new Intent(
                                        Settings.ACTION_SYNC_SETTINGS);
                                startActivity(i);
                                dialog.dismiss();
                            }
                        });
                confirm.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                dialog.dismiss();
                            }
                        });
                confirm.show();
            }
        }

    });

    btnFacebook.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnFacebook.isSelected()) {
                btnFacebook.setSelected(true);
            } else {
                btnFacebook.setSelected(false);
            }
            saveBtnFlag = 1;
            // if (connection.isInternetOn()) {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                getCurrentImage();
                Intent i = new Intent(DrawAppActivity.this,
                        FaceBookAuthentication.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(i);
            }

            else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);
            }
        }
    });
    d.show();

}

public void tempImageSaving(String tmpPath, byte[] image) {
    Random rand = new Random();

    tempfile = new File(Environment.getExternalStorageDirectory(), tmpPath);
    if (!tempfile.exists()) {
        tempfile.mkdirs();
    }

    tempPath = new File(tempfile.getPath(), "DrawApp" + rand.nextInt()
            + ".jpg");
    try {
        FileOutputStream fos1 = new FileOutputStream(tempPath.getPath());
        fos1.write(image);

        fos1.flush();
        fos1.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}

public byte[] getCurrentImage() {

    Bitmap b = drawingSurface.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.PNG, 100, stream);

    byteArray = stream.toByteArray();

    return byteArray;
}

private class emailSendingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

private class ImageSavingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

            if (CommonFunctions.createDirIfNotExists(getResources()
                    .getString(R.string.path)))

            {
                saveImageInSdCard(getResources().getString(R.string.path),
                        getCurrentImage());
            }
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

For facebook application use facebook SDK