Programs & Examples On #Servicedcomponent

Construct pandas DataFrame from list of tuples of (row,col,values)

You can pivot your DataFrame after creating:

>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1      c1     c2
0               
r1  avg11  avg12
r2  avg21  avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1        c1       c2
0                   
r1  stdev11  stdev12
r2  stdev21  stdev22

Initialise numpy array of unknown length

For posterity, I think this is quicker:

a = np.array([np.array(list()) for _ in y])

You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.


Responding to comment below:

>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object),
       array(<type 'list'>, dtype=object)], dtype=object)

How to hide keyboard in swift on pressing return key?

All in One Hide Keyboard and Move View on Keyboard Open: Swift 5

override func viewDidLoad() {
    super.viewDidLoad()
    let tap = UITapGestureRecognizer(target: self, action: #selector(taped))
    view.addGestureRecognizer(tap)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}


   override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
 @objc func taped(){

    self.view.endEditing(true)

}

@objc func KeyboardWillShow(sender: NSNotification){

    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y == 0{
        self.view.frame.origin.y -= keyboardSize.height
    }


}

@objc func KeyboardWillHide(sender : NSNotification){

    let keyboardSize : CGSize = ((sender.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size)!
    if self.view.frame.origin.y != 0{
        self.view.frame.origin.y += keyboardSize.height
    }

}

FTP/SFTP access to an Amazon S3 Bucket

Answer from 2014 for the people who are down-voting me:

Well, S3 isn't FTP. There are lots and lots of clients that support S3, however.

Pretty much every notable FTP client on OS X has support, including Transmit and Cyberduck.

If you're on Windows, take a look at Cyberduck or CloudBerry.

Updated answer for 2019:

AWS has recently released the AWS Transfer for SFTP service, which may do what you're looking for.

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

How can I check if the current date/time is past a set date/time?

Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php

If strtotime can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr to parse/correct your format and retrieve your timestamp through another function, e.g. mktime.

Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.

I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.

HTML text-overflow ellipsis detection

there are some mistasks in demo http://jsfiddle.net/brandonzylstra/hjk9mvcy/ mentioned by https://stackoverflow.com/users/241142/iconoclast.

in his demo, add these code will works:

setTimeout(() => {      
  console.log(EntryElm[0].offsetWidth)
}, 0)

IPython/Jupyter Problems saving notebook as PDF

What I found was that the nbconvert/utils/pandoc.py had a code bug that resulted in the error for my machine. The code checks if pandoc is in your environmental variables path. For my machine the answer is no. However pandoc.exe is!

Solution was to add '.exe' to the code on line 69

if __version is None:
    if not which('pandoc.exe'):
        raise PandocMissing()

The same goes for 'xelatex' is not installed. Add to the file nbconvert/exporters/pdf.py on line 94

    cmd = which(command_list[0]+'.exe')

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

I know that there's already an accepted answer, but I don't see how it works for the OP because I don't think FLAG_ACTIVITY_CLEAR_TOP is meaningful in his particular case. That flag is relevant only with activities in the same task. Based on his description, each activity is in its own task: A, B, and the browser.

Something that is maybe throwing him off is that A is singleTop, when it should be singleTask. If A is singleTop, and B starts A, then a new A will be created because A is not in B's task. From the documentation for singleTop:

"If an instance of the activity already exists at the top of the current task, the system routes the intent to that instance..."

Since B starts A, the current task is B's task, which is for a singleInstance and therefore cannot include A. Use singleTask to achieve the desired result there because then the system will find the task that has A and bring that task to the foreground.

Lastly, after B has started A, and the user presses back from A, the OP does not want to see either B or the browser. To achieve this, calling finish() in B is correct; again, FLAG_ACTIVITY_CLEAR_TOP won't remove the other activities in A's task because his other activities are all in different tasks. The piece that he was missing, though is that B should also use FLAG_ACTIVITY_NO_HISTORY when firing the intent for the browser. Note: if the browser is already running prior to even starting the OP's application, then of course you will see the browser when pressing back from A. So to really test this, be sure to back out of the browser before starting the application.

How do I create an abstract base class in JavaScript?

Reference: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Classes

class Animal {
  
  constructor(sound) {
    this.sound = sound;
      }

  say() {
    return `This animal does ${this.sound}`;}

};

const dog = new Animal('bark');
console.log(dog.say());

What methods of ‘clearfix’ can I use?

_x000D_
_x000D_
#content{float:left;}_x000D_
#sidebar{float:left;}_x000D_
.clear{clear:both; display:block; height:0px; width:0px; overflow:hidden;}
_x000D_
<div id="container">_x000D_
  <div id="content">text 1 </div>_x000D_
  <div id="sidebar">text 2</div>_x000D_
  <div class="clear"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

How to create separate AngularJS controller files?

What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:

app.js

var app = angular.module("myApp", ['deps']);

myCtrl.js

app.controller("myCtrl", function($scope) { ..});

html

<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.

How do I center list items inside a UL element?

I had a problem slimier to yours I this quick and its the best solution I have found so far.

What the output looks like

Shows what the output of the code looks like The borders are just to show the spacing and are not needed.


Html:

    <div class="center">
      <ul class="dots">
        <span>
          <li></li>
          <li></li>
          <li></li>
        </span>
      </ul>
    </div>

CSS:

    ul {list-style-type: none;}
    ul li{
        display: inline-block;
        padding: 2px;
        border: 2px solid black;
        border-radius: 5px;}
    .center{
        width: 100%;
        border: 3px solid black;}
    .dots{
        padding: 0px;
        border: 5px solid red;
        text-align: center;}
    span{
        width: 100%;
        border: 5px solid blue;}

Not everything here is needed to center the list items.

You can cut the css down to this to get the same effect:

    ul {list-style-type: none;}
    ul li{display: inline-block;}
    .center{width: 100%;}
    .dots{
        text-align: center;
        padding: 0px;}
    span{width: 100%;}

Javascript Cookie with no expiration date

There is no syntax for what you want. Not setting expires causes the cookie to expire at the end of the session. The only option is to pick some arbitrarily large value. Be aware that some browsers have problems with dates past 2038 (when unix epoch time exceeds a 32-bit int).

Checking if a website is up via Python

my 2 cents

def getResponseCode(url):
conn = urllib.request.urlopen(url)
return conn.getcode()

if getResponseCode(url) != 200:
    print('Wrong URL')
else:
    print('Good URL')

Replace transparency in PNG images with white background

This is not exactly the answer to your question, but I found your question while trying to figure out how to remove the alpha channel, so I decided to add this answer here:

If you want to remove alpha channel using imagemagick, you can use this command:

mogrify -alpha off ./*.png

How do I use hexadecimal color strings in Flutter?

Easy way :

String color = yourHexColor.replaceAll('#', '0xff');

Usage:

Container(
    color: Color(int.parse(color)),
)

Redirect HTTP to HTTPS on default virtual host without ServerName

I have use mkcert to create infinites *.dev.net subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)

I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):

mkcert -install
mkcert localhost "*.dev.net"

This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)

localhost+1.pem
localhost+1-key.pem

Overwrite the XAMPP default certs:

copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem"  C:\xampp\apache\conf\ssl.key\server.key

Now, in Apache2 for Debian 10, activate SSL & vhost_alias

a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2

For vhost_alias add this Apache2 config:

nano /etc/apache2/sites-available/999-vhosts_alias.conf

With this content:

<VirtualHost *:80>
   UseCanonicalName Off
   ServerAlias *.dev.net
   VirtualDocumentRoot "/var/www/html/%0/"
</VirtualHost>

Add the site:

a2ensite 999-vhosts_alias

Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:

systemctl stop apache2

mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak

cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key

chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key

systemctl start apache2

Edit the SSL config

nano /etc/apache2/sites-enabled/default-ssl.conf

At the start edit the file with this content:

<IfModule mod_ssl.c>
    <VirtualHost *:443>

            UseCanonicalName Off
            ServerAlias *.dev.net
            ServerAdmin webmaster@localhost

            # DocumentRoot /var/www/html/
            VirtualDocumentRoot /var/www/html/%0/

...

Last restart:

systemctl restart apache2

NOTE: don´t forget to create the folders for your subdomains in /var/www/html/

/var/www/html/subdomain1.dev.net
/var/www/html/subdomain2.dev.net
/var/www/html/subdomain3.dev.net

Error: Specified cast is not valid. (SqlManagerUI)

I had a similar error "Specified cast is not valid" restoring from SQL Server 2012 to SQL Server 2008 R2

First I got the MDF and LDF Names:

RESTORE FILELISTONLY 
FROM  DISK = N'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak' 
GO

Second I restored with a MOVE using those names returned:

RESTORE DATABASE Davincis3 
FROM DISK = 'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak'
WITH 
   MOVE 'JQueryExampleDb' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.mdf', 
   MOVE 'JQueryExampleDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.ldf', 
REPLACE
GO  

I have no clue as to the name "JQueryExampleDb", but this worked for me.

Nevertheless, backups (and databases) are not backwards compatible with older versions.

Difference between DataFrame, Dataset, and RDD in Spark

Most of answers are correct only want to add one point here

In Spark 2.0 the two APIs (DataFrame +DataSet) will be unified together into a single API.

"Unifying DataFrame and Dataset: In Scala and Java, DataFrame and Dataset have been unified, i.e. DataFrame is just a type alias for Dataset of Row. In Python and R, given the lack of type safety, DataFrame is the main programming interface."

Datasets are similar to RDDs, however, instead of using Java serialization or Kryo they use a specialized Encoder to serialize the objects for processing or transmitting over the network.

Spark SQL supports two different methods for converting existing RDDs into Datasets. The first method uses reflection to infer the schema of an RDD that contains specific types of objects. This reflection based approach leads to more concise code and works well when you already know the schema while writing your Spark application.

The second method for creating Datasets is through a programmatic interface that allows you to construct a schema and then apply it to an existing RDD. While this method is more verbose, it allows you to construct Datasets when the columns and their types are not known until runtime.

Here you can find RDD tof Data frame conversation answer

How to convert rdd object to dataframe in spark

How can I remove a style added with .css() function?

The accepted answer works but leaves an empty style attribute on the DOM in my tests. No big deal, but this removes it all:

removeAttr( 'style' );

This assumes you want to remove all dynamic styling and return back to the stylesheet styling.

how to check the version of jar file?

Each jar version has a unique checksum. You can calculate the checksum for you jar (that had no version info) and compare it with the different versions of the jar. We can also search a jar using checksum.

Refer this Question to calculate checksum: What is the best way to calculate a checksum for a file that is on my machine?

net::ERR_INSECURE_RESPONSE in Chrome

I was getting this error on amazon.ca, meetup.com, and the Symantec homepage.

I went to the update page in the Chrome browser (it was at 53.*) and checked for an upgrade, and it showed there was no updates available. After asking around my office, it turns out the latest version was 55 but I was stuck on 53 for some reason.

After upgrading (had to manually download from the Chrome website) the issues were gone!

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

Remove Elements from a HashSet while Iterating

You can manually iterate over the elements of the set:

Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
    Integer element = iterator.next();
    if (element % 2 == 0) {
        iterator.remove();
    }
}

You will often see this pattern using a for loop rather than a while loop:

for (Iterator<Integer> i = set.iterator(); i.hasNext();) {
    Integer element = i.next();
    if (element % 2 == 0) {
        i.remove();
    }
}

As people have pointed out, using a for loop is preferred because it keeps the iterator variable (i in this case) confined to a smaller scope.

Upload video files via PHP and save them in appropriate folder and have a database entry

"Could you suggest a simpler code main thing is uploading the file Data base entry is secondary"

^--- As per OP's request. ---^

Image and video uploading code (tested with PHP Version 5.4.17)

HTML form

<!DOCTYPE html>

<head>
<title></title>
</head>

<body>

<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file"><span>Filename:</span></label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

PHP handler (upload_file.php)

Change upload folder to preferred name. Presently saves to upload/

<?php

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if ((($_FILES["file"]["type"] == "video/mp4")
|| ($_FILES["file"]["type"] == "audio/mp3")
|| ($_FILES["file"]["type"] == "audio/wma")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg"))

&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))

  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Moment.js with Vuejs

If your project is a single page application, (eg project created by vue init webpack myproject), I found this way is most intuitive and simple:

In main.js

import moment from 'moment'

Vue.prototype.moment = moment

Then in your template, simply use

<span>{{moment(date).format('YYYY-MM-DD')}}</span>

MySQL CURRENT_TIMESTAMP on create and on update

Guess this is a old post but actually i guess mysql supports 2 TIMESTAMP in its recent editions mysql 5.6.25 thats what im using as of now.

Converting DateTime format using razor

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")

PostgreSQL: role is not permitted to log in

The role you have created is not allowed to log in. You have to give the role permission to log in.

One way to do this is to log in as the postgres user and update the role:

psql -U postgres

Once you are logged in, type:

ALTER ROLE "asunotest" WITH LOGIN;

Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html

ThreadStart with parameters

Simple way using lambda like so..

Thread t = new Thread(() => DoSomething("param1", "param2"));
t.Start();

OR you could even delegate using ThreadStart like so...

ThreadStart ts = delegate
{
     bool moreWork = DoWork("param1", "param2", "param3");
     if (moreWork) 
     {
          DoMoreWork("param4", "param5");
     }
};
new Thread(ts).Start();

OR using VS 2019 .NET 4.5+ even cleaner like so..

private void DoSomething(int param1, string param2)
{
    //DO SOMETHING..
    void ts()
    {
        if (param1 > 0) DoSomethingElse(param2, "param3");
    }
    new Thread(ts).Start();
    //DO SOMETHING..
}

How to pass an object into a state using UI-router?

1)

$stateProvider
        .state('app.example1', {
                url: '/example',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/example.html',
                        controller: 'ExampleCtrl'
                    }
                }
            })
            .state('app.example2', {
                url: '/example2/:object',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/example2.html',
                        controller: 'Example2Ctrl'
                    }
                }
            })

2)

.controller('ExampleCtrl', function ($state, $scope, UserService) {


        $scope.goExample2 = function (obj) {

            $state.go("app.example2", {object: JSON.stringify(obj)});
        }

    })
    .controller('Example2Ctrl', function ($state, $scope, $stateParams) {

        console.log(JSON.parse($state.params.object));


    })

await is only valid in async function

Yes, await / async was a great concept, but the implementation is completely broken.

For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.

Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.

This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.

If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.

So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...

  • await can only be used to CALL async functions.
  • await can appear in any kind of function, synchronous or asynchronous.
  • Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Updated answer of Jesse Crossen for Swift 4:

extension UIButton {
    func alignVertical(spacing: CGFloat = 6.0) {
        guard let imageSize = self.imageView?.image?.size,
            let text = self.titleLabel?.text,
            let font = self.titleLabel?.font
            else { return }
        self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0)
        let labelString = NSString(string: text)
        let titleSize = labelString.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: font])
        self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
        let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
        self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0)
    }
}

Use this way:

override func viewDidLayoutSubviews() {
    button.alignVertical()
}

Pass multiple optional parameters to a C# function

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

Trusting all certificates using HttpClient over HTTPS

I'm looked response from "emmby" (answered Jun 16 '11 at 21:29), item #4: "Create a custom SSLSocketFactory that uses the built-in certificate KeyStore, but falls back on an alternate KeyStore for anything that fails to verify with the default."

This is a simplified implementation. Load the system keystore & merge with application keystore.

public HttpClient getNewHttpClient() {
    try {
        InputStream in = null;
        // Load default system keystore
        KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); 
        try {
            in = new BufferedInputStream(new FileInputStream(System.getProperty("javax.net.ssl.trustStore"))); // Normally: "/system/etc/security/cacerts.bks"
            trusted.load(in, null); // no password is "changeit"
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
        }

        // Load application keystore & merge with system
        try {
            KeyStore appTrusted = KeyStore.getInstance("BKS"); 
            in = context.getResources().openRawResource(R.raw.mykeystore);
            appTrusted.load(in, null); // no password is "changeit"
            for (Enumeration<String> e = appTrusted.aliases(); e.hasMoreElements();) {
                final String alias = e.nextElement();
                final KeyStore.Entry entry = appTrusted.getEntry(alias, null);
                trusted.setEntry(System.currentTimeMillis() + ":" + alias, entry, null);
            }
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
        }

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        sf.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

A simple mode to convert from JKS to BKS:

keytool -importkeystore -destkeystore cacerts.bks -deststoretype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk16-141.jar -deststorepass changeit -srcstorepass changeit -srckeystore $JAVA_HOME/jre/lib/security/cacerts -srcstoretype JKS -noprompt

*Note: In Android 4.0 (ICS) the Trust Store has changed, more info: http://nelenkov.blogspot.com.es/2011/12/ics-trust-store-implementation.html

SyntaxError: Unexpected token o in JSON at position 1

Unexpected 'O' error is thrown when JSON data or String happens to get parsed.

If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.

I faced similar( although in different context), I solved the following error by removing JSON Producer.

    @POST
    @Produces({ **MediaType.APPLICATION_JSON**})
    public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
      return Response.status(200).entity("OK").build();

  }

The response contains "OK" string return. The annotation marked as @Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.

Removing @Produces({ MediaType.APPLICATION_JSON}) works fine. Output : OK

Beware: Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'

O is the first letter of the string

JSON.parse(object) compares with jQuery.parseJSON(object);

JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

What is "android.R.layout.simple_list_item_1"?

Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.

From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).

Calling Python in Java?

Jython has some limitations:

There are a number of differences. First, Jython programs cannot use CPython extension modules written in C. These modules usually have files with the extension .so, .pyd or .dll. If you want to use such a module, you should look for an equivalent written in pure Python or Java. Although it is technically feasible to support such extensions - IronPython does so - there are no plans to do so in Jython.

Distributing my Python scripts as JAR files with Jython?

you can simply call python scripts (or bash or Perl scripts) from Java using Runtime or ProcessBuilder and pass output back to Java:

Running a bash shell script in java

Running Command Line in Java

java runtime.getruntime() getting output from executing a command line program

java how to use classes in other package?

You have to provide the full path that you want to import.

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

How can I remove an entry in global configuration with git config?

You can check all the config settings using

git config --global --list

You can remove the setting for example username

git config --global --unset user.name

You can edit the configuration or remove the config setting manually by hand using:

git config --global --edit 

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:

if(theHref){
   // do stuff
}else{
  // do other stuff
}

An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

Byte Array to Image object

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ImageIO.read(new ByteArrayInputStream(data));
} catch (IOException e) {
    e.printStackTrace();
}
drawPicture(img);  //  void drawPicture(Image img);

Get Element value with minidom with Python

Here is a slightly modified answer of Henrik's for multiple nodes (ie. when getElementsByTagName returns more than one instance)

images = xml.getElementsByTagName("imageUrl")
for i in images:
    print " ".join(t.nodeValue for t in i.childNodes if t.nodeType == t.TEXT_NODE)

How should strace be used?

In simple words, strace traces all system calls issued by a program along with their return codes. Think things such as file/socket operations and a lot more obscure ones.

It is most useful if you have some working knowledge of C since here system calls would more accurately stand for standard C library calls.

Let's say your program is /usr/local/bin/cough. Simply use:

strace /usr/local/bin/cough <any required argument for cough here>

or

strace -o <out_file> /usr/local/bin/cough <any required argument for cough here>

to write into 'out_file'.

All strace output will go to stderr (beware, the sheer volume of it often asks for a redirection to a file). In the simplest cases, your program will abort with an error and you'll be able to see what where its last interactions with the OS in strace output.

More information should be available with:

man strace

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

I have found that adding these lines of code to the pom.xml file of the maven project solves similar issues for me:-

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.packagename.MainClassName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Proper use cases for Android UserManager.isUserAGoat()?

There is a similar call, isUserAMonkey(), that returns true if the MonkeyRunner tool is being used. The SDK explanation is just as curious as this one.

public static boolean isUserAMonkey(){}     

Returns true if the user interface is currently being messed with by a monkey.

Here is the source.

I expect that this was added in anticipation of a new SDK tool named something with a goat and will actually be functional to test for the presence of that tool.

Also see a similar question, Strange function in ActivityManager: isUserAMonkey. What does this mean, what is its use?.

How to create a delay in Swift?

Instead of a sleep, which will lock up your program if called from the UI thread, consider using NSTimer or a dispatch timer.

But, if you really need a delay in the current thread:

do {
    sleep(4)
}

This uses the sleep function from UNIX.

Regular vs Context Free Grammars

a regular grammer is never ambiguous because it is either left linear or right linear so we cant make two decision tree for regular grammer so it is always unambiguous.but othert than regular grammar all are may or may not be regular

Unicode via CSS :before

The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).

However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.

document.getElementById(id).focus() is not working for firefox or chrome

Your focus is working before return false; ,After that is not working. You try this solution. Control after return false;

Put code in function:

function  validateNumber(){
    var mnumber = document.getElementById('mobileno').value; 
    if(mnumber.length >=10) {
        alert("Mobile Number Should be in 10 digits only"); 
        document.getElementById('mobileno').value = ""; 
        return false; 
    }else{
        return true;
    }
}

Caller function:

function submitButton(){
        if(!validateNumber()){
            document.getElementById('mobileno').focus();
            return false;
        }
}

HTML:

Input:<input type="text" id="mobileno">
<button onclick="submitButton();" >Submit</button>

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

What is the difference between getText() and getAttribute() in Selenium WebDriver?

getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like

<input name="Name Locator" value="selenium">Hello</input>

Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".

Returns:

The attribute's current value or null if the value is not set.

driver.findElement(By.name("Name Locator")).getAttribute("value")  //

The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.

getText() -> delivers the innerText of a WebElement. Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.

Returns:

The innerText of this element.

driver.findElement(By.name("Name Locator")).getText();

'Hello' will appear

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

Your vm does not find the class org/apache/juli/logging/LogFactory check if this class is present in the tomcat-juli.jar that you use (unzip it and search the file), if it's not present download the library from apache web site else if it's present put the tomcat-juli.jar in a path (the lib directory) that Tomcat use to load classes. If your Tomcat does not find it you can copy the jar in the lib directory of the JRE that you are using.

Can I apply the required attribute to <select> fields in HTML5?

In html5 you can do using the full expression:

<select required="required">

I don't know why the short expression doesn't work, but try this one. It will solve.

Unable to execute dex: Multiple dex files define

Go to Project/properties and Java Built Path and unchecked the Android Private Libraries

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

How to restore the menu bar in Visual Studio Code

Press Ctrl + Shift + P to open the Command Palette, then write command : Toggle Menu Bar

Entity Framework 5 Updating a Record

foreach(PropertyInfo propertyInfo in original.GetType().GetProperties()) {
    if (propertyInfo.GetValue(updatedUser, null) == null)
        propertyInfo.SetValue(updatedUser, propertyInfo.GetValue(original, null), null);
}
db.Entry(original).CurrentValues.SetValues(updatedUser);
db.SaveChanges();

Create a tar.xz in one command

Quick Solution

tarxz() { tar cf - "$1" | xz -4e > "$1".tar.xz ; }
tarxz name_of_directory

(Notice, not name_of_directory/)


Using xz compression options

If you want to use compression options for xz, or if you are using tar on MacOS, you probably want to avoid the tar -cJf syntax.

According to man xz, the way to do this is:

tar cf - filename | xz -4e > filename.tar.xz

Because I liked Wojciech Adam Koszek's format, but not information:

  1. c creates a new archive for the specified files.
  2. f reads from a directory (best to put this second because -cf != -fc)
  3. - outputs to Standard Output
  4. | pipes output to the next command
  5. xz -4e calls xz with the -4e compression option. (equal to -4 --extreme)
  6. > filename.tar.xz directs the tarred and compressed file to filename.tar.xz

where -4e is, use your own compression options. I often use -k to --keep the original file and -9 for really heavy compression. -z to manually set xz to zip, though it defaults to zipping if not otherwise directed.

To uncompress and untar

To echo Rafael van Horn, to uncompress & untar (see note below):

xz -dc filename.tar.xz | tar x

Note: unlike Rafael's answer, use xz -dc instead of catxz. The docs recommend this in case you are using this for scripting. Best to have a habit of using -d or --decompress instead of unxz as well. However, if you must, using those commands from the command line is fine.

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

HTTP Error 503, the service is unavailable

I had the same issue for the longest time and I thought there was an issue with my code. Turns out, in the IIS server, my application pool for that particular project was stopped. I turned it back on and that fixed the issue. Error 503 is most likely related to the Application Pool

Getting value of select (dropdown) before change

_x000D_
_x000D_
var last_value;
var current_value;
$(document).on("click","select",function(){
    last_value = $(this).val();
}).on("change","select",function(){
    current_value = $(this).val();

    console.log('last value - '+last_value);
    console.log('current value - '+current_value);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="test">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
</select>
_x000D_
_x000D_
_x000D_

Delete terminal history in Linux

You can clear your bash history like this:

history -cw

C++ equivalent of Java's toString?

You can also do it this way, allowing polymorphism:

class Base {
public:
   virtual std::ostream& dump(std::ostream& o) const {
      return o << "Base: " << b << "; ";
   }
private:
  int b;
};

class Derived : public Base {
public:
   virtual std::ostream& dump(std::ostream& o) const {
      return o << "Derived: " << d << "; ";
   }
private:
   int d;
}

std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }

Extract time from moment js object

You can do something like this

var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');

Remove Android App Title Bar

Just change the theme in the design view of your activity to NoActionBar like the one here

How can I read the client's machine/computer name from the browser?

Try getting the client computer name in Mozilla Firefox by using the code given below.

netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 

var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;

Also, the same piece of code can be put as an extension, and it can called from your web page.

Please find the sample code below.

Extension code:

var myExtension = {
  myListener: function(evt) {

//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' ); 
var dnsComp = Components.classes["@mozilla.org/network/dns-service;1"]; 
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;    
  }
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage

Webpage Code:

<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{ 
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>

</form>
</body>
</html>

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Get characters after last / in url

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

How to get selenium to wait for ajax response?

This work for me

public  void waitForAjax(WebDriver driver) {
    new WebDriverWait(driver, 180).until(new ExpectedCondition<Boolean>(){
        public Boolean apply(WebDriver driver) {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            return (Boolean) js.executeScript("return jQuery.active == 0");
        }
    });
}

Best way to replace multiple characters in a string?

How about this?

def replace_all(dict, str):
    for key in dict:
        str = str.replace(key, dict[key])
    return str

then

print(replace_all({"&":"\&", "#":"\#"}, "&#"))

output

\&\#

similar to answer

get next and previous day with PHP

just in case if you want next day or previous day from today's date

date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y")));

just change the "-1" to the "+1" regards, Yosafat

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

how to prevent adding duplicate keys to a javascript array

You can try this:

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el);
});

Easiest way to find duplicate values in a JavaScript array

Delete all rows with timestamp older than x days

DELETE FROM on_search 
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))

How do I pass parameters to a jar file at the time of execution?

To pass arguments to the jar:

java -jar myjar.jar one two

You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf file of a JAR).

String one = args[0];  
String two = args[1];  

gradle build fails on lint task

if abortOnError false will not resolve your problem, you can try this.

lintOptions {
    checkReleaseBuilds false
}

How to verify a Text present in the loaded page through WebDriver

If you are not bothered about the location of the text present, then you could use Driver.PageSource property as below:

Driver.PageSource.Contains("expected message");

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

They way I did it was by selecting all of the data

select * from myTable and then right-clicking on the result set and chose "Save results as..." a csv file.

Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.

Font Awesome 5 font-family issue

I didn't want to use the 'all' version, so searched the 'fontawesome-all.min.css' file (previously included in the header) for 'family' tag and found at the end a declaration @font-face{font-family:**Font Awesome\ 5 Free**;font-style:normal;

So, in the stylesheet for an element where I wanted to use the content: "\f0c8"; code, I've added (or changed to) font-family: Font Awesome\ 5 Free; and it worked.

.frb input[type="checkbox"] ~ label:before {
    font-family: Font Awesome\ 5 Free;
    content: "\f0c8";
    font-weight: 900;
    position: absolute;
}

Exporting data In SQL Server as INSERT INTO

In SSMS in the Object Explorer, right click on the database, right-click and pick "Tasks" and then "Generate Scripts".

This will allow you to generate scripts for a single or all tables, and one of the options is "Script Data". If you set that to TRUE, the wizard will generate a script with INSERT INTO () statement for your data.

If using 2008 R2 or 2012 it is called something else, see screenshot below this one

alt text

2008 R2 or later eg 2012

Select "Types of Data to Script" which can be "Data Only", "Schema and Data" or "Schema Only" - the default).

enter image description here

And then there's a "SSMS Addin" Package on Codeplex (including source) which promises pretty much the same functionality and a few more (like quick find etc.)

alt text

How can I get nth element from a list?

I know it's an old post ... but it may be useful for someone ... in a "functional" way ...

import Data.List

safeIndex :: [a] -> Int -> Maybe a
safeIndex xs i 
        | (i> -1) && (length xs > i) = Just (xs!!i)
        | otherwise = Nothing

Which ChromeDriver version is compatible with which Chrome Browser version?

I found, that chrome and chromedriver versions support policy has changed recently.

As stated on downloads page:

There is general guide to select version of crhomedriver for specific chrome version: https://sites.google.com/a/chromium.org/chromedriver/downloads/version-selection

Here is excerpt:

  • First, find out which version of Chrome you are using. Let's say you have Chrome 72.0.3626.81.
  • Take the Chrome version number, remove the last part, and append the result to URL "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_". For example, with Chrome version 72.0.3626.81, you'd get a URL "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_72.0.3626".
  • Use the URL created in the last step to retrieve a small file containing the version of ChromeDriver to use. For example, the above URL will get your a file containing "72.0.3626.69". (The actual number may change in the future, of course.)
  • Use the version number retrieved from the previous step to construct the URL to download ChromeDriver. With version 72.0.3626.69, the URL would be "https://chromedriver.storage.googleapis.com/index.html?path=72.0.3626.69/".
  • After the initial download, it is recommended that you occasionally go through the above process again to see if there are any bug fix releases.

Note, that this version selection algorithm can be easily automated. For example, simple powershell script in another answer has automated chromedriver updating on windows platform.

Reset MySQL root password using ALTER USER statement after install on Mac

On MySQL 5.7.x you need to switch to native password to be able to change it, like:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';

How to get value of Radio Buttons?

For Win Forms :

To get the value (assuming that you want the value, not the text) out of a radio button, you get the Checked property:

string value = "";
bool isChecked = radioButton1.Checked;
if(isChecked )
  value=radioButton1.Text;
else
  value=radioButton2.Text;

For Web Forms :

<asp:RadioButtonList ID="rdoPriceRange" runat="server" RepeatLayout="Flow">
    <asp:ListItem Value="Male">Male</asp:ListItem>
    <asp:ListItem Value="Female">Female</asp:ListItem>
</asp:RadioButtonList>

And CS-in some button click

string value=rdoPriceRange.SelectedItem.Value.ToString();

Calling stored procedure from another stored procedure SQL Server

You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:

SELECT @NewIdOutputParam = SCOPE_IDENTITY()

Then in test1, retrieve it like so:

DECLARE @NewId INTEGER
EXECUTE test2 @NewId OUTPUT
-- Now use @NewId as needed

Exception thrown inside catch block - will it be caught again?

The Java Language Specification says in section 14.19.1:

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

  • If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

Reference: http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134

In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.

One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.

EntityType has no key defined error

All is right but in my case i have two class like this

namespace WebAPI.Model
{
   public class ProductsModel
{ 
        [Table("products")]
        public class Products
        {
            [Key]
            public int slno { get; set; }

            public int productId { get; set; }
            public string ProductName { get; set; }

            public int Price { get; set; }
}
        }
    }

After deleting the upper class it works fine for me.

OpenCV get pixel channel value from Mat image

The below code works for me, for both accessing and changing a pixel value.

For accessing pixel's channel value :

for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            uchar col = intensity.val[k]; 
        }   
    }
}

For changing a pixel value of a channel :

uchar pixValue;
for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b &intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            // calculate pixValue
            intensity.val[k] = pixValue;
        }
     }
}

`

Source : Accessing pixel value

Git: How do I list only local branches?

Other way for get a list just local branch is:

git branch -a | grep -v 'remotes'

How do I rename a local Git branch?

Just three steps to replicate change in name on remote as well as on GitHub:

Step 1 git branch -m old_branchname new_branchname

Step 2 git push origin :old_branchname new_branchname

Step 3 git push --set-upstream origin new_branchname

How to append elements at the end of ArrayList in Java?

I ran into a similar problem and just passed the end of the array to the ArrayList.add() index param like so:

public class Stack {

    private ArrayList<String> stringList = new ArrayList<String>();

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        stringList.add(stringList.size(), random);
    }

}

Want to show/hide div based on dropdown box selection

https://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-select-box It's working well in my case

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $("select").change(function(){_x000D_
        $(this).find("option:selected").each(function(){_x000D_
            var optionValue = $(this).attr("value");_x000D_
            if(optionValue){_x000D_
                $(".box").not("." + optionValue).hide();_x000D_
                $("." + optionValue).show();_x000D_
            } else{_x000D_
                $(".box").hide();_x000D_
            }_x000D_
        });_x000D_
    }).change();_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>jQuery Show Hide Elements Using Select Box</title>_x000D_
<style>_x000D_
    .box{_x000D_
        color: #fff;_x000D_
        padding: 50px;_x000D_
        display: none;_x000D_
        margin-top: 10px;_x000D_
    }_x000D_
    .red{ background: #ff0000; }_x000D_
    .green{ background: #228B22; }_x000D_
    .blue{ background: #0000ff; }_x000D_
</style>_x000D_
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div>_x000D_
        <select>_x000D_
            <option>Choose Color</option>_x000D_
            <option value="red">Red</option>_x000D_
            <option value="green">Green</option>_x000D_
            <option value="blue">Blue</option>_x000D_
        </select>_x000D_
    </div>_x000D_
    <div class="red box">You have selected <strong>red option</strong> so i am here</div>_x000D_
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>_x000D_
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to create NSIndexPath for TableView

Use [NSIndexPath indexPathForRow:inSection:] to quickly create an index path.

Edit: In Swift 3:

let indexPath = IndexPath(row: rowIndex, section: sectionIndex)

Swift 5

IndexPath(row: 0, section: 0)

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

Can a background image be larger than the div itself?

This could help. It requires the footer height to be a fixed number. Basically, you have a div inside the footer div with it's normal content, with position: absolute, and then the image with position: relative, a negative z-index so it stays "below" everything, and a negative top value of the footer's height minus the image height (in my example, 50px - 600px = -550px). Tested in Chrome 8, FireFox 3.6 and IE 9.

git status shows fatal: bad object HEAD

I solved this by renaming the branch in the file .git/refs/remotes/origin/HEAD.

How to access a preexisting collection with Mongoose?

You can do something like this, than you you'll access the native mongodb functions inside mongoose:

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/local');

var connection = mongoose.connection;

connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', function () {

    connection.db.collection("YourCollectionName", function(err, collection){
        collection.find({}).toArray(function(err, data){
            console.log(data); // it will print your collection data
        })
    });

});

insert data into database with codeigniter

Try this in your model:

function order_summary_insert()
    $OrderLines=$this->input->post('orderlines');
    $CustomerName=$this->input->post('customer');
    $data = array(
        'OrderLines'=>$OrderLines,
        'CustomerName'=>$CustomerName
    );

    $this->db->insert('Customer_Orders',$data);
}

Try to use controller just to control the view and models always post your values in model. it makes easy to understand. Your controller will be:

function new_blank_order_summary() {
    $this->sales_model->order_summary_insert($data);
    $this->load->view('sales/new_blank_order_summary');
}

Run as java application option disabled in eclipse

You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".

Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X to open up a context menu, then press J.

How do I force a vertical scrollbar to appear?

Give your body tag an overflow: scroll;

body {
    overflow: scroll;
}

or if you only want a vertical scrollbar use overflow-y

body {
    overflow-y: scroll;
}

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Another solution I've found is NOT to use the transformations but just have a separate config file, e.g. app.Release.config. Then add this line to your csproj file.

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <AppConfig>App.Release.config</AppConfig>
  </PropertyGroup>

This will not only generate the right myprogram.exe.config file but if you're using Setup and Deployment Project in Visual Studio to generate MSI, it'll force the deployment project to use the correct config file when packaging.

Generate HTML table from 2D JavaScript array

Based on the accepted solution:

function createTable (tableData) {
  const table = document.createElement('table').appendChild(
    tableData.reduce((tbody, rowData) => {
      tbody.appendChild(
        rowData.reduce((tr, cellData) => {
          tr.appendChild(
            document
              .createElement('td')
              .appendChild(document.createTextNode(cellData))
          )
          return tr
        }, document.createElement('tr'))
      )
      return tbody
    }, document.createElement('tbody'))
  )

  document.body.appendChild(table)
}

createTable([
  ['row 1, cell 1', 'row 1, cell 2'],
  ['row 2, cell 1', 'row 2, cell 2']
])

With a simple change it is possible to return the table as HTML element.

Dialog to pick image from gallery or from camera

If you want to get the image from gallery or capture the image and set it to the imageview in portrait mode then following code will help you..

In onCreate()

imageViewRound.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            selectImage();
        }
    });




    private void selectImage() {
    Constants.iscamera = true;
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

     TextView title = new TextView(context);
     title.setText("Add Photo!");
        title.setBackgroundColor(Color.BLACK);
        title.setPadding(10, 15, 15, 10);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.WHITE);
        title.setTextSize(22);


    AlertDialog.Builder builder = new AlertDialog.Builder(
            AddContactActivity.this);



    builder.setCustomTitle(title);

    // builder.setTitle("Add Photo!");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                // Intent intent = new
                // Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                Intent intent = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                /*
                 * File photo = new
                 * File(Environment.getExternalStorageDirectory(),
                 * "Pic.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT,
                 * Uri.fromFile(photo)); imageUri = Uri.fromFile(photo);
                 */
                // startActivityForResult(intent,TAKE_PICTURE);

                Intent intents = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

                intents.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

                // start the image capture Intent
                startActivityForResult(intents, TAKE_PICTURE);

            } else if (items[item].equals("Choose from Library")) {
                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(
                        Intent.createChooser(intent, "Select Picture"),
                        SELECT_PICTURE);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}




    @SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case SELECT_PICTURE:
        Bitmap bitmap = null;
        if (resultCode == RESULT_OK) {
            if (data != null) {


                try {
                    Uri selectedImage = data.getData();
                    String[] filePath = { MediaStore.Images.Media.DATA };
                    Cursor c = context.getContentResolver().query(
                            selectedImage, filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    imageViewRound.setVisibility(View.VISIBLE);
                    // Bitmap thumbnail =
                    // (BitmapFactory.decodeFile(picturePath));
                    Bitmap thumbnail = decodeSampledBitmapFromResource(
                            picturePath, 500, 500);

                    // rotated
                    Bitmap thumbnail_r = imageOreintationValidator(
                            thumbnail, picturePath);
                    imageViewRound.setBackground(null);
                    imageViewRound.setImageBitmap(thumbnail_r);
                    IsImageSet = true;
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        break;
    case TAKE_PICTURE:
        if (resultCode == RESULT_OK) {

            previewCapturedImage();

        }

        break;
    }

}



 @SuppressLint("NewApi")
private void previewCapturedImage() {
    try {
        // hide video preview

        imageViewRound.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 500, 500,
                false);

        // rotated
        Bitmap thumbnail_r = imageOreintationValidator(resizedBitmap,
                fileUri.getPath());

        imageViewRound.setBackground(null);
        imageViewRound.setImageBitmap(thumbnail_r);
        IsImageSet = true;
        Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG)
                .show();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}






    // for roted image......
private Bitmap imageOreintationValidator(Bitmap bitmap, String path) {

    ExifInterface ei;
    try {
        ei = new ExifInterface(path);
        int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            bitmap = rotateImage(bitmap, 90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            bitmap = rotateImage(bitmap, 180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            bitmap = rotateImage(bitmap, 270);
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bitmap;
}



private Bitmap rotateImage(Bitmap source, float angle) {

    Bitmap bitmap = null;
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    try {
        bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(),
                source.getHeight(), matrix, true);
    } catch (OutOfMemoryError err) {
        source.recycle();
        Date d = new Date();
        CharSequence s = DateFormat
                .format("MM-dd-yy-hh-mm-ss", d.getTime());
        String fullPath = Environment.getExternalStorageDirectory()
                + "/RYB_pic/" + s.toString() + ".jpg";
        if ((fullPath != null) && (new File(fullPath).exists())) {
            new File(fullPath).delete();
        }
        bitmap = null;
        err.printStackTrace();
    }
    return bitmap;
}




public static Bitmap decodeSampledBitmapFromResource(String pathToFile,
        int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathToFile, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    Log.e("inSampleSize", "inSampleSize______________in storage"
            + options.inSampleSize);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(pathToFile, options);
}




public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

    }

    return inSampleSize;
}




public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}






private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}






public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

Hope This will help you....!!!

If targetSdkVersion is higher than 24, then FileProvider is used to grant access.

Create an xml file(Path: res\xml) provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Add a Provider in AndroidManifest.xml

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths"/>
</provider>

and replace

return Uri.fromFile(getOutputMediaFile(type));

To

               return FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID + ".provider", getOutputMediaFile(type));

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The iPhone 6+ renders internally using @3x assets at a virtual resolution of 2208×1242 (with 736x414 points), then samples that down for display. The same as using a scaled resolution on a Retina MacBook — it lets them hit an integral multiple for pixel assets while still having e.g. 12 pt text look the same size on the screen.

So, yes, the launch screens need to be that size.

The maths:

The 6, the 5s, the 5, the 4s and the 4 are all 326 pixels per inch, and use @2x assets to stick to the approximately 160 points per inch of all previous devices.

The 6+ is 401 pixels per inch. So it'd hypothetically need roughly @2.46x assets. Instead Apple uses @3x assets and scales the complete output down to about 84% of its natural size.

In practice Apple has decided to go with more like 87%, turning the 1080 into 1242. No doubt that was to find something as close as possible to 84% that still produced integral sizes in both directions — 1242/1080 = 2208/1920 exactly, whereas if you'd turned the 1080 into, say, 1286, you'd somehow need to render 2286.22 pixels vertically to scale well.

How to round a Double to the nearest Int in swift?

There is a round available in the Foundation library (it's actually in Darwin, but Foundation imports Darwin and most of the time you'll want to use Foundation instead of using Darwin directly).

import Foundation

users = round(users)

Running your code in a playground and then calling:

print(round(users))

Outputs:

15.0

round() always rounds up when the decimal place is >= .5 and down when it's < .5 (standard rounding). You can use floor() to force rounding down, and ceil() to force rounding up.

If you need to round to a specific place, then you multiply by pow(10.0, number of places), round, and then divide by pow(10, number of places):

Round to 2 decimal places:

let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)

Outputs:

10.12

Note: Due to the way floating point math works, rounded may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.

Sass - Converting Hex to RGBa for background opacity

The rgba() function can accept a single hex color as well decimal RGB values. For example, this would work just fine:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

If you ever need to break the hex color into RGB components, though, you can use the red(), green(), and blue() functions to do so:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         

Source

React-Native: Module AppRegistry is not a registered callable module

I had this issue - across iOS & Android, developing on Mac - after I had been fiddling with a dependency's code in the node_modules dir.

I solved it with:

rm -rf node_modules
npm i
npx pod-install ios

Which basically just re-installs your dependencies fresh.

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

Visualizing decision tree in scikit-learn

Here is the minimal code to have a nice looking graph with just 3 lines of code :

from sklearn import tree
import pydotplus

dot_data=tree.export_graphviz(dt,filled=True,rounded=True)
graph=pydotplus.graph_from_dot_data(dot_data)
graph.write_png('tree.png')    
plt.imshow(plt.imread('tree.png'))

I have added the plt.imgshow to view the graph it Jupyter Notebook. You can ignore it if you are only interested in saving the png file.

I installed the following dependencies:

pip3 install graphviz
pip3 install pydotplus

For MacOs the pip version of Graphviz did not work. Following Graphviz's official documentation I installed it with brew and everything worked fine.

brew install graphviz

enter image description here

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Class Not Found: Empty Test Suite in IntelliJ

solved by manually run testClasses task before running unit test.

Fitting empirical distribution to theoretical ones with Scipy (Python)?

AFAICU, your distribution is discrete (and nothing but discrete). Therefore just counting the frequencies of different values and normalizing them should be enough for your purposes. So, an example to demonstrate this:

In []: values= [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
In []: counts= asarray(bincount(values), dtype= float)
In []: cdf= counts.cumsum()/ counts.sum()

Thus, probability of seeing values higher than 1 is simply (according to the complementary cumulative distribution function (ccdf):

In []: 1- cdf[1]
Out[]: 0.40000000000000002

Please note that ccdf is closely related to survival function (sf), but it's also defined with discrete distributions, whereas sf is defined only for contiguous distributions.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

css3 text-shadow in IE9

Yes, but not how you would imagine. According to caniuse (a very good resource) there is no support and no polyfill available for adding text-shadow support to IE9. However, IE has their own proprietary text shadow (detailed here).

Example implementation, taken from their website (works in IE5.5 through IE9):

p.shadow { 
    filter: progid:DXImageTransform.Microsoft.Shadow(color=#0000FF,direction=45);
}

For cross-browser compatibility and future-proofing of code, remember to also use the CSS3 standard text-shadow property (detailed here). This is especially important considering that IE10 has officially announced their intent to drop support for legacy dx filters. Going forward, IE10+ will only support the CSS3 standard text-shadow.

How to create a simple checkbox in iOS?

On iOS there is the switch UI component instead of a checkbox, look into the UISwitch class. The property on (boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

How to check whether dynamically attached event listener exists or not?

I usually attach a class to the element then check if the class exist like this:

let element = document.getElementsById("someElement");

if(!element.classList.contains('attached-listener'))
   element.addEventListener("click", this.itemClicked);

element.classList.add('attached-listener');

How to serialize Object to JSON?

The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

import javax.json.*;

JsonObject value = Json.createObjectBuilder()
 .add("firstName", "John")
 .add("lastName", "Smith")
 .add("age", 25)
 .add("address", Json.createObjectBuilder()
     .add("streetAddress", "21 2nd Street")
     .add("city", "New York")
     .add("state", "NY")
     .add("postalCode", "10021"))
 .add("phoneNumber", Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("type", "home")
         .add("number", "212 555-1234"))
     .add(Json.createObjectBuilder()
         .add("type", "fax")
         .add("number", "646 555-4567")))
 .build();

JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();

But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

how to create inline style with :before and :after

You can, using CSS variables (more precisely called CSS custom properties).

  • Set your variable in your style attribute:
    style="--my-color-var: orange;"
  • Use the variable in your stylesheet:
    background-color: var(--my-color-var);

Browser compatibility

Minimal example:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  position: relative;
  border: 1px solid black;
}

div:after {
  background-color: var(--my-color-var);
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
_x000D_
_x000D_

Your example:

_x000D_
_x000D_
.bubble {
  position: relative;
  width: 30px;
  height: 15px;
  padding: 0;
  background: #FFF;
  border: 1px solid #000;
  border-radius: 5px;
  text-align: center;
  background-color: var(--bubble-color);
}

.bubble:after {
  content: "";
  position: absolute;
  top: 4px;
  left: -4px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent var(--bubble-color);
   display: block;
  width: 0;
  z-index: 1;
  
}

.bubble:before {
  content: "";
  position: absolute;
  top: 4px;
  left: -5px;
  border-style: solid;
  border-width: 3px 4px 3px 0;
  border-color: transparent #000;
  display: block;
  width: 0;
  z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
_x000D_
_x000D_

svn over HTTP proxy

If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.

TypeError: Router.use() requires middleware function but got a Object

In any one of your js pages you are missing

module.exports = router;

Check and verify all your JS pages

htaccess Access-Control-Allow-Origin

BTW: the .htaccess config must be done on the server hosting the API. For example you create an AngularJS app on x.com domain and create a Rest API on y.com, you should set Access-Control-Allow-Origin "*" in the .htaccess file on the root folder of y.com not x.com :)

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Also as Lukas mentioned make sure you have enabled mod_headers if you use Apache

What is the difference between a candidate key and a primary key?

A primary key is a column (or columns) in a table that uniquely identifies the rows in that table.

CUSTOMERS


CustomerNo  FirstName   LastName
1   Sally   Thompson
2   Sally   Henderson
3   Harry   Henderson
4   Sandra  Wellington

For example, in the table above, CustomerNo is the primary key.

The values placed in primary key columns must be unique for each row: no duplicates can be tolerated. In addition, nulls are not allowed in primary key columns.

So, having told you that it is possible to use one or more columns as a primary key, how do you decide which columns (and how many) to choose?

Well there are times when it is advisable or essential to use multiple columns. However, if you cannot see an immediate reason to use multiple columns, then use one. This isn't an absolute rule, it is simply advice. However, primary keys made up of single columns are generally easier to maintain and faster in operation. This means that if you query the database, you will usually get the answer back faster if the tables have single column primary keys.

Next question — which column should you pick? The easiest way to choose a column as a primary key (and a method that is reasonably commonly employed) is to get the database itself to automatically allocate a unique number to each row.

In a table of employees, clearly any column like FirstName is a poor choice since you cannot control employee's first names. Often there is only one choice for the primary key, as in the case above. However, if there is more than one, these can be described as 'candidate keys' — the name reflects that they are candidates for the responsible job of primary key.

List of macOS text editors and code editors

I have installed both Smultron and Textwrangler, but find myself using Smultron most of the time.

Importing class/java files in Eclipse

You can import a bunch of .java files to your existing project without creating a new project. Here are the steps:

  1. Right-click on the Default Package in the Project Manager pane underneath your project and choose Import
  2. An Import Wizard window will display. Choose File system and select the Next button
  3. You are now prompted to choose a file
  4. Simply browse your folder with .java files in it
  5. Select desired .java files
  6. Click on Finish to finish the import wizard

Check the following webpage for more information: http://people.cs.uchicago.edu/~kaharris/10200/tutorials/eclipse/Step_04.html

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

Forcing label to flow inline with input that they label

What I did so that input didn't take up the whole line, and be able to place the input in a paragraph, I used a span tag and display to inline-block

html:

<span>cluster:
        <input class="short-input" type="text" name="cluster">
</span>

css:

span{display: inline-block;}

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

This should fix the error

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.7</version>
     <dependencies>
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-filtering</artifactId>
             <version>1.3</version>
          </dependency>
      </dependencies>
</plugin>

What's the most elegant way to cap a number to a segment?

If you are able to use es6 arrow functions, you could also use a partial application approach:

const clamp = (min, max) => (value) =>
    value < min ? min : value > max ? max : value;

clamp(2, 9)(8); // 8
clamp(2, 9)(1); // 2
clamp(2, 9)(10); // 9

or

const clamp2to9 = clamp(2, 9);
clamp2to9(8); // 8
clamp2to9(1); // 2
clamp2to9(10); // 9

Ruby: How to convert a string to boolean

A gem like https://rubygems.org/gems/to_bool can be used, but it can easily be written in one line using a regex or ternary.

regex example:

boolean = (var.to_s =~ /^true$/i) == 0

ternary example:

boolean = var.to_s.eql?('true') ? true : false

The advantage to the regex method is that regular expressions are flexible and can match a wide variety of patterns. For example, if you suspect that var could be any of "True", "False", 'T', 'F', 't', or 'f', then you can modify the regex:

boolean = (var.to_s =~ /^[Tt].*$/i) == 0

Android: adb pull file on desktop

On Windows, start up Command Prompt (cmd.exe) or PowerShell (powershell.exe). To do this quickly, open a Run Command window by pressing Windows Key + R. In the Run Command window, type "cmd.exe" to launch Command Prompt; However, to start PowerShell instead, then type "powershell". If you are connecting your Android device to your computer using a USB cable, then you will need to check whether your device is communicating with adb by entering the command below:

# adb devices -l  

Next, pull (copy) the file from your Android device over to Windows. This can be accomplished by entering the following command:

# adb pull /sdcard/log.txt %HOME%\Desktop\log.txt  

Optionally, you may enter this command instead:

# adb pull /sdcard/log.txt C:\Users\admin\Desktop\log.txt 

Random float number generation

Take a look at Boost.Random. You could do something like this:

float gen_random_float(float min, float max)
{
    boost::mt19937 rng;
    boost::uniform_real<float> u(min, max);
    boost::variate_generator<boost::mt19937&, boost::uniform_real<float> > gen(rng, u);
    return gen();
}

Play around, you might do better passing the same mt19937 object around instead of constructing a new one every time, but hopefully you get the idea.

How to set delay in vbscript

Here is an update to the solution provided by @user235218 that allows you to specify number of milliseconds you require.

Note: The -n option is the number of retries and the -w is the timeout in milliseconds for ping. I chose the 127.255.255.254 address because it is in the loopback range and ms windows doesn’t respond to it.

I also doubt this will provide millisecond accuracy but on another note i tried it in an application using the ms script control and whilst the built in sleep function locked up the interface this method didn't.

If somebody can provide an explanation for why this method didn't lock up the interface we could make this answer more complete. Both sleep functions where run in the user thread.

Const WshHide = 0
Const WAIT_ON_RETURN = True

Sub Sleep(ByVal ms)

   Dim shell 'As WScript.Shell

   If Not IsNumeric(ms) Then _
       Exit Sub

   Set shell = CreateObject("WScript.Shell")

   Call shell.Run("%COMSPEC% /c ping -n 1 -w " & ms & " 127.255.255.254 > nul", WshHide, WAIT_ON_RETURN)

End Sub

How to refresh Gridview after pressed a button in asp.net

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.

Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    GridView1.DataBind()
End Sub

Difference between "read commited" and "repeatable read"

Repeatable Read

The state of the database is maintained from the start of the transaction. If you retrieve a value in session1, then update that value in session2, retrieving it again in session1 will return the same results. Reads are repeatable.

session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron

session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;

session1> SELECT firstname FROM names WHERE id = 7;
Aaron

Read Committed

Within the context of a transaction, you will always retrieve the most recently committed value. If you retrieve a value in session1, update it in session2, then retrieve it in session1again, you will get the value as modified in session2. It reads the last committed row.

session1> BEGIN;
session1> SELECT firstname FROM names WHERE id = 7;
Aaron

session2> BEGIN;
session2> SELECT firstname FROM names WHERE id = 7;
Aaron
session2> UPDATE names SET firstname = 'Bob' WHERE id = 7;
session2> SELECT firstname FROM names WHERE id = 7;
Bob
session2> COMMIT;

session1> SELECT firstname FROM names WHERE id = 7;
Bob

Makes sense?

What is the difference between a strongly typed language and a statically typed language?

Answer is already given above. Trying to differentiate between strong vs week and static vs dynamic concept.

What is Strongly typed VS Weakly typed?

Strongly Typed: Will not be automatically converted from one type to another

In Go or Python like strongly typed languages "2" + 8 will raise a type error, because they don't allow for "type coercion".

Weakly (loosely) Typed: Will be automatically converted to one type to another: Weakly typed languages like JavaScript or Perl won't throw an error and in this case JavaScript will results '28' and perl will result 10.

Perl Example:

my $a = "2" + 8;
print $a,"\n";

Save it to main.pl and run perl main.pl and you will get output 10.

What is Static VS Dynamic type?

In programming, programmer define static typing and dynamic typing with respect to the point at which the variable types are checked. Static typed languages are those in which type checking is done at compile-time, whereas dynamic typed languages are those in which type checking is done at run-time.

  • Static: Types checked before run-time
  • Dynamic: Types checked on the fly, during execution

What is this means?

In Go it checks typed before run-time (static check). This mean it not only translates and type-checks code it’s executing, but it will scan through all the code and type error would be thrown before the code is even run. For example,

package main

import "fmt"

func foo(a int) {
    if (a > 0) {
        fmt.Println("I am feeling lucky (maybe).")
    } else {
        fmt.Println("2" + 8)
    }
}

func main() {
    foo(2)
}

Save this file in main.go and run it, you will get compilation failed message for this.

go run main.go
# command-line-arguments
./main.go:9:25: cannot convert "2" (type untyped string) to type int
./main.go:9:25: invalid operation: "2" + 8 (mismatched types string and int)

But this case is not valid for Python. For example following block of code will execute for first foo(2) call and will fail for second foo(0) call. It's because Python is dynamically typed, it only translates and type-checks code it’s executing on. The else block never executes for foo(2), so "2" + 8 is never even looked at and for foo(0) call it will try to execute that block and failed.

def foo(a):
    if a > 0:
        print 'I am feeling lucky.'
    else:
        print "2" + 8
foo(2)
foo(0)

You will see following output

python main.py
I am feeling lucky.
Traceback (most recent call last):
  File "pyth.py", line 7, in <module>
    foo(0)
  File "pyth.py", line 5, in foo
    print "2" + 8
TypeError: cannot concatenate 'str' and 'int' objects

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

How to convert an NSTimeInterval (seconds) into minutes

All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:

NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long

int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;

Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)

Detecting request type in PHP (GET, POST, PUT or DELETE)

REST in PHP can be done pretty simple. Create http://example.com/test.php (outlined below). Use this for REST calls, e.g. http://example.com/test.php/testing/123/hello. This works with Apache and Lighttpd out of the box, and no rewrite rules are needed.

<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

switch ($method) {
  case 'PUT':
    do_something_with_put($request);  
    break;
  case 'POST':
    do_something_with_post($request);  
    break;
  case 'GET':
    do_something_with_get($request);  
    break;
  default:
    handle_error($request);  
    break;
}

javac: file not found: first.java Usage: javac <options> <source files>

If this is the problem then go to the place where the javac is present and then type

  1. notepad Yourfilename.java
  2. it will ask for creation of the file
  3. say yes and copy the code from your previous source file to this file
  4. now execute the cmd------>javac Yourfilename.java

It will work for sure.

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

I found the below stuff in ffmpeg Docs. Hope this helps! :)

Reference: http://ffmpeg.org/ffmpeg.html#toc-Generic-options

‘-report’ Dump full command line and console output to a file named program-YYYYMMDD-HHMMSS.log in the current directory. This file can be useful for bug reports. It also implies -loglevel verbose.

Note: setting the environment variable FFREPORT to any value has the same effect.

When to use NSInteger vs. int

Why use int at all?

Apple uses int because for a loop control variable (which is only used to control the loop iterations) int datatype is fine, both in datatype size and in the values it can hold for your loop. No need for platform dependent datatype here. For a loop control variable even a 16-bit int will do most of the time.

Apple uses NSInteger for a function return value or for a function argument because in this case datatype [size] matters, because what you are doing with a function is communicating/passing data with other programs or with other pieces of code; see the answer to When should I be using NSInteger vs int? in your question itself...

they [Apple] use NSInteger (or NSUInteger) when passing a value as an argument to a function or returning a value from a function.

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

How to check if AlarmManager already has an alarm set?

Working example with receiver (the top answer was just with action).

//starting
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), MyReceiver.class);
intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER);//my custom string action name
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1001, intent, PendingIntent.FLAG_CANCEL_CURRENT);//used unique ID as 1001
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), aroundInterval, pendingIntent);//first start will start asap

//and stopping
Intent intent = new Intent(getActivity(), MyReceiver.class);//the same as up
intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER);//the same as up
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1001, intent, PendingIntent.FLAG_CANCEL_CURRENT);//the same as up
alarmManager.cancel(pendingIntent);//important
pendingIntent.cancel();//important

//checking if alarm is working with pendingIntent
Intent intent = new Intent(getActivity(), MyReceiver.class);//the same as up
intent.setAction(MyReceiver.ACTION_ALARM_RECEIVER);//the same as up
boolean isWorking = (PendingIntent.getBroadcast(getActivity(), 1001, intent, PendingIntent.FLAG_NO_CREATE) != null);//just changed the flag
Log.d(TAG, "alarm is " + (isWorking ? "" : "not") + " working...");

It is worth to mention:

If the creating application later (process) re-retrieves the same kind of PendingIntent (same operation, same Intent's - action, data, categories, components, flags), it will receive a PendingIntent representing the same token if that is still valid, and can thus call cancel() to remove it.

In short, your PendingIntent should have the same features (operation and intent's structure) to take control over it.

Insert a string at a specific index

I wanted to compare the method using substring and the method using slice from Base33 and user113716 respectively, to do that I wrote some code

also have a look at this performance comparison, substring, slice

The code I used creates huge strings and inserts the string "bar " multiple times into the huge string

_x000D_
_x000D_
if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function (start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

String.prototype.splice = function (idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};


String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);

    return string + this;
};


function createString(size) {
    var s = ""
    for (var i = 0; i < size; i++) {
        s += "Some String "
    }
    return s
}


function testSubStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.insert(4, "bar ")
}

function testSpliceStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.splice(4, 0, "bar ")
}


function doTests(repeatMax, sSizeMax) {
    n = 1000
    sSize = 1000
    for (var i = 1; i <= repeatMax; i++) {
        var repeatTimes = n * (10 * i)
        for (var j = 1; j <= sSizeMax; j++) {
            var actualStringSize = sSize *  (10 * j)
            var s1 = createString(actualStringSize)
            var s2 = createString(actualStringSize)
            var start = performance.now()
            testSubStringPerformance(s1, repeatTimes)
            var end = performance.now()
            var subStrPerf = end - start

            start = performance.now()
            testSpliceStringPerformance(s2, repeatTimes)
            end = performance.now()
            var splicePerf = end - start

            console.log(
                "string size           =", "Some String ".length * actualStringSize, "\n",
                "repeat count          = ", repeatTimes, "\n",
                "splice performance    = ", splicePerf, "\n",
                "substring performance = ", subStrPerf, "\n",
                "difference = ", splicePerf - subStrPerf  // + = splice is faster, - = subStr is faster
                )

        }
    }
}

doTests(1, 100)
_x000D_
_x000D_
_x000D_

The general difference in performance is marginal at best and both methods work just fine (even on strings of length ~~ 12000000)

How to use enums in C++

I think your root issue is the use of . instead of ::, which will use the namespace.

Try:

enum Days {Saturday, Sunday, Tuesday, Wednesday, Thursday, Friday};
Days day = Days::Saturday;
if(Days::Saturday == day)  // I like literals before variables :)
{
    std::cout<<"Ok its Saturday";
}

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.

SQL to search objects, including stored procedures, in Oracle

i'm not sure if i understand you, but to query the source code of your triggers, procedures, package and functions you can try with the "user_source" table.

select * from user_source

C# Convert a Base64 -> byte[]

I've written an extension method for this purpose:

public static byte[] FromBase64Bytes(this byte[] base64Bytes)
{
    string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
    return Convert.FromBase64String(base64String);
}

Call it like this:

byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();

I hope it helps someone.

git visual diff between branches

Have a look at git show-branch

There's a lot you can do with core git functionality. It might be good to specify what you'd like to include in your visual diff. Most answers focus on line-by-line diffs of commits, where your example focuses on names of files affected in a given commit.

One visual that seems not to be addressed is how to see the commits that branches contain (whether in common or uniquely).

For this visual, I'm a big fan of git show-branch; it breaks out a well organized table of commits per branch back to the common ancestor. - to try it on a repo with multiple branches with divergences, just type git show-branch and check the output - for a writeup with examples, see Compare Commits Between Git Branches

How to Get a Specific Column Value from a DataTable?

As per the title of the post I just needed to get all values from a specific column. Here is the code I used to achieve that.

    public static IEnumerable<T> ColumnValues<T>(this DataColumn self)
    {
        return self.Table.Select().Select(dr => (T)Convert.ChangeType(dr[self], typeof(T)));
    }

numpy get index where value is true

A simple and clean way: use np.argwhere to group the indices by element, rather than dimension as in np.nonzero(a) (i.e., np.argwhere returns a row for each non-zero element).

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.argwhere(a>4)
array([[5],
       [6],
       [7],
       [8],
       [9]])

np.argwhere(a) is the same as np.transpose(np.nonzero(a)).

Note: You cannot use a(np.argwhere(a>4)) to get the corresponding values in a. The recommended way is to use a[(a>4).astype(bool)] or a[(a>4) != 0] rather than a[np.nonzero(a>4)] as they handle 0-d arrays correctly. See the documentation for more details. As can be seen in the following example, a[(a>4).astype(bool)] and a[(a>4) != 0] can be simplified to a[a>4].

Another example:

>>> a = np.array([5,-15,-8,-5,10])
>>> a
array([  5, -15,  -8,  -5,  10])
>>> a > 4
array([ True, False, False, False,  True])
>>> a[a > 4]
array([ 5, 10])
>>> a = np.add.outer(a,a)
>>> a
array([[ 10, -10,  -3,   0,  15],
       [-10, -30, -23, -20,  -5],
       [ -3, -23, -16, -13,   2],
       [  0, -20, -13, -10,   5],
       [ 15,  -5,   2,   5,  20]])
>>> a = np.argwhere(a>4)
>>> a
array([[0, 0],
       [0, 4],
       [3, 4],
       [4, 0],
       [4, 3],
       [4, 4]])
>>> [print(i,j) for i,j in a]
0 0
0 4
3 4
4 0
4 3
4 4

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account 
SET (student_education_facility_id) = ( 
    SELECT teacher.education_facility_id
    FROM user_account teacher
    WHERE teacher.user_account_id = teacher_id
    AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE user_type = 'ROLE_STUDENT'

Above are the sample update query...

You can write sub query with update SQL statement, you don't need to give alias name for that table. give alias name to sub query table. I tried and it's working fine for me....

Limit results in jQuery UI Autocomplete

Plugin: jquery-ui-autocomplete-scroll with scroller and limit results are beautiful

$('#task').autocomplete({
  maxShowItems: 5,
  source: myarray
});

AngularJS - Multiple ng-view in single template

It is possible to have multiple or nested views. But not by ng-view.

The primary routing module in angular does not support multiple views. But you can use ui-router. This is a third party module which you can get via Github, angular-ui/ui-router, https://github.com/angular-ui/ui-router . Also a new version of ngRouter (ngNewRouter) currently, is being developed. It is not stable at the moment. So I provide you a simple start up example with ui-router. Using it you can name views and specify which templates and controllers should be used for rendering them. Using $stateProvider you should specify how view placeholders should be rendered for specific state.

<body ng-app="main">
    <script type="text/javascript">
    angular.module('main', ['ui.router'])
    .config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) {
        $stateProvider
        .state('home', {
            url: '/',
            views: {
                'header': {
                    templateUrl: '/app/header.html'
                },
                'content': {
                    templateUrl: '/app/content.html'
                }
            }
        });
    }]);
    </script>
    <a ui-sref="home">home</a>
    <div ui-view="header">header</div>
    <div ui-view="content">content</div>
    <div ui-view="bottom">footer</div>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js">
</body>

You need referencing angularjs, and angular-ui.router for this sample.

$ bower install angular-ui-router

How to schedule a task to run when shutting down windows

I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.

Open URL in Java to get the content

It works for me. Please check if you are using the right imports?

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

CSS: Set Div height to 100% - Pixels

The best way to do this is to use view port styles. It just does the work and no other techniques needed.

Code:

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

CSS3 equivalent to jQuery slideUp and slideDown?

You could do something like this:

#youritem .fade.in {
    animation-name: fadeIn;
}

#youritem .fade.out {
    animation-name: fadeOut;
}

@keyframes fadeIn {
    0% {
        opacity: 0;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 1;
        transform: translateY(endYposition);
    }
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 0;
        transform: translateY(endYposition);
    }
}

Example - Slide and Fade:

This slides and animates the opacity - not based on height of the container, but on the top/coordinate. View example

Example - Auto-height/No Javascript: Here is a live sample, not needing height - dealing with automatic height and no javascript.
View example

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Different connections pools have different configs.

For example Tomcat (default) expects:

spring.datasource.ourdb.url=...

and HikariCP will be happy with:

spring.datasource.ourdb.jdbc-url=...

We can satisfy both without boilerplate configuration:

spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}

There is no property to define connection pool provider.

Take a look at source DataSourceBuilder.java

If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).

... so, we can easily replace connection pool provider using this maven configuration (pom.xml):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>       

    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>

https connection using CURL from command line

use --cacert to specify a .crt file. ca-root-nss.crt for example.

What's the difference between ng-model and ng-bind

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

Example Plunker

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • Registering the control with its parent form.

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

Example Plunker

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

  • Replacing the text content of the specified HTML element with the value of a given expression.

How to add Python to Windows registry

You can find the Python executable with this command:

C:\> where python.exe

It should return something like:

C:\Users\<user>\AppData\Local\enthought\Canopy32\User\python.exe

Open regedit, navigate to HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\<version>\PythonPath and add or edit the default key with this the value found in the first command. Logout, login and python should be found. SciKit can now be installed.

See Additional “application paths” in https://docs.python.org/2/using/windows.html#finding-modules for more details.

How to run python script with elevated privilege on windows

Here is a solution with an stdout redirection:

def elevate():
    import ctypes, win32com.shell.shell, win32event, win32process
    outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
    if ctypes.windll.shell32.IsUserAnAdmin():
        if os.path.isfile(outpath):
            sys.stderr = sys.stdout = open(outpath, 'w', 0)
        return
    with open(outpath, 'w+', 0) as outfile:
        hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
            lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
        while True:
            hr = win32event.WaitForSingleObject(hProc, 40)
            while True:
                line = outfile.readline()
                if not line: break
                sys.stdout.write(line)
            if hr != 0x102: break
    os.remove(outpath)
    sys.stderr = ''
    sys.exit(win32process.GetExitCodeProcess(hProc))

if __name__ == '__main__':
    elevate()
    main()

Set database timeout in Entity Framework

You can use DbContext.Database.CommandTimeout = 180; // seconds

It's pretty simple and no cast required.

Convert boolean result into number/integer

if you want integer x value change if 1 to 0 and if 0 to 1 you can use (x + 1) % 2

Trouble setting up git with my GitHub Account error: could not lock config file

So I know this thread is Old, but I had the same issue and fixed it. Hopefully this works for someone else.

When i tried using "sudo" or anything in powershell/cmd it was an unrecognized command. So i reinstalled git for windows, during the install it failed and pointed me to C:/ProgramFiles/git/etc/gitconfig I deleted that file, and reinstalled. Same Error when saving credentials, So i moved the newly created gitconfig from programfiles, to my HomePath location C:/Users/Name

Now I can save credentials under file-->Options-->git Finally, I can commit/push on githubdesktop

How to use ES6 Fat Arrow to .filter() an array of objects

As simple as you can use const adults = family.filter(({ age }) => age > 18 );

_x000D_
_x000D_
const family =[{"name":"Jack",  "age": 26},_x000D_
              {"name":"Jill",  "age": 22},_x000D_
              {"name":"James", "age": 5 },_x000D_
              {"name":"Jenny", "age": 2 }];_x000D_
_x000D_
const adults = family.filter(({ age }) => age > 18 );_x000D_
_x000D_
console.log(adults)
_x000D_
_x000D_
_x000D_

ASP.NET custom error page - Server.GetLastError() is null

Looking more closely at my web.config set up, one of the comments in this post is very helpful

in asp.net 3.5 sp1 there is a new parameter redirectMode

So we can amend customErrors to add this parameter:

<customErrors mode="RemoteOnly" defaultRedirect="~/errors/GeneralError.aspx" redirectMode="ResponseRewrite" />

the ResponseRewrite mode allows us to load the «Error Page» without redirecting the browser, so the URL stays the same, and importantly for me, exception information is not lost.

PHP Fatal error: Cannot redeclare class

This function will print a stack telling you where it was called from:

function PrintTrace() {
    $trace = debug_backtrace();
    echo '<pre>';
    $sb = array();
    foreach($trace as $item) {
        if(isset($item['file'])) {
            $sb[] = htmlspecialchars("$item[file]:$item[line]");
        } else {
            $sb[] = htmlspecialchars("$item[class]:$item[function]");
        }
    }
    echo implode("\n",$sb);
    echo '</pre>';
}

Call this function at the top of the file that includes your class.

Sometimes it will only print once, even though your class is being included two or more times. This is because PHP actually parses all the top-level classes in a file before executing any code and throws the fatal error immediately. To remedy this, wrap your class declaration in if(true) { ... }, which will move your class down a level in scope. Then you should get your two traces before PHP fatal errors.

This should help you find where you class is being included from multiple times in a complex project.

How to flatten only some dimensions of a numpy array

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

e.g. to flatten all but the last two dimensions:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

How do I get JSON data from RESTful service using Python?

Something like this should work unless I'm missing the point:

import json
import urllib2
json.load(urllib2.urlopen("url"))

How do I filter query objects by date range in Django?

Is simple,

YourModel.objects.filter(YOUR_DATE_FIELD__date=timezone.now())

Works for me

Resize UIImage by keeping Aspect ratio and width

thanks @Maverick1st the algorithm, I implemented it to Swift, in my case height is the input parameter

class func resizeImage(image: UIImage, newHeight: CGFloat) -> UIImage {

    let scale = newHeight / image.size.height
    let newWidth = image.size.width * scale
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
    image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

SELECT with a Replace()

if you want any hope of ever using an index, store the data in a consistent manner (with the spaces removed). Either just remove the spaces or add a persisted computed column, Then you can just select from that column and not have to add all the space removing overhead every time you run your query.

add a PERSISTED computed column:

ALTER TABLE Contacts ADD PostcodeSpaceFree AS Replace(Postcode, ' ', '') PERSISTED 
go
CREATE NONCLUSTERED INDEX IX_Contacts_PostcodeSpaceFree 
ON Contacts (PostcodeSpaceFree) --INCLUDE (covered columns here!!)
go

to just fix the column by removing the spaces use:

UPDATE Contacts
    SET Postcode=Replace(Postcode, ' ', '')

now you can search like this, either select can use an index:

--search the PERSISTED computed column
SELECT 
    PostcodeSpaceFree 
    FROM Contacts
    WHERE PostcodeSpaceFree  LIKE 'NW101%'

or

--search the fixed (spaces removed column)
SELECT 
    Postcode
    FROM Contacts
    WHERE PostcodeLIKE 'NW101%'

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

I've simply added

jQuery.browser = {
    msie: false,
    version: 0
};

after jquery script, because I don't care about IE anymore.

How do I change the android actionbar title and icon

For set Title :

getActionBar().setTitle("Title");

For set Icon :

getActionBar().setIcon(R.drawable.YOUR_ICON_NAME);

How to do while loops with multiple conditions

condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code

while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
    val,something1,something2 = getstuff()

    if something1 == 10:
        condition1 = True

    elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead    
    condition2 = True
# ihope it can be helpfull

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I'm using chrome too and facing same problem on my localhost. I did a lot of things like clear using CCleaner and restart OS. But my problem was solved with clearing cookie. In order to clear cookie:

  1. Go to Chrome settings > Privacy > Content Settings > Cookie > All cookie and Site Data > Delete domain problem

OR

  1. Right Click > Inspect Element > Tab Resources > Cookie (Left Menu) > Select domain > Delete All cookie One By One (Right Menu)

How to check empty DataTable

As from MSDN for GetChanges

A filtered copy of the DataTable that can have actions performed on it, and later be merged back in the DataTable using Merge. If no rows of the desired DataRowState are found, the method returns Nothing (null).

dataTable1 is null so just check before you iterate over it.

A column-vector y was passed when a 1d array was expected

use below code:

model = forest.fit(train_fold, train_y.ravel())

if you are still getting slap by error as identical as below ?

Unknown label type: %r" % y

use this code:

y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)

What is the difference between char array and char pointer in C?

For cases like this, the effect is the same: You end up passing the address of the first character in a string of characters.

The declarations are obviously not the same though.

The following sets aside memory for a string and also a character pointer, and then initializes the pointer to point to the first character in the string.

char *p = "hello";

While the following sets aside memory just for the string. So it can actually use less memory.

char p[10] = "hello";

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Can HTTP POST be limitless?

HTTP may not have an upper limit, but webservers may have one. In ASP.NET there is a default accept-limit of 4 MB, but you (the developer/webmaster) can change that to be higher or lower.

How to HTML encode/escape a string? Is there a built-in?

h() is also useful for escaping quotes.

For example, I have a view that generates a link using a text field result[r].thtitle. The text could include single quotes. If I didn't escape result[r].thtitle in the confirm method, the Javascript would break:

&lt;%= link_to_remote "#{result[r].thtitle}", :url=>{ :controller=>:resource,
:action         =>:delete_resourced,
:id     => result[r].id,
:th     => thread,                                                                                                      
:html       =>{:title=> "<= Remove"},                                                       
:confirm    => h("#{result[r].thtitle} will be removed"),                                                   
:method     => :delete %>

&lt;a href="#" onclick="if (confirm('docs: add column &amp;apos;dummy&amp;apos; will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&amp;th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="&lt;= Remove">docs: add column 'dummy'</a>

Note: the :html title declaration is magically escaped by Rails.

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

SQL Bulk Insert with FIRSTROW parameter skips the following line

To let SQL handle quote escape and everything else do this

BULK INSERT Test_CSV
FROM  'C:\MyCSV.csv' 
WITH (
 FORMAT='CSV'
 --FIRSTROW = 2,  --uncomment this if your CSV contains header, so start parsing at line 2
);

In regards to other answers, here is valuable info as well:

I keep seeing this in all answers: ROWTERMINATOR = '\n'
The \n means LF and it is Linux style EOL

In Windows the EOL is made of 2 chars CRLF so you need ROWTERMINATOR = '\r\n'

enter image description here

enter image description here

Problem in running .net framework 4.0 website on iis 7.0

  1. Go to the IIS Manager.
  2. open the server name like (PC-Name)\.
  3. then double click on the ISAPI and CGI Restriction.
  4. then select ASP.NET v4.0.30319(32-bit) Restriction allowed.