Programs & Examples On #Xmp

The Adobe Extensible Metadata Platform (XMP) is a standard, created by Adobe Systems Inc., for processing and storing standardized and proprietary information relating to the contents of a file.

Getting Image from API in Angular 4/5+?

You should set responseType: ResponseContentType.Blob in your GET-Request settings, because so you can get your image as blob and convert it later da base64-encoded source. You code above is not good. If you would like to do this correctly, then create separate service to get images from API. Beacuse it ism't good to call HTTP-Request in components.

Here is an working example:

Create image.service.ts and put following code:

Angular 4:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Angular 5+:

getImage(imageUrl: string): Observable<Blob> {
  return this.httpClient.get(imageUrl, { responseType: 'blob' });
}

Important: Since Angular 5+ you should use the new HttpClient.

The new HttpClient returns JSON by default. If you need other response type, so you can specify that by setting responseType: 'blob'. Read more about that here.

Now you need to create some function in your image.component.ts to get image and show it in html.

For creating an image from Blob you need to use JavaScript's FileReader. Here is function which creates new FileReader and listen to FileReader's load-Event. As result this function returns base64-encoded image, which you can use in img src-attribute:

imageToShow: any;

createImageFromBlob(image: Blob) {
   let reader = new FileReader();
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result;
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

Now you should use your created ImageService to get image from api. You should to subscribe to data and give this data to createImageFromBlob-function. Here is an example function:

getImageFromService() {
      this.isImageLoading = true;
      this.imageService.getImage(yourImageUrl).subscribe(data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      }, error => {
        this.isImageLoading = false;
        console.log(error);
      });
}

Now you can use your imageToShow-variable in HTML template like this:

<img [src]="imageToShow"
     alt="Place image title"
     *ngIf="!isImageLoading; else noImageFound">
<ng-template #noImageFound>
     <img src="fallbackImage.png" alt="Fallbackimage">
</ng-template>

I hope this description is clear to understand and you can use it in your project.

See the working example for Angular 5+ here.

How to programmatically set the SSLContext of a JAX-WS client?

For those trying and still not getting it to work, this did it for me with Wildfly 8, using the dynamic Dispatcher:

bindingProvider.getRequestContext().put("com.sun.xml.ws.transport.https.client.SSLSocketFactory", yourSslSocketFactory);

Note that the internal part from the Property key is gone here.

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

Position absolute and overflow hidden

What about position: relative for the outer div? In the example that hides the inner one. It also won't move it in its layout since you don't specify a top or left.

Which port(s) does XMPP use?

The official ports (TCP:5222 and TCP:5269) are listed in RFC 6120. Contrary to the claims of a previous answer, XEP-0174 does not specify a port. Thus TCP:5298 might be customary for Link-Local XMPP, but is not official.

You can use other ports than the reserved ones, though: You can make your DNS SRV record point to any machine and port you like.

File transfers (XEP-0234) are these days handled using Jingle (XEP-0166). The same goes for RTP sessions (XEP-0167). They do not specify ports, though, since Jingle negotiates the creation of the data stream between the XMPP clients, but the actual data is then transferred by other means (e.g. RTP) through that stream (i.e. not usually through the XMPP server, even though in-band transfers are possible). Beware that Jingle is comprised of several XEPs, so make sure to have a look at the whole list of XMPP extensions.

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

Is there a WebSocket client implemented for Python?

web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653

What is the ellipsis (...) for in this method signature?

Those are varargs they are used to create a method that receive any number of arguments.

For instance PrintStream.printf method uses it, since you don't know how many would arguments you'll use.

They can only be used as final position of the arguments.

varargs was was added on Java 1.5

How do you use a variable in a regular expression?

Here's another replaceAll implementation:

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if ( stringToFind == stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

accessing a docker container from another container

Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.

The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.

https://deis.com/blog/2016/connecting-docker-containers-1/

The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.

Example:

you named the db container db1 and the webserver container web0. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.

So if you have a web config file for your app, then for DB host you will use the name db1.

if you are using an older version of docker, then you should use --link.

Example:

Step 1: docker run --name db1 oracle/database:12.1.0.2-ee

then when you start the web app. use:

Step 2: docker run --name web0 --link db1 webapp/webapp:3.0

and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.

I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites

an example setup is like this:

file name is base.yml

version: "2"
services:
  webserver:
    image: "moodlehq/moodle-php-apache:7.1
    depends_on:
      - db
    volumes:
      - "/var/www/html:/var/www/html"
      - "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"
  db:
    image: postgres:9
    environment:
      POSTGRES_USER: moodle
      POSTGRES_PASSWORD: "m@0dl3ing"
      POSTGRES_DB: moodle
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"

this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.

IE docker-compose --name setup1 up base.yml

NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.

Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command

best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.

Example:

db.yml

version: "2"
services:
  webserver:
    environment:
      MOODLE_DOCKER_DBTYPE: oci
      MOODLE_DOCKER_DBNAME: XE
  db:
    image: moodlehq/moodle-db-oracle

Then call docker-compose --name setup1 up base.yml db.yml

This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.

I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.

NOTE: I did not use the --port command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.

UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.

Example:

docker network create test_network

The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network switch operator.

Example:

docker run \
    --detach \
    --name db1 \
    --network test_network \
    -e MYSQL_ROOT_PASSWORD="${DBPASS}" \
    -e MYSQL_DATABASE="${DBNAME}" \
    -e MYSQL_USER="${DBUSER}" \
    -e MYSQL_PASSWORD="${DBPASS}" \
    --tmpfs /var/lib/mysql:rw \
    mysql:5

Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1. You just have to make sure all containers are connected to the same network, and you are good to go.

For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh

Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.

Why does IE9 switch to compatibility mode on my website?

I put

<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>

first thing after

<head>

(I read it somewhere, I can't recall)

I could not believe it did work!!

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

I have a use case where I think finally should be a perfectly acceptable part of the C++11 language, as I think it is easier to read from a flow point of view. My use case is a consumer/producer chain of threads, where a sentinel nullptr is sent at the end of the run to shut down all threads.

If C++ supported it, you would want your code to look like this:

    extern Queue downstream, upstream;

    int Example()
    {
        try
        {
           while(!ExitRequested())
           {
             X* x = upstream.pop();
             if (!x) break;
             x->doSomething();
             downstream.push(x);
           } 
        }
        finally { 
            downstream.push(nullptr);
        }
    }

I think this is more logical that putting your finally declaration at the start of the loop, since it occurs after the loop has exited... but that is wishful thinking because we can't do it in C++. Note that the queue downstream is connected to another thread, so you can't put in the sentinel push(nullptr) in the destructor of downstream because it can't be destroyed at this point... it needs to stay alive until the other thread receives the nullptr.

So here is how to use a RAII class with lambda to do the same:

    class Finally
    {
    public:

        Finally(std::function<void(void)> callback) : callback_(callback)
        {
        }
        ~Finally()
        {
            callback_();
        }
        std::function<void(void)> callback_;
    };

and here is how you use it:

    extern Queue downstream, upstream;

    int Example()
    {
        Finally atEnd([](){ 
           downstream.push(nullptr);
        });
        while(!ExitRequested())
        {
           X* x = upstream.pop();
           if (!x) break;
           x->doSomething();
           downstream.push(x);
        }
    }

ant warning: "'includeantruntime' was not set"

The answer from Daniel works just perfect. Here is a sample snippet that I added to my build.xml:

<target name="compile">
    <mkdir dir="${classes.dir}"/>
    <javac srcdir="${src.dir}" destdir="${classes.dir}" includeantruntime="false">
                                                 <!--   ^^^^^^^^^^^^^^^^^^^^^^^^^  -->
        <classpath>
            <path id="application" location="${jar.dir}/${ant.project.name}.jar"/>
            <path id="junit" location="${lib.dir}/junit-4.9b2.jar"/>
        </classpath>
    </javac>
</target>

Working with huge files in VIM

I had a 12GB file to edit today. The vim LargeFile plugin did not work for me. It still used up all my memory and then printed an error message :-(. I could not use hexedit for either, as it cannot insert anything, just overwrite. Here is an alternative approach:

You split the file, edit the parts and then recombine it. You still need twice the disk space though.

  • Grep for something surrounding the line you would like to edit:

    grep -n 'something' HUGEFILE | head -n 1
    
  • Extract that range of the file. Say the lines you want to edit are at line 4 and 5. Then do:

    sed -n -e '4,5p' -e '5q' HUGEFILE > SMALLPART
    
    • The -n option is required to suppress the default behaviour of sed to print everything
    • 4,5p prints lines 4 and 5
    • 5q aborts sed after processing line 5
  • Edit SMALLPART using your favourite editor.

  • Combine the file:

    (head -n 3 HUGEFILE; cat SMALLPART; sed -e '1,5d' HUGEFILE) > HUGEFILE.new 
    
    • i.e: pick all the lines before the edited lines from the HUGEFILE (which in this case is the top 3 lines), combine it with the edited lines (in this case lines 4 and 5) and use this combined set of lines to replace the equivalent (in this case the top 5 lines) in the HUGEFILE and write it all to a new file.

    HUGEFILE.new will now be your edited file, you can delete the original HUGEFILE.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

Java: Add elements to arraylist with FOR loop where element name has increasing number

Using Random function to generate number and iterating them on al using for loop

ArrayList<Integer> al=new ArrayList<Integer>(5);
    for (int i=0;i<=4;i++){

       Random rand=new Random();
        al.add(i,rand.nextInt(100));
        System.out.println(al);
    }
System.out.println(al.size());

Android: keep Service running when app is killed

If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved method of your service as follows:

 Intent intent = new Intent("com.android.ServiceStopped");
 sendBroadcast(intent);

and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.

AJAX reload page with POST

If you want to refresh the entire page, it makes no sense to use AJAX. Use normal Javascript to post the form element in that page. Make sure the form submits to the same page, or that the form submits to a page which then redirects back to that page

Javascript to be used (always in myForm.php):

function submitform()
{
  document.getElementById('myForm').submit();
}

Suppose your form is on myForm.php: Method 1:

<form action="./myForm.php" method="post" id="myForm">
    ...
</form>

Method 2:

myForm.php:

<form action="./myFormActor.php" method="post" id="myForm">
    ...
</form>

myFormActor.php:

<?php
    //all code here, no output
    header("Location: ./myForm.php");
?>

Is std::vector copying the objects with a push_back?

if you want not the copies; then the best way is to use a pointer vector(or another structure that serves for the same goal). if you want the copies; use directly push_back(). you dont have any other choice.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Add vertical scroll bar to panel

Add to your panel's style code something like this:

<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>

What and where are the stack and heap?

You can do some interesting things with the stack. For instance, you have functions like alloca (assuming you can get past the copious warnings concerning its use), which is a form of malloc that specifically uses the stack, not the heap, for memory.

That said, stack-based memory errors are some of the worst I've experienced. If you use heap memory, and you overstep the bounds of your allocated block, you have a decent chance of triggering a segment fault. (Not 100%: your block may be incidentally contiguous with another that you have previously allocated.) But since variables created on the stack are always contiguous with each other, writing out of bounds can change the value of another variable. I have learned that whenever I feel that my program has stopped obeying the laws of logic, it is probably buffer overflow.

API vs. Webservice

Think of Web service as a web api. API is such a general term now so a web service is an interface to functionality, usually business related, that you can get to from the network over a variety of protocols.

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

View/edit ID3 data for MP3 files

I wrapped mp3 decoder library and made it available for .net developers. You can find it here:

http://sourceforge.net/projects/mpg123net/

Included are the samples to convert mp3 file to PCM, and read ID3 tags.

Angularjs how to upload multipart form data and a file?

You can check out this method for sending image and form data altogether

<div class="form-group ml-5 mt-4" ng-app="myApp" ng-controller="myCtrl">
                    <label for="image_name">Image Name:</label>
                    <input type="text"   placeholder="Image name" ng-model="fileName" class="form-control" required>
                    <br>

                    <br>
                    <input id="file_src" type="file"   accept="image/jpeg" file-input="files"   >
                    <br>
                        {{file_name}}
            <img class="rounded mt-2 mb-2 " id="prvw_img" width="150" height="100" >
                    <hr>
                      <button class="btn btn-info" ng-click="uploadFile()">Upload</button>
                        <br>

                       <div ng-show = "IsVisible" class="alert alert-info w-100 shadow mt-2" role="alert">
              <strong> {{response_msg}} </strong>
            </div>
                            <div class="alert alert-danger " id="filealert"> <strong> File Size should be less than 4 MB </strong></div>
                    </div>

Angular JS Code

    var app = angular.module("myApp", []);
 app.directive("fileInput", function($parse){
      return{
           link: function($scope, element, attrs){
                element.on("change", function(event){
                     var files = event.target.files;


                     $parse(attrs.fileInput).assign($scope, element[0].files);
                     $scope.$apply();
                });
           }
      }
 });
 app.controller("myCtrl", function($scope, $http){
      $scope.IsVisible = false;
      $scope.uploadFile = function(){
           var form_data = new FormData();
           angular.forEach($scope.files, function(file){
                form_data.append('file', file); //form file
                                form_data.append('file_Name',$scope.fileName); //form text data
           });
           $http.post('upload.php', form_data,
           {
                //'file_Name':$scope.file_name;
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined,'Process-Data': false}
           }).success(function(response){
             $scope.IsVisible = $scope.IsVisible = true;
                      $scope.response_msg=response;
               // alert(response);
               // $scope.select();
           });
      }

 });

Asp.net 4.0 has not been registered

Open:

Start Menu
-> Programs
-> Microsoft Visual Studio 2010
-> Visual Studio Tools
-> Visual Studio Command Prompt (2010)

Run in command prompt:

aspnet_regiis -i

Make sure it is run at administrator, check that the title starts with Administrator:

enter image description here

How to add composite primary key to table

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

enter image description here

How to echo in PHP, HTML tags

If you want to output large quantities of HTML you should consider using heredoc or nowdoc syntax. This will allow you to write your strings without the need for escaping.

echo <<<EOD
You can put "s and 's here if you like.
EOD;

Also note that because PHP is an embedded language you can add it between you HTML content and you don't need to echo any tags.

<div>
    <p>No PHP here!</p>
    <?php
    $name = "Marcel";
    echo "<p>Hello $name!</p>";
    ?>
</div>

Also if you just want to output a variable you should use the short-hand output tags <?=$var?>. This is equivalent to <?php echo $var; ?>.

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

How do I get the last day of a month?

var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);

How can I convert a date to GMT?

I was just working on this, I may be a bit late, but I did a workaround. Here are steps: - Get current time from whatever timezone the app is fired.- - Get time zone offset of that zone from gmt 0. then add your timezone value in miliseconds. You will get the date in your time zone. I added some extra code to remove anything after the actual time.

getCurrentDate() {
    var date = new Date();
    var newDate = new Date(8 * 60 * 60000 + date.valueOf() + 
                           (date.getTimezoneOffset() * 60000));
    var ampm = newDate.getHours() < 12 ? ' AM' : ' PM';
    var strDate = newDate + '';
    return (strDate).substring(0, strDate.indexOf(' GMT')) + ampm
}

DISABLE the Horizontal Scroll

So to fix this properly, I did what others here did and used css to get hide the horizontal toolbar:

.name {
  max-width: 100%;
  overflow-x: hidden;
}

Then in js, I created an event listener to look for scrolling, and counteracted the users attempted horizontal scroll.

var scrollEventHandler = function()
{
  window.scroll(0, window.pageYOffset)
}

window.addEventListener("scroll", scrollEventHandler, false);

I saw somebody do something similar, but apparently that didn't work. This however is working perfectly fine for me.

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How to darken an image on mouseover?

Create black png with lets say 50% transparency. Overlay this on mouseover.

How to measure the a time-span in seconds using System.currentTimeMillis()?

I have written the following code in my last assignment, it may help you:

// A method that converts the nano-seconds to Seconds-Minutes-Hours form
private static String formatTime(long nanoSeconds)
{
    int hours, minutes, remainder, totalSecondsNoFraction;
    double totalSeconds, seconds;


    // Calculating hours, minutes and seconds
    totalSeconds = (double) nanoSeconds / 1000000000.0;
    String s = Double.toString(totalSeconds);
    String [] arr = s.split("\\.");
    totalSecondsNoFraction = Integer.parseInt(arr[0]);
    hours = totalSecondsNoFraction / 3600;
    remainder = totalSecondsNoFraction % 3600;
    minutes = remainder / 60;
    seconds = remainder % 60;
    if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
    else seconds += Double.parseDouble("." + arr[1]);


    // Formatting the string that conatins hours, minutes and seconds
    StringBuilder result = new StringBuilder(".");
    String sep = "", nextSep = " and ";
    if(seconds > 0)
    {
        result.insert(0, " seconds").insert(0, seconds);
        sep = nextSep;
        nextSep = ", ";
    }
    if(minutes > 0)
    {
        if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
        else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
        sep = nextSep;
        nextSep = ", ";
    }
    if(hours > 0)
    {
        if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
        else result.insert(0, sep).insert(0, " hour").insert(0, hours);
    }
    return result.toString();
}

Just convert nano-seconds to milli-seconds.

Using PI in python 2.7

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793

Check out the Python tutorial on modules and how to use them.

As for the second part of your question, Python comes with batteries included, of course:

>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793

Bootstrap visible and hidden classes not working properly

Your mobile class Isn't correct:

.mobile {
  display: none !important;
  visibility: hidden !important; //This is what's keeping the div from showing, remove this.
}

What does it mean if a Python object is "subscriptable" or not?

The meaning of subscript in computing is: "a symbol (notionally written as a subscript but in practice usually not) used in a program, alone or with others, to specify one of the elements of an array."

Now, in the simple example given by @user2194711 we can see that the appending element is not able to be a part of the list because of two reasons:-

1) We are not really calling the method append; because it needs () to call it.

2) The error is indicating that the function or method is not subscriptable; means they are not indexable like a list or sequence.

Now see this:-

>>> var = "myString"
>>> def foo(): return 0
... 
>>> var[3]
't'
>>> foo[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

That means there are no subscripts or say elements in function like they occur in sequences; and we cannot access them like we do, with the help of [].

Also; as mipadi said in his answer; It basically means that the object implements the __getitem__() method. (if it is subscriptable). Thus the error produced:

arr.append["HI"]

TypeError: 'builtin_function_or_method' object is not subscriptable

Ruby: Easiest Way to Filter Hash Keys?

Edit to original answer: Even though this is answer (as of the time of this comment) is the selected answer, the original version of this answer is outdated.

I'm adding an update here to help others avoid getting sidetracked by this answer like I did.

As the other answer mentions, Ruby >= 2.5 added the Hash#slice method which was previously only available in Rails.

Example:

> { one: 1, two: 2, three: 3 }.slice(:one, :two)
=> {:one=>1, :two=>2}

End of edit. What follows is the original answer which I guess will be useful if you're on Ruby < 2.5 without Rails, although I imagine that case is pretty uncommon at this point.


If you're using Ruby, you can use the select method. You'll need to convert the key from a Symbol to a String to do the regexp match. This will give you a new Hash with just the choices in it.

choices = params.select { |key, value| key.to_s.match(/^choice\d+/) }

or you can use delete_if and modify the existing Hash e.g.

params.delete_if { |key, value| !key.to_s.match(/choice\d+/) }

or if it is just the keys and not the values you want then you can do:

params.keys.select { |key| key.to_s.match(/^choice\d+/) }

and this will give the just an Array of the keys e.g. [:choice1, :choice2, :choice3]

Error: unexpected symbol/input/string constant/numeric constant/SPECIAL in my code

If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.

How to allocate aligned memory only using the standard library?

If there are constraints that, you cannot waste a single byte, then this solution works: Note: There is a case where this may be executed infinitely :D

   void *mem;  
   void *ptr;
try:
   mem =  malloc(1024);  
   if (mem % 16 != 0) {  
       free(mem);  
       goto try;
   }  
   ptr = mem;  
   memset_16aligned(ptr, 0, 1024);

What is a None value?

Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.

Example:

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

Now try to guess output of above list. Well, the answer is surprisingly as below:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

But Why?

Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.

However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.

list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).


'None' the savior: (Modify example above to produce desired behavior)

def extendList(val, list=None):
    if list is None:
       list = []
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

With this revised implementation, the output would be:

list1 = [10]
list2 = [123]
list3 = ['a']

Note - Example credit to toptal.com

How do I import an SQL file using the command line in MySQL?

To import a single database, use the following command.

mysql -u username -p password dbname < dump.sql

To import multiple database dumps, use the following command.

mysql -u username -p password < dump.sql

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I'm having the same problem, reading some answers (posted here), I saw my certificate expired.

Just create a new one from my start project. Then at certificates manager deleted the expired certificate.

Now everything compiles fine.

Properties file in python (similar to Java Properties)

import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)

Contents of test.json: {"host": "127.0.0.1", "user": "jms"}

Drawing Isometric game worlds

Update: Corrected map rendering algorithm, added more illustrations, changed formating.

Perhaps the advantage for the "zig-zag" technique for mapping the tiles to the screen can be said that the tile's x and y coordinates are on the vertical and horizontal axes.

"Drawing in a diamond" approach:

By drawing an isometric map using "drawing in a diamond", which I believe refers to just rendering the map by using a nested for-loop over the two-dimensional array, such as this example:

tile_map[][] = [[...],...]

for (cellY = 0; cellY < tile_map.size; cellY++):
    for (cellX = 0; cellX < tile_map[cellY].size cellX++):
        draw(
            tile_map[cellX][cellY],
            screenX = (cellX * tile_width  / 2) + (cellY * tile_width  / 2)
            screenY = (cellY * tile_height / 2) - (cellX * tile_height / 2)
        )

Advantage:

The advantage to the approach is that it is a simple nested for-loop with fairly straight forward logic that works consistently throughout all tiles.

Disadvantage:

One downside to that approach is that the x and y coordinates of the tiles on the map will increase in diagonal lines, which might make it more difficult to visually map the location on the screen to the map represented as an array:

Image of tile map

However, there is going to be a pitfall to implementing the above example code -- the rendering order will cause tiles that are supposed to be behind certain tiles to be drawn on top of the tiles in front:

Resulting image from incorrect rendering order

In order to amend this problem, the inner for-loop's order must be reversed -- starting from the highest value, and rendering toward the lower value:

tile_map[][] = [[...],...]

for (i = 0; i < tile_map.size; i++):
    for (j = tile_map[i].size; j >= 0; j--):  // Changed loop condition here.
        draw(
            tile_map[i][j],
            x = (j * tile_width / 2) + (i * tile_width / 2)
            y = (i * tile_height / 2) - (j * tile_height / 2)
        )

With the above fix, the rendering of the map should be corrected:

Resulting image from correct rendering order

"Zig-zag" approach:

Advantage:

Perhaps the advantage of the "zig-zag" approach is that the rendered map may appear to be a little more vertically compact than the "diamond" approach:

Zig-zag approach to rendering seems compact

Disadvantage:

From trying to implement the zig-zag technique, the disadvantage may be that it is a little bit harder to write the rendering code because it cannot be written as simple as a nested for-loop over each element in an array:

tile_map[][] = [[...],...]

for (i = 0; i < tile_map.size; i++):
    if i is odd:
        offset_x = tile_width / 2
    else:
        offset_x = 0

    for (j = 0; j < tile_map[i].size; j++):
        draw(
            tile_map[i][j],
            x = (j * tile_width) + offset_x,
            y = i * tile_height / 2
        )

Also, it may be a little bit difficult to try to figure out the coordinate of a tile due to the staggered nature of the rendering order:

Coordinates on a zig-zag order rendering

Note: The illustrations included in this answer were created with a Java implementation of the tile rendering code presented, with the following int array as the map:

tileMap = new int[][] {
    {0, 1, 2, 3},
    {3, 2, 1, 0},
    {0, 0, 1, 1},
    {2, 2, 3, 3}
};

The tile images are:

  • tileImage[0] -> A box with a box inside.
  • tileImage[1] -> A black box.
  • tileImage[2] -> A white box.
  • tileImage[3] -> A box with a tall gray object in it.

A Note on Tile Widths and Heights

The variables tile_width and tile_height which are used in the above code examples refer to the width and height of the ground tile in the image representing the tile:

Image showing the tile width and height

Using the dimensions of the image will work, as long as the image dimensions and the tile dimensions match. Otherwise, the tile map could be rendered with gaps between the tiles.

jQuery serialize does not register checkboxes

The trick is to intercept the form post and change the check boxes to hidden input fields.

Example: Plain Submit

$('form').on("submit", function (e) {
    //find the checkboxes
    var $checkboxes = $(this).find('input[type=checkbox]');

    //loop through the checkboxes and change to hidden fields
    $checkboxes.each(function() {
        if ($(this)[0].checked) {
            $(this).attr('type', 'hidden');
            $(this).val(1);
        } else {
            $(this).attr('type', 'hidden');
            $(this).val(0);
        }
    });
});

Example: AJAX

You need to jump through a few more hoops if you are posting the form via ajax to not update the UI.

$('form').on("submit", function (e) {
    e.preventDefault();

    //clone the form, we don't want this to impact the ui
    var $form = $('form').clone();

    //find the checkboxes
    var $checkboxes = $form.find('input[type=checkbox]');

    //loop through the checkboxes and change to hidden fields
    $checkboxes.each(function() {
        if ($(this)[0].checked) {
            $(this).attr('type', 'hidden');
            $(this).val(1);
        } else {
            $(this).attr('type', 'hidden');
            $(this).val(0);
        }
    });

    $.post("/your/path", $form.serialize());

How do I center floated elements?

Just adding

left:15%; 

into my css menu of

#menu li {
float: left;
position:relative;
left: 15%;
list-style:none;
}

did the centering trick too

What's the difference between compiled and interpreted language?

As other have said, compiled and interpreted are specific to an implementation of a programming language; they are not inherent in the language. For example, there are C interpreters.

However, we can (and in practice we do) classify programming languages based on its most common (sometimes canonical) implementation. For example, we say C is compiled.

First, we must define without ambiguity interpreters and compilers:

An interpreter for language X is a program (or a machine, or just some kind of mechanism in general) that executes any program p written in language X such that it performs the effects and evaluates the results as prescribed by the specification of X.

A compiler from X to Y is a program (or a machine, or just some kind of mechanism in general) that translates any program p from some language X into a semantically equivalent program p' in some language Y in such a way that interpreting p' with an interpreter for Y will yield the same results and have the same effects as interpreting p with an interpreter for X.

Notice that from a programmer point of view, CPUs are machine interpreters for their respective native machine language.

Now, we can do a tentative classification of programming languages into 3 categories depending on its most common implementation:

  • Hard Compiled languages: When the programs are compiled entirely to machine language. The only interpreter used is a CPU. Example: Usually, to run a program in C, the source code is compiled to machine language, which is then executed by a CPU.
  • Interpreted languages: When there is no compilation of any part of the original program to machine language. In other words, no new machine code is generated; only existing machine code is executed. An interpreter other than the CPU must also be used (usually a program).Example: In the canonical implementation of Python, the source code is compiled first to Python bytecode and then that bytecode is executed by CPython, an interpreter program for Python bytecode.
  • Soft Compiled languages: When an interpreter other than the CPU is used but also parts of the original program may be compiled to machine language. This is the case of Java, where the source code is compiled to bytecode first and then, the bytecode may be interpreted by the Java Interpreter and/or further compiled by the JIT compiler.

Sometimes, soft and hard compiled languages are refered to simply compiled, thus C#, Java, C, C++ are said to be compiled.

Within this categorization, JavaScript used to be an interpreted language, but that was many years ago. Nowadays, it is JIT-compiled to native machine language in most major JavaScript implementations so I would say that it falls into soft compiled languages.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

Another possible case if none works is to see that there is a running Java application . may be your previous open and close has left unkilled java instances.

  1. Do look for any java instance is running if there are two at least you need to kill one.But ,most of the time i kill any java running :) because that java is using the work space earlier and still will if don't kill it.

  2. Change another work space in case if you want a multiple IDE to use and work on diffrent or same project , but you should import project form workspace after you open your IDE.

How can I test a change made to Jenkinsfile locally?

Aside from the Replay feature that others already mentioned (ditto on its usefulness!), I found the following to be useful as well:

  1. Create a test Pipeline job where you can type in Pipeline code or point to your repo/branch of a Jenkinsfile to quickly test out something. For more accurate testing, use a Multibranch Pipeline that points to your own fork where you can quickly make changes and commit without affecting prod. Stuff like BRANCH_NAME env is only available in Multibranch.
  2. Since Jenkinsfile is Groovy code, simply invoke it with "groovy Jenkinsfile" to validate basic syntax.

Get text from pressed button

Try to use:

String buttonText = ((Button)v).getText().toString();

What is Linux’s native GUI API?

Wayland

As you might hear, wayland is the featured choice of many distros these days, because of its protocol is simpler than the X.

Toolkits of wayland

Toolkits or gui libraries that wayland suggests are:

  • QT 5
  • GTK+
  • LSD
  • Clutter
  • EFL

python requests file upload

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

Understanding the Rails Authenticity Token

Methods Where authenticity_token is required

authenticity_token is required in case of idempotent methods like post, put and delete, Because Idempotent methods are affecting to data.

Why It is Required

It is required to prevent from evil actions. authenticity_token is stored in session, whenever a form is created on web pages for creating or updating to resources then a authenticity token is stored in hidden field and it sent with form on server. Before executing action user sent authenticity_token is cross checked with authenticity_token stored in session. If authenticity_token is same then process is continue otherwise it does not perform actions.

Why extend the Android Application class?

Source: https://github.com/codepath/android_guides/wiki/Understanding-the-Android-Application-Class

In many apps, there's no need to work with an application class directly. However, there are a few acceptable uses of a custom application class:

  • Specialized tasks that need to run before the creation of your first activity
  • Global initialization that needs to be shared across all components (crash reporting, persistence)
  • Static methods for easy access to static immutable data such as a shared network client object

You should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

An array of List in c#

I can suggest that you both create and initialize your array at the same line using linq:

List<int>[] a = new List<int>[100].Select(item=>new List<int>()).ToArray();

C++ compiling on Windows and Linux: ifdef switch

It depends on the compiler. If you compile with, say, G++ on Linux and VC++ on Windows, this will do :

#ifdef linux
    ...
#elif _WIN32
    ...
#else
    ...
#endif

Count number of records returned by group by

Following for PrestoDb, where FirstField can have multiple values:

select *
            , concat(cast(cast((ThirdTable.Total_Records_in_Group * 100 / ThirdTable.Total_Records_in_baseTable) as DECIMAL(5,2)) as varchar), '%') PERCENTage
from 
(
    SELECT FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable, count(*) Total_Records_in_Group
    FROM BaseTable FirstTable
    JOIN (
            SELECT FK1, count(*) AS Total_Records_in_baseTable 
            FROM BaseTable
            GROUP BY FK1
        ) SecondTable
    ON FirstTable.FirstField = SecondTable.FK1
    GROUP BY FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable
    ORDER BY FirstTable.FirstField, FirstTable.SecondField
) ThirdTable

Read all worksheets in an Excel workbook into an R list with data.frames

I tried the above and had issues with the amount of data that my 20MB Excel I needed to convert consisted of; therefore the above did not work for me.

After more research I stumbled upon openxlsx and this one finally did the trick (and fast) Importing a big xlsx file into R?

https://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf

How to fix git error: RPC failed; curl 56 GnuTLS

I am also using Ubuntu based system (Mint mate 18), got the similar issue when clone large repo from github.

The simple solution worked for me is to use ssh protocol instead of http(s) protocol.

e.g

git clone [email protected]:xxx/yyy.git

Converting integer to binary in python

def int_to_bin(num, fill):
    bin_result = ''

    def int_to_binary(number):
        nonlocal bin_result
        if number > 1:
            int_to_binary(number // 2)
        bin_result = bin_result + str(number % 2)

    int_to_binary(num)
    return bin_result.zfill(fill)

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

give polpetta a try ...

npm install -g polpetta

then you can

polpetta ~/folder

and you are ready to go :-)

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How can I check if given int exists in array?

You almost never have to write your own loops in C++. Here, you can use std::find.

const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
  std::cout << "Found.\n"
}
else
{
  std::cout << "Not found.\n";
}

std::end requires C++11. Without it, you can find the number of elements in the array with:

const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);

...and the end with:

int* end = myArray + numElements;

Should I declare Jackson's ObjectMapper as a static field?

Although it is safe to declare a static ObjectMapper in terms of thread safety, you should be aware that constructing static Object variables in Java is considered bad practice. For more details, see Why are static variables considered evil? (and if you'd like, my answer)

In short, statics should be avoided because the make it difficult to write concise unit tests. For example, with a static final ObjectMapper, you can't swap out the JSON serialization for dummy code or a no-op.

In addition, a static final prevents you from ever reconfiguring ObjectMapper at runtime. You might not envision a reason for that now, but if you lock yourself into a static final pattern, nothing short of tearing down the classloader will let you re-initialize it.

In the case of ObjectMapper its fine, but in general it is bad practice and there is no advantage over using a singleton pattern or inversion-of-control to manage your long-lived objects.

Select statement to find duplicates on certain fields

Try this query to find duplicate records on multiple fields

SELECT a.column1, a.column2
FROM dbo.a a
JOIN (SELECT column1, 
       column2, count(*) as countC
FROM dbo.a 
GROUP BY column4, column5
HAVING count(*) > 1 ) b
ON a.column1 = b.column1
AND a.column2 = b.column2

jQuery get the location of an element relative to window

    function trbl(e, relative) {
            var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);

            return {
                    t : r.top    + relative['scrollTop'] (),
                    r : r.right  + relative['scrollLeft'](),
                    b : r.bottom + relative['scrollTop'] (),
                    l : r.left   + relative['scrollLeft']() 

            }
    }

    // Example
    trbl(e, window);

How to pass anonymous types as parameters?

You can do it like this:

public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
    foreach (T item in list)
    {

    }
}

... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name and Id directly.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

Your file doesn't actually contain UTF-8 encoded data; it contains some other encoding. Figure out what that encoding is and use it in the open call.

In Windows-1252 encoding, for example, the 0xe9 would be the character é.

Replace \n with <br />

You could also have problems if the string has <, > or & chars in it, etc. Pass it to cgi.escape() to deal with those.

http://docs.python.org/library/cgi.html?highlight=cgi#cgi.escape

List<T> or IList<T>

The interface ensures that you at least get the methods you are expecting; being aware of the definition of the interface ie. all abstract methods that are there to be implemented by any class inheriting the interface. so if some one makes a huge class of his own with several methods besides the ones he inherited from the interface for some addition functionality, and those are of no use to you, its better to use a reference to a subclass (in this case the interface) and assign the concrete class object to it.

additional advantage is that your code is safe from any changes to concrete class as you are subscribing to only few of the methods of concrete class and those are the ones that are going to be there as long as the concrete class inherits from the interface you are using. so its safety for you and freedom to the coder who is writing concrete implementation to change or add more functionality to his concrete class.

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

Socket.IO - how do I get a list of connected sockets/clients?

In Socket.IO 1.4

To get the array of All connected Users :

var allConnectedClients = Object.keys(io.sockets.connected);// This will return the array of SockeId of all the connected clients

To get the Count of all clients :

var clientsCount = io.engine.clientsCount ; // This will return the count of connected clients

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

Re-ordering columns in pandas dataframe based on column name

If you need an arbitrary sequence instead of sorted sequence, you could do:

sequence = ['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]
your_dataframe = your_dataframe.reindex(columns=sequence)

I tested this in 2.7.10 and it worked for me.

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

The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:

Maven defines 4 items of a build process:

  1. Lifecycle

    Three built-in lifecycles (aka build lifecycles): default, clean, site. (Lifecycle Reference)

  2. Phase

    Each lifecycle is made up of phases, e.g. for the default lifecycle: compile, test, package, install, etc.

  3. Plugin

    An artifact that provides one or more goals.

    Based on packaging type (jar, war, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)

  4. Goal

    The task (action) that is executed. A plugin can have one or more goals.

    One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.

Maven can be invoked with:

  1. a phase (e.g clean, package)
  2. <plugin-prefix>:<goal> (e.g. dependency:copy-dependencies)
  3. <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal> (e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile)

with one or more combinations of any or all, e.g.:

mvn clean dependency:copy-dependencies package

How can I pass a parameter to a Java Thread?

You can derive a class from Runnable, and during the construction (say) pass the parameter in.

Then launch it using Thread.start(Runnable r);

If you mean whilst the thread is running, then simply hold a reference to your derived object in the calling thread, and call the appropriate setter methods (synchronising where appropriate)

Animate background image change with jQuery

building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:

http://jsfiddle.net/srd76/36/

$(document).ready(function(){

var images = Array("http://placekitten.com/500/200",
               "http://placekitten.com/499/200",
               "http://placekitten.com/501/200",
               "http://placekitten.com/500/199");
var currimg = 0;


function loadimg(){

   $('#background').animate({ opacity: 1 }, 500,function(){

        //finished animating, minifade out and fade new back in           
        $('#background').animate({ opacity: 0.7 }, 100,function(){

            currimg++;

            if(currimg > images.length-1){

                currimg=0;

            }

            var newimage = images[currimg];

            //swap out bg src                
            $('#background').css("background-image", "url("+newimage+")"); 

            //animate fully back in
            $('#background').animate({ opacity: 1 }, 400,function(){

                //set timer for next
                setTimeout(loadimg,5000);

            });

        });

    });

  }
  setTimeout(loadimg,5000);

});

Escape sequence \f - form feed - what exactly is it?

It comes from the era of Line Printers and green-striped fan-fold paper.

Trust me, you ain't gonna need it...

Java Reflection: How to get the name of a variable?

You can do like this:

Field[] fields = YourClass.class.getDeclaredFields();
//gives no of fields
System.out.println(fields.length);         
for (Field field : fields) {
    //gives the names of the fields
    System.out.println(field.getName());   
}

Form Submit Execute JavaScript Best Practice?

I know it's a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.

function validate(){
    //do stuff
}
function init(){
    document.getElementById('form').onsubmit = validate;
}
window.onload = init;

That way you don't have a bunch of event listeners throughout your HTML.

Should you always favor xrange() over range()?

While xrange is faster than range in most circumstances, the difference in performance is pretty minimal. The little program below compares iterating over a range and an xrange:

import timeit
# Try various list sizes.
for list_len in [1, 10, 100, 1000, 10000, 100000, 1000000]:
  # Time doing a range and an xrange.
  rtime = timeit.timeit('a=0;\nfor n in range(%d): a += n'%list_len, number=1000)
  xrtime = timeit.timeit('a=0;\nfor n in xrange(%d): a += n'%list_len, number=1000)
  # Print the result
  print "Loop list of len %d: range=%.4f, xrange=%.4f"%(list_len, rtime, xrtime)

The results below shows that xrange is indeed faster, but not enough to sweat over.

Loop list of len 1: range=0.0003, xrange=0.0003
Loop list of len 10: range=0.0013, xrange=0.0011
Loop list of len 100: range=0.0068, xrange=0.0034
Loop list of len 1000: range=0.0609, xrange=0.0438
Loop list of len 10000: range=0.5527, xrange=0.5266
Loop list of len 100000: range=10.1666, xrange=7.8481
Loop list of len 1000000: range=168.3425, xrange=155.8719

So by all means use xrange, but unless you're on a constrained hardware, don't worry too much about it.

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

If so,go into your config file,my.cnf and add or uncomment these lines:

character-set-server = utf8
collation-server = utf8_unicode_ci

Restart the server. Yes late to the party,just encountered the same issue.

C++/CLI Converting from System::String^ to std::string

C# uses the UTF16 format for its strings.
So, besides just converting the types, you should also be conscious about the string's actual format.

When compiling for Multi-byte Character set Visual Studio and the Win API assumes UTF8 (Actually windows encoding which is Windows-28591 ).
When compiling for Unicode Character set Visual studio and the Win API assume UTF16.

So, you must convert the string from UTF16 to UTF8 format as well, and not just convert to std::string.
This will become necessary when working with multi-character formats like some non-latin languages.

The idea is to decide that std::wstring always represents UTF16.
And std::string always represents UTF8.

This isn't enforced by the compiler, it's more of a good policy to have.

#include "stdafx.h"
#include <string>
#include <codecvt>
#include <msclr\marshal_cppstd.h>

using namespace System;

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;

    //Actual format is UTF16, so represent as wstring
    std::wstring utf16NativeString = context.marshal_as<std::wstring>(managedString); 

    //C++11 format converter
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    //convert to UTF8 and std::string
    std::string utf8NativeString = convert.to_bytes(utf16NativeString);

    return 0;
}

Or have it in a more compact syntax:

int main(array<System::String ^> ^args)
{
    System::String^ managedString = "test";

    msclr::interop::marshal_context context;
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> convert;

    std::string utf8NativeString = convert.to_bytes(context.marshal_as<std::wstring>(managedString));

    return 0;
}

Adding a css class to select using @Html.DropDownList()

As the signature from the error message implies, the second argument must be an IEnumerable, more specifically, an IEnumerable of SelectListItem. It is the list of choices. You can use the SelectList type, which is a IEnumerable of SelectListItem. For a list with no choices:

@Html.DropDownList("PriorityID", new List<SelectListItem>(), new {@class="textbox"} )

For a list with a few choices:

@Html.DropDownList(
    "PriorityID", 
    new List<SelectListItem> 
    { 
        new SelectListItem { Text = "High", Value = 1 }, 
        new SelectListItem { Text = "Low",  Value = 0 },
    }, 
    new {@class="textbox"})

Maybe this tutorial can be of help: How to create a DropDownList with ASP.NET MVC

Update ViewPager dynamically?

This solution won't work for everyone, but in my case, every Fragment in my ViewPager is a different class, and only one of them ever exist at a time.

With this constraint, this solution is safe and should be safe to use in production.

private void updateFragment(Item item) {

    List<Fragment> fragments = getSupportFragmentManager().getFragments();
    for (Fragment fragment : fragments) {

        if (fragment instanceof MyItemFragment && fragment.isVisible()) {
            ((MyItemFragment) fragment).update(item);
        }

    }
}

If you have multiple versions of the same fragment, you can use this same strategy to call methods on those fragments to determine if it is the fragment you wish to update.

Datetime equal or greater than today in MySQL

If 'created' is datetime type

SELECT * FROM users WHERE created < DATE_ADD(CURDATE(), INTERVAL 1 DAY);

CURDATE() means also '2013-05-09 00:00:00'

How to include static library in makefile

The -L merely gives the path where to find the .a or .so file. What you're looking for is to add -lmine to the LIBS variable.

Make that -static -lmine to force it to pick the static library (in case both static and dynamic library exist).

Addition: Suppose the path to the file has been conveyed to the linker (or compiler driver) via -L you can also specifically tell it to link libfoo.a by giving -l:libfoo.a. Note that in this case the name includes the conventional lib-prefix. You can also give a full path this way. Sometimes this is the better method to "guide" the linker to the right location.

String array initialization in Java

You can do the following during declaration:

String names[] = {"Ankit","Bohra","Xyz"};

And if you want to do this somewhere after declaration:

String names[];
names = new String[] {"Ankit","Bohra","Xyz"};

How to add empty spaces into MD markdown readme on GitHub?

Markdown gets converted into HTML/XHMTL.

John Gruber created the Markdown language in 2004 in collaboration with Aaron Swartz on the syntax, with the goal of enabling people to write using an easy-to-read, easy-to-write plain text format, and optionally convert it to structurally valid HTML (or XHTML).

HTML is completely based on using &nbsp; for adding extra spaces if it doesn't externally define/use JavaScript or CSS for elements.

Markdown is a lightweight markup language with plain text formatting syntax. It is designed so that it can be converted to HTML and many other formats using a tool by the same name.


If you want to use »

  1. only one space » either use &nbsp; or just hit Spacebar (2nd one is good choice in this case)

  2. more than one space » use &nbsp;+space (for 2 consecutive spaces)


eg. If you want to add 10 spaces contiguously then you should use

&nbsp;   &nbsp;   &nbsp;   &nbsp;   &nbsp;  

&nbsp;space&nbsp;space&nbsp;space&nbsp;space&nbsp;space

instead of using 10 &nbsp; one after one as the below one

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;


For more details check

  1. Adding multiple spaces between text in Markdown,
  2. How to create extra space in HTML or web page.

jQuery, get ID of each element in a class using .each?

Try this, replacing .myClassName with the actual name of the class (but keep the period at the beginning).

$('.myClassName').each(function() {
    alert( this.id );
});

So if the class is "test", you'd do $('.test').each(func....

This is the specific form of .each() that iterates over a jQuery object.

The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t.

Using that form of $.each(), you would need to do it like this:

$.each($('.myClassName'), function() {
    alert( this.id );
});

...which will have the same result as the example above.

How to add "active" class to Html.ActionLink in ASP.NET MVC

This solution is simple for Asp.net MCV 5.

  1. Create a static class, for example Utilitarios.cs.

  2. Inside the Class create a static method:

    public static string IsLinkActive(this UrlHelper url, string action, string controller)
    {
        if (url.RequestContext.RouteData.Values["controller"].ToString() == controller &&
            url.RequestContext.RouteData.Values["action"].ToString() == action)
        {
            return "active";
        }
    
        return "";
    }
    
  3. call like this

    <ul class="sidebar-menu" data-widget="tree">
        <li class="header">HEADER</li>
        <li class="@Url.IsLinkActive("Index", "Home")">
            <a href="@Url.Action("Index", "Home")"><i class="fa fa-link"></i> <span>Home</span></a>
        </li>
        <li class="@Url.IsLinkActive("About", "Home")">
            <a href="@Url.Action("About", "Home")"><i class="fa fa-link"></i><span>About</span></a>
        </li>
    </ul>
    

Rotating a Div Element in jQuery

To rotate a DIV Make use of WebkitTransform / -moz-transform: rotate(Xdeg).

This will not work in IE. The Raphael library does work with IE and it does rotation. I believe it uses canvases

If you want to animate the rotation, you can use a recursive setTimeout()

You could probably even do part of a spin with jQuery's .animate()

Make sure that you consider the width of your element. If rotate an that has a larger width than its visible content, you'll get funny results. However you can narrow the widths of elements, and then rotate them.

Here is a simply jQuery snippet that rotates the elements in a jQuery object. Rotatation can be started and stopped:

$(function() {
    var $elie = $(selectorForElementsToRotate);
    rotate(0);
    function rotate(degree) {

          // For webkit browsers: e.g. Chrome
        $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
          // For Mozilla browser: e.g. Firefox
        $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

          // Animate rotation with a recursive call
        setTimeout(function() { rotate(++degree); },5);
    }
});

jsFiddle example

Note:
Taking the degree and increasing it, will rotate the image clockwise. Decreasing the degree of rotation will rotate the image counter clockwise.

How to convert a string to integer in C?

This function will help you

int strtoint_n(char* str, int n)
{
    int sign = 1;
    int place = 1;
    int ret = 0;

    int i;
    for (i = n-1; i >= 0; i--, place *= 10)
    {
        int c = str[i];
        switch (c)
        {
            case '-':
                if (i == 0) sign = -1;
                else return -1;
                break;
            default:
                if (c >= '0' && c <= '9')   ret += (c - '0') * place;
                else return -1;
        }
    }

    return sign * ret;
}

int strtoint(char* str)
{
    char* temp = str;
    int n = 0;
    while (*temp != '\0')
    {
        n++;
        temp++;
    }
    return strtoint_n(str, n);
}

Ref: http://amscata.blogspot.com/2013/09/strnumstr-version-2.html

Bootstrap footer at the bottom of the page

You can just add style="min-height:100vh" to your page content conteiner and place footer in another conteiner

How to ignore parent css style

It must be overridden. You could use:

<!-- Add a class name to override -->
<select name="funTimes" class="funTimes" size="5">

#elementId select.funTimes {
   /* Override styles here */
}

Make sure you use !important flag in css style e.g. margin-top: 0px !important What does !important mean in CSS?

You could use an attribute selector, but since that isn't supported by legacy browsers (read IE6 etc), it's better to add a class name

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

The first syntax is redundant - the WITH CHECK is default for new constraints, and the constraint is turned on by default as well.

This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.

What is the effect of encoding an image in base64?

It will definitely cost you more space & bandwidth if you want to use base64 encoded images. However if your site has a lot of small images you can decrease the page loading time by encoding your images to base64 and placing them into html. In this way, the client browser wont need to make a lot of connections to the images, but will have them in html.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

Here is another solution if you want to include different browsers in on file. If you and Mac user, from sublime menu go to, Tools > New Plugin. Delete the generated code and past the following:

import sublime, sublime_plugin
import webbrowser


class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self,edit,keyPressed):
      url = self.view.file_name()
      if keyPressed == "1":
         navegator = webbrowser.get("open -a /Applications/Firefox.app %s")
      if keyPressed == "2":
         navegator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
      if keyPressed == "3":
         navegator = webbrowser.get("open -a /Applications/Safari.app %s")
      navegator.open_new(url)

Save. Then open up User Keybindings. (Tools > Command Palette > "User Key bindings"), and add this somewhere to the list:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3"}}

Now open any html file in Sublime and use one of the keybindings, which it would open that file in your favourite browser.

How may I align text to the left and text to the right in the same line?

Add span on each or group of words you want to align left or right. then add id or class on the span such as:

<h3>
<span id = "makeLeft"> Left Text</span>
<span id = "makeRight"> Right Text</span>
</h3>

CSS-

#makeLeft{
float: left;
}

#makeRight{
float: right;
}

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

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

To summarize the contents of other (already good!) answers, isinstance caters for inheritance (an instance of a derived class is an instance of a base class, too), while checking for equality of type does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).

Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so isinstance is less bad than checking identity of types because it seamlessly supports inheritance.

It's not that isinstance is good, mind you—it's just less bad than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except clause, try something else (using the argument "as if" it was of some other type).

basestring is, however, quite a special case—a builtin type that exists only to let you use isinstance (both str and unicode subclass basestring). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" types—it's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and basestring plus isinstance helps you do that—the overall structure of this idiom is something like:

if isinstance(x, basestring)
  return treatasscalar(x)
try:
  return treatasiter(iter(x))
except TypeError:
  return treatasscalar(x)

You could say that basestring is an Abstract Base Class ("ABC")—it offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with isinstance. The concept is obviously a growing one in Python, since PEP 3119, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.

The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that (see here). ABCs as implemented in recent Python versions do however offer extra goodies: isinstance (and issubclass) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications (see here and here [[part II]] for more on the TM DP, in general and specifically in Python, independent of ABCs).

For the underlying mechanics of ABC support as offered in Python 2.6, see here; for their 3.1 version, very similar, see here. In both versions, standard library module collections (that's the 3.1 version—for the very similar 2.6 version, see here) offers several useful ABCs.

For the purpose of this answer, the key thing to retain about ABCs (beyond an arguably more natural placement for TM DP functionality, compared to the classic Python alternative of mixin classes such as UserDict.DictMixin) is that they make isinstance (and issubclass) much more attractive and pervasive (in Python 2.6 and going forward) than they used to be (in 2.5 and before), and therefore, by contrast, make checking type equality an even worse practice in recent Python versions than it already used to be.

How do I implement __getattribute__ without an infinite recursion error?

Python language reference:

In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.__getattribute__(self, name).

Meaning:

def __getattribute__(self,name):
    ...
        return self.__dict__[name]

You're calling for an attribute called __dict__. Because it's an attribute, __getattribute__ gets called in search for __dict__ which calls __getattribute__ which calls ... yada yada yada

return  object.__getattribute__(self, name)

Using the base classes __getattribute__ helps finding the real attribute.

$rootScope.$broadcast vs. $scope.$emit

tl;dr (this tl;dr is from @sp00m's answer below)

$emit dispatches an event upwards ... $broadcast dispatches an event downwards

Detailed explanation

$rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them.

$rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it.

$scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear).

$scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.

How to check whether a string is a valid HTTP URL?

bool passed = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Slack clean all messages (~8K) in a channel

!!UPDATE!!

as @niels-van-reijmersdal metioned in comment.

This feature has been removed. See this thread for more info: twitter.com/slackhq/status/467182697979588608?lang=en

!!END UPDATE!!

Here is a nice answer from SlackHQ in twitter, and it works without any third party stuff. https://twitter.com/slackhq/status/467182697979588608?lang=en

You can bulk delete via the archives (http://my.slack.com/archives ) page for a particular channel: look for "delete messages" in menu

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.

Purpose of returning by const value?

It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.

Though any optimizer would most likely optimize it out anyway...

Pandas dataframe fillna() only some columns in place

For some odd reason this DID NOT work (using Pandas: '0.25.1')

df[['col1', 'col2']].fillna(value=0, inplace=True)

Another solution:

subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]

Example:

df = pd.DataFrame(data={'col1':[1,2,np.nan,], 'col2':[1,np.nan,3], 'col3':[np.nan,2,3]})

output:

   col1  col2  col3
0  1.00  1.00   nan
1  2.00   nan  2.00
2   nan  3.00  3.00

Apply list comp. to fillna values:

subset_cols = ['col1','col2']
[df[col].fillna(0, inplace=True) for col in subset_cols]

Output:

   col1  col2  col3
0  1.00  1.00   nan
1  2.00  0.00  2.00
2  0.00  3.00  3.00

Remove quotes from String in Python

if string.startswith('"'):
    string = string[1:]

if string.endswith('"'):
    string = string[:-1]

"You may need an appropriate loader to handle this file type" with Webpack and Babel

BABEL TEAM UPDATE:

We're super excited that you're trying to use ES2015 syntax, but instead of continuing yearly presets, the team recommends using babel-preset-env. By default, it has the same behavior as previous presets to compile ES2015+ to ES5

If you are using Babel version 7 you will need to run npm install @babel/preset-env and have "presets": ["@babel/preset-env"] in your .babelrc configuration.

This will compile all latest features to es5 transpiled code:

Prerequisites:

  1. Webpack 4+
  2. Babel 7+

Step-1:: npm install --save-dev @babel/preset-env

Step-2: In order to compile JSX code to es5 babel provides @babel/preset-react package to convert reactjsx extension file to native browser understandable code.

Step-3: npm install --save-dev @babel/preset-react

Step-4: create .babelrc file inside root path path of your project where webpack.config.js exists.

{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

Step-5: webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        path: path.resolve(__dirname, 'output'),
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [{
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader'
                }
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./public/index.html",
            filename: "./index.html"
         })
    ]
}

Start new Activity and finish current one in Android?

FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.

http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY

grep without showing path/file:line

From the man page:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default when there
    is only one file (or only standard input) to search.

How to autosize a textarea using Prototype?

Internet Explorer, Safari, Chrome and Opera users need to remember to explicidly set the line-height value in CSS. I do a stylesheet that sets the initial properites for all text boxes as follows.

<style>
    TEXTAREA { line-height: 14px; font-size: 12px; font-family: arial }
</style>

Best way to remove from NSMutableArray while iterating?

Either use loop counting down over indices:

for (NSInteger i = array.count - 1; i >= 0; --i) {

or make a copy with the objects you want to keep.

In particular, do not use a for (id object in array) loop or NSEnumerator.

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

Could not commit JPA transaction: Transaction marked as rollbackOnly

For those who can't (or don't want to) setup a debugger to track down the original exception which was causing the rollback-flag to get set, you can just add a bunch of debug statements throughout your code to find the lines of code which trigger the rollback-only flag:

logger.debug("Is rollbackOnly: " + TransactionAspectSupport.currentTransactionStatus().isRollbackOnly());

Adding this throughout the code allowed me to narrow down the root cause, by numbering the debug statements and looking to see where the above method goes from returning "false" to "true".

SQL User Defined Function Within Select

Use a scalar-valued UDF, not a table-value one, then you can use it in a SELECT as you want.

How to convert int to string on Arduino?

Here below is a self composed myitoa() which is by far smaller in code, and reserves a FIXED array of 7 (including terminating 0) in char *mystring, which is often desirable. It is obvious that one can build the code with character-shift instead, if one need a variable-length output-string.

void myitoa(int number, char *mystring) {
  boolean negative = number>0;

  mystring[0] = number<0? '-' : '+';
  number = number<0 ? -number : number;
  for (int n=5; n>0; n--) {
     mystring[n] = ' ';
     if(number > 0) mystring[n] = number%10 + 48;
     number /= 10;
  }  
  mystring[6]=0;
}

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

SELECT COLUMN_NAME, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.columns WHERE table_name = '<name_of_table_or_view>'

Run SELECT * in the above statement to see what information_schema.columns returns.

This question has been previously answered - https://stackoverflow.com/a/11268456/6169225

Javascript code for showing yesterday's date and todays date

Yesterday Date can be calculated as:-

let now = new Date();
    var defaultDate = now - 1000 * 60 * 60 * 24 * 1;
    defaultDate = new Date(defaultDate);

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Compilation error: stray ‘\302’ in program etc

Whenever compiler found special character .. it gives these king of compile error .... what error i found is as following

error: stray '\302' in program and error: stray '\240' in program

....

Some piece of code i copied from chatting messanger. In messanger it was special character only.. after copiying into vim editor it changed to correct character only. But compiler was giving above error .. then .. that stamenet i wrote mannualy after .. it got resolve.. :)

How do I use IValidatableObject?

The thing i don't like about iValidate is it seems to only run AFTER all other validation.
Additionally, at least in our site, it would run again during a save attempt. I would suggest you simply create a function and place all your validation code in that. Alternately for websites, you could have your "special" validation in the controller after the model is created. Example:

 public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Exclude = "Terminal")] Driver driver)
    {

        if (db.Drivers.Where(m => m.IDNumber == driver.IDNumber && m.ID != driver.ID).Any())
        {
            ModelState.AddModelError("Update", string.Format("ID # '{0}' is already in use", driver.IDNumber));
        }
        if (db.Drivers.Where(d => d.CarrierID == driver.CarrierID
                                && d.FirstName.Equals(driver.FirstName, StringComparison.CurrentCultureIgnoreCase)
                                && d.LastName.Equals(driver.LastName, StringComparison.CurrentCultureIgnoreCase)
                                && (driver.ID == 0 || d.ID != driver.ID)).Any())
        {
            ModelState.AddModelError("Update", "Driver already exists for this carrier");
        }

        if (ModelState.IsValid)
        {
            try
            {

How to clear the Entry widget after a button is pressed in Tkinter?

First of all, make sure the Text is enabled, then delete your tags, and then the content.

myText.config(state=NORMAL)
myText.tag_delete ("myTags")
myText.delete(1.0, END)

When the Text is "DISABLE", the delete does not work because the Text field is in read-only mode.

What is the purpose of the HTML "no-js" class?

The no-js class gets removed by a javascript script, so you can modify/display/hide things using css if js is disabled.

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Accessing controller method means accessing a method on parent scope from directive controller/link/scope.

If the directive is sharing/inheriting the parent scope then it is quite straight forward to just invoke a parent scope method.

Little more work is required when you want to access parent scope method from Isolated directive scope.

There are few options (may be more than listed below) to invoke a parent scope method from isolated directives scope or watch parent scope variables (option#6 specially).

Note that I used link function in these examples but you can use a directive controller as well based on requirement.

Option#1. Through Object literal and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChanged({selectedItems:selectedItems})" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/rgKUsYGDo9O3tewL6xgr?p=preview

Option#2. Through Object literal and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged({selectedItems:scope.selectedItems});  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/BRvYm2SpSpBK9uxNIcTa?p=preview

Option#3. Through Function reference and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChanged()(selectedItems)" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems:'=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/Jo6FcYfVXCCg3vH42BIz?p=preview

Option#4. Through Function reference and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged()(scope.selectedItems);  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/BSqx2J1yCY86IJwAnQF1?p=preview

Option#5: Through ng-model and two way binding, you can update parent scope variables.. So, you may not require to invoke parent scope functions in some cases.

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter ng-model="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=ngModel'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/hNui3xgzdTnfcdzljihY?p=preview

Option#6: Through $watch and $watchCollection It is two way binding for items in all above examples, if items are modified in parent scope, items in directive would also reflect the changes.

If you want to watch other attributes or objects from parent scope, you can do that using $watch and $watchCollection as given below

html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{user}}!</p>
  <p>directive is watching name and current item</p>
  <table>
    <tr>
      <td>Id:</td>
      <td>
        <input type="text" ng-model="id" />
      </td>
    </tr>
    <tr>
      <td>Name:</td>
      <td>
        <input type="text" ng-model="name" />
      </td>
    </tr>
    <tr>
      <td>Model:</td>
      <td>
        <input type="text" ng-model="model" />
      </td>
    </tr>
  </table>

  <button style="margin-left:50px" type="buttun" ng-click="addItem()">Add Item</button>

  <p>Directive Contents</p>
  <sd-items-filter ng-model="selectedItems" current-item="currentItem" name="{{name}}" selected-items-changed="selectedItemsChanged" items="items"></sd-items-filter>

  <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}}</p>
</body>

</html>

script app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@',
      currentItem: '=',
      items: '=',
      selectedItems: '=ngModel'
    },
    template: '<select ng-model="selectedItems" multiple="multiple" style="height: 140px; width: 250px;"' +
      'ng-options="item.id as item.name group by item.model for item in items | orderBy:\'name\'">' +
      '<option>--</option> </select>',
    link: function(scope, element, attrs) {
      scope.$watchCollection('currentItem', function() {
        console.log(JSON.stringify(scope.currentItem));
      });
      scope.$watch('name', function() {
        console.log(JSON.stringify(scope.name));
      });
    }
  }
})

 app.controller('MainCtrl', function($scope) {
  $scope.user = 'World';

  $scope.addItem = function() {
    $scope.items.push({
      id: $scope.id,
      name: $scope.name,
      model: $scope.model
    });
    $scope.currentItem = {};
    $scope.currentItem.id = $scope.id;
    $scope.currentItem.name = $scope.name;
    $scope.currentItem.model = $scope.model;
  }

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
  }]
});

You can always refer AngularJs documentation for detailed explanations about directives.

using CASE in the WHERE clause

You don't have to use CASE...WHEN, you could use an OR condition, like this:

WHERE
  pw='correct'
  AND (id>=800 OR success=1) 
  AND YEAR(timestamp)=2011

this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway.

It is less common, however you could still use CASE WHEN, like this:

WHERE
  pw='correct'
  AND CASE WHEN id<800 THEN success=1 ELSE TRUE END 
  AND YEAR(timestamp)=2011

this means: return success=1 (which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

As it turns out, one should not forget to include jacson dependency into the pom file. This solved the issue for me:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes (64 KB) maximum.

If you need more consider using:

  • a MEDIUMBLOB for 16777215 bytes (16 MB)

  • a LONGBLOB for 4294967295 bytes (4 GB).

See Storage Requirements for String Types for more info.

Can I stretch text using CSS?

The only way I can think of for short texts like "MENU" is to put every single letter in a span and justify them in a container afterwards. Like this:

<div class="menu-burger">
  <span></span>
  <span></span>
  <span></span>
  <div>
    <span>M</span>
    <span>E</span>
    <span>N</span>
    <span>U</span>
  </div>
</div>

And then the CSS:

.menu-burger {
  width: 50px;
  height: 50px;
  padding: 5px;
}

...

.menu-burger > div {
  display: flex;
  justify-content: space-between;
}

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add an specific class to the father element and control its pseudo elements in CSS.

EXAMPLE

In jQuery:

<script type="text/javascript">
    $('span').addClass('change');
</script>

In CSS:

span.change:after { content: 'bar' }

Scroll / Jump to id without jQuery

below code might help you

var objControl=document.getElementById("divid");
objControl.scrollTop = objControl.offsetTop;

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

Passing data through intent using Serializable

I use the following method when sending a List<MySerializableObject> via intent:

List<Thumbnail> thumbList = new ArrayList<>();
//Populate ...

Intent intent = new Intent(context, OtherClass.class);
intent.putExtra("ThumbArray", thumbList.toArray(new Thumbnail[0]));
//Send intent...

And retrieving it like so:

Thumbnail[] thumbArr = (Thumbnail[]) getIntent().getSerializableExtra("ThumbArray");
if (thumbArr != null) {
    List<Thumbnail> thumbList = Arrays.asList(thumbArr);
}

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

Copy text from nano editor to shell

Much easier method:
$ cat my_file

Ctrl+Shift+c to copy the required output from the terminal

Ctrl+Shift+v to paste it wherever you like

Facebook Graph API, how to get users email?

To get the user email, you have to log in the user with his Facebook account using the email permission. Use for that the Facebook PHP SDK (see on github) as following.

First check if the user is already logged in :

require "facebook.php";
$facebook = new Facebook(array(
    'appId'  => YOUR_APP_ID,
    'secret' => YOUR_APP_SECRET,
));

$user = $facebook->getUser();
if ($user) {
    try {
        $user_profile = $facebook->api('/me');
    } catch (FacebookApiException $e) {
        $user = null;
    }
}

If he his not, you can display the login link asking for the email permission :

if (!$user) {
    $args = array('scope' => 'email');
    echo '<a href="' . $facebook->getLoginUrl() . '">Login with Facebook</a>';
} else {
    echo '<a href="' . $facebook->getLogoutUrl() . '">Logout</a>';
}

When he is logged in the email can be found in the $user_profile array.

Hope that helps !

How can I specify the schema to run an sql file against in the Postgresql command line

This works for me:

psql postgresql://myuser:password@myhost/my_db -f myInsertFile.sql

How to configure Visual Studio to use Beyond Compare

The answer posted by @schellack is perfect for most scenarios, but I wanted Beyond Compare to simulate the '2 Way merge with a result panel' view that Visual Studio uses in its own merge window.

This config hides the middle panel (which is unused in most cases AFAIK).

 %1 %2 "" %4 /title1=%6 /title2=%7 /title3="" /title4=%9

With thanks to Morgen

concatenate two strings

The best way in my eyes is to use the concat() method provided by the String class itself.

The useage would, in your case, look like this:

String myConcatedString = cursor.getString(numcol).concat('-').
       concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));

How to remove unwanted space between rows and columns in table?

Adding to vectran's answer: You also have to set cellspacing attribute on the table element for cross-browser compatibility.

<table cellspacing="0">

EDIT (for the sake of completeness I'm expanding this 5 years later:):

Internet Explorer 6 and Internet Explorer 7 required you to set cellspacing directly as a table attribute, otherwise the spacing wouldn't vanish.

Internet Explorer 8 and later versions and all other versions of popular browsers - Chrome, Firefox, Opera 4+ - support the CSS property border-spacing.

So in order to make a cross-browser table cell spacing reset (supporting IE6 as a dinosaur browser), you can follow the below code sample:

_x000D_
_x000D_
table{_x000D_
  border: 1px solid black;_x000D_
}_x000D_
table td {_x000D_
  border: 1px solid black; /* Style just to show the table cell boundaries */_x000D_
}_x000D_
_x000D_
_x000D_
table.no-spacing {_x000D_
  border-spacing:0; /* Removes the cell spacing via CSS */_x000D_
  border-collapse: collapse;  /* Optional - if you don't want to have double border where cells touch */_x000D_
}
_x000D_
<p>Default table:</p>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<p>Removed spacing:</p>_x000D_
_x000D_
<table class="no-spacing" cellspacing="0"> <!-- cellspacing 0 to support IE6 and IE7 -->_x000D_
  <tr>_x000D_
    <td>First cell</td>_x000D_
    <td>Second cell</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

How to conclude your merge of a file?

Check status (git status) of your repository. Every unmerged file (after you resolve conficts by yourself) should be added (git add), and if there is no unmerged file you should git commit

Assign a synthesizable initial value to a reg in Verilog

You can combine the register declaration with initialization.

reg [7:0] data_reg = 8'b10101011;

Or you can use an initial block

reg [7:0] data_reg;
initial data_reg = 8'b10101011;

What's the best way to determine the location of the current PowerShell script?

I found that the older solutions posted here didn't work for me on PowerShell V5. I came up with this:

try {
    $scriptPath = $PSScriptRoot
    if (!$scriptPath)
    {
        if ($psISE)
        {
            $scriptPath = Split-Path -Parent -Path $psISE.CurrentFile.FullPath
        }
        else {
            Write-Host -ForegroundColor Red "Cannot resolve script file's path"
            exit 1
        }
    }
}
catch {
    Write-Host -ForegroundColor Red "Caught Exception: $($Error[0].Exception.Message)"
    exit 2
}

Write-Host "Path: $scriptPath"

CSS ''background-color" attribute not working on checkbox inside <div>

Improving another answer here

input[type=checkbox] {
  cursor: pointer;
  margin-right: 10px;
}

input[type=checkbox]:after {
  content: " ";
  background-color: lightgray;
  display: inline-block;
  position: relative;
  top: -4px;
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

input[type=checkbox]:checked:after {
  content: "\00a0\2714";
}

What is the opposite of evt.preventDefault();

There is no opposite method of event.preventDefault() to understand why you first have to look into what event.preventDefault() does when you call it.

Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).

As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.

See below for an explanation:

;(function($, window, document, undefined)) {

    $(function() {
        // By default deny the submit
        var allowSubmit = false;

        $("#someform").on("submit", function(event) {

            if (!allowSubmit) {
                event.preventDefault();

                // Your code logic in here (maybe form validation or something)
                // Then you set allowSubmit to true so this code is bypassed

                allowSubmit = true;
            }

        });
    });

})(jQuery, window, document);

In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.

This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.

Difference between SelectedItem, SelectedValue and SelectedValuePath

Their names can be a bit confusing :). Here's a summary:

  • The SelectedItem property returns the entire object that your list is bound to. So say you've bound a list to a collection of Category objects (with each Category object having Name and ID properties). eg. ObservableCollection<Category>. The SelectedItem property will return you the currently selected Category object. For binding purposes however, this is not always what you want, as this only enables you to bind an entire Category object to the property that the list is bound to, not the value of a single property on that Category object (such as its ID property).

  • Therefore we have the SelectedValuePath property and the SelectedValue property as an alternative means of binding (you use them in conjunction with one another). Let's say you have a Product object, that your view is bound to (with properties for things like ProductName, Weight, etc). Let's also say you have a CategoryID property on that Product object, and you want the user to be able to select a category for the product from a list of categories. You need the ID property of the Category object to be assigned to the CategoryID property on the Product object. This is where the SelectedValuePath and the SelectedValue properties come in. You specify that the ID property on the Category object should be assigned to the property on the Product object that the list is bound to using SelectedValuePath='ID', and then bind the SelectedValue property to the property on the DataContext (ie. the Product).

The example below demonstrates this. We have a ComboBox bound to a list of Categories (via ItemsSource). We're binding the CategoryID property on the Product as the selected value (using the SelectedValue property). We're relating this to the Category's ID property via the SelectedValuePath property. And we're saying only display the Name property in the ComboBox, with the DisplayMemberPath property).

<ComboBox ItemsSource="{Binding Categories}" 
          SelectedValue="{Binding CategoryID, Mode=TwoWay}" 
          SelectedValuePath="ID" 
          DisplayMemberPath="Name" />
public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class Product
{
    public int CategoryID { get; set; }
}

It's a little confusing initially, but hopefully this makes it a bit clearer... :)

Chris

How do I list all files of a directory?

Returning a list of absolute filepaths, does not recurse into subdirectories

L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]

How to redirect to a different domain using NGINX?

Temporary redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;

Permanent redirect

rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;

In nginx configuration file for specific site:

server {    
    server_name www.example.com;
    rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;

}

Download pdf file using jquery ajax

You can do this with html5 very easily:

var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()

How can I merge the columns from two tables into one output?

Specifying the columns on your query should do the trick:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a, items_b b 
where a.category_id = b.category_id

should do the trick with regards to picking the columns you want.

To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:

select 
  coalesce(a.col1, b.col1) as col1, 
  coalesce(a.col2, b.col2) as col2,
  coalesce(a.col3, b.col3) as col3,
  a.category_id
from items_a a, items_b b
where a.category_id = b.category_id

The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.

How to change the docker image installation directory?

Following advice from comments I utilize Docker systemd documentation to improve this answer. Below procedure doesn't require reboot and is much cleaner.

First create directory and file for custom configuration:

sudo mkdir -p /etc/systemd/system/docker.service.d
sudo $EDITOR /etc/systemd/system/docker.service.d/docker-storage.conf

For docker version before 17.06-ce paste:

[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// --graph="/mnt"

For docker after 17.06-ce paste:

[Service]
ExecStart=
ExecStart=/usr/bin/dockerd -H fd:// --data-root="/mnt"

Alternative method through daemon.json

I recently tried above procedure with 17.09-ce on Fedora 25 and it seem to not work. Instead of that simple modification in /etc/docker/daemon.json do the trick:

{
    "graph": "/mnt",
    "storage-driver": "overlay"
}

Despite the method you have to reload configuration and restart Docker:

sudo systemctl daemon-reload
sudo systemctl restart docker

To confirm that Docker was reconfigured:

docker info|grep "loop file"

In recent version (17.03) different command is required:

docker info|grep "Docker Root Dir"

Output should look like this:

 Data loop file: /mnt/devicemapper/devicemapper/data
 Metadata loop file: /mnt/devicemapper/devicemapper/metadata

Or:

 Docker Root Dir: /mnt

Then you can safely remove old Docker storage:

rm -rf /var/lib/docker

I'm getting favicon.ico error

Also, be careful so your href location isn't faulty. Study case:

My index page was in a temporary sub-folder named LAYOUTS. To reach the favicon.png from inside the IMAGES folder, which was a sibling of the LAYOUTS folder, I had to put a path in my href like this

href="../images/favicon-32x32.png"

Double periods are necessary for folder navigation "upwards", then the forward slash + images string gets you into the images folder (performing a tree branch "jump") and finally you get to reference your file by writing favicon-32x32.png.

This explanation is useful for those that start out from scratch and it would have been useful to have seen it a couple of times since I would forget that I had certain *.php files outside the LAYOUTS folder which needed different tree hrefs on my links, from the HEAD section of each page.

Reference the path to your favicon image accordingly.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Well, I'm late.


In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(???) channel in HSV color space. Take refer to wiki HSL_and_HSV first. Then I'll copy most idea from my answer in this Detect Colored Segment in an image.


Main steps:

  1. Read into BGR
  2. Convert the image from bgr to hsv space
  3. Threshold the S channel
  4. Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is my result:

enter image description here


The Python code(Python 3.5 + OpenCV 3.3):

#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
#_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

Related answers:

  1. How to detect colored patches in an image using OpenCV?
  2. Edge detection on colored background using OpenCV
  3. OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection
  4. How to use `cv2.findContours` in different OpenCV versions?

Create a list from two object lists with linq

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

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

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

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

    return Equals(person);
}

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

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

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

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

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

Best way to format if statement with multiple conditions

The first one is easier, because, if you read it left to right you get: "If something AND somethingelse AND somethingelse THEN" , which is an easy to understand sentence. The second example reads "If something THEN if somethingelse THEN if something else THEN", which is clumsy.

Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?

Get the value for a listbox item by index

Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.

Items of a ListBox control may be DataRowView, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember.

ListBox control has a GetItemText which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue method.

GetItemValue Extension Method

We can create GetItemValue Extension Method to get item value which works like GetItemText:

using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
    public static object GetItemValue(this ListControl list, object item)
    {
        if (item == null)
            throw new ArgumentNullException("item");

        if (string.IsNullOrEmpty(list.ValueMember))
            return item;

        var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
        if (property == null)
            throw new ArgumentException(
                string.Format("item doesn't contain '{0}' property or column.",
                list.ValueMember));
        return property.GetValue(item);
    }
}

Using above method you don't need to worry about settings of ListBox and it will return expected Value for an item. It works with List<T>, Array, ArrayList, DataTable, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:

//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);

Since we created the GetItemValue method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.

This method is applicable on ComboBox and CheckedListBox too.

Setting a max character length in CSS

You could always use a truncate method by setting a max-width and overflow ellipsis like this

p {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

An example:

_x000D_
_x000D_
.wrapper {
  padding: 20px;
  background: #eaeaea;
  max-width: 400px;
  margin: 50px auto;
}

.demo-1 {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.demo-2 {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 150px;
}
_x000D_
<div class="wrapper">
  <p class="demo-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>

<div class="wrapper">
  <p class="demo-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
_x000D_
_x000D_
_x000D_

For a multi-line truncation have a look at a flex solution. An example with truncation on 3 rows.

p {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

An example:

_x000D_
_x000D_
p {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!</p>
_x000D_
_x000D_
_x000D_

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Escaping double quotes in JavaScript onClick event handler

You may also want to try two backslashes (\\") to escape the escape character.

How do I set proxy for chrome in python webdriver?

I had an issue with the same thing. ChromeOptions is very weird because it's not integrated with the desiredcapabilities like you would think. I forget the exact details, but basically ChromeOptions will reset to default certain values based on whether you did or did not pass a desired capabilities dict.

I did the following monkey-patch that allows me to specify my own dict without worrying about the complications of ChromeOptions

change the following code in /selenium/webdriver/chrome/webdriver.py:

def __init__(self, executable_path="chromedriver", port=0,
             chrome_options=None, service_args=None,
             desired_capabilities=None, service_log_path=None, skip_capabilities_update=False):
    """
    Creates a new instance of the chrome driver.

    Starts the service and then creates new instance of chrome driver.

    :Args:
     - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH
     - port - port you would like the service to run, if left as 0, a free port will be found.
     - desired_capabilities: Dictionary object with non-browser specific
       capabilities only, such as "proxy" or "loggingPref".
     - chrome_options: this takes an instance of ChromeOptions
    """
    if chrome_options is None:
        options = Options()
    else:
        options = chrome_options

    if skip_capabilities_update:
        pass
    elif desired_capabilities is not None:
        desired_capabilities.update(options.to_capabilities())
    else:
        desired_capabilities = options.to_capabilities()

    self.service = Service(executable_path, port=port,
        service_args=service_args, log_path=service_log_path)
    self.service.start()

    try:
        RemoteWebDriver.__init__(self,
            command_executor=self.service.service_url,
            desired_capabilities=desired_capabilities)
    except:
        self.quit()
        raise 
    self._is_remote = False

all that changed was the "skip_capabilities_update" kwarg. Now I just do this to set my own dict:

capabilities = dict( DesiredCapabilities.CHROME )

if not "chromeOptions" in capabilities:
    capabilities['chromeOptions'] = {
        'args' : [],
        'binary' : "",
        'extensions' : [],
        'prefs' : {}
    }

capabilities['proxy'] = {
    'httpProxy' : "%s:%i" %(proxy_address, proxy_port),
    'ftpProxy' : "%s:%i" %(proxy_address, proxy_port),
    'sslProxy' : "%s:%i" %(proxy_address, proxy_port),
    'noProxy' : None,
    'proxyType' : "MANUAL",
    'class' : "org.openqa.selenium.Proxy",
    'autodetect' : False
}

driver = webdriver.Chrome( executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True )

Styling an anchor tag to look like a submit button

The best you can get with simple styles would be something like:

.likeabutton {
    text-decoration: none; font: menu;
    display: inline-block; padding: 2px 8px;
    background: ButtonFace; color: ButtonText;
    border-style: solid; border-width: 2px;
    border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.likeabutton:active {
    border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
}

(Possibly with some kind of fix to stop IE6-IE7 treating focused buttons as being ‘active’.)

This won't necessarily look exactly like the buttons on the native desktop, though; indeed, for many desktop themes it won't be possible to reproduce the look of a button in simple CSS.

However, you can ask the browser to use native rendering, which is best of all:

.likeabutton {
    appearance: button;
    -moz-appearance: button;
    -webkit-appearance: button;
    text-decoration: none; font: menu; color: ButtonText;
    display: inline-block; padding: 2px 8px;
}

Unfortunately, as you may have guessed from the browser-specific prefixes, this is a CSS3 feature that isn't suppoorted everywhere yet. In particular IE and Opera will ignore it. But if you include the other styles as backup, the browsers that do support appearance drop that property, preferring the explicit backgrounds and borders!

What you might do is use the appearance styles as above by default, and do JavaScript fixups as necessary, eg.:

<script type="text/javascript">
    var r= document.documentElement;
    if (!('appearance' in r || 'MozAppearance' in r || 'WebkitAppearance' in r)) {
        // add styles for background and border colours
        if (/* IE6 or IE7 */)
            // add mousedown, mouseup handlers to push the button in, if you can be bothered
        else
            // add styles for 'active' button
    }
</script>

Automate scp file transfer using a shell script

Try lftp

lftp -u $user,$pass sftp://$host << --EOF--

cd $directory

put $srcfile

quit

--EOF--

SQL query for a carriage return in a string and ultimately removing carriage return

In SQL Server I would use:

WHERE CHARINDEX(CHAR(13), name) <> 0 OR CHARINDEX(CHAR(10), name) <> 0

This will search for both carriage returns and line feeds.

If you want to search for tabs too just add:

OR CHARINDEX(CHAR(9), name) <> 0

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

Adding n hours to a date in Java?

With Joda-Time

DateTime dt = new DateTime();
DateTime added = dt.plusHours(6);

Grep to find item in Perl array

I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.

Perhaps,

if (grep(/^$match$/, @array)) more apt.

Thread pooling in C++11

Follwoing [PhD EcE](https://stackoverflow.com/users/3818417/phd-ece) suggestion, I implemented the thread pool:

function_pool.h

#pragma once
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <cassert>

class Function_pool
{

private:
    std::queue<std::function<void()>> m_function_queue;
    std::mutex m_lock;
    std::condition_variable m_data_condition;
    std::atomic<bool> m_accept_functions;

public:

    Function_pool();
    ~Function_pool();
    void push(std::function<void()> func);
    void done();
    void infinite_loop_func();
};

function_pool.cpp

#include "function_pool.h"

Function_pool::Function_pool() : m_function_queue(), m_lock(), m_data_condition(), m_accept_functions(true)
{
}

Function_pool::~Function_pool()
{
}

void Function_pool::push(std::function<void()> func)
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_function_queue.push(func);
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    lock.unlock();
    m_data_condition.notify_one();
}

void Function_pool::done()
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_accept_functions = false;
    lock.unlock();
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    m_data_condition.notify_all();
    //notify all waiting threads.
}

void Function_pool::infinite_loop_func()
{
    std::function<void()> func;
    while (true)
    {
        {
            std::unique_lock<std::mutex> lock(m_lock);
            m_data_condition.wait(lock, [this]() {return !m_function_queue.empty() || !m_accept_functions; });
            if (!m_accept_functions && m_function_queue.empty())
            {
                //lock will be release automatically.
                //finish the thread loop and let it join in the main thread.
                return;
            }
            func = m_function_queue.front();
            m_function_queue.pop();
            //release the lock
        }
        func();
    }
}

main.cpp

#include "function_pool.h"
#include <string>
#include <iostream>
#include <mutex>
#include <functional>
#include <thread>
#include <vector>

Function_pool func_pool;

class quit_worker_exception : public std::exception {};

void example_function()
{
    std::cout << "bla" << std::endl;
}

int main()
{
    std::cout << "stating operation" << std::endl;
    int num_threads = std::thread::hardware_concurrency();
    std::cout << "number of threads = " << num_threads << std::endl;
    std::vector<std::thread> thread_pool;
    for (int i = 0; i < num_threads; i++)
    {
        thread_pool.push_back(std::thread(&Function_pool::infinite_loop_func, &func_pool));
    }

    //here we should send our functions
    for (int i = 0; i < 50; i++)
    {
        func_pool.push(example_function);
    }
    func_pool.done();
    for (unsigned int i = 0; i < thread_pool.size(); i++)
    {
        thread_pool.at(i).join();
    }
}

JUNIT testing void methods

I want to make some unit test to get maximal code coverage

Code coverage should never be the goal of writing unit tests. You should write unit tests to prove that your code is correct, or help you design it better, or help someone else understand what the code is meant to do.

but I dont see how I can test my method checkIfValidElements, it returns nothing or change nothing.

Well you should probably give a few tests, which between them check that all 7 methods are called appropriately - both with an invalid argument and with a valid argument, checking the results of ErrorFile each time.

For example, suppose someone removed the call to:

method4(arg1, arg2);

... or accidentally changed the argument order:

method4(arg2, arg1);

How would you notice those problems? Go from that, and design tests to prove it.

SQL Query Multiple Columns Using Distinct on One Column Only

you have various ways to distinct values on one column or multi columns.

  • using the GROUP BY

    SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
       o.tblFruit_FruitType,
       MAX(o.tblFruit_FruitName)
    FROM   tblFruit  AS o
    GROUP BY
         tblFruit_FruitType
    
  • using the subquery

    SELECT b.tblFruit_ID,
       b.tblFruit_FruitType,
       b.tblFruit_FruitName
    FROM   (
           SELECT DISTINCT(tblFruit_FruitType),
                  MIN(tblFruit_ID) tblFruit_ID
           FROM   tblFruit
           GROUP BY
                  tblFruit_FruitType
       ) AS a
       INNER JOIN tblFruit b
            ON  a.tblFruit_ID = b.tblFruit_I
    
  • using the join with subquery

    SELECT t1.tblFruit_ID,
        t1.tblFruit_FruitType,
        t1.tblFruit_FruitName
    FROM   tblFruit  AS t1
       INNER JOIN (
                SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                       tblFruit_FruitType
                FROM   tblFruit
                GROUP BY
                       tblFruit_FruitType
            )  AS t2
            ON  t1.tblFruit_ID = t2.tblFruit_ID 
    
  • using the window functions only one column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
        rn
           FROM   tblFruit
        ) t
        WHERE  rn = 1 
    
  • using the window functions multi column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
        ORDER BY tblFruit_ID) rn
              FROM   tblFruit
         ) t
        WHERE  rn = 1 
    

Origin is not allowed by Access-Control-Allow-Origin

If you're writing a Chrome Extension and get this error, then be sure you have added the API's base URL to your manifest.json's permissions block, example:

"permissions": [
    "https://itunes.apple.com/"
]

Why do python lists have pop() but not push()

Because it appends an element to a list? Push is usually used when referring to stacks.

Inserting a Python datetime.datetime object into MySQL

Use Python method datetime.strftime(format), where format = '%Y-%m-%d %H:%M:%S'.

import datetime

now = datetime.datetime.utcnow()

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, %s)",
               ("name", 4, now.strftime('%Y-%m-%d %H:%M:%S')))

Timezones

If timezones are a concern, the MySQL timezone can be set for UTC as follows:

cursor.execute("SET time_zone = '+00:00'")

And the timezone can be set in Python:

now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

MySQL Documentation

MySQL recognizes DATETIME and TIMESTAMP values in these formats:

As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.

The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.

As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.

Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists

This error can be because of no SSH key on the your local machine. Check the SSH key locally:

$ cat ~/.ssh/id_rsa.pub

If above command do not give any output use below command to create ssh key(Linux/Mac):

$ ssh-keygen 

Now again run cat ~/.ssh/id_rsa.pub This is your SSH key. Copy and add this key to your SSH keys in on git. In gitlab/bitbucket go to

profile settings -> SSH Keys -> add Key

and add the key

"detached entity passed to persist error" with JPA/EJB code

If you set id in your database to be primary key and autoincrement, then this line of code is wrong:

user.setId(1);

Try with this:

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

Generating Random Passwords

I created this class that uses RNGCryptoServiceProvider and it is flexible. Example:

var generator = new PasswordGenerator(minimumLengthPassword: 8,
                                      maximumLengthPassword: 15,
                                      minimumUpperCaseChars: 2,
                                      minimumNumericChars: 3,
                                      minimumSpecialChars: 2);
string password = generator.Generate();

HTML Text with tags to formatted text in an Excel cell

I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below

  1. First enable developer mode in Excel: Link
  2. Select the Developer Tab > Visual Basic
  3. Click View > Code
  4. Paste the code below updating the lines that require cell references to be correct.
  5. Click the Green Run Arrow or press F5
Sub Sample()
    Dim Ie As Object
    Set Ie = CreateObject("InternetExplorer.Application")
    With Ie
        .Visible = False
        .Navigate "about:blank"
        .document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
             'update to the cell that contains HTML you want converted
        .ExecWB 17, 0
             'Select all contents in browser
        .ExecWB 12, 2
             'Copy them
        ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
             'update to cell you want converted HTML pasted in
        .Quit
    End With
End Sub

How to pass parameters on onChange of html select

this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.

<html>
    <head>
        <title>Register</title>
    </head>
    <body>
    <script>
        function show(){
            var option = document.getElementById("category").value;
            if(option == "Student")
                  {
                        document.getElementById("enroll1").style.display="block";
                  }
            if(option == "Parents")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
            if(option == "Guardians")
                  {
                        document.getElementById("enroll1").style.display="none";
                  }
        }
    </script>
            <form action="#" method="post">
                <table>
                    <tr>
                        <td><label>Name </label></td>
                        <td><input type="text" id="name" size=20 maxlength=20 value=""></td>
                    </tr>
                    <tr style="display:block;" id="enroll1">
                        <td><label>Enrollment No. </label></td>
                        <td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Email </label></td>
                        <td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Mobile No. </label></td>
                        <td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
                    </tr>
                    <tr>
                        <td><label>Address</label></td>
                        <td><textarea rows="2" cols="20"></textarea></td>
                    </tr>
                    <tr >
                        <td><label>Category</label></td>
                        <td><select id="category" onchange="show()">    <!--onchange show methos is call-->
                                <option value="Student">Student</option>
                                <option value="Parents">Parents</option>
                                <option value="Guardians">Guardians</option>
                            </select>
                        </td>
                    </tr>
                </table><br/>
            <input type="submit" value="Sign Up">
        </form>
    </body>
</html>

angular.js ng-repeat li items with html content

Note that ng-bind-html-unsafe is no longer suppported in rc 1.2. Use ng-bind-html instead. See: With ng-bind-html-unsafe removed, how do I inject HTML?

Activate a virtualenv with a Python script

It turns out that, yes, the problem is not simple, but the solution is.

First I had to create a shell script to wrap the "source" command. That said I used the "." instead, because I've read that it's better to use it than source for Bash scripts.

#!/bin/bash
. /path/to/env/bin/activate

Then from my Python script I can simply do this:

import os
os.system('/bin/bash --rcfile /path/to/myscript.sh')

The whole trick lies within the --rcfile argument.

When the Python interpreter exits it leaves the current shell in the activated environment.

Win!

Hive External Table Skip First Row

create external table table_name( 
Year int, 
Month int,
column_name data_type ) 
row format delimited fields terminated by ',' 
location '/user/user_name/example_data' TBLPROPERTIES('serialization.null.format'='', 'skip.header.line.count'='1');

Getting a count of rows in a datatable that meet certain criteria

int numberOfRecords = 0;

numberOfRecords = dtFoo.Select().Length;

MessageBox.Show(numberOfRecords.ToString());

bootstrap popover not showing on top of all elements

I had a similar issue with 2 fixed elements - even though the z-index heirachy was correct, the bootstrap tooltip was hidden behind the one element wth a lower z-index.

Adding data-container="body" resolved the issue and now works as expected.

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Visual Studio debugging/loading very slow

To clear cache etc. use Options 1 & 2, For settings/troubleshooting Options 3 & 4, enjoy!

Option 1: Navigate to IIS express , clear cache and sites

cd "C:\Program Files (x86)\IIS Express\"
  • run this appcmd.exe list site /xml | appcmd delete site /in
  • run this Del /S /F /Q %temp% - to clear the Userprofile Temp folder.
  • run this Del /S /F /Q %Windir%\Temp

Also, clear your temp files in %temp% and logout, or reboot

this clears the Windows temp folder. This will delete all the sites, enjoy!


Option 2: remove/recreate the temp folders

  • Cmd> rmdir C:\Users\\{username}\AppData\Local\Microsoft\WebsiteCache /s /q
  • Cmd> rmdir C:\Users\\{username}\AppData\Local\Temp /s /q

Option 3: JMC (Just My Code) Option from MSDN

To enable or disable Just My Code in Visual Studio, under Tools > Options (or Debug > Options) > Debugging > General, select or deselect Enable Just My Code.

enter image description here


Option 4: configure the Visual Studio/Disable Common plugin issues

Even more Visual Studio settings You can also configure the Visual Studio and disable resource-killing features on the environment, cant remember where I got this, but threes some more I will post shortly.

Environment -> General

  • Uncheck “Automatically adjust visual experience based on client performance”
  • Uncheck “Enable rich client visual experience” Check “Use hardware graphics acceleration if available” Environment -> AutoRecover
  • Uncheck “Save AutoRecover information every”
  • Environment -> Documents
  • Check “Save documents as Unicode when data cannot be saved in codepage” Environment -> Keyboard
  • Set “ForceGC” to ctrl+num1
  • Set “ReSharper_Toggle” to ctrl+num0 (if ReSharper is used)
  • Set “ReSharper_EnableDaemon” to ctrl+num8 (if ReSharper is used) Environment -> Startup
  • Set “At startup” to “Show empty environment at startup”
  • Uncheck “Download content every” Environment -> Synchronized settings
  • Uncheck “Synchronize settings across devices when signed into Visual Studio”

How do I get a file's last modified time in Perl?

Calling the built-in function stat($fh) returns an array with the following information about the file handle passed in (from the perlfunc man page for stat):

  0 dev      device number of filesystem
  1 ino      inode number
  2 mode     file mode  (type and permissions)
  3 nlink    number of (hard) links to the file
  4 uid      numeric user ID of file's owner
  5 gid      numeric group ID of file's owner
  6 rdev     the device identifier (special files only)
  7 size     total size of file, in bytes
  8 atime    last access time since the epoch
  9 mtime    last modify time since the epoch
 10 ctime    inode change time (NOT creation time!) since the epoch
 11 blksize  preferred block size for file system I/O
 12 blocks   actual number of blocks allocated

Element number 9 in this array will give you the last modified time since the epoch (00:00 January 1, 1970 GMT). From that you can determine the local time:

my $epoch_timestamp = (stat($fh))[9];
my $timestamp       = localtime($epoch_timestamp);

Alternatively, you can use the built-in module File::stat (included as of Perl 5.004) for a more object-oriented interface.

And to avoid the magic number 9 needed in the previous example, additionally use Time::localtime, another built-in module (also included as of Perl 5.004). Together these lead to some (arguably) more legible code:

use File::stat;
use Time::localtime;
my $timestamp = ctime(stat($fh)->mtime);

Configuring angularjs with eclipse IDE

Now you can see the Angularjs tags available as shown below.

AngularJS Tags are available.

Insert text into textarea with jQuery

I use this function in my code:

_x000D_
_x000D_
$.fn.extend({_x000D_
  insertAtCaret: function(myValue) {_x000D_
    this.each(function() {_x000D_
      if (document.selection) {_x000D_
        this.focus();_x000D_
        var sel = document.selection.createRange();_x000D_
        sel.text = myValue;_x000D_
        this.focus();_x000D_
      } else if (this.selectionStart || this.selectionStart == '0') {_x000D_
        var startPos = this.selectionStart;_x000D_
        var endPos = this.selectionEnd;_x000D_
        var scrollTop = this.scrollTop;_x000D_
        this.value = this.value.substring(0, startPos) +_x000D_
          myValue + this.value.substring(endPos,this.value.length);_x000D_
        this.focus();_x000D_
        this.selectionStart = startPos + myValue.length;_x000D_
        this.selectionEnd = startPos + myValue.length;_x000D_
        this.scrollTop = scrollTop;_x000D_
      } else {_x000D_
        this.value += myValue;_x000D_
        this.focus();_x000D_
      }_x000D_
    });_x000D_
    return this;_x000D_
  }_x000D_
});
_x000D_
input{width:100px}_x000D_
label{display:block;margin:10px 0}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>Copy text from: <input id="in2copy" type="text" value="x"></label>_x000D_
<label>Insert text in: <input id="in2ins" type="text" value="1,2,3" autofocus></label>_x000D_
<button onclick="$('#in2ins').insertAtCaret($('#in2copy').val())">Insert</button>
_x000D_
_x000D_
_x000D_

It's not 100% mine, I googled it somewhere and then tuned for mine app.

Usage: $('#element').insertAtCaret('text');

Passing data to a bootstrap modal

If you are on bootstrap 3+, this can be shortened a bit further if using Jquery.

HTML

<a href="#" data-target="#my_modal" data-toggle="modal" class="identifyingClass" data-id="my_id_value">Open Modal</a>

<div class="modal fade" id="my_modal" tabindex="-1" role="dialog" aria-labelledby="my_modalLabel">
<div class="modal-dialog" role="dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal Title</h4>
        </div>
        <div class="modal-body">
            Modal Body
            <input type="hidden" name="hiddenValue" id="hiddenValue" value="" />
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
            <button type="button" class="btn btn-primary">Yes</button>
        </div>
    </div>
</div>

JQUERY

<script type="text/javascript">
    $(function () {
        $(".identifyingClass").click(function () {
            var my_id_value = $(this).data('id');
            $(".modal-body #hiddenValue").val(my_id_value);
        })
    });
</script>

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value