Programs & Examples On #Nsbutton

The NSButton class is a subclass of NSControl that intercepts mouse-down events and sends an action message to a target object when it’s clicked or pressed.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

open cmd as Administrator then try to register in both location

How to specify multiple conditions in an if statement in javascript

function go(type, pageCount) {
    if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
        pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
    }
}

http://localhost:8080/ Access Error: 404 -- Not Found Cannot locate document: /

A tip for others: if you have NI applications installed, the NI Application Web Server also uses the port 8080.

"Press Any Key to Continue" function in C

Try this:-

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();

getch() is used to get a character from console but does not echo to the screen.

How do I choose the URL for my Spring Boot webapp?

The issue of changing the context path of a Spring application is handled very well in the post titled Spring Boot Change Context Path

Basically the post discusses multiple ways of realizing this viz.

  1. Java Config
  2. Command Line Arguments
  3. Java System Properties
  4. OS Environment Variables
  5. application.properties in Current Directory
  6. application.properties in the classpath (src/main/resources or the packaged jar file)

How to set component default props on React component

class Example extends React.Component {
  render() {
    return <h1>{this.props.text}</h1>;
  }
}

Example.defaultProps = { text: 'yo' }; 

RabbitMQ / AMQP: single queue, multiple consumers for same message?

There is one interesting option in this scenario I haven`t found in answers here.

You can Nack messages with "requeue" feature in one consumer to process them in another. Generally speaking it is not a right way, but maybe it will be good enough for someone.

https://www.rabbitmq.com/nack.html

And beware of loops (when all concumers nack+requeue message)!

InputStream from a URL

Use java.net.URL#openStream() with a proper URL (including the protocol!). E.g.

InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...

See also:

date format yyyy-MM-ddTHH:mm:ssZ

It works fine with Salesforce REST API query datetime formats

DateTime now = DateTime.UtcNow;
string startDate = now.AddDays(-5).ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");   
string endDate = now.ToString("yyyy-MM-ddTHH\\:mm\\:ssZ");  
//REST service Query 
string salesforceUrl= https://csxx.salesforce.com//services/data/v33.0/sobjects/Account/updated/?start=" + startDate + "&end=" + endDate;

// https://csxx.salesforce.com/services/data/v33.0/sobjects/Account/updated/?start=2015-03-10T15:15:57Z&end=2015-03-15T15:15:57Z

It returns the results from Salesforce without any issues.

Convert command line argument to string

You can create an std::string

#include <string>
#include <vector>
int main(int argc, char *argv[])
{
  // check if there is more than one argument and use the second one
  //  (the first argument is the executable)
  if (argc > 1)
  {
    std::string arg1(argv[1]);
    // do stuff with arg1
  }

  // Or, copy all arguments into a container of strings
  std::vector<std::string> allArgs(argv, argv + argc);
}

Regex for numbers only

It is matching because it is finding "a match" not a match of the full string. You can fix this by changing your regexp to specifically look for the beginning and end of the string.

^\d+$

Kill all processes for a given user

What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?

Simplest Way to Test ODBC on WIndows

You can use the "Test Connection" feature after creating the ODBC connection through Control Panel > Administrative Tools > Data Sources.

To test a SQL command itself you could try:

http://www.sqledit.com/odbc/runner.html

http://www.sqledit.com/sqlrun.zip

Or (perhaps easier and more useful in the long run) you can make a test ASP.NET or PHP page in a couple minutes to run SQL statement yourself through IIS.

Calling one Activity from another in Android

Put this inside the onCreate() method of MainActivity1.java

Button btnEins = (Button) findViewById(R.id.save);
        btnEins.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent intencion = new Intent(v.getContext(),MainActivity2.class );     
                startActivity(intencion);
            }

        });

How to read the output from git diff?

@@ -1,2 +3,4 @@ part of the diff

This part took me a while to understand, so I've created a minimal example.

The format is basically the same the diff -u unified diff.

For instance:

diff -u <(seq 16) <(seq 16 | grep -Ev '^(2|3|14|15)$')

Here we removed lines 2, 3, 14 and 15. Output:

@@ -1,6 +1,4 @@
 1
-2
-3
 4
 5
 6
@@ -11,6 +9,4 @@
 11
 12
 13
-14
-15
 16

@@ -1,6 +1,4 @@ means:

  • -1,6 means that this piece of the first file starts at line 1 and shows a total of 6 lines. Therefore it shows lines 1 to 6.

    1
    2
    3
    4
    5
    6
    

    - means "old", as we usually invoke it as diff -u old new.

  • +1,4 means that this piece of the second file starts at line 1 and shows a total of 4 lines. Therefore it shows lines 1 to 4.

    + means "new".

    We only have 4 lines instead of 6 because 2 lines were removed! The new hunk is just:

    1
    4
    5
    6
    

@@ -11,6 +9,4 @@ for the second hunk is analogous:

  • on the old file, we have 6 lines, starting at line 11 of the old file:

    11
    12
    13
    14
    15
    16
    
  • on the new file, we have 4 lines, starting at line 9 of the new file:

    11
    12
    13
    16
    

    Note that line 11 is the 9th line of the new file because we have already removed 2 lines on the previous hunk: 2 and 3.

Hunk header

Depending on your git version and configuration, you can also get a code line next to the @@ line, e.g. the func1() { in:

@@ -4,7 +4,6 @@ func1() {

This can also be obtained with the -p flag of plain diff.

Example: old file:

func1() {
    1;
    2;
    3;
    4;
    5;
    6;
    7;
    8;
    9;
}

If we remove line 6, the diff shows:

@@ -4,7 +4,6 @@ func1() {
     3;
     4;
     5;
-    6;
     7;
     8;
     9;

Note that this is not the correct line for func1: it skipped lines 1 and 2.

This awesome feature often tells exactly to which function or class each hunk belongs, which is very useful to interpret the diff.

How the algorithm to choose the header works exactly is discussed at: Where does the excerpt in the git diff hunk header come from?

Pass mouse events through absolutely-positioned element

There is a javascript version available which manually redirects events from one div to another.

I cleaned it up and made it into a jQuery plugin.

Here's the Github repository: https://github.com/BaronVonSmeaton/jquery.forwardevents

Unfortunately, the purpose I was using it for - overlaying a mask over Google Maps did not capture click and drag events, and the mouse cursor does not change which degrades the user experience enough that I just decided to hide the mask under IE and Opera - the two browsers which dont support pointer events.

Create array of regex matches

In Java 9, you can now use Matcher#results() to get a Stream<MatchResult> which you can use to get a list/array of matches.

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
String[] matches = Pattern.compile("your regex here")
                          .matcher("string to search from here")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
                    // or .collect(Collectors.toList())

pip install access denied on Windows

In case of windows, in cmd try to run pip install using python executable

e.g.

python -m pip install mitmproxy

this should work, at least it worked for me for other package installation.

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Android check internet connection

No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE permission and just make a connected method

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

You can also use requestRouteToHost if you have a particualr host and connection type (wifi/mobile) in mind.

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in your android manifest.

for more detail go here

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.

To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).

The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:

include "header.php";

This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.

<?php
session_start();

                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php



require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

Creating custom function in React component

With React Functional way

import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";

const App = () => {
  const saySomething = (something) => {
    console.log(something);
  };
  useEffect(() => {
    saySomething("from useEffect");
  });
  const handleClick = (e) => {
    saySomething("element clicked");
  };
  return (
    <Button variant="contained" color="primary" onClick={handleClick}>
      Hello World
    </Button>
  );
};

ReactDOM.render(<App />, document.querySelector("#app"));

https://codesandbox.io/s/currying-meadow-gm9g0

How to count string occurrence in string?

_x000D_
_x000D_
var countInstances = function(body, target) {_x000D_
  var globalcounter = 0;_x000D_
  var concatstring  = '';_x000D_
  for(var i=0,j=target.length;i<body.length;i++){_x000D_
    concatstring = body.substring(i-1,j);_x000D_
    _x000D_
    if(concatstring === target){_x000D_
       globalcounter += 1;_x000D_
       concatstring = '';_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  _x000D_
  return globalcounter;_x000D_
 _x000D_
};_x000D_
_x000D_
console.log(   countInstances('abcabc', 'abc')   ); // ==> 2_x000D_
console.log(   countInstances('ababa', 'aba')   ); // ==> 2_x000D_
console.log(   countInstances('aaabbb', 'ab')   ); // ==> 1
_x000D_
_x000D_
_x000D_

Firebase Permission Denied

  1. Open firebase, select database on the left hand side.
  2. Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

How to connect to SQL Server from command prompt with Windows authentication

here is the commend which is tested Sqlcmd -E -S "server name" -d "DB name" -i "SQL file path"

-E stand for windows trusted

How to set URL query params in Vue with Vue-Router

this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })

Service vs IntentService in the Android platform

Android IntentService vs Service

1.Service

  • A Service is invoked using startService().
  • A Service can be invoked from any thread.
  • A Service runs background operations on the Main Thread of the Application by default. Hence it can block your Application’s UI.
  • A Service invoked multiple times would create multiple instances.
  • A service needs to be stopped using stopSelf() or stopService().
  • Android service can run parallel operations.

2. IntentService

  • An IntentService is invoked using Intent.
  • An IntentService can in invoked from the Main thread only.
  • An IntentService creates a separate worker thread to run background operations.
  • An IntentService invoked multiple times won’t create multiple instances.
  • An IntentService automatically stops after the queue is completed. No need to trigger stopService() or stopSelf().
  • In an IntentService, multiple intent calls are automatically Queued and they would be executed sequentially.
  • An IntentService cannot run parallel operation like a Service.

Refer from Here

Calculating sum of repeated elements in AngularJS ng-repeat

You can calculate total inside ng-repeat follow:

<tbody ng-init="total = 0">
  <tr ng-repeat="product in products">
    <td>{{ product.name }}</td>
    <td>{{ product.quantity }}</td>
    <td ng-init="$parent.total = $parent.total + (product.price * product.quantity)">${{ product.price * product.quantity }}</td>
  </tr>
  <tr>
    <td>Total</td>
    <td></td>
    <td>${{ total }}</td>
  </tr>
</tbody>

Check result here: http://plnkr.co/edit/Gb8XiCf2RWiozFI3xWzp?p=preview

In case automatic update result: http://plnkr.co/edit/QSxYbgjDjkuSH2s5JBPf?p=preview (Thanks – VicJordan)

What is the proper way to re-attach detached objects in Hibernate?

Undiplomatic answer: You're probably looking for an extended persistence context. This is one of the main reasons behind the Seam Framework... If you're struggling to use Hibernate in Spring in particular, check out this piece of Seam's docs.

Diplomatic answer: This is described in the Hibernate docs. If you need more clarification, have a look at Section 9.3.2 of Java Persistence with Hibernate called "Working with Detached Objects." I'd strongly recommend you get this book if you're doing anything more than CRUD with Hibernate.

Using only CSS, show div on hover over <a>

From my testing using this CSS:

.expandable{
display: none;
}
.expand:hover+.expandable{
display:inline !important;
}
.expandable:hover{
display:inline !important;
}

And this HTML:

<div class="expand">expand</div>
<div class="expand">expand</div>
<div class="expandable">expandable</div>

, it resulted that it does expand using the second , but does not expand using the first one. So if there is a div between the hover target and the hidden div, then it will not work.

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Linus Torvalds would kill you for this. Git is the name of the version manager program he wrote. GitHub is a website on which there are source code repositories manageable by Git. Thus, GitHub is completely unrelated to the original Git tool.

  2. Is git saving every repository locally (in the user's machine) and in GitHub?

    If you commit changes, it stores locally. Then, if you push the commits, it also sotres them remotely.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    You can, but I'm sure you don't want to manually set up a git server for yourself. Benefits of GitHub? Well, easy to use, lot of people know it so others may find your code and follow/fork it to make improvements as well.

  4. How does Git compare to a backup system such as Time Machine?

    Git is specifically designed and optimized for source code.

  5. Is this a manual process, in other words if you don't commit you wont have a new version of the changes made?

    Exactly.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    See #4.

variable or field declared void

The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like

initializeJSP(Experiment);

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

How to serve static files in Flask

A simplest working example based on the other answers is the following:

from flask import Flask, request
app = Flask(__name__, static_url_path='')

@app.route('/index/')
def root():
    return app.send_static_file('index.html')

if __name__ == '__main__':
  app.run(debug=True)

With the HTML called index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    <div>
         <p>
            This is a test.
         </p>
    </div>
</body>
</html>

IMPORTANT: And index.html is in a folder called static, meaning <projectpath> has the .py file, and <projectpath>\static has the html file.

If you want the server to be visible on the network, use app.run(debug=True, host='0.0.0.0')

EDIT: For showing all files in the folder if requested, use this

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

Which is essentially BlackMamba's answer, so give them an upvote.

How to convert a const char * to std::string

std::string str(c_str, strnlen(c_str, max_length));

At Christian Rau's request:

strnlen is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.

Java - How to create new Entry (key, value)

You can just implement the Map.Entry<K, V> interface yourself:

import java.util.Map;

final class MyEntry<K, V> implements Map.Entry<K, V> {
    private final K key;
    private V value;

    public MyEntry(K key, V value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public K getKey() {
        return key;
    }

    @Override
    public V getValue() {
        return value;
    }

    @Override
    public V setValue(V value) {
        V old = this.value;
        this.value = value;
        return old;
    }
}

And then use it:

Map.Entry<String, Object> entry = new MyEntry<String, Object>("Hello", 123);
System.out.println(entry.getKey());
System.out.println(entry.getValue());

Centering the image in Bootstrap

.img-responsive {
     margin: 0 auto;
 }

you can write like above code in your document so no need to add one another class in image tag.

How to declare a variable in MySQL?

Use set or select

SET @counter := 100;
SELECT @variable_name := value;

example :

SELECT @price := MAX(product.price)
FROM product 

How do I load an url in iframe with Jquery

here is Iframe in view:

<iframe class="img-responsive" id="ifmReport" width="1090" height="1200" >

    </iframe>

Load it in script:

 $('#ifmReport').attr('src', '/ReportViewer/ReportViewer.aspx');

Twitter-Bootstrap-2 logo image on top of navbar

You have to also add the "navbar-brand" class to your image a container, also you have to include it inside the .navbar-inner container, like so:

 <div class="navbar navbar-fixed-top">
   <div class="navbar-inner">
     <div class="container">
        <a class="navbar-brand" href="index.html"> <img src="images/57x57x300.jpg"></a>
     </div>
   </div>
 </div>

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

Get public/external IP address?

I've refactored @Academy of Programmer's answer to shorter code and altered it so that it only hits https:// URLs:

    public static string GetExternalIPAddress()
    {
        string result = string.Empty;

        string[] checkIPUrl =
        {
            "https://ipinfo.io/ip",
            "https://checkip.amazonaws.com/",
            "https://api.ipify.org",
            "https://icanhazip.com",
            "https://wtfismyip.com/text"
        };

        using (var client = new WebClient())
        {
            client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
                "(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

            foreach (var url in checkIPUrl)
            {
                try
                {
                    result = client.DownloadString(url);
                }
                catch
                {
                }

                if (!string.IsNullOrEmpty(result))
                    break;
            }
        }

        return result.Replace("\n", "").Trim();
    }
}

Make xargs execute the command once for each line of input

You can limit the number of lines, or arguments (if there are spaces between each argument) using the --max-lines or --max-args flags, respectively.

  -L max-lines
         Use at most max-lines nonblank input lines per command line.  Trailing blanks cause an input line to be logically continued on the next  input
         line.  Implies -x.

  --max-lines[=max-lines], -l[max-lines]
         Synonym  for  the -L option.  Unlike -L, the max-lines argument is optional.  If max-args is not specified, it defaults to one.  The -l option
         is deprecated since the POSIX standard specifies -L instead.

  --max-args=max-args, -n max-args
         Use at most max-args arguments per command line.  Fewer than max-args arguments will be used if the size (see  the  -s  option)  is  exceeded,
         unless the -x option is given, in which case xargs will exit.

What is causing this error - "Fatal error: Unable to find local grunt"

Install Grunt in node_modules rather than globally

Unable to find local Grunt likely means that you have installed Grunt globally.

The Grunt CLI insists that you install grunt in your local node_modules directory, so Grunt is local to your project.

This will fail:

npm install -g grunt

Do this instead:

npm install grunt --save-dev

Get the first element of each tuple in a list in Python

If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:

>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

Alternatively, you could setup your submodules so that rather than being in their default detached head state you check out a branch.

Edited to add:

One way is to checkout a particular branch of the submodule when you add it with the -b flag:

git submodule add -b master <remote-repo> <path-to-add-it-to>

Another way is to just go into the submodule directory and just check it out

git checkout master

Create an array with same element repeated multiple times

_x000D_
_x000D_
var finalAry = [..."2".repeat(5).split("")].map(Number);_x000D_
console.log(finalAry);
_x000D_
_x000D_
_x000D_

How can we generate getters and setters in Visual Studio?

I don't have Visual Studio installed on my machine anymore (and I'm using Linux), but I do remember that there was an wizard hidden somewhere inside one of the menus that gave access to a class builder.

With this wizard, you could define all your classes' details, including methods and attributes. If I remember well, there was an option through which you could ask Visual Studio to create the setters and getters automatically for you.

I know it's quite vague, but check it out and you might find it.

Cross-browser bookmark/add to favorites JavaScript

I'm thinking no. Bookmarks/favorites should be under the control of the user, imagine if any site you visited could insert itself into your bookmarks with just some javascript.

How to make Java work with SQL Server?

For anyone still googling this, go to \blackboard\config\tomcat\conf and in wrapper.conf put an extra line in wrapper.java.classpath pointing to the sqljdbc4.jar and then update the wrapper.conf.bb as well

Then restart the blackboard services and tomcat and it should work

It won't work by simply setting your java classpath, you have to set it up in the blackboard config files to point to your jar file with the jdbc library

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

How to implement the Softmax function in Python

(Well... much confusion here, both in the question and in the answers...)

To start with, the two solutions (i.e. yours and the suggested one) are not equivalent; they happen to be equivalent only for the special case of 1-D score arrays. You would have discovered it if you had tried also the 2-D score array in the Udacity quiz provided example.

Results-wise, the only actual difference between the two solutions is the axis=0 argument. To see that this is the case, let's try your solution (your_softmax) and one where the only difference is the axis argument:

import numpy as np

# your solution:
def your_softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum()

# correct solution:
def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=0) # only difference

As I said, for a 1-D score array, the results are indeed identical:

scores = [3.0, 1.0, 0.2]
print(your_softmax(scores))
# [ 0.8360188   0.11314284  0.05083836]
print(softmax(scores))
# [ 0.8360188   0.11314284  0.05083836]
your_softmax(scores) == softmax(scores)
# array([ True,  True,  True], dtype=bool)

Nevertheless, here are the results for the 2-D score array given in the Udacity quiz as a test example:

scores2D = np.array([[1, 2, 3, 6],
                     [2, 4, 5, 6],
                     [3, 8, 7, 6]])

print(your_softmax(scores2D))
# [[  4.89907947e-04   1.33170787e-03   3.61995731e-03   7.27087861e-02]
#  [  1.33170787e-03   9.84006416e-03   2.67480676e-02   7.27087861e-02]
#  [  3.61995731e-03   5.37249300e-01   1.97642972e-01   7.27087861e-02]]

print(softmax(scores2D))
# [[ 0.09003057  0.00242826  0.01587624  0.33333333]
#  [ 0.24472847  0.01794253  0.11731043  0.33333333]
#  [ 0.66524096  0.97962921  0.86681333  0.33333333]]

The results are different - the second one is indeed identical with the one expected in the Udacity quiz, where all columns indeed sum to 1, which is not the case with the first (wrong) result.

So, all the fuss was actually for an implementation detail - the axis argument. According to the numpy.sum documentation:

The default, axis=None, will sum all of the elements of the input array

while here we want to sum row-wise, hence axis=0. For a 1-D array, the sum of the (only) row and the sum of all the elements happen to be identical, hence your identical results in that case...

The axis issue aside, your implementation (i.e. your choice to subtract the max first) is actually better than the suggested solution! In fact, it is the recommended way of implementing the softmax function - see here for the justification (numeric stability, also pointed out by some other answers here).

Integrating the ZXing library directly into my Android application

Have you seen the wiki pages on the zxing website? It seems you might find GettingStarted, DeveloperNotes and ScanningViaIntent helpful.

Enabling/Disabling Microsoft Virtual WiFi Miniport

I have the same issue after I disabled the adapter in the Network setting. But when I go to the System->Device Manager and find it from the "Network adapters" and re-enable it. Then everything works again.

How to pass arguments to Shell Script through docker run

There are a few things interacting here:

  1. docker run your_image arg1 arg2 will replace the value of CMD with arg1 arg2. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash to run a bash shell in the container.

  2. When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh, you can now run the container with additional args that will be passed as args to file.sh.

  3. Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh", which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2" as the command being launched inside your container, not so good. See the table here for more on how these two options interact

  4. The shell -c option only takes a single argument. Everything after that would get passed as $1, $2, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2" would work, but /bin/sh -c "file.sh" "arg1" "arg2" would not since file.sh would be called with no args.

Putting that all together, the common design is:

FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]

And you then run that with:

docker run your_image arg1 arg2

There's a fair bit more detail on this at:

Set QLineEdit to accept only numbers

QLineEdit::setValidator(), for example:

myLineEdit->setValidator( new QIntValidator(0, 100, this) );

or

myLineEdit->setValidator( new QDoubleValidator(0, 100, 2, this) );

See: QIntValidator, QDoubleValidator, QLineEdit::setValidator

Error running android: Gradle project sync failed. Please fix your project and try again

This could be due to Android Studio version conflict of v3 and v4 especially when you import a project in android stdio v4 which was previously built in v3.

Here are the few things you need to do:

  • remove the .gradle and .idea folders from the main Application folder.
  • import the project in the android studio.
  • after the sync finished, it will ask you to update the android studio supported version.
  • click update.
  • done.

filter out multiple criteria using excel vba

Alternative using VBA's Filter function

As an innovative alternative to @schlebe 's recent answer, I tried to use the Filter function integrated in VBA, which allows to filter out a given search string setting the third argument to False. All "negative" search strings (e.g. A, B, C) are defined in an array. I read the criteria in column A to a datafield array and basicly execute a subsequent filtering (A - C) to filter these items out.

Code

Sub FilterOut()
Dim ws  As Worksheet
Dim rng As Range, i As Integer, n As Long, v As Variant
' 1) define strings to be filtered out in array
  Dim a()                    ' declare as array
  a = Array("A", "B", "C")   ' << filter out values
' 2) define your sheetname and range (e.g. criteria in column A)
  Set ws = ThisWorkbook.Worksheets("FilterOut")
  n = ws.Range("A" & ws.Rows.Count).End(xlUp).row
  Set rng = ws.Range("A2:A" & n)
' 3) hide complete range rows temporarily
  rng.EntireRow.Hidden = True
' 4) set range to a variant 2-dim datafield array
  v = rng
' 5) code array items by appending row numbers
  For i = 1 To UBound(v): v(i, 1) = v(i, 1) & "#" & i + 1: Next i
' 6) transform to 1-dim array and FILTER OUT the first search string, e.g. "A"
  v = Filter(Application.Transpose(Application.Index(v, 0, 1)), a(0), False, False)
' 7) filter out each subsequent search string, i.e. "B" and "C"
  For i = 1 To UBound(a): v = Filter(v, a(i), False, False): Next i
' 8) get coded row numbers via split function and unhide valid rows
  For i = LBound(v) To UBound(v)
      ws.Range("A" & Split(v(i) & "#", "#")(1)).EntireRow.Hidden = False
  Next i
End Sub

Set initial value in datepicker with jquery?

From jQuery:

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

Code examples

Initialize a datepicker with the defaultDate option specified.

$(".selector").datepicker({ defaultDate: +7 });

Get or set the defaultDate option, after init.

//getter
var defaultDate = $(".selector").datepicker("option", "defaultDate");
//setter
$(".selector").datepicker("option", "defaultDate", +7);

After the datepicker is intialized you should also be able to set the date with:

$(/*selector*/).datepicker("setDate" , date)

How to find file accessed/created just few minutes ago

To find files accessed 1, 2, or 3 minutes ago use -3

find . -cmin -3

SQL grouping by month and year

If I understand correctly. In order to group your results as requested, your Group By clause needs to have the same expression as your select statement.

GROUP BY MONTH(date) + '.' + YEAR(date)

To display the date as "month-date" format change the '.' to '-' The full syntax would be something like this.

SELECT MONTH(date) + '-' + YEAR(date) AS Mjesec, SUM(marketingExpense) AS
SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order]
WHERE (idCustomer = 1) AND (date BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY MONTH(date) + '.' + YEAR(date)

Show Error on the tip of the Edit Text Android

With youredittext.equals("")you can know if user hasn't entered any letter.

Convert varchar to float IF ISNUMERIC

You can't cast to float and keep the string in the same column. You can do like this to get null when isnumeric returns 0.

SELECT CASE ISNUMERIC(QTY) WHEN 1 THEN CAST(QTY AS float) ELSE null END

Making a flex item float right

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
    <div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
             divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div>another child </div>_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PostgreSQL wildcard LIKE for any of a list of words

All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE.

Reference: https://www.postgresql.org/docs/current/functions-matching.html

Mapping list in Yaml to list of objects in Spring Boot

  • You don't need constructors
  • You don't need to annotate inner classes
  • RefreshScope have some problems when using with @Configuration. Please see this github issue

Change your class like this:

@ConfigurationProperties(prefix = "available-payment-channels-list")
@Configuration
public class AvailableChannelsConfiguration {

    private String xyz;
    private List<ChannelConfiguration> channelConfigurations;

    // getters, setters

    public static class ChannelConfiguration {
        private String name;
        private String companyBankAccount;

        // getters, setters
    }

}

Search all the occurrences of a string in the entire project in Android Studio

In Android Studio on a Windows or Linux based machine use shortcut Ctrl + Shift + R to search and replace any string in the whole project.

In Angular, how do you determine the active route?

I was seeking a way to use a Twitter Bootstrap style nav with Angular2, but had trouble getting the active class applied to the parent element of the selected link. Found that @alex-correia-santos's solution works perfectly!

The component containing your tabs has to import the router and define it in its constructor before you can make the necessary calls.

Here's a simplified version of my implementation...

import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {HomeComponent} from './home.component';
import {LoginComponent} from './login.component';
import {FeedComponent} from './feed.component';

@Component({
  selector: 'my-app',
  template: `
    <ul class="nav nav-tabs">
      <li [class.active]="_r.isRouteActive(_r.generate(['Home']))">
        <a [routerLink]="['Home']">Home</a>
      </li>
      <li [class.active]="_r.isRouteActive(_r.generate(['Login']))">
        <a [routerLink]="['Login']">Sign In</a>
      </li>
      <li [class.active]="_r.isRouteActive(_r.generate(['Feed']))">
        <a [routerLink]="['Feed']">Feed</a>
      </li>
    </ul>`,
  styleUrls: ['app/app.component.css'],
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  { path:'/', component:HomeComponent, name:'Home', useAsDefault:true },
  { path:'/login', component:LoginComponent, name:'Login' },
  { path:'/feed', component:FeedComponent, name:'Feed' }
])
export class AppComponent {
  title = 'My App';
  constructor( private _r:Router ){}
}

Find the most common element in a list

>>> li  = ['goose', 'duck', 'duck']

>>> def foo(li):
         st = set(li)
         mx = -1
         for each in st:
             temp = li.count(each):
             if mx < temp:
                 mx = temp 
                 h = each 
         return h

>>> foo(li)
'duck'

Create two-dimensional arrays and access sub-arrays in Ruby

Here is the simple version

 #one
 a = [[0]*10]*10

 #two
row, col = 10, 10
a = [[0]*row]*col

Eclipse Build Path Nesting Errors

Here is a simple solution:

  1. Right click the project >> properties >> build path;
  2. In Source tab, Select all the source folders;
  3. Remove them;
  4. Right click on project, Maven >> Update the project.

Session variables not working php

The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.

session_set_cookie_params(0)

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Good examples of python-memcache (memcached) being used in Python?

I would advise you to use pylibmc instead.

It can act as a drop-in replacement of python-memcache, but a lot faster(as it's written in C). And you can find handy documentation for it here.

And to the question, as pylibmc just acts as a drop-in replacement, you can still refer to documentations of pylibmc for your python-memcache programming.

Is it possible to interactively delete matching search pattern in Vim?

There are 3 ways I can think of:

The way that is easiest to explain is

:%s/phrase to delete//gc

but you can also (personally I use this second one more often) do a regular search for the phrase to delete

/phrase to delete

Vim will take you to the beginning of the next occurrence of the phrase.

Go into insert mode (hit i) and use the Delete key to remove the phrase.

Hit escape when you have deleted all of the phrase.

Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed

Continue hitting n and dot until you are done.

Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you

Count the number of characters you want to delete

Type that number in (with number keys)

Hit the x key - characters should get deleted

Continue through with n and dot like in the second method.

PS - And if you didn't know already you can do a capital n to move backwards through the search matches.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

If your jar file already has an absolute pathname as shown, it is particularly easy:

cd /where/you/want/it; jar xf /path/to/jarfile.jar

That is, you have the shell executed by Python change directory for you and then run the extraction.

If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar can find it after the change of directory.

The only issues left to worry about are things like blanks in the path names.

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

no target device found android studio 2.1.1

try with

sudo adb kill-server
sudo devices

or

echo $ANDROID_HOME
sudo $ANDROID_HOME/platform-tools/adb kill-server 
sudo $ANDROID_HOME/platform-tools/adb devices

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

Make Font Awesome icons in a circle?

You can also do this. I wanted to add a circle around my icomoon icons. Here is the code.

span {
font-size: 54px;
border-radius: 50%;
border: 10px solid rgb(205, 209, 215);
padding: 30px;
}

How to list processes attached to a shared memory segment in linux?

I don't think you can do this with the standard tools. You can use ipcs -mp to get the process ID of the last process to attach/detach but I'm not aware of how to get all attached processes with ipcs.

With a two-process-attached segment, assuming they both stayed attached, you can possibly figure out from the creator PID cpid and last-attached PID lpid which are the two processes but that won't scale to more than two processes so its usefulness is limited.

The cat /proc/sysvipc/shm method seems similarly limited but I believe there's a way to do it with other parts of the /proc filesystem, as shown below:

When I do a grep on the procfs maps for all processes, I get entries containing lines for the cpid and lpid processes.

For example, I get the following shared memory segment from ipcs -m:

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      
0x00000000 123456     pax        600        1024       2          dest

and, from ipcs -mp, the cpid is 3956 and the lpid is 9999 for that given shared memory segment (123456).

Then, with the command grep 123456 /proc/*/maps, I see:

/proc/3956/maps: blah blah blah 123456 /SYSV000000 (deleted)
/proc/9999/maps: blah blah blah 123456 /SYSV000000 (deleted)

So there is a way to get the processes that attached to it. I'm pretty certain that the dest status and (deleted) indicator are because the creator has marked the segment for destruction once the final detach occurs, not that it's already been destroyed.

So, by scanning of the /proc/*/maps "files", you should be able to discover which PIDs are currently attached to a given segment.

How to replace comma (,) with a dot (.) using java

For the current information you are giving, it will be enought with this simple regex to do the replacement:

str.replaceAll(",", ".");

When should I use mmap for file access?

One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.

Convert RGB to Black & White in OpenCV

Simple binary threshold method is sufficient.

include

#include <string>
#include "opencv/highgui.h"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

int main()
{
    Mat img = imread("./img.jpg",0);//loading gray scale image
    threshold(img, img, 128, 255, CV_THRESH_BINARY);//threshold binary, you can change threshold 128 to your convenient threshold
    imwrite("./black-white.jpg",img);
    return 0;
}

You can use GaussianBlur to get a smooth black and white image.

how to save DOMPDF generated content to file?

<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

Difference between RUN and CMD in a Dockerfile

RUN Command: RUN command will basically, execute the default command, when we are building the image. It also will commit the image changes for next step.

There can be more than 1 RUN command, to aid in process of building a new image.

CMD Command: CMD commands will just set the default command for the new container. This will not be executed at build time.

If a docker file has more than 1 CMD commands then all of them are ignored except the last one. As this command will not execute anything but just set the default command.

Solving "adb server version doesn't match this client" error

For those of you that have HTC Sync installed, uninstalling the application fixed this problem for me.

jQuery UI DatePicker - Change Date Format

dateFormat

The format for parsed and displayed dates. This attribute is one of the regionalisation attributes. For a full list of the possible formats see the formatDate function.

Code examples Initialize a datepicker with the dateFormat option specified.

$( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' });

Get or set the dateFormat option, after init.

//getter
var dateFormat = $( ".selector" ).datepicker( "option", "dateFormat" );
//setter
$( ".selector" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

jQuery - setting the selected value of a select control via its text description

I haven't tested this, but this might work for you.

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

Android global variable

Try Like This:

Create a shared data class:

SharedData.java

import android.app.Application;

/**
 * Created by kundan on 6/23/2015.
 */
public class Globals {


    private static Globals instance = new Globals();

    // Getter-Setters
    public static Globals getInstance() {
        return instance;
    }

    public static void setInstance(Globals instance) {
        Globals.instance = instance;
    }

    private String notification_index;


    private Globals() {

    }


    public String getValue() {
        return notification_index;
    }


    public void setValue(String notification_index) {
        this.notification_index = notification_index;
    }



}

Declared/Initiaze an instance of class globally in those classes where you want to set/get data (using this code before onCreate() method):-

Globals sharedData = Globals.getInstance();

Set data:

sharedData.setValue("kundan");

Get data:

String n = sharedData.getValue();

How can I INSERT data into two tables simultaneously in SQL Server?

BEGIN TRANSACTION;

DECLARE @tblMapping table(sourceid int, destid int)

INSERT INTO [table1] ([data]) 
OUTPUT source.id, new.id
Select [data] from [external_table] source;

INSERT INTO [table2] ([table1_id], [data])
Select map.destid, source.[more data] 
from [external_table] source
    inner join @tblMapping map on source.id=map.sourceid;

COMMIT TRANSACTION;

require(vendor/autoload.php): failed to open stream

I was able to resolve by removing composer and reinstalling the proper way. Here is what I did:

I was then able to get composer install to work again. Found my answer at the bottom of this issue: https://github.com/composer/composer/issues/5510

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

Windows 7: unable to register DLL - Error Code:0X80004005

Open the start menu and type cmd into the search box Hold Ctrl + Shift and press Enter

This runs the Command Prompt in Administrator mode.

Now type regsvr32 MyComobject.dll

Failed binder transaction when putting an bitmap dynamically in a widget

I have solved this issue by storing images on internal storage and then using .setImageURI() rather than .setBitmap().

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

The answer in my view is related to whether you have a tangible problem to solve or if you just want to learn for example to be prepared for a possible new job. If you have a problem then you are in better shape. You can start by looking around and seeing how other people went about solving that problem. Languages in general you should be able to pick up fairly quickly (after all you hold an MS in EE, no small feat IMO).

What you need to be on the lookout for is good programming practices. You'll probably see yourself asking "why is this method so small", "why is this method empty and what the heck is this abstract word doing here". That will give you perspective beyond syntax towards good writing.

Making custom right-click context menus for my web-app

Simple One

  1. show context menu when right click anywhere in document
  2. avoid context menu hide when click inside context menu
  3. close context menu when press left mouse button

Note: dont use display:none instead use opacity to hide and show

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:70px;
background:lightgrey;
padding:5px;
 opacity :0;
}
.context_menu div{
margin:5px;
background:grey;

}
.context_menu div:hover{
margin:5px;
background:red;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
</div>
_x000D_
_x000D_
_x000D_

extra css

_x000D_
_x000D_
var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {      
            e.preventDefault();  
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';        
             menu.style.opacity = 1;
        });
       
  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
_x000D_
.context_menu{

width:120px;
background:white;
border:1px solid lightgrey;

 opacity :0;
}
.context_menu div{
padding:5px;
padding-left:15px;
margin:5px 2px;
border-bottom:1px solid lightgrey;
}
.context_menu div:last-child {
border:none;
}
.context_menu div:hover{

background:lightgrey;
   cursor:pointer;

}
_x000D_
<div class="context_menu">
<div>menu 1</div>
<div>menu 2</div>
<div>menu 3</div>
<div>menu 4</div>
</div>
_x000D_
_x000D_
_x000D_

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

iOS 7: UITableView shows under status bar

The following solution works well enough in code without using magic constants, and accounts for the user changing the size class, e.g. through rotations or side-by-side apps on ipads:

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // Fix up content offset to ensure the tableview isn't underlapping the status bar.
    self.tableView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0.0, 0.0, 0.0);
}

Custom HTTP headers : naming conventions

The header field name registry is defined in RFC3864, and there's nothing special with "X-".

As far as I can tell, there are no guidelines for private headers; in doubt, avoid them. Or have a look at the HTTP Extension Framework (RFC 2774).

It would be interesting to understand more of the use case; why can't the information be added to the message body?

How do I alter the precision of a decimal column in Sql Server?

Go to enterprise manager, design table, click on your field.

Make a decimal column

In the properties at the bottom there is a precision property

Why should a Java class implement comparable?

Comparable defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".

Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?

TreeSet<Integer> m = new TreeSet<Integer>(); 
m.add(1);
m.add(3);
m.add(2);
for (Integer i : m)
... // values will be sorted

But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:

public class District {
  String zipcode; 
  Double populationDensity;
}

Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:

public class District implements Comparable<District>{
  String zipcode; 
  Double populationDensity;
  public int compareTo(District other)
  {
    return populationDensity.compareTo(other.populationDensity);
  }
}

Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.

Basically the ordering logic has to exist somewhere. That can be -

  • in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)

  • supplied in an external comparator, as in the example above.

Get current controller in view

Create base class for all controllers and put here name attribute:

public abstract class MyBaseController : Controller
{
    public abstract string Name { get; }
}

In view

@{
    var controller = ViewContext.Controller as MyBaseController;
    if (controller != null)
    {
       @controller.Name
    }
}

Controller example

 public class SampleController: MyBaseController 
    { 
      public override string Name { get { return "Sample"; } 
    }

Using android.support.v7.widget.CardView in my project (Eclipse)

I was able to work it out only after adding those two TOGETHER:

dependencies {
...
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'
...
}

in my build.gradle (Module:app) file

and then press the sync now button

How to get current foreground activity context in android?

Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.

Java FileReader encoding issue

For Java 7+ doc you can use this:

BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);

Here are all Charsets doc

For example if your file is in CP1252, use this method

Charset.forName("windows-1252");

Here is other canonical names for Java encodings both for IO and NIO doc

If you do not know with exactly encoding you have got in a file, you may use some third-party libs like this tool from Google this which works fairly neat.

Replace whitespaces with tabs in linux

better tr command:

tr [:blank:] \\t

This will clean up the output of say, unzip -l , for further processing with grep, cut, etc.

e.g.,

unzip -l some-jars-and-textfiles.zip | tr [:blank:] \\t | cut -f 5 | grep jar

How to get IP address of running docker container

while read ctr;do
    sudo docker inspect --format "$ctr "'{{.Name}}{{ .NetworkSettings.IPAddress }}' $ctr
done < <(docker ps -a --filter status=running --format '{{.ID}}')

Search and get a line in Python

With regular expressions

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

How can I check if some text exist or not in the page using Selenium?

There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.

Python

In Python driver you can write the following function:

def is_text_present(self, text):
    return str(text) in self.driver.page_source

then use it as:

try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))

To use regular expression, try:

def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
    self.assertRegex(self.driver.page_source, text)
    return True

See: FooTest.py file for full example.

Or check below few other alternatives:

self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text

Source: Another way to check (assert) if text exists using Selenium Python

Java

In Java the following function:

public void verifyTextPresent(String value)
{
  driver.PageSource.Contains(value);
}

and the usage would be:

try
{
  Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
  Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
  Console.WriteLine("Selenium Wiki test is not present on the home page");
}

Source: Using verifyTextPresent in Selenium 2 Webdriver


Behat

For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php:

/**
 * Checks, that page doesn't contain text matching specified pattern
 * Example: Then I should see text matching "Bruce Wayne, the vigilante"
 * Example: And I should not see "Bruce Wayne, the vigilante"
 *
 * @Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
 */
public function assertPageNotMatchesText($pattern)
{
    $this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}

/**
 * Checks, that HTML response contains specified string
 * Example: Then the response should contain "Batman is the hero Gotham deserves."
 * Example: And the response should contain "Batman is the hero Gotham deserves."
 *
 * @Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
 */
public function assertResponseContains($text)
{
    $this->assertSession()->responseContains($this->fixStepArgument($text));
}

Automatically run %matplotlib inline in IPython Notebook

In your ipython_config.py file, search for the following lines

# c.InteractiveShellApp.matplotlib = None

and

# c.InteractiveShellApp.pylab = None

and uncomment them. Then, change None to the backend that you're using (I use 'qt4') and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir() command to verify which modules are in the global namespace.

What are Maven goals and phases and what is their difference?

Goals are executed in phases which help determine the order goals get executed in. The best understanding of this is to look at the default Maven lifecycle bindings which shows which goals get run in which phases by default. The compile phase goals will always be executed before the test phase goals, which will always be executed before the package phase goals and so on.

Part of the confusion is exacerbated by the fact that when you execute Maven you can specify a goal or a phase. If you specify a phase then Maven will run all phases up to the phase you specified in order (e.g. if you specify package it will first run through the compile phase and then the test phase and finally the package phase) and for each phase it will run all goals attached to that phase.

When you create a plugin execution in your Maven build file and you only specify the goal then it will bind that goal to a given default phase. For example, the jaxb:xjc goal binds by default to the generate-resources phase. However, when you specify the execution you can also explicitly specify the phase for that goal as well.

If you specify a goal when you execute Maven then it will run that goal and only that goal. In other words, if you specify the jar:jar goal it will only run the jar:jar goal to package your code into a jar. If you have not previously run the compile goal or prepared your compiled code in some other way this may very likely fail.

How to solve WAMP and Skype conflict on Windows 7?

Run Wamp services before Skype
Quit Skype >>> Run WAMP >>> Run Skype

Declaring & Setting Variables in a Select Statement

I have tried this and it worked:

define PROPp_START_DT = TO_DATE('01-SEP-1999')

select * from proposal where prop_start_dt = &PROPp_START_DT

 

Swift Set to Array

ADDITION :

Swift has no DEFINED ORDER for Set and Dictionary.For that reason you should use sorted() method to prevent from getting unexpected results such as your array can be like ["a","b"] or ["b","a"] and you do not want this.

TO FIX THIS:

FOR SETS

var example:Set = ["a","b","c"]
let makeExampleArray = [example.sorted()]
makeExampleArray 

Result: ["a","b","c"]

Without sorted()

It can be:

["a","b","c"] or ["b","c","a",] or ["c","a","b"] or ["a","c","b"] or ["b","a","c"] or ["c","b","a"] 

simple math : 3! = 6

C# int to enum conversion

It's fine just to cast your int to Foo:

int i = 1;
Foo f = (Foo)i;

If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.

If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:

int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
    Foo f = (Foo)i;
}
else
{
   // Throw exception, etc.
}

However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.

Also note that you don't have to specify that your enum inherits from int; this is the default behavior.

Getting JSONObject from JSONArray

When using google gson library.

var getRowData =
[{
    "dayOfWeek": "Sun",
    "date": "11-Mar-2012",
    "los": "1",
    "specialEvent": "",
    "lrv": "0"
},
{
    "dayOfWeek": "Mon",
    "date": "",
    "los": "2",
    "specialEvent": "",
    "lrv": "0.16"
}];

    JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
     JsonArray  jsonArray = root.getAsJsonArray();
     JsonObject  jsonObject1 = jsonArray.get(0).getAsJsonObject();
     String dayOfWeek = jsonObject1.get("dayOfWeek").toString();

// when using jackson library

    JsonFactory f = new JsonFactory();
              ObjectMapper mapper = new ObjectMapper();
          JsonParser jp = f.createJsonParser(getRowData);
          // advance stream to START_ARRAY first:
          jp.nextToken();
          // and then each time, advance to opening START_OBJECT
         while (jp.nextToken() == JsonToken.START_OBJECT) {
            Map<String,Object> userData = mapper.readValue(jp, Map.class);
            userData.get("dayOfWeek");
            // process
           // after binding, stream points to closing END_OBJECT
        }

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

How can I change UIButton title color?

If you are using Swift, this will do the same:

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Hope that helps!

SQL Server default character encoding

I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.

How to use mouseover and mouseout in Angular 6

To avoid blinking problem use following code
its not mouseover and mouseout instead of that use mouseenter and mouseleave


**app.component.html**

    <div (mouseenter)="changeText=true" (mouseleave)="changeText=false">
      <span *ngIf="!changeText">Hide</span>
      <span *ngIf="changeText">Show</span>
    </div>

**app.component.ts**

@Component({
   selector: 'app-main',
   templateUrl: './app.component.html'
})
export class AppComponent {
    changeText: boolean;
    constructor() {
       this.changeText = false;
    }
}

Migration: Cannot add foreign key constraint

For me, the issue was an old table was using MyISAM and not InnoDB. This fixed it

    $tables = [
        'table_1',
        'table_2'
    ];

    foreach ($tables as $table) {
        \DB::statement('ALTER TABLE ' . $table . ' ENGINE = InnoDB');
    }

Find all packages installed with easy_install/pip?

If Debian behaves like recent Ubuntu versions regarding pip install default target, it's dead easy: it installs to /usr/local/lib/ instead of /usr/lib (apt default target). Check https://askubuntu.com/questions/173323/how-do-i-detect-and-remove-python-packages-installed-via-pip/259747#259747

I am an ArchLinux user and as I experimented with pip I met this same problem. Here's how I solved it in Arch.

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'

Key here is /usr/lib/python2.7/site-packages, which is the directory pip installs to, YMMV. pacman -Qo is how Arch's pac kage man ager checks for ownership of the file. No package is part of the return it gives when no package owns the file: error: No package owns $FILENAME. Tricky workaround: I'm querying about __init__.py because pacman -Qo is a little bit ignorant when it comes to directories :(

In order to do it for other distros, you have to find out where pip installs stuff (just sudo pip install something), how to query ownership of a file (Debian/Ubuntu method is dpkg -S) and what is the "no package owns that path" return (Debian/Ubuntu is no path found matching pattern). Debian/Ubuntu users, beware: dpkg -S will fail if you give it a symbolic link. Just resolve it first by using realpath. Like this:

find /usr/local/lib/python2.7/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'

Fedora users can try (thanks @eddygeek):

find /usr/lib/python2.7/site-packages -maxdepth 2 -name __init__.py | xargs rpm -qf | grep 'not owned by any package'

Creating a LINQ select from multiple tables

You can use anonymous types for this, i.e.:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new { pg, op }).SingleOrDefault();

This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new
                  {
                      PermissionName = pg, 
                      ObjectPermission = op
                  }).SingleOrDefault();

This will enable you to say:-

if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();

For example :-)

How to manipulate arrays. Find the average. Beginner Java

Best way to find the average of some numbers is trying Classes ......

public static void main(String[] args) {
    average(1,2,5,4);

}

public static void average(int...numbers){
    int total = 0;
    for(int x: numbers){
        total+=x;
    }
    System.out.println("Average is: "+(double)total/numbers.length);

}

Access non-numeric Object properties by index?

Get the array of keys, reverse it, then run your loop

  var keys = Object.keys( obj ).reverse();
  for(var i = 0; i < keys.length; i++){
    var key = keys[i];
    var value = obj[key];
    //do stuff backwards
  }

Create a custom View by inflating a layout?

Here is a simple demo to create customview (compoundview) by inflating from xml

attrs.xml

<resources>

    <declare-styleable name="CustomView">
        <attr format="string" name="text"/>
        <attr format="reference" name="image"/>
    </declare-styleable>
</resources>

CustomView.kt

class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        ConstraintLayout(context, attrs, defStyleAttr) {

    init {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?) {
        View.inflate(context, R.layout.custom_layout, this)

        val ta = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
        try {
            val text = ta.getString(R.styleable.CustomView_text)
            val drawableId = ta.getResourceId(R.styleable.CustomView_image, 0)
            if (drawableId != 0) {
                val drawable = AppCompatResources.getDrawable(context, drawableId)
                image_thumb.setImageDrawable(drawable)
            }
            text_title.text = text
        } finally {
            ta.recycle()
        }
    }
}

custom_layout.xml

We should use merge here instead of ConstraintLayout because

If we use ConstraintLayout here, layout hierarchy will be ConstraintLayout->ConstraintLayout -> ImageView + TextView => we have 1 redundant ConstraintLayout => not very good for performance

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="android.support.constraint.ConstraintLayout">

    <ImageView
        android:id="@+id/image_thumb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:ignore="ContentDescription"
        tools:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/text_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="@id/image_thumb"
        app:layout_constraintStart_toStartOf="@id/image_thumb"
        app:layout_constraintTop_toBottomOf="@id/image_thumb"
        tools:text="Text" />

</merge>

Using activity_main.xml

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

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#f00"
        app:image="@drawable/ic_android"
        app:text="Android" />

    <your_package.CustomView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0f0"
        app:image="@drawable/ic_adb"
        app:text="ADB" />

</LinearLayout>

Result

enter image description here

Github demo

What strategies and tools are useful for finding memory leaks in .NET?

You still need to worry about memory when you are writing managed code unless your application is trivial. I will suggest two things: first, read CLR via C# because it will help you understand memory management in .NET. Second, learn to use a tool like CLRProfiler (Microsoft). This can give you an idea of what is causing your memory leak (e.g. you can take a look at your large object heap fragmentation)

In C#, how to check if a TCP port is available?

ipGlobalProperties.GetActiveTcpConnections() doesn't return connections in Listen State.

Port can be used for listening, but with no one connected to it the method described above will not work.

CSS scrollbar style cross browser

jScrollPane is a good solution to cross browser scrollbars and degrades nicely.

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

If you wanted to copy all s3 bucket objects using the command "aws s3 cp s3://bucket-name/data/all-data/ . --recursive" as you mentioned, here is a safe and minimal policy to do that:

{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
              "s3:ListBucket"
          ],
          "Resource": [
              "arn:aws:s3:::bucket-name"
          ],
          "Condition": {
              "StringLike": {
                  "s3:prefix": "data/all-data/*"
              }
          }
      },
      {
          "Effect": "Allow",
          "Action": [
              "s3:GetObject"
          ],
          "Resource": [
              "arn:aws:s3:::bucket-name/data/all-data/*"
          ]
      }
  ]
}

The first statement in this policy allows for listing objects inside a specific bucket's sub directory. The resource needs to be the arn of the S3 bucket, and to limit listing to only a sub-directory in that bucket you can edit the "s3:prefix" value.

The second statement in this policy allows for getting objects inside of the bucket at a specific sub-directory. This means that anything inside the "s3://bucket-name/data/all-data/" path you will be able to copy. Be aware that this doesn't allow you to copy from parent paths such as "s3://bucket-name/data/".

This solution is specific to limiting use for AWS CLI commands; if you need to limit S3 access through the AWS console or API, then more policies will be needed. I suggest taking a look here: https://aws.amazon.com/blogs/security/writing-iam-policies-grant-access-to-user-specific-folders-in-an-amazon-s3-bucket/.

A similar issue to this can be found here which led me to the solution I am giving. https://github.com/aws/aws-cli/issues/2408

Hope this helps!

How to automatically convert strongly typed enum into int?

The reason for the absence of implicit conversion (by design) was given in other answers.

I personally use unary operator+ for the conversion from enum classes to their underlying type:

template <typename T>
constexpr auto operator+(T e) noexcept
    -> std::enable_if_t<std::is_enum<T>::value, std::underlying_type_t<T>>
{
    return static_cast<std::underlying_type_t<T>>(e);
}

Which gives quite little "typing overhead":

std::cout << foo(+b::B2) << std::endl;

Where I actually use a macro to create enums and the operator functions in one shot.

#define UNSIGNED_ENUM_CLASS(name, ...) enum class name : unsigned { __VA_ARGS__ };\
inline constexpr unsigned operator+ (name const val) { return static_cast<unsigned>(val); }

How to access SOAP services from iPhone

I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient (soapclient) that is open source (BSD licensed) and available on Google Code (mac-soapclient) that might be of interest.

I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs.

Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: wsdl2objc

How to strip HTML tags with jQuery?

This is a example for get the url image, escape the p tag from some item.

Try this:

$('#img').attr('src').split('<p>')[1].split('</p>')[0]

How do I make a Windows batch script completely silent?

If you want that all normal output of your Batch script be silent (like in your example), the easiest way to do that is to run the Batch file with a redirection:

C:\Temp> test.bat >nul

This method does not require to modify a single line in the script and it still show error messages in the screen. To supress all the output, including error messages:

C:\Temp> test.bat >nul 2>&1

If your script have lines that produce output you want to appear in screen, perhaps will be simpler to add redirection to those lineas instead of all the lines you want to keep silent:

@ECHO OFF
SET scriptDirectory=%~dp0
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat
FOR /F %%f IN ('dir /B "%scriptDirectory%*.noext"') DO (
del "%scriptDirectory%%%f"
)
ECHO
REM Next line DO appear in the screen
ECHO Script completed >con

Antonio

Add IIS 7 AppPool Identities as SQL Server Logons

CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS;
CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool];

Running stages in parallel with Jenkins workflow / pipeline

that syntax is now deprecated, you will get this error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Expected a stage @ line 14, column 9.
       parallel firstTask: {
       ^

WorkflowScript: 14: Stage does not have a name @ line 14, column 9.
       parallel secondTask: {
       ^

2 errors

You should do something like:

stage("Parallel") {
    steps {
        parallel (
            "firstTask" : {
                //do some stuff
            },
            "secondTask" : {
                // Do some other stuff in parallel
            }
        )
    }
}

Just to add the use of node here, to distribute jobs across multiple build servers/ VMs:

pipeline {
  stages {
    stage("Work 1"){
     steps{
      parallel ( "Build common Library":   
            {
              node('<Label>'){
                  /// your stuff
                  }
            },

        "Build Utilities" : {
            node('<Label>'){
               /// your stuff
              }
           }
         )
    }
}

All VMs should be labelled as to use as a pool.

int to string in MySQL

Try it using CONCAT

CONCAT('site.com/path/','%', CAST(t1.id AS CHAR(25)), '%','/more')

Get $_POST from multiple checkboxes

<input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">

And after the post, you can loop through them:

   if(!empty($_POST['check_list'])){
     foreach($_POST['check_list'] as $report_id){
        echo "$report_id was checked! ";
     }
   }

Or get a certain value posted from previous page:

if(isset($_POST['check_list'][$report_id])){
  echo $report_id . " was checked!<br/>";
}

Is it possible to remove the focus from a text input when a page loads?

A jQuery solution would be something like:

$(function () {
    $('input').blur();
});

URLEncoder not able to translate space character

use character-set "ISO-8859-1" for URLEncoder

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:

.navbar-brand {
    min-height: 80px;
}

@media (min-width: 768px) {
    #navbar-collapse {
        position: absolute;
        bottom: 0px;
        left: 250px;
    }
}

My brand image is SVG and I used height: 50px; width: auto which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px; to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse's left setting until it looked right.

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Setting PHPMyAdmin Language

In config.inc.php in the top-level directory, set

$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users

If Lang isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.

WebView and HTML5 <video>

A-M's is similar to what the BrowerActivity does. for FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams (768, 512);

I think we can use

FrameLayout.LayoutParams LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.FILL_PARENT) 

instead.

Another issue I met is if the video is playing, and user clicks the back button, next time, you go to this activity(singleTop one) and can not play the video. to fix this, I called the

try { 
    mCustomVideoView.stopPlayback();  
    mCustomViewCallback.onCustomViewHidden();
} catch(Throwable e) { //ignore }

in the activity's onBackPressed method.

Javascript split regex question

or just (anything but numbers):

date.split(/\D/);

How can I stop .gitignore from appearing in the list of untracked files?

If someone has already added a .gitignore to your repo, but you want to make some changes to it and have those changes ignored do the following:

git update-index --assume-unchanged .gitignore

Source.

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

What does -1 mean in numpy reshape?

I didn't manage to understand what np.reshape() does until I read this article.

Mechanically it is clear what reshape() does. But how do we interpret the data before and after reshape?

The missing piece for me was:

When we train a machine learning model, the nesting levels of arrays have precisely defined meaning.

This means that the reshape operation has to be keenly aware both points below before the operation has any meaning:

  • the data it operates on (how the reshape intput looks like)
  • how the algorithm/model expects the reshaped data to be (how the reshape output looks like)

For example:

The external array contains observations/rows. The inner array contains columns/features. This causes two special cases when we have either an array of multiple observations of only one feature or a single observation of multiple features.

For more advanced example: See this stackoverflow question

How to calculate the bounding box for a given lat/lng location?

Here is an simple implementation using javascript which is based on the conversion of latitude degree to kms where 1 degree latitude ~ 111.2 km.

I am calculating bounds of the map from a given latitude, longitude and radius in kilometers.

function getBoundsFromLatLng(lat, lng, radiusInKm){
     var lat_change = radiusInKm/111.2;
     var lon_change = Math.abs(Math.cos(lat*(Math.PI/180)));
     var bounds = { 
         lat_min : lat - lat_change,
         lon_min : lng - lon_change,
         lat_max : lat + lat_change,
         lon_max : lng + lon_change
     };
     return bounds;
}

In Python, how do I convert all of the items in a list to floats?

This would be an other method (without using any loop!):

import numpy as np
list(np.float_(list_name))

Rails and PostgreSQL: Role postgres does not exist

You might be able to workaround this by running initdb -U postgres -D /path/to/data or running it as user postgres, since it defaults to the current user. GL!

ORA-12154 could not resolve the connect identifier specified

Had a similar issue, only my web app was fine and it was SQLPlus that was giving me issues connecting, and the ORA-12154 could not resolve the connect identifier specified error. I had 11g and 12 Oracle clients installed. My environment variables were all set to point at my 12 instance:

  • ORACLE_HOME = C:\oracle\product\12
  • PATH = C:\oracle\product\12\bin;....
  • TNS_ADMIN = C:\oracle\product\12\network\admin

There is also a registry entry required at HKLM\Software\Oracle\KEY_OraClient12Home1, a string entry of TNS_ADMIN with the same path as the environment variable.

I have a tnsnames.ora at both C:\oracle\product\11\network\admin and C:\oracle\product\12\network\admin. As far as I know, both my web app and the 12 SQLPlus client I was using should have been using all 12 version variables.

My troubleshooting steps:

  • Change all environmental variables above from 12 to 11.
  • Connect with 11g's SQLPlus (worked!)
  • Change all environmental variables above back from 11 to 12.
  • Connect with 12's SQLPlus again (worked!)

So I don't really know what caused 12's SQLPlus to stop connecting, but this kind of reset may work for someone, so thought I'd document it here.

Is it a bad practice to use break in a for loop?

It depends on the language. While you can possibly check a boolean variable here:

for (int i = 0; i < 100 && stayInLoop; i++) { ... }

it is not possible to do it when itering over an array:

for element in bigList: ...

Anyway, break would make both codes more readable.

How to get SQL from Hibernate Criteria API (*not* for logging)

Here's "another" way to get the SQL :

CriteriaImpl criteriaImpl = (CriteriaImpl)criteria;
SessionImplementor session = criteriaImpl.getSession();
SessionFactoryImplementor factory = session.getFactory();
CriteriaQueryTranslator translator=new CriteriaQueryTranslator(factory,criteriaImpl,criteriaImpl.getEntityOrClassName(),CriteriaQueryTranslator.ROOT_SQL_ALIAS);
String[] implementors = factory.getImplementors( criteriaImpl.getEntityOrClassName() );

CriteriaJoinWalker walker = new CriteriaJoinWalker((OuterJoinLoadable)factory.getEntityPersister(implementors[0]), 
                        translator,
                        factory, 
                        criteriaImpl, 
                        criteriaImpl.getEntityOrClassName(), 
                        session.getLoadQueryInfluencers()   );

String sql=walker.getSQLString();

Best way to write to the console in PowerShell

Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host. What Out-Host does is obviously host-dependent.

Just letting things fall out of the pipeline is not a substitute for Write-Host which exists for the sole reason of outputting text in the host application.

If you want output, then use the Write-* cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.

Create Table from JSON Data with angularjs and ng-repeat

You can use $http.get() method to fetch your JSON file. Then assign response data to a $scope object. In HTML to create table use ng-repeat for $scope object. ng-repeat will loop the rows in-side this loop you can bind data to columns dynamically.

I have checked your code and you have created static table

<table>
<tr>
<th>Name</th>
<th>Relationship</th>
</tr>
<tr ng-repeat="indivisual in members">
<td>{{ indivisual.Name }}</td>
<td>{{ indivisual.Relation }}</td>
</tr>
</table>

so better your can go to my code to create dynamic table as per data you column and row will be increase or decrease..

How to use a class object in C++ as a function parameter

If you want to pass class instances (objects), you either use

 void function(const MyClass& object){
   // do something with object  
 }

or

 void process(MyClass& object_to_be_changed){
   // change member variables  
 }

On the other hand if you want to "pass" the class itself

template<class AnyClass>
void function_taking_class(){
   // use static functions of AnyClass
   AnyClass::count_instances();
   // or create an object of AnyClass and use it
   AnyClass object;
   object.member = value;
}
// call it as 
function_taking_class<MyClass>();
// or 
function_taking_class<MyStruct>();

with

class MyClass{
  int member;
  //...
};
MyClass object1;

jQuery make global variable

You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.

Correct way to push into state array

You should not be operating the state at all. At least, not directly. If you want to update your array, you'll want to do something like this.

var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);

Working on the state object directly is not desirable. You can also take a look at React's immutability helpers.

https://facebook.github.io/react/docs/update.html

Basic authentication with fetch?

You can also use btoa instead of base64.encode().

headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));

Converting List<Integer> to List<String>

Here's a one-liner solution without cheating with a non-JDK library.

List<String> strings = Arrays.asList(list.toString().replaceAll("\\[(.*)\\]", "$1").split(", "));

Screen width in React Native

First get Dimensions from react-native

import { Dimensions } from 'react-native';

then

const windowWidth = Dimensions.get('window').width;

const windowHeight = Dimensions.get('window').height;

in windowWidth you will find the width of the screen while in windowHeight you will find the height of the screen.

How to perform a real time search and filter on a HTML table

Thank you @dfsq for the very helpful code!

I've made some adjustments and maybe some others like them too. I ensured that you can search for multiple words, without having a strict match.

Example rows:

  • Apples and Pears
  • Apples and Bananas
  • Apples and Oranges
  • ...

You could search for 'ap pe' and it would recognise the first row
You could search for 'banana apple' and it would recognise the second row

Demo: http://jsfiddle.net/JeroenSormani/xhpkfwgd/1/

var $rows = $('#table tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');

  $rows.hide().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    var matchesSearch = true;
    $(val).each(function(index, value) {
      matchesSearch = (!matchesSearch) ? false : ~text.indexOf(value);
    });
    return matchesSearch;
  }).show();
});

Fatal error: Maximum execution time of 30 seconds exceeded

You can do it easily with WHM. Just got to:

WHM -> Service Configuration -> PHP configuration

editor-> max_execution_time=30

( 30 is default change it to whatever value u want)

How to keep the console window open in Visual C++?

Had the same problem. I am using _getch() just before the return statement. It works.

RGB to hex and hex to RGB

@ Tim, to add to your answer (its a little awkward fitting this into a comment).

As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.

I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.

function rgbToHex(r, g, b) {
    if(r < 0 || r > 255) alert("r is out of bounds; "+r);
    if(g < 0 || g > 255) alert("g is out of bounds; "+g);
    if(b < 0 || b > 255) alert("b is out of bounds; "+b);
    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}

Clearing a string buffer/builder after loop

I suggest creating a new StringBuffer (or even better, StringBuilder) for each iteration. The performance difference is really negligible, but your code will be shorter and simpler.

How do I use sudo to redirect output to a location I don't have permission to write to?

A trick I figured out myself was

sudo ls -hal /root/ | sudo dd of=/root/test.out

Calculating how many days are between two dates in DB2?

It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

So your Query will be

select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';

What is the difference between DSA and RSA?

Btw, you cannot encrypt with DSA, only sign. Although they are mathematically equivalent (more or less) you cannot use DSA in practice as an encryption scheme, only as a digital signature scheme.

Class not registered Error

I was getting the below error in my 32 bit application.

Error: Retrieving the COM class factory for component with CLSID {4911BB26-11EE-4182-B66C-64DF2FA6502D} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

And on setting the "Enable32bitApplications" to true in defaultapplicationpool in IIS worked for me.

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

You only have to add the millisecond field in your date format string:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

The API doc of SimpleDateFormat describes the format string in detail.

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

It's in the app.config file.

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceDebug includeExceptionDetailInFaults="true"/>

ConcurrentHashMap vs Synchronized HashMap

ConcurrentHashMap :

1)Both maps are thread-safe implementations of the Map interface.

2)ConcurrentHashMap is implemented for higher throughput in cases where high concurrency is expected.

3) There is no locking in object level.

Synchronized Hash Map:

1) Each method is synchronized using an object level lock.

How do I export an Android Studio project?

As mentioned by other answers, as of now android studio does not provide this out of the box. However, there are ways to do this easily.

As mentioned by @Elad Lavi, you should consider cloud hosting of your source code. Checkout github, bitbucket, gitlab, etc. All these provide private repositories, some free, some not.

If all you want is to just zip the sources, you can achieve this using git's git archive. Here are the steps:

git init       # on the root of the project folder
git add .      # note: android studio already created .gitignore
git commit -m 'ready to zip sources'
git archive HEAD --format=zip > /tmp/archive.zip

Note: If you intend to send this by email, you have to remove gradlew.bat from zip file.

Both these solutions are possible thanks to VCS like git.

File input 'accept' attribute - is it useful?

Yes, it is extremely useful in browsers that support it, but the "limiting" is as a convenience to users (so they are not overwhelmed with irrelevant files) rather than as a way to prevent them from uploading things you don't want them uploading.

It is supported in

  • Chrome 16 +
  • Safari 6 +
  • Firefox 9 +
  • IE 10 +
  • Opera 11 +

Here is a list of content types you can use with it, followed by the corresponding file extensions (though of course you can use any file extension):

application/envoy   evy
application/fractals    fif
application/futuresplash    spl
application/hta hta
application/internet-property-stream    acx
application/mac-binhex40    hqx
application/msword  doc
application/msword  dot
application/octet-stream    *
application/octet-stream    bin
application/octet-stream    class
application/octet-stream    dms
application/octet-stream    exe
application/octet-stream    lha
application/octet-stream    lzh
application/oda oda
application/olescript   axs
application/pdf pdf
application/pics-rules  prf
application/pkcs10  p10
application/pkix-crl    crl
application/postscript  ai
application/postscript  eps
application/postscript  ps
application/rtf rtf
application/set-payment-initiation  setpay
application/set-registration-initiation setreg
application/vnd.ms-excel    xla
application/vnd.ms-excel    xlc
application/vnd.ms-excel    xlm
application/vnd.ms-excel    xls
application/vnd.ms-excel    xlt
application/vnd.ms-excel    xlw
application/vnd.ms-outlook  msg
application/vnd.ms-pkicertstore sst
application/vnd.ms-pkiseccat    cat
application/vnd.ms-pkistl   stl
application/vnd.ms-powerpoint   pot
application/vnd.ms-powerpoint   pps
application/vnd.ms-powerpoint   ppt
application/vnd.ms-project  mpp
application/vnd.ms-works    wcm
application/vnd.ms-works    wdb
application/vnd.ms-works    wks
application/vnd.ms-works    wps
application/winhlp  hlp
application/x-bcpio bcpio
application/x-cdf   cdf
application/x-compress  z
application/x-compressed    tgz
application/x-cpio  cpio
application/x-csh   csh
application/x-director  dcr
application/x-director  dir
application/x-director  dxr
application/x-dvi   dvi
application/x-gtar  gtar
application/x-gzip  gz
application/x-hdf   hdf
application/x-internet-signup   ins
application/x-internet-signup   isp
application/x-iphone    iii
application/x-javascript    js
application/x-latex latex
application/x-msaccess  mdb
application/x-mscardfile    crd
application/x-msclip    clp
application/x-msdownload    dll
application/x-msmediaview   m13
application/x-msmediaview   m14
application/x-msmediaview   mvb
application/x-msmetafile    wmf
application/x-msmoney   mny
application/x-mspublisher   pub
application/x-msschedule    scd
application/x-msterminal    trm
application/x-mswrite   wri
application/x-netcdf    cdf
application/x-netcdf    nc
application/x-perfmon   pma
application/x-perfmon   pmc
application/x-perfmon   pml
application/x-perfmon   pmr
application/x-perfmon   pmw
application/x-pkcs12    p12
application/x-pkcs12    pfx
application/x-pkcs7-certificates    p7b
application/x-pkcs7-certificates    spc
application/x-pkcs7-certreqresp p7r
application/x-pkcs7-mime    p7c
application/x-pkcs7-mime    p7m
application/x-pkcs7-signature   p7s
application/x-sh    sh
application/x-shar  shar
application/x-shockwave-flash   swf
application/x-stuffit   sit
application/x-sv4cpio   sv4cpio
application/x-sv4crc    sv4crc
application/x-tar   tar
application/x-tcl   tcl
application/x-tex   tex
application/x-texinfo   texi
application/x-texinfo   texinfo
application/x-troff roff
application/x-troff t
application/x-troff tr
application/x-troff-man man
application/x-troff-me  me
application/x-troff-ms  ms
application/x-ustar ustar
application/x-wais-source   src
application/x-x509-ca-cert  cer
application/x-x509-ca-cert  crt
application/x-x509-ca-cert  der
application/ynd.ms-pkipko   pko
application/zip zip
audio/basic au
audio/basic snd
audio/mid   mid
audio/mid   rmi
audio/mpeg  mp3
audio/x-aiff    aif
audio/x-aiff    aifc
audio/x-aiff    aiff
audio/x-mpegurl m3u
audio/x-pn-realaudio    ra
audio/x-pn-realaudio    ram
audio/x-wav wav
image/bmp   bmp
image/cis-cod   cod
image/gif   gif
image/ief   ief
image/jpeg  jpe
image/jpeg  jpeg
image/jpeg  jpg
image/pipeg jfif
image/svg+xml   svg
image/tiff  tif
image/tiff  tiff
image/x-cmu-raster  ras
image/x-cmx cmx
image/x-icon    ico
image/x-portable-anymap pnm
image/x-portable-bitmap pbm
image/x-portable-graymap    pgm
image/x-portable-pixmap ppm
image/x-rgb rgb
image/x-xbitmap xbm
image/x-xpixmap xpm
image/x-xwindowdump xwd
message/rfc822  mht
message/rfc822  mhtml
message/rfc822  nws
text/css    css
text/h323   323
text/html   htm
text/html   html
text/html   stm
text/iuls   uls
text/plain  bas
text/plain  c
text/plain  h
text/plain  txt
text/richtext   rtx
text/scriptlet  sct
text/tab-separated-values   tsv
text/webviewhtml    htt
text/x-component    htc
text/x-setext   etx
text/x-vcard    vcf
video/mpeg  mp2
video/mpeg  mpa
video/mpeg  mpe
video/mpeg  mpeg
video/mpeg  mpg
video/mpeg  mpv2
video/quicktime mov
video/quicktime qt
video/x-la-asf  lsf
video/x-la-asf  lsx
video/x-ms-asf  asf
video/x-ms-asf  asr
video/x-ms-asf  asx
video/x-msvideo avi
video/x-sgi-movie   movie
x-world/x-vrml  flr
x-world/x-vrml  vrml
x-world/x-vrml  wrl
x-world/x-vrml  wrz
x-world/x-vrml  xaf
x-world/x-vrml  xof

Printing image with PrintDocument. how to adjust the image to fit paper size

Not to trample on BBoy's already decent answer, but I've done the code that maintains aspect ratio. I took his suggestion, so he should get partial credit here!

PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
pd.DefaultPageSettings.Landscape = true; //or false!
pd.PrintPage += (sender, args) =>
{
    Image i = Image.FromFile(@"C:\...\...\image.jpg");
    Rectangle m = args.MarginBounds;

    if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
    {
        m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
    }
    else
    {
        m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
    }
    args.Graphics.DrawImage(i, m);
};
pd.Print();

Where is jarsigner?

This will install jdk for you and check for the jarsigner inside it

sudo apt install -y default-jdk

to find jarsigner you can use whereis jarsigner

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

I ran into a problem in the docker node:current-slim (running npm 7.0.9) where npm install appeared to ignore --production, --only=prod and --only=production. I found two work-arounds:

  1. use ci instead (RUN npm ci --only=production) which requires an up-to-date package-lock.json
  2. before npm install, brutally edit the package.json with:

RUN node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("./package.json", "utf-8")); delete pkg.devDependencies; fs.writeFileSync("./package.json", JSON.stringify(pkg), "utf-8");'

This won't edit your working package.json, just the one copied to the docker container. Of course, this shouldn't be necessary, but if it is (as it was for me), there's your hack.

What is the best way to delete a value from an array in Perl?

Use splice if you already know the index of the element you want to delete.

Grep works if you are searching.

If you need to do a lot of these, you will get much better performance if you keep your array in sorted order, since you can then do binary search to find the necessary index.

If it makes sense in your context, you may want to consider using a "magic value" for deleted records, rather then deleting them, to save on data movement -- set deleted elements to undef, for example. Naturally, this has its own issues (if you need to know the number of "live" elements, you need to keep track of it separately, etc), but may be worth the trouble depending on your application.

Edit Actually now that I take a second look -- don't use the grep code above. It would be more efficient to find the index of the element you want to delete, then use splice to delete it (the code you have accumulates all the non-matching results..)

my $index = 0;
$index++ until $arr[$index] eq 'foo';
splice(@arr, $index, 1);

That will delete the first occurrence. Deleting all occurrences is very similar, except you will want to get all indexes in one pass:

my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;

The rest is left as an excercise for the reader -- remember that the array changes as you splice it!

Edit2 John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.

How to split a string, but also keep the delimiters?

I like the idea of StringTokenizer because it is Enumerable.
But it is also obsolete, and replace by String.split which return a boring String[] (and does not includes the delimiters).

So I implemented a StringTokenizerEx which is an Iterable, and which takes a true regexp to split a string.

A true regexp means it is not a 'Character sequence' repeated to form the delimiter:
'o' will only match 'o', and split 'ooo' into three delimiter, with two empty string inside:

[o], '', [o], '', [o]

But the regexp o+ will return the expected result when splitting "aooob"

[], 'a', [ooo], 'b', []

To use this StringTokenizerEx:

final StringTokenizerEx aStringTokenizerEx = new StringTokenizerEx("boo:and:foo", "o+");
final String firstDelimiter = aStringTokenizerEx.getDelimiter();
for(String aString: aStringTokenizerEx )
{
    // uses the split String detected and memorized in 'aString'
    final nextDelimiter = aStringTokenizerEx.getDelimiter();
}

The code of this class is available at DZone Snippets.

As usual for a code-challenge response (one self-contained class with test cases included), copy-paste it (in a 'src/test' directory) and run it. Its main() method illustrates the different usages.


Note: (late 2009 edit)

The article Final Thoughts: Java Puzzler: Splitting Hairs does a good work explaning the bizarre behavior in String.split().
Josh Bloch even commented in response to that article:

Yes, this is a pain. FWIW, it was done for a very good reason: compatibility with Perl.
The guy who did it is Mike "madbot" McCloskey, who now works with us at Google. Mike made sure that Java's regular expressions passed virtually every one of the 30K Perl regular expression tests (and ran faster).

The Google common-library Guava contains also a Splitter which is:

  • simpler to use
  • maintained by Google (and not by you)

So it may worth being checked out. From their initial rough documentation (pdf):

JDK has this:

String[] pieces = "foo.bar".split("\\.");

It's fine to use this if you want exactly what it does: - regular expression - result as an array - its way of handling empty pieces

Mini-puzzler: ",a,,b,".split(",") returns...

(a) "", "a", "", "b", ""
(b) null, "a", null, "b", null
(c) "a", null, "b"
(d) "a", "b"
(e) None of the above

Answer: (e) None of the above.

",a,,b,".split(",")
returns
"", "a", "", "b"

Only trailing empties are skipped! (Who knows the workaround to prevent the skipping? It's a fun one...)

In any case, our Splitter is simply more flexible: The default behavior is simplistic:

Splitter.on(',').split(" foo, ,bar, quux,")
--> [" foo", " ", "bar", " quux", ""]

If you want extra features, ask for them!

Splitter.on(',')
.trimResults()
.omitEmptyStrings()
.split(" foo, ,bar, quux,")
--> ["foo", "bar", "quux"]

Order of config methods doesn't matter -- during splitting, trimming happens before checking for empties.

How I can print to stderr in C?

To print your context ,you can write code like this :

FILE *fp;
char *of;
sprintf(of,"%s%s",text1,text2);
fp=fopen(of,'w');
fprintf(fp,"your print line");

How to apply a function to two columns of Pandas dataframe

My example to your questions:

def get_sublist(row, col1, col2):
    return mylist[row[col1]:row[col2]+1]
df.apply(get_sublist, axis=1, col1='col_1', col2='col_2')

Use jQuery to scroll to the bottom of a div with lots of text

No need to calculate the actual height of the contents; you can just scroll down a lot:

$(function () {
  $('.messageScrollArea').scrollTop(1E10);
});

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

Using Font Awesome icon for bullet points, with a single list item element

I'd like to build upon some of the answers above and given elsewhere and suggest using absolute positioning along with the :before pseudo class. A lot of the examples above (and in similar questions) are utilizing custom HTML markup, including Font Awesome's method of handling. This goes against the original question, and isn't strictly necessary.

DEMO HERE

ul {
  list-style-type: none;
  padding-left: 20px;
}

li {
  position: relative;
  padding-left: 20px;
  margin-bottom: 10px
}

li:before {
  position: absolute;
  top: 0;
  left: 0;
  font-family: FontAwesome;
  content: "\f058";
  color: green;
}

That's basically it. You can get the ISO value for use in CSS content on the Font Awesome cheatsheet. Simply use the last 4 alphanumerics prefixed with a backslash. So [&#xf058;] becomes \f058

How to get a function name as a string?

import inspect

def foo():
   print(inspect.stack()[0][3])

where

  • stack()[0] is the caller

  • stack()[3] is the string name of the method

Can I add color to bootstrap icons only using CSS?

Also works with the style tag:

<span class="glyphicon glyphicon-ok" style="color:#00FF00;"></span>

<span class="glyphicon glyphicon-remove" style="color:#FF0000;"></span>

enter image description here

How does += (plus equal) work?

  1. 1 += 2 won't throw an error but you still shouldn't do it. In this statement you are basically saying "set 1 equal to 1 + 2" but 1 is a constant number and not a variable of type :number or :string so it probably wouldn't do anything. Saying
    var myVariable = 1
    myVariable += 2
    console.log(myVariable)
    
    would log 3 to the console, as x += y is just short for x = x + y
  2. var data = [1,2,3,4,5]
    var sum
    data.forEach(function(value){
      sum += value
    })
    
    would make sum = 15 because:
    sum += 1 //sum = 1
    sum += 2 //sum = 3
    sum += 3 //sum = 6
    sum += 4 //sum = 10
    sum += 5 //sum = 15
    

Why is json_encode adding backslashes?

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);

Sum all values in every column of a data.frame in R

For the sake of completion:

 apply(people[,-1], 2, function(x) sum(x))
#Height Weight 
#   199    425