Programs & Examples On #Plone

Plone is a content management system (CMS) written in Python. Its strengths are in intranets, websites and document management. It has support for multilingual content and versioning.

How to impose maxlength on textArea in HTML using JavaScript

Also add the following event to deal with pasting into the textarea:

...

txts[i].onkeyup = function() {
  ...
}

txts[i].paste = function() {
  var len = parseInt(this.getAttribute("maxlength"), 10);

  if (this.value.length + window.clipboardData.getData("Text").length > len) {
    alert('Maximum length exceeded: ' + len);
    this.value = this.value.substr(0, len);
    return false;
  }
}

...

Selecting data from two different servers in SQL Server

sp_addlinkedserver('servername')

so its should go like this -

select * from table1
unionall
select * from [server1].[database].[dbo].[table1]

How to access cookies in AngularJS?

AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Here is some method of AngularJS Cookie.

  • get(key); // This method returns the value of given cookie key.

  • getObject(key); //This method returns the deserialized value of given cookie key.

  • getAll(); //This method returns a key value object with all the cookies.

  • put(key, value, [options]); //This method sets a value for given cookie key.

  • remove(key, [options]); //This method remove given cookie.

Example

Html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>

JavaScript

var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert(this.id)"></button>

Convert AM/PM time to 24 hours format?

using System;

class Solution
{
    static string timeConversion(string s)
    {
        return DateTime.Parse(s).ToString("HH:mm");
    }

    static void Main(string[] args)
    {
        Console.WriteLine(timeConversion("01:00 PM"));
        Console.Read();
    }
}

How do I delete all messages from a single queue using the CLI?

RabbitMQ implements the Advanced Message Queuing Protocol (AMQP) so you can use generic tools for stuff like this.

On Debian/Ubuntu or similar system, do:

sudo apt-get install amqp-tools
amqp-delete-queue -q celery  # where celery is the name of the queue to delete

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Kotlin style.

    startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
        data = Uri.fromParts("package", packageName, null)
    })

Define a struct inside a class in C++

Something like this:

class Class {
    // visibility will default to private unless you specify it
    struct Struct {
        //specify members here;
    };
};

Replace new line/return with space using regex

You May use first split and rejoin it using white space. it will work sure.

String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
   L = L+" "+Larray[i];  
}

CSS Outside Border

I shared two solutions depending on your needs:

<style type="text/css" ref="stylesheet">
  .border-inside-box {
    border: 1px solid black;
  }
  .border-inside-box-v1 {
    outline: 1px solid black; /* 'border-radius' not available */
  }
  .border-outside-box-v2 {
    box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
  }
</style>

example: https://codepen.io/danieldd/pen/gObEYKj

Which MIME type to use for a binary file that's specific to my program?

According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname is not allowed, but application/x-myappname is allowed and sounds most appropriate for you're application to me.

How to change the Title of the window in Qt?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.setWindowTitle("Main Page");
    w.show();
    return a.exec();
}

enter image description here

How to count how many values per level in a given factor?

Or using the dplyr library:

library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))

Note the use of %>%, which is similar to the use of pipes in bash. Effectively, the code above pipes dat into group_by, and the result of that operation is piped into summarise.

The result is:

Source: local data frame [26 x 2]

   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1

See the dplyr introduction for some more context, and the documentation for details regarding the individual functions.

Can I inject a service into a directive in AngularJS?

Change your directive definition from app.module to app.directive. Apart from that everything looks fine. Btw, very rarely do you have to inject a service into a directive. If you are injecting a service ( which usually is a data source or model ) into your directive ( which is kind of part of a view ), you are creating a direct coupling between your view and model. You need to separate them out by wiring them together using a controller.

It does work fine. I am not sure what you are doing which is wrong. Here is a plunk of it working.

http://plnkr.co/edit/M8omDEjvPvBtrBHM84Am

Setting unique Constraint with fluent API?

Here is an extension method for setting unique indexes more fluently:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

Will generate migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

Src: Creating Unique Index with Entity Framework 6.1 fluent API

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

jQuery: how to change title of document during .ready()?

If you have got a serverside script get_title.php that echoes the current title session this works fine in jQuery:

$.get('get_title.php',function(*respons*){
    title=*respons* + 'whatever you want'   
    $(document).attr('title',title)
})

How to list all properties of a PowerShell object

If you want to know what properties (and methods) there are:

Get-WmiObject -Class "Win32_computersystem" | Get-Member

jQuery selectors on custom data attributes using HTML5

$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"

$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"

Look in to jQuery Selectors :contains is a selector

here is info on the :contains selector

Create PDF with Java

Following are few libraries to create PDF with Java:

  1. iText
  2. Apache PDFBox
  3. BFO

I have used iText for genarating PDF's with a little bit of pain in the past.

Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

For those the above answer does not work, here is another possible solution to look at.

Issue: On installing npm os-service package i was getting below error error MSB4019: The imported project "d:\M icrosoft.Cpp.Default.props" was not found. Confirm that the path in the declaration is correct

Even the installation of build tools or VS 2015 did not work for me. So I tried installing below directly via PowerShell (as admin)

https://chocolatey.org/packages/visualcpp-build-tools/14.0.25420.1 Command: choco install visualcpp-build-tools --version 14.0.25420.1

Once this was installed, set an environment variable VCTargetsPath=C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140

Then installation of the package worked perfectly fine after these.

Shell script to send email

#!/bin/sh
#set -x
LANG=fr_FR

# ARG
FROM="[email protected]"
TO="[email protected]"
SUBJECT="test é"
MSG="BODY éé"
FILES="fic1.pdf fic2.pdf"

# http://fr.wikipedia.org/wiki/Multipurpose_Internet_Mail_Extensions
SUB_CHARSET=$(echo ${SUBJECT} | file -bi - | cut -d"=" -f2)
SUB_B64=$(echo ${SUBJECT} | uuencode --base64 - | tail -n+2 | head -n+1)

NB_FILES=$(echo ${FILES} | wc -w)
NB=0
cat <<EOF | /usr/sbin/sendmail -t
From: ${FROM}
To: ${TO}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=frontier
Subject: =?${SUB_CHARSET}?B?${SUB_B64}?=

--frontier
Content-Type: $(echo ${MSG} | file -bi -)
Content-Transfer-Encoding: 7bit

${MSG}
$(test $NB_FILES -eq 0 && echo "--frontier--" || echo "--frontier")
$(for file in ${FILES} ; do
        let NB=${NB}+1
        FILE_NAME="$(basename $file)"
        echo "Content-Type: $(file -bi $file); name=\"${FILE_NAME}\""
        echo "Content-Transfer-Encoding: base64"
        echo "Content-Disposition: attachment; filename=\"${FILE_NAME}\""
        #echo ""
        uuencode --base64 ${file} ${FILE_NAME}
        test ${NB} -eq ${NB_FILES} && echo "--frontier--" || echo 
"--frontier"
done)
EOF

Jquery- Get the value of first td in table

$(".hit").click(function(){
   var values = [];
   var table = $(this).closest("table");
   table.find("tr").each(function() {
      values.push($(this).find("td:first").html());
   });

   alert(values);    
});

You should avoid $(".hit") it's really inefficient. Try using event delegation instead.

How do I grant myself admin access to a local SQL Server instance?

Microsoft has an article about this issue. It goes through it all step by step.

https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/connect-to-sql-server-when-system-administrators-are-locked-out

In short it involves starting up the instance of sqlserver with -m like all the other answers suggest. However Microsoft provides slightly more detailed instructions.

From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already registered, right-click Local Server Groups, point to Tasks, and then click Register Local Servers.)

In the Registered Servers area, right-click your server, and then click SQL Server Configuration Manager. This should ask for permission to run as administrator, and then open the Configuration Manager program.

Close Management Studio.

In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, find your instance of SQL Server. (The default instance of SQL Server includes (MSSQLSERVER) after the computer name. Named instances appear in upper case with the same name that they have in Registered Servers.) Right-click the instance of SQL Server, and then click Properties.

On the Startup Parameters tab, in the Specify a startup parameter box, type -m and then click Add. (That's a dash then lower case letter m.)

Note

For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then click OK. (That's a semi-colon then a dash then lower case letter m.)

Click OK, and after the message to restart, right-click your server name, and then click Restart.

After SQL Server has restarted your server will be in single-user mode. Make sure that that SQL Server Agent is not running. If started, it will take your only connection.

On the Windows 8 start screen, right-click the icon for Management Studio. At the bottom of the screen, select Run as administrator. (This will pass your administrator credentials to SSMS.)

Note

For earlier versions of Windows, the Run as administrator option appears as a sub-menu.

In some configurations, SSMS will attempt to make several connections. Multiple connections will fail because SQL Server is in single-user mode. You can select one of the following actions to perform. Do one of the following.

a) Connect with Object Explorer using Windows Authentication (which includes your Administrator credentials). Expand Security, expand Logins, and double-click your own login. On the Server Roles page, select sysadmin, and then click OK.

b) Instead of connecting with Object Explorer, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). (You can only connect this way if you did not connect with Object Explorer.) Execute code such as the following to add a new Windows Authentication login that is a member of the sysadmin fixed server role. The following example adds a domain user named CONTOSO\PatK.

CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS;   ALTER SERVER ROLE
sysadmin ADD MEMBER [CONTOSO\PatK];   

c) If your SQL Server is running in mixed authentication mode, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Execute code such as the following to create a new SQL Server Authentication login that is a member of the sysadmin fixed server role.

CREATE LOGIN TempLogin WITH PASSWORD = '************';   ALTER
SERVER ROLE sysadmin ADD MEMBER TempLogin;   

Warning:

Replace ************ with a strong password.

d) If your SQL Server is running in mixed authentication mode and you want to reset the password of the sa account, connect with a Query Window using Windows Authentication (which includes your Administrator credentials). Change the password of the sa account with the following syntax.

ALTER LOGIN sa WITH PASSWORD = '************';   Warning

Replace ************ with a strong password.

The following steps now change SQL Server back to multi-user mode. Close SSMS.

In SQL Server Configuration Manager, in the left pane, select SQL Server Services. In the right-pane, right-click the instance of SQL Server, and then click Properties.

On the Startup Parameters tab, in the Existing parameters box, select -m and then click Remove.

Note

For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a very small window. Remove the ;-m which you added earlier, and then click OK.

Right-click your server name, and then click Restart.

Now you should be able to connect normally with one of the accounts which is now a member of the sysadmin fixed server role.

How to convert int to float in C?

This can give you the correct Answer

#include <stdio.h>
int main()
{
    float total=100, number=50;
    float percentage;
    percentage=(number/total)*100;
    printf("%0.2f",percentage);
    return 0;
}

Android add placeholder text to EditText

If you want to insert text inside your EditText view that stays there after the field is selected (unlike how hint behaves), do this:

In Java:

// Cast Your EditText as a TextView
((TextView) findViewById(R.id.email)).setText("your Text")

In Kotlin:

// Cast your EditText into a TextView
// Like this
(findViewById(R.id.email) as TextView).text = "Your Text"
// Or simply like this
findViewById<TextView>(R.id.email).text = "Your Text"

How to load a model from an HDF5 file in Keras?

load_weights only sets the weights of your network. You still need to define its architecture before calling load_weights:

def create_model():
   model = Sequential()
   model.add(Dense(64, input_dim=14, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5)) 
   model.add(Dense(64, init='uniform'))
   model.add(LeakyReLU(alpha=0.3))
   model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
   model.add(Dropout(0.5))
   model.add(Dense(2, init='uniform'))
   model.add(Activation('softmax'))
   return model

def train():
   model = create_model()
   sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
   model.compile(loss='binary_crossentropy', optimizer=sgd)

   checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
   model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])

def load_trained_model(weights_path):
   model = create_model()
   model.load_weights(weights_path)

Service will not start: error 1067: the process terminated unexpectedly

I resolved the problem.This is for EAServer Windows Service

Resolution is --> Open Regedit in Run prompt

Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\EAServer

In parameters, give SERVERNAME entry as EAServer.

[It is sometime overwritten with Envirnoment variable : Path value]

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Ran into the same issue and researched this for a few minutes.

I was taught to use Windows 3.1 and DOS, remember those days? Shortly after I worked with Macintosh computers strictly for some time, then began to sway back to Windows after buying a x64-bit machine.

There are actual reasons behind these changes (some would say historical significance), that are necessary for programmers to continue their work.

Most of the changes are mentioned above:

  • Program Files vs Program Files (x86)

    In the beginning the 16/86bit files were written on, '86' Intel processors.

  • System32 really means System64 (on 64-bit Windows)

    When developers first started working with Windows7, there were several compatibility issues where other applications where stored.

  • SysWOW64 really means SysWOW32

    Essentially, in plain english, it means 'Windows on Windows within a 64-bit machine'. Each folder is indicating where the DLLs are located for applications it they wish to use them.

Here are two links with all the basic info you need:

Hope this clears things up!

error: Unable to find vcvarsall.bat

http://www.stickpeople.com/projects/python/win-psycopg/

Installing Appropriate file from above link fixed my issue.

Mention: Jason Erickson [[email protected]]. He manages this page fairly well for Windows users.

What is the difference between GitHub and gist?

My personal understanding or to say my personal usage of Gist and Github is:

  • Github

A big project work. If you wanna build website, develop mobile or web application or do your assignment with your teammates of course use github.

  • Gist

more like a memo. for example you can write the implementation of a small feature and share it to your blog or write down what you think about the project and share it with your teammates. Just like what the above answers said, gist is used for more like code snippet thing. So normally if you work on a project you use github.

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

PHP JSON String, escape Double Quotes for JS output

I just ran into this problem and the actual issue was that I forgot to add a proper application/json header before spitting out the actual JSON data.

header('Content-Type: application/json');

Optimal number of threads per core

I know this question is rather old, but things have evolved since 2009.

There are two things to take into account now: the number of cores, and the number of threads that can run within each core.

With Intel processors, the number of threads is defined by the Hyperthreading which is just 2 (when available). But Hyperthreading cuts your execution time by two, even when not using 2 threads! (i.e. 1 pipeline shared between two processes -- this is good when you have more processes, not so good otherwise. More cores are definitively better!)

On other processors you may have 2, 4, or even 8 threads. So if you have 8 cores each of which support 8 threads, you could have 64 processes running in parallel without context switching.

"No context switching" is obviously not true if you run with a standard operating system which will do context switching for all sorts of other things out of your control. But that's the main idea. Some OSes let you allocate processors so only your application has access/usage of said processor!

From my own experience, if you have a lot of I/O, multiple threads is good. If you have very heavy memory intensive work (read source 1, read source 2, fast computation, write) then having more threads doesn't help. Again, this depends on how much data you read/write simultaneously (i.e. if you use SSE 4.2 and read 256 bits values, that stops all threads in their step... in other words, 1 thread is probably a lot easier to implement and probably nearly as speedy if not actually faster. This will depend on your process & memory architecture, some advanced servers manage separate memory ranges for separate cores so separate threads will be faster assuming your data is properly filed... which is why, on some architectures, 4 processes will run faster than 1 process with 4 threads.)

How to call a method after a delay in Android

Kotlin & Java Many Ways

1. Using Handler

Handler().postDelayed({
    TODO("Do something")
    }, 2000)

2. Using TimerTask

Timer().schedule(object : TimerTask() {
    override fun run() {
        TODO("Do something")
    }
}, 2000)

Or even shorter

Timer().schedule(timerTask {
    TODO("Do something")
}, 2000)

Or shortest would be

Timer().schedule(2000) {
    TODO("Do something")
}

3. Using Executors

Executors.newSingleThreadScheduledExecutor().schedule({
    TODO("Do something")
}, 2, TimeUnit.SECONDS)

In Java

1. Using Handler

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        //Do something
    }
}, 2000);

2. Using Timer

new Timer().schedule(new TimerTask() {          
    @Override
    public void run() {
        // Do something
    }
}, 2000);

3. Using ScheduledExecutorService

private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();

Runnable runnable = new Runnable() {
  public void run() {
      // Do something
  }
  };
worker.schedule(runnable, 2, TimeUnit.SECONDS);

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

go to you build.gradle (app level)

build.gradle module app

and replace the word "compile" by "implementation"

it will work 100%

Shortest distance between a point and a line segment

Wanted to do this in GLSL, but it's better to avoid all those conditionals if possible. Using clamp() avoids the two end-point cases:

// find closest point to P on line segment AB:
vec3 closest_point_on_line_segment(in vec3 P, in vec3 A, in vec3 B) {
    vec3 AP = P - A, AB = B - A;
    float l = dot(AB, AB);
    if (l <= 0.0000001) return A;    // A and B are practically the same
    return AP - AB*clamp(dot(AP, AB)/l, 0.0, 1.0);  // do the projection
}

If you can be sure that A and B are never very close to each other, this can be simplified to remove the if(). In fact, even if A and B are the same, my GPU still gives the right result with this condition-free version (but this is using pre-OpenGL 4.1 in which GLSL divide by zero is undefined):

// find closest point to P on line segment AB:
vec3 closest_point_on_line_segment(in vec3 P, in vec3 A, in vec3 B) {
    vec3 AP = P - A, AB = B - A;
    return AP - AB*clamp(dot(AP, AB)/dot(AB, AB), 0.0, 1.0);
}

To compute the distance is trivial -- GLSL provides a distance() function which you can use on this closest point and P.

Inspired by Iñigo Quilez's code for a capsule distance function

How do I get a YouTube video thumbnail from the YouTube API?

YouTube is serving thumbnails from 2 servers. You just need to replace <YouTube_Video_ID_HERE> with your own YouTube video id. These days webP is best format for fast loading of images due to small image size.

https://img.youtube.com https://i.ytimg.com

Examples are with https://i.ytimg.com server just because it’s shorter, no other particular reason. You can use both.

Player Background Thumbnail (480x360):

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/0.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/0.jpg

Video frames thumbnails (120x90)

WebP:
Start: https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/1.webp
Middle: https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/2.webp
End: https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/3.webp

JPG:
Start: https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/1.jpg
Middle: https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/2.jpg
End: https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/3.jpg

Lowest quality thumbnail (120x90)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/default.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/default.jpg

Medium quality thumbnail (320x180)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/mqdefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg

High quality thumbnail (480x360)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/hqdefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg

Standard quality thumbnail (640x480)

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/sddefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg

Unscaled thumbnail resolution

WebP
https://i.ytimg.com/vi_webp/<YouTube_Video_ID_HERE>/maxresdefault.webp

JPG
https://i.ytimg.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg

How to set specific Java version to Maven

You can set Maven to use any java version following the instructions below.

Install jenv in your machine link

Check the available java versions installed in your machine by issuing the following command in command line.

jenv versions

You can specify global Java version using the following command.

jenv global oracle64-1.6.0.39

You can specify local Java version for any directory(Project) using the following command in the directory in command line.

jenv local oracle64-1.7.0.11

add the correct java version in your pom.xml

if you are running maven in command line install jenv maven plugin using below command

jenv enable-plugin maven

Now you can configure any java version in your machine to any project with out any trouble.

How do I import a namespace in Razor View Page?

You can try this

@using MyNamespace

How to build & install GLFW 3 and use it in a Linux project

Since the accepted answer does not allow more edits, I'm going to summarize it with a single copy-paste command (Replace 3.2.1 with the latest version available in the first line):

version="3.2.1" && \
wget "https://github.com/glfw/glfw/releases/download/${version}/glfw-${version}.zip" && \
unzip glfw-${version}.zip && \
cd glfw-${version} && \
sudo apt-get install cmake xorg-dev libglu1-mesa-dev && \
sudo cmake -G "Unix Makefiles" && \
sudo make && \
sudo make install

If you want to compile a program use the following commands:

g++ -std=c++11 -c main.cpp && \
g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor

If you are following the learnopengl.com tutorial you may have to set up GLAD as well. In such case click on this link

http://glad.dav1d.de/#profile=core&specification=gl&api=gl%3D3.3&api=gles1%3Dnone&api=gles2%3Dnone&api=glsc2%3Dnone&language=c&loader=on

and then click on the "Generate" button at the bottom right corner of the website and download the zip file. Extract it and compile the sources with the following command:

g++ glad/src/glad.c -c -Iglad/include

Now, the commands to compile your program become like this:

g++ -std=c++11 -c main.cpp -Iglad/include && \
g++ main.o glad.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor

Why does Firebug say toFixed() is not a function?

toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
    High = parseFloat($SliderValTo.val());

How to round up value C# to the nearest integer?

Math.Round

Rounds a double-precision floating-point value to the nearest integral value.

Export JAR with Netbeans

You need to enable the option

Project Properties -> Build -> Packaging -> Build JAR after compiling

(but this is enabled by default)

Winforms TableLayoutPanel adding rows programmatically

I just did this last week. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns, then your code should work:

// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);

Here is some working code that seems similar to what you are doing:

    private Int32 tlpRowCount = 0;

    private void BindAddress()
    {
        Addlabel(Addresses.Street);
        if (!String.IsNullOrEmpty(Addresses.Street2))
        {
            Addlabel(Addresses.Street2);
        }
        Addlabel(Addresses.CityStateZip);
        if (!String.IsNullOrEmpty(Account.Country))
        {
            Addlabel(Address.Country);
        }
        Addlabel(String.Empty); // Notice the empty label...
    }

    private void Addlabel(String text)
    {            
        label = new Label();
        label.Dock = DockStyle.Fill;
        label.Text = text;
        label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        tlpAddress.Controls.Add(label, 1, tlpRowCount);
        tlpRowCount++;
    }

The TableLayoutPanel always gives me fits with size. In my example above, I'm filing an address card that might grow or shrink depending on the account having an address line two, or a country. Because the last row, or column, of the table layout panel will stretch, I throw the empty label in there to force a new empty row, then everything lines up nicely.

Here is the designer code so you can see the table I start with:

        //
        // tlpAddress
        // 
        this.tlpAddress.AutoSize = true;
        this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
        this.tlpAddress.ColumnCount = 2;
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
        this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
        this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
        this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
        this.tlpAddress.Location = new System.Drawing.Point(0, 0);
        this.tlpAddress.Name = "tlpAddress";
        this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
        this.tlpAddress.RowCount = 2;
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
        this.tlpAddress.Size = new System.Drawing.Size(220, 95);
        this.tlpAddress.TabIndex = 0;

Get month and year from date cells Excel

You could right click on those cells, go to format, select custom, then type mm yyyy.

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

AngularJS: how to implement a simple file upload with multipart form?

I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!

<input type="file" multiple ng-simple-upload web-api-url="/api/post"
       callback-fn="myCallback" />

ng-simple-upload more on Github with an example using Web API.

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can't solve it. Simply answer1.sum()==0, and you can't perform a division by zero.

This happens because answer1 is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.

nan is returned in this case because of the division by zero.

Now to solve your problem you could:

  • go for a library for high-precision mathematics, like mpmath. But that's less fun.
  • as an alternative to a bigger weapon, do some math manipulation, as detailed below.
  • go for a tailored scipy/numpy function that does exactly what you want! Check out @Warren Weckesser answer.

Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:

exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
                = exp(log(exp(-x)*[1+exp(-y+x)]))
                = exp(log(exp(-x) + log(1+exp(-y+x)))
                = exp(-x + log(1+exp(-y+x)))

where above x=3* 1089 and y=3* 1093. Now, the argument of this exponential is

-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06

For the denominator you could proceed similarly but obtain that log(1+exp(-z+k)) is already rounded to 0, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000. You then have that your result is

exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x)) 
                                   = exp(-266.99999385580668)

which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089 in the numerator and the first number 1000 at the denominator):

exp(3*(1089-1000))=exp(-267)

For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):

Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523

The difference between this number and the exponent above is +1.7053025658242404e-13, so the approximation we made at the denominator was fine.

The final result is

'exp(-266.99999385580668) = 1.1050349147204485e-116

From wolfram alpha is (link)

1.105034914720621496.. × 10^-116 # Wolfram alpha.

and again, it is safe to use numpy here too.

how to get 2 digits after decimal point in tsql?

DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))

Both factor and result requires casting to be considered as decimals.

Transition of background-color

To me, it is better to put the transition codes with the original/minimum selectors than with the :hover or any other additional selectors:

_x000D_
_x000D_
#content #nav a {_x000D_
    background-color: #FF0;_x000D_
    _x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -moz-transition: background-color 1000ms linear;_x000D_
    -o-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}_x000D_
_x000D_
#content #nav a:hover {_x000D_
    background-color: #AD310B;_x000D_
}
_x000D_
<div id="content">_x000D_
    <div id="nav">_x000D_
        <a href="#link1">Link 1</a>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

VARCHAR to DECIMAL

After testing I found that it was not the decimal place that was causing the problem, it was the precision (10)

This doesn't work: Arithmetic overflow error converting varchar to data type numeric.

DECLARE @TestConvert VARCHAR(MAX) = '123456789.12343594'

SELECT CAST(@TestConvert AS DECIMAL(10, 4))

This worked

DECLARE @TestConvert VARCHAR(MAX) = '123456789.12343594'

SELECT CAST(@TestConvert AS DECIMAL(18, 4))

Copying a rsa public key to clipboard

For using Git bash on Windows:

cat ~/.ssh/id_rsa.pub > /dev/clipboard

(modified from Jupiter St John's post on Coderwall)

php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel

I was also getting the same error --> "[PDOException]
could not find driver "

After that I used many commands but not didn't get any help

Finally I used the following command, which solved my problem.

sudo apt-get install php5-sqlite

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

Between matplotlib+pylab and NumPy I don't think there's much actual difference between Matlab and python other than cultural inertia as suggested by @Adam Bellaire.

Converting char[] to byte[]

char[] ch = ?
new String(ch).getBytes();

or

new String(ch).getBytes("UTF-8");

to get non-default charset.

Update: Since Java 7: new String(ch).getBytes(StandardCharsets.UTF_8);

How to remove td border with html?

To remove borders between cells, while retaining the border around the table, add the attribute rules=none to the table tag.

There is no way in HTML to achieve the rendering specified in the last figure of the question. There are various tricky workarounds that are based on using some other markup structure.

Retrofit 2.0 how to get deserialised error response.body

I solved it by:

 if(!response.isSuccessful()){
       Gson gson = new Gson();
       MyErrorMessage message=gson.fromJson(response.errorBody().charStream(),MyErrorMessage.class);
       if(message.getCode()==ErrorCode.DUPLICATE_EMAIL_ID_CODE){
                  //DO Error Code specific handling                        
        }else{
                 //DO GENERAL Error Code Specific handling                               
        }
    }

MyErrorMessage Class:

  public class MyErrorMessage {
     private int code;
     private String message;

     public int getCode() {
        return code;
     }

     public void setCode(int code) {
        this.code = code;
     }

     public String getMessage() {
         return message;
     }

     public void setMessage(String message) {
        this.message = message;
     }
   }

Python set to list

Your code works with Python 3.2.1 on Win7 x64

a = set(["Blah", "Hello"])
a = list(a)
type(a)
<class 'list'>

How do I make the first letter of a string uppercase in JavaScript?

In CoffeeScript, add to the prototype for a string:

String::capitalize = ->
  @substr(0, 1).toUpperCase() + @substr(1)

Usage would be:

"woobie".capitalize()

Which yields:

"Woobie"

How to get primary key column in Oracle?

Save the following script as something like findPK.sql.

set verify off
accept TABLE_NAME char prompt 'Table name>'

SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');

It can then be called using

@findPK

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

Try this:

"0x" + BitConverter.ToString(arraytoinsert).Replace("-", "")

Although you should really be using a parameterised query rather than string concatenation of course...

How to trap on UIViewAlertForUnsatisfiableConstraints?

Followed Stephen's advice and tried to debug the code and whoa! it worked. The answer lies in the debug message itself.

Will attempt to recover by breaking constraint NSLayoutConstraint:0x191f0920 H:[MPKnockoutButton:0x17a876b0]-(34)-[MPDetailSlider:0x17a8bc50](LTR)>

The line above tells you that the runtime worked by removing this constraint. May be you don't need Horizontal Spacing on your button (MPKnockoutButton). Once you clear this constraint, it won't complain at runtime & you would get the desired behaviour.

utf-8 special characters not displaying

If all the other answers didn't work for you, try disabling HTTP input encoding translation.

This is a setting related to PHP extension mbstring. This was the problem in my case. This setting was enabled by default in my server.

"Error 404 Not Found" in Magento Admin Login Page

Finally, I found the solution to my problem.

I looked into the Magento system log file (var/log/system.log). There I saw the exact error.

The error is as below:-

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227

Actually, I had this error before. But, error display message like Error: 404 Not Found was new to me.

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.

Open PhpMyAdmin and run the following query in your database:-

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

I have written about this problem and solution over here:-

Magento: Solution to "Error: 404 Not Found" in Admin Login Page

Get output parameter value in ADO.NET

For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.

using (SqlConnection conn = new SqlConnection())
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters
    SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
    outputParam.Direction = ParameterDirection.Output;

    conn.Open();

    using(IDataReader reader = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            //read in data
        }
    }
    // reader is closed/disposed after exiting the using statement
    int id = outputParam.Value;
}

Handling multiple IDs in jQuery

Yes, #id selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.

However, for your example, since <script> comes before the elements, you need a document.ready handler, so it waits until the elements are in the DOM to go looking for them, like this:

<script>
  $(function() {
    $("#segement1,#segement2,#segement3").hide()
  });
</script>

<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>

Getting only Month and Year from SQL DATE

select convert(varchar(11), transfer_date, 106) 

got me my desired result of date formatted as 07 Mar 2018

My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure

Open Cygwin at a specific folder

Create a bash file say move.sh which has the following code C:\cygwin64\bin\run.exe -p /bin bash runFile.sh This starts the Cygwin and executes the runFile.sh present in the bin directory of Cygwin Suppose you want to navigate to a specific directory say E:\code then runFile.sh has the following code cd E: cd code

ngFor with index as value in attribute

with laravel pagination

file.component.ts file

    datasource: any = {
        data: []
    }

    loadData() {
        this.service.find(this.params).subscribe((res: any) => {
            this.datasource = res;
        });
    }

html file

   <tr *ngFor="let item of datasource.data; let i = index">
       <th>{{ datasource.from + i }}</th>
   </tr>

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

@ViewChild in *ngIf

It Work for me if i use ChangeDetectorRef in Angular 9

@ViewChild('search', {static: false})
public searchElementRef: ElementRef;

constructor(private changeDetector: ChangeDetectorRef) {}

//then call this when this.display = true;
show() {
   this.display = true;
   this.changeDetector.detectChanges();
}

HTML5 Canvas 100% Width Height of Viewport?

In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.

Example: http://jsfiddle.net/jaredwilli/qFuDr/

HTML

<canvas id="canvas"></canvas>

JavaScript

(function() {
    var canvas = document.getElementById('canvas'),
            context = canvas.getContext('2d');

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);

    function resizeCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            /**
             * Your drawings need to be inside this function otherwise they will be reset when 
             * you resize the browser window and the canvas goes will be cleared.
             */
            drawStuff(); 
    }
    resizeCanvas();

    function drawStuff() {
            // do your drawing stuff here
    }
})();

CSS

* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas { display:block; } /* To remove the scrollbars */

That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

How to access elements of a JArray (or iterate over them)

Update - I verified the below works. Maybe the creation of your JArray isn't quite right.

[TestMethod]
    public void TestJson()
    {
        var jsonString = @"{""trends"": [
              {
                ""name"": ""Croke Park II"",
                ""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
                ""promoted_content"": null,
                ""query"": ""%22Croke+Park+II%22"",
                ""events"": null
              },
              {
                ""name"": ""Siptu"",
                ""url"": ""http://twitter.com/search?q=Siptu"",
                ""promoted_content"": null,
                ""query"": ""Siptu"",
                ""events"": null
              },
              {
                ""name"": ""#HNCJ"",
                ""url"": ""http://twitter.com/search?q=%23HNCJ"",
                ""promoted_content"": null,
                ""query"": ""%23HNCJ"",
                ""events"": null
              },
              {
                ""name"": ""Boston"",
                ""url"": ""http://twitter.com/search?q=Boston"",
                ""promoted_content"": null,
                ""query"": ""Boston"",
                ""events"": null
              },
              {
                ""name"": ""#prayforboston"",
                ""url"": ""http://twitter.com/search?q=%23prayforboston"",
                ""promoted_content"": null,
                ""query"": ""%23prayforboston"",
                ""events"": null
              },
              {
                ""name"": ""#TheMrsCarterShow"",
                ""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
                ""promoted_content"": null,
                ""query"": ""%23TheMrsCarterShow"",
                ""events"": null
              },
              {
                ""name"": ""#Raw"",
                ""url"": ""http://twitter.com/search?q=%23Raw"",
                ""promoted_content"": null,
                ""query"": ""%23Raw"",
                ""events"": null
              },
              {
                ""name"": ""Iran"",
                ""url"": ""http://twitter.com/search?q=Iran"",
                ""promoted_content"": null,
                ""query"": ""Iran"",
                ""events"": null
              },
              {
                ""name"": ""#gaa"",
                ""url"": ""http://twitter.com/search?q=%23gaa"",
                ""promoted_content"": null,
                ""query"": ""gaa"",
                ""events"": null
              },
              {
                ""name"": ""Facebook"",
                ""url"": ""http://twitter.com/search?q=Facebook"",
                ""promoted_content"": null,
                ""query"": ""Facebook"",
                ""events"": null
              }]}";

        var twitterObject = JToken.Parse(jsonString);
        var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;


        foreach (var item in trendsArray.Children())
        {
            var itemProperties = item.Children<JProperty>();
            //you could do a foreach or a linq here depending on what you need to do exactly with the value
            var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            var myElementValue = myElement.Value; ////This is a JValue type
        }
    }

So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.

foreach(var item in yourJArray.Children())
{
    var itemProperties = item.Children<JProperty>();
    //you could do a foreach or a linq here depending on what you need to do exactly with the value
    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
    var myElementValue = myElement.Value; ////This is a JValue type
}

How to capture Curl output to a file?

If you want to store your output into your desktop, follow the below command using post command in git bash.It worked for me.

curl https://localhost:8080 --request POST --header "Content-Type: application/json" -o "C:\Desktop\test.txt"

Insert images to XML file

XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.

How to get ERD diagram for an existing database?

Our team use Visual Paradigm to generate ER diagram from database in many of our projects. While we mainly work on MS SQL and Oracle, as I know they also support some other DBMS like PostgreSQL, MySQL, Sybase, DB2 and SQLite.

Steps:

  1. Select Tools > DB > Reverse Database... from the toolbar of Visual Paradigm
  2. Keep the settings as is and click Next Select PostgreSQL as driver and provide the driver file there. You can simply click on the download link there to get the driver.
  3. Enter the hostname, database name, user and password, and then click Next
  4. They will then study your database and lists out the tables in it.
  5. Select the table to form an ERD and continue, and that's it. An ERD will be generated with the tables you selected presented.

BTW they also support generating and updating database schema from ERD.

Hope this helps. :-)

More information about generating ERD from PostgreSQL database

How to use an image for the background in tkinter?

You can use the root.configure(background='your colour') example:- import tkinter root=tkiner.Tk() root.configure(background='pink')

What is lexical scope?

A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.

This concept is heavily used in closures in JavaScript.

Let's say we have the below code.

var x = 2;
var add = function() {
    var y = 1;
    return x + y;
};

Now, when you call add() --> this will print 3.

So, the add() function is accessing the global variable x which is defined before method function add. This is called due to lexical scoping in JavaScript.

Does overflow:hidden applied to <body> work on iPhone Safari?

For me this:

height: 100%; 
overflow: hidden; 
width: 100%; 
position: fixed;

Wasn't enough, i't didn't work on iOS on Safari. I also had to add:

top: 0;
left: 0;
right: 0;
bottom: 0;

To make it work good. Works fine now :)

ng is not recognized as an internal or external command

try to set system variable path with %AppData%\npm\. and make sure visibility of AppData folder. this folder should be visible (not hidden).

convert iso date to milliseconds in javascript

Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.

var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);

See the fiddle for more details.

VBA using ubound on a multidimensional array

[This is a late answer addressing the title of the question (since that is what people would encounter when searching) rather than the specifics of OP's question which has already been answered adequately]

Ubound is a bit fragile in that it provides no way to know how many dimensions an array has. You can use error trapping to determine the full layout of an array. The following returns a collection of arrays, one for each dimension. The count property can be used to determine the number of dimensions and their lower and upper bounds can be extracted as needed:

Function Bounds(A As Variant) As Collection
    Dim C As New Collection
    Dim v As Variant, i As Long

    On Error GoTo exit_function
    i = 1
    Do While True
        v = Array(LBound(A, i), UBound(A, i))
        C.Add v
        i = i + 1
    Loop
exit_function:
    Set Bounds = C
End Function

Used like this:

Sub test()
    Dim i As Long
    Dim A(1 To 10, 1 To 5, 4 To 10) As Integer
    Dim B(1 To 5) As Variant
    Dim C As Variant
    Dim sizes As Collection

    Set sizes = Bounds(A)
    Debug.Print "A has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(B)
    Debug.Print vbCrLf & "B has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(C)
    Debug.Print vbCrLf & "C has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i
End Sub

Output:

A has 3 dimensions:
1 to 10
1 to 5
4 to 10

B has 1 dimensions:
1 to 5

C has 0 dimensions:

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

Since the beginning, Swift has provided some facilities for making ObjC and C more Swifty, adding more with each version. Now, in Swift 3, the new "import as member" feature lets frameworks with certain styles of C API -- where you have a data type that works sort of like a class, and a bunch of global functions to work with it -- act more like Swift-native APIs. The data types import as Swift classes, their related global functions import as methods and properties on those classes, and some related things like sets of constants can become subtypes where appropriate.

In Xcode 8 / Swift 3 beta, Apple has applied this feature (along with a few others) to make the Dispatch framework much more Swifty. (And Core Graphics, too.) If you've been following the Swift open-source efforts, this isn't news, but now is the first time it's part of Xcode.

Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose Edit > Convert > To Current Swift Syntax... in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)

The result is that the common pattern for bouncing work to the background and back now looks like this:

// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
    let image = self.loadOrGenerateAnImage()
    // Bounce back to the main thread to update the UI
    DispatchQueue.main.async {
        self.imageView.image = image
    }
}

Note we're using .userInitiated instead of one of the old DISPATCH_QUEUE_PRIORITY constants. Quality of Service (QoS) specifiers were introduced in OS X 10.10 / iOS 8.0, providing a clearer way for the system to prioritize work and deprecating the old priority specifiers. See Apple's docs on background work and energy efficiency for details.

By the way, if you're keeping your own queues to organize work, the way to get one now looks like this (notice that DispatchQueueAttributes is an OptionSet, so you use collection-style literals to combine options):

class Foo { 
    let queue = DispatchQueue(label: "com.example.my-serial-queue",
                           attributes: [.serial, .qosUtility])
    func doStuff() {
        queue.async {
            print("Hello World")
        }
    }
}

Using dispatch_after to do work later? That's a method on queues, too, and it takes a DispatchTime, which has operators for various numeric types so you can just add whole or fractional seconds:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
    print("Are we there yet?")
}

You can find your way around the new Dispatch API by opening its interface in Xcode 8 -- use Open Quickly to find the Dispatch module, or put a symbol (like DispatchQueue) in your Swift project/playground and command-click it, then brouse around the module from there. (You can find the Swift Dispatch API in Apple's spiffy new API Reference website and in-Xcode doc viewer, but it looks like the doc content from the C version hasn't moved into it just yet.)

See the Migration Guide for more tips.

How to convert Strings to and from UTF8 byte arrays in Java

Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

Count number of occurrences for each unique value

Yes, you can use GROUP BY:

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;

How to stop an app on Heroku?

You might have to be more specific and specify the app name as well (this is the name of the app as you have it in heroku). For example:

heroku ps:scale web=0 --app myAppName 

Otherwise you might get the following message:

 % heroku ps:scale web=0
Scaling dynos... failed
 !    No app specified.
 !    Run this command from an app folder or specify which app to use with --app APP.

Why does this "Slow network detected..." log appear in Chrome?

I faced same issue for chrome build 61.0.3163.100 on MacOs Sierra with localhost as server. Chrome started logging this message when I changed network speed configuration to 3G fast/ 3G slow and again back to Online.

Fix: When I tried selecting Offline mode and again Online mode, the logging issue disappeared. (This fix may no work on some devices or versions)

Update on 30th Jan 2018

I updated google chrome to Version 64.0.3282.119 (Official Build) (64-bit), it seems this bug is fixed now.

iOS: How to store username/password within an app?

If you need an ARC version of the wrapper here is the link https://gist.github.com/1170641 Thanks to

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Html.HiddenFor value property not getting set

Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

Delete all data in SQL Server database

Below a script that I used to remove all data from an SQL Server database

------------------------------------------------------------
/* Use database */ 
-------------------------------------------------------------

use somedatabase;

GO

------------------------------------------------------------------
/* Script to delete an repopulate the base [init database] */
------------------------------------------------------------------

-------------------------------------------------------------
/* Procedure delete all constraints */ 
-------------------------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_DeleteAllConstraints' AND type = 'P')
    DROP PROCEDURE dbo.sp_DeleteAllConstraints
GO

CREATE PROCEDURE sp_DeleteAllConstraints
AS
    EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
    EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
GO

-----------------------------------------------------
/* Procedure delete all data from the database */ 
-----------------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_DeleteAllData' AND type = 'P')
    DROP PROCEDURE dbo.sp_DeleteAllData
GO

CREATE PROCEDURE sp_DeleteAllData
AS
    EXEC sp_MSForEachTable 'DELETE FROM ?'
GO

-----------------------------------------------
/* Procedure enable all constraints */ 
-----------------------------------------------

IF EXISTS (SELECT name  
           FROM  sysobjects 
           WHERE name = 'sp_EnableAllConstraints' AND type = 'P')
    DROP PROCEDURE dbo.sp_EnableAllConstraints
GO
-- ....
-- ....
-- ....

Java 8 List<V> into Map<K, V>

You can create a Stream of the indices using an IntStream and then convert them to a Map :

Map<Integer,Item> map = 
IntStream.range(0,items.size())
         .boxed()
         .collect(Collectors.toMap (i -> i, i -> items.get(i)));

No input file specified

It worked for me..add on top of .htaccess file. It would disable FastCGI on godaddy shared hosting account.

Options +ExecCGI

addhandler x-httpd-php5-cgi .php

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.

If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

to:

RewriteRule ^(wp-(content|admin|includes).*) - [L]

The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.

It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.

How to add minutes to current time in swift

I think the simplest will be

let minutes = Date(timeIntervalSinceNow:(minutes * 60.0))

What are bitwise shift (bit-shift) operators and how do they work?

I am writing tips and tricks only. It may be useful in tests and exams.

  1. n = n*2: n = n<<1
  2. n = n/2: n = n>>1
  3. Checking if n is power of 2 (1,2,4,8,...): check !(n & (n-1))
  4. Getting xth bit of n: n |= (1 << x)
  5. Checking if x is even or odd: x&1 == 0 (even)
  6. Toggle the nth bit of x: x ^ (1<<n)

Word wrapping in phpstorm

WebStorm 10.0.4

For wrapping text/code line by deafault, but for all types of file: File -> Settings -> Editor -> General -> section "Soft Wraps" -> checkbox "Use soft wraps in editor"

(imho)

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

When to throw an exception?

There are two main classes of exception:

1) System exception (eg Database connection lost) or 2) User exception. (eg User input validation, 'password is incorrect')

I found it helpful to create my own User Exception Class and when I want to throw a user error I want to be handled differently (ie resourced error displayed to the user) then all I need do in my main error handler is check the object type:

            If TypeName(ex) = "UserException" Then
               Display(ex.message)
            Else
               DisplayError("An unexpected error has occured, contact your help  desk")                   
               LogError(ex)
            End If

SQLRecoverableException: I/O Exception: Connection reset

This simply means that something in the backend ( DBMS ) decided to stop working due to unavailability of resources etc. It has nothing to do with your code or the number of inserts. You can read more about similar problems here:

This may not answer your question, but you will get an idea of why it might be happening. You could further discuss with your DBA and see if there is something specific in your case.

Command failed due to signal: Segmentation fault: 11

Named tuples in array in a let property gave me the seg fault issue.

Android fastboot waiting for devices

In my case (on windows 10), it would connect fine to adb and I could type any adb commands. But as soon as it got to the bootloader using adb reboot bootloader I wasn't able to perform any fastboot commands.

What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID), and that fixed my waiting for device issue

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

What tool to use to draw file tree diagram

Copying and pasting from the MS-DOS tree command might also work for you. Examples:

tree

C:\Foobar>tree
C:.
+---FooScripts
+---barconfig
+---Baz
¦   +---BadBaz
¦   +---Drop
...

tree /F

C:\Foobar>tree
C:.
+---FooScripts
¦    foo.sh
+---barconfig
¦    bar.xml
+---Baz
¦   +---BadBaz
¦   ¦    badbaz.xml
¦   +---Drop
...

tree /A

C:\Foobar>tree /A
C:.
+---FooScripts
+---barconfig
+---Baz
¦   +---BadBaz
¦   \---Drop
...

tree /F /A

C:\Foobar>tree /A
C:.
+---FooScripts
¦    foo.sh
+---barconfig
¦    bar.xml
+---Baz
¦   +---BadBaz
¦   ¦    badbaz.xml
¦   \---Drop
...

Syntax [source]

tree [drive:][path] [/F] [/A]

drive:\path — Drive and directory containing disk for display of directory structure, without listing files.

/F — Include all files living in every directory.

/A — Replace graphic characters used for linking lines with ext characters , instead of graphic characters. /a is used with code pages that do not support graphic characters and to send output to printers that do not properly interpret graphic characters.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

Escape double quotes in parameter

The 2nd document quoted by Peter Mortensen in his comment on the answer of Codesmith made things much clearer for me. That document was written by windowsinspired.com. The link repeated: A Better Way To Understand Quoting and Escaping of Windows Command Line Arguments.

Some further trial and error leads to the following guideline:

Escape every double quote " with a caret ^. If you want other characters with special meaning to the Windows command shell (e.g., <, >, |, &) to be interpreted as regular characters instead, then escape them with a caret, too.

If you want your program foo to receive the command line text "a\"b c" > d and redirect its output to file out.txt, then start your program as follows from the Windows command shell:

foo ^"a\^"b c^" ^> d > out.txt

If foo interprets \" as a literal double quote and expects unescaped double quotes to delimit arguments that include whitespace, then foo interprets the command as specifying one argument a"b c, one argument >, and one argument d.

If instead foo interprets a doubled double quote "" as a literal double quote, then start your program as

foo ^"a^"^"b c^" ^> d > out.txt

The key insight from the quoted document is that, to the Windows command shell, an unescaped double quote triggers switching between two possible states.

Some further trial and error implies that in the initial state, redirection (to a file or pipe) is recognized and a caret ^ escapes a double quote and the caret is removed from the input. In the other state, redirection is not recognized and a caret does not escape a double quote and isn't removed. Let's refer to these states as 'outside' and 'inside', respectively.

If you want to redirect the output of your command, then the command shell must be in the outside state when it reaches the redirection, so there must be an even number of unescaped (by caret) double quotes preceding the redirection. foo "a\"b " > out.txt won't work -- the command shell passes the entire "a\"b " > out.txt to foo as its combined command line arguments, instead of passing only "a\"b " and redirecting the output to out.txt.

foo "a\^"b " > out.txt won't work, either, because the caret ^ is encountered in the inside state where it is an ordinary character and not an escape character, so "a\^"b " > out.txt gets passed to foo.

The only way that (hopefully) always works is to keep the command shell always in the outside state, because then redirection works.

If you don't need redirection (or other characters with special meaning to the command shell), then you can do without the carets. If foo interprets \" as a literal double quote, then you can call it as

foo "a\"b c"

Then foo receives "a\"b c" as its combined arguments text and can interpret it as a single argument equal to a"b c.

Now -- finally -- to the original question. myscript '"test"' called from the Windows command shell passes '"test"' to myscript. Apparently myscript interprets the single and double quotes as argument delimiters and removes them. You need to figure out what myscript accepts as a literal double quote and then specify that in your command, using ^ to escape any characters that have special meaning to the Windows command shell. Given that myscript is also available on Unix, perhaps \" does the trick. Try

myscript \^"test\^"

or, if you don't need redirection,

myscript \"test\"

How to call a php script/function on a html button click

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>

How can I tell if a DOM element is visible in the current viewport?

My shorter and faster version:

function isElementOutViewport(el){
    var rect = el.getBoundingClientRect();
    return rect.bottom < 0 || rect.right < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight;
}

And a jsFiddle as required: https://jsfiddle.net/on1g619L/1/

Compiling a C++ program with gcc

If I recall correctly, gcc determines the filetype from the suffix. So, make it foo.cc and it should work.

And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.

How do I concatenate const/literal strings in C?

The first argument of strcat() needs to be able to hold enough space for the concatenated string. So allocate a buffer with enough space to receive the result.

char bigEnough[64] = "";

strcat(bigEnough, "TEXT");
strcat(bigEnough, foo);

/* and so on */

strcat() will concatenate the second argument with the first argument, and store the result in the first argument, the returned char* is simply this first argument, and only for your convenience.

You do not get a newly allocated string with the first and second argument concatenated, which I'd guess you expected based on your code.

How to extract custom header value in Web API message handler?

Create a new method - 'Returns an individual HTTP Header value' and call this method with key value everytime when you need to access multiple key Values from HttpRequestMessage.

public static string GetHeader(this HttpRequestMessage request, string key)
        {
            IEnumerable<string> keys = null;
            if (!request.Headers.TryGetValues(key, out keys))
                return null;

            return keys.First();
        }

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, I had a OneToOne relation which I was using with @Column by mistake. I changed it to @JoinColumn and added @OneToOne annotation and it fixed the exception.

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

If you are in a test environment and do not want to set security settings you have to allow less secure apps via. this link in Gmail.

https://myaccount.google.com/lesssecureapps

Java - ignore exception and continue

Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Child element click event trigger the parent click event

Click event Bubbles, now what is meant by bubbling, a good point to starts is here. you can use event.stopPropagation(), if you don't want that event should propagate further.

Also a good link to refer on MDN

How do I parallelize a simple Python loop?

This could be useful when implementing multiprocessing and parallel/ distributed computing in Python.

YouTube tutorial on using techila package

Techila is a distributed computing middleware, which integrates directly with Python using the techila package. The peach function in the package can be useful in parallelizing loop structures. (Following code snippet is from the Techila Community Forums)

techila.peach(funcname = 'theheavyalgorithm', # Function that will be called on the compute nodes/ Workers
    files = 'theheavyalgorithm.py', # Python-file that will be sourced on Workers
    jobs = jobcount # Number of Jobs in the Project
    )

Implode an array with JavaScript?

For future reference, if you want to mimic the behaviour of PHP's implode() when no delimiter is specified (literally just join the pieces together), you need to pass an empty string into Javascript's join() otherwise it defaults to using commas as delimiters:

var bits = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
alert(bits.join());    // H,e,l,l,o, ,W,o,r,l,d
alert(bits.join(''));  // Hello World

Check if a parameter is null or empty in a stored procedure

you can use:

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')

Comparing two input values in a form validation with AngularJS

Of course for very simple comparisons you can always use ngMin/ngMax.

Otherwise, you can go with a custom directive, and there is no need of doing any $watch or $observe or $eval or this fancy $setValidity back and forth. Also, there is no need to hook into the postLink function at all. Try to stay out of the DOM as much as possible, as it is against the angular spirit.

Just use the lifecycle hooks the framework gives you. Add a validator and $validate at each change. Simple as that.

app.directive('sameAs', function() {
  return {
    restrict: 'A',
    require: {
      ngModelCtrl: 'ngModel'
    },
    scope: {
      reference: '<sameAs'
    },
    bindToController: true,
    controller: function($scope) {
      var $ctrl = $scope.$ctrl;

      //add the validator to the ngModelController
      $ctrl.$onInit = function() {
        function sameAsReference (modelValue, viewValue) {
          if (!$ctrl.reference || !modelValue) { //nothing to compare
            return true;
          }
          return modelValue === $ctrl.reference;
        }
        $ctrl.ngModelCtrl.$validators.sameas = sameAsReference;
      };

      //do the check at each change
      $ctrl.$onChanges = function(changesObj) {
        $ctrl.ngModelCtrl.$validate();
      };
    },
    controllerAs: '$ctrl'
  };
});

Your plunker.

How do I add space between two variables after a print in Python

You can do it this way in python3:

print(a,b,end=" ")

How to concatenate string and int in C?

Look at snprintf or, if GNU extensions are OK, asprintf (which will allocate memory for you).

How to call a vue.js function on page load

If you get data in array you can do like below. It's worked for me

    <template>
    {{ id }}
    </template>
    <script>

    import axios from "axios";

        export default {
            name: 'HelloWorld',
            data () {
                return {
                    id: "",

                }
            },
    mounted() {
                axios({ method: "GET", "url": "https://localhost:42/api/getdata" }).then(result => {
                    console.log(result.data[0].LoginId);
                    this.id = result.data[0].LoginId;
                }, error => {
                    console.error(error);
                });
            },
</script>

File size exceeds configured limit (2560000), code insight features not available

For those who don't know where to find the file they're talking about. On my machine (OSX) it is in:

  • PyCharm CE: /Applications/PyCharm CE.app/Contents/bin/idea.properties
  • WebStorm: /Applications/WebStorm.app/Contents/bin/idea.properties

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8 or other encoder that can represent your data. Then you can print it to sys.stdout.

First, run following code in the console:

chcp 65001
set PYTHONIOENCODING=utf-8

Then, start python do anything you want.

Spring Boot - inject map from application.yml

Below solution is a shorthand for @Andy Wilkinson's solution, except that it doesn't have to use a separate class or on a @Bean annotated method.

application.yml:

input:
  name: raja
  age: 12
  somedata:
    abcd: 1 
    bcbd: 2
    cdbd: 3

SomeComponent.java:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "input")
class SomeComponent {

    @Value("${input.name}")
    private String name;

    @Value("${input.age}")
    private Integer age;

    private HashMap<String, Integer> somedata;

    public HashMap<String, Integer> getSomedata() {
        return somedata;
    }

    public void setSomedata(HashMap<String, Integer> somedata) {
        this.somedata = somedata;
    }

}

We can club both @Value annotation and @ConfigurationProperties, no issues. But getters and setters are important and @EnableConfigurationProperties is must to have the @ConfigurationProperties to work.

I tried this idea from groovy solution provided by @Szymon Stepniak, thought it will be useful for someone.

Rename package in Android Studio

  1. Select option enter image description here

  2. Uncheck the Compact Empty Middle Packages option.

  3. Select which directory you want to change(I have selected 'crl' shown in step 6).
  4. Shift+F6
  5. Rename Package
  6. Renaming directory crl to crl1 enter image description here

  7. Finally click on Do Refactor button marked in image below enter image description here enter code here

  8. After Changes done enter image description here

The listener supports no services

for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address

alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;

Currency format for display

Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.

You can use it with either String.Format or the overloaded ToString method for a numeric type.

For example:

double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("da-DK")));

// The example displays the following output on a system whose
// current culture is English (United States):
//       $12,345.68
//       $12,345.679
//       kr 12.345,679

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

Same here people, this works perfect btw in Chrome (stable, dev and canary) just not in FF and Safari. It also works perfect on my iPhone and iPad (Safari!). This might be due to the relative newness of this feature (i.e. it is a bug). I spend almost a week on this now and I just cannot get it to work on those browsers

Here's what I found:

The first time you call getCurrentPosition it works perfect. Any subsequent call never returns, i.e. it does not fire the successCallback or the errorCallback functions. I added a few position options to my call to prove my point:

 navigator.geolocation.getCurrentPosition(successCallback, errorCallback,  {timeout: 10000});

and it times out every time (after the first successful call). I thought I could fix it with maximumAge, but that doesn't seem to be working as it is suppose to work either:

navigator.geolocation.getCurrentPosition(successCallback, errorCallback,  {maximumAge:60000, timeout: 2000});

this should prevent actually calling the getCurrentPosition function if you call it within 60 seconds, but it ignores this (however, this could be due because I actually refresh my page to trigger the second call, not sure if this is persistent accross calls)

btw, even google's examples fail on these browsers which leads me to believe that this are indeed browser bugs, try it, load it twice in Safari and it won't work the second time.

If anybody finds a solution for this, PLEASE let me know :-)

Cheers.

Function passed as template argument

Function pointers can be passed as template parameters, and this is part of standard C++ . However in the template they are declared and used as functions rather than pointer-to-function. At template instantiation one passes the address of the function rather than just the name.

For example:

int i;


void add1(int& i) { i += 1; }

template<void op(int&)>
void do_op_fn_ptr_tpl(int& i) { op(i); }

i = 0;
do_op_fn_ptr_tpl<&add1>(i);

If you want to pass a functor type as a template argument:

struct add2_t {
  void operator()(int& i) { i += 2; }
};

template<typename op>
void do_op_fntr_tpl(int& i) {
  op o;
  o(i);
}

i = 0;
do_op_fntr_tpl<add2_t>(i);

Several answers pass a functor instance as an argument:

template<typename op>
void do_op_fntr_arg(int& i, op o) { o(i); }

i = 0;
add2_t add2;

// This has the advantage of looking identical whether 
// you pass a functor or a free function:
do_op_fntr_arg(i, add1);
do_op_fntr_arg(i, add2);

The closest you can get to this uniform appearance with a template argument is to define do_op twice- once with a non-type parameter and once with a type parameter.

// non-type (function pointer) template parameter
template<void op(int&)>
void do_op(int& i) { op(i); }

// type (functor class) template parameter
template<typename op>
void do_op(int& i) {
  op o; 
  o(i); 
}

i = 0;
do_op<&add1>(i); // still need address-of operator in the function pointer case.
do_op<add2_t>(i);

Honestly, I really expected this not to compile, but it worked for me with gcc-4.8 and Visual Studio 2013.

Design Patterns web based applications

In the beaten-up MVC pattern, the Servlet is "C" - controller.

Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.

I would not, though, start writing raw Servlet classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.

Why I got " cannot be resolved to a type" error?

I had this problem while the other class (CarService) was still empty, no methods, nothing. When it had methods and variables, the error was gone.

C# - What does the Assert() method do? Is it still useful?

From Code Complete

8 Defensive Programming

8.2 Assertions

An assertion is code that’s used during development—usually a routine or macro—that allows a program to check itself as it runs. When a assertion is true, that means everything is operating as expected. When it’s false, that means it has detected an unexpected error in the code. For example, if the system assumes that a customer-information file will never have more than 50,000 records, the program might contain an assertion that the number of records is less than or equal to 50,000. As long as the number of records is less than or equal to 50,000, the assertion will be silent. If it encounters more than 50,000 records, however, it will loudly “assert” that there is a error in the program.

Assertions are especially useful in large, complicated programs and in high-reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when the code is modified, and so on.

An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it isn’t.

(…)

Normally, you don’t want users to see assertion messages in production code; assertions are primarily for use during development and maintenance. Assertions are normally compiled into the code at development time and compiled out of the code for production. During development, assertions flush out contradictory assumptions, unexpected conditions, bad values passed to routines, and so on. During production, they are compiled out of the code so that the assertions don’t degrade system performance.

How to use PHP with Visual Studio

Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.

This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.

Maybe you can now understand why your approach so far could never work out.

Deleting an element from an array in PHP

To avoid doing a search one can play around with array_diff:

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

In this case one doesn't have to search/use the key.

How to turn a String into a JavaScript function call?

In javascript that uses the CommonJS spec, like node.js for instance you can do what I show below. Which is pretty handy for accessing a variable by a string even if its not defined on the window object. If there is a class named MyClass, defined within a CommonJS module named MyClass.js

// MyClass.js
var MyClass = function() {
    // I do stuff in here. Probably return an object
    return {
       foo: "bar"
    }
}

module.exports = MyClass;

You can then do this nice bit o witchcraft from another file called MyOtherFile.js

// MyOtherFile.js

var myString = "MyClass";

var MyClass = require('./' + myString);
var obj = new MyClass();

console.log(obj.foo); // returns "bar"

One more reason why CommonJS is such a pleasure.

how to write an array to a file Java

If you're okay with Apache commons lib

outputWriter.write(ArrayUtils.join(array, ","));

Groovy executing shell commands

// a wrapper closure around executing a string                                  
// can take either a string or a list of strings (for arguments with spaces)    
// prints all output, complains and halts on error                              
def runCommand = { strList ->
  assert ( strList instanceof String ||
           ( strList instanceof List && strList.each{ it instanceof String } ) \
)
  def proc = strList.execute()
  proc.in.eachLine { line -> println line }
  proc.out.close()
  proc.waitFor()

  print "[INFO] ( "
  if(strList instanceof List) {
    strList.each { print "${it} " }
  } else {
    print strList
  }
  println " )"

  if (proc.exitValue()) {
    println "gave the following error: "
    println "[ERROR] ${proc.getErrorStream()}"
  }
  assert !proc.exitValue()
}

How do I make a C++ macro behave like a function?

Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once.

If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator:

#define MACRO(X,Y) \
 ( \
  (cout << "1st arg is:" << (X) << endl), \
  (cout << "2nd arg is:" << (Y) << endl), \
  (cout << "3rd arg is:" << ((X) + (Y)) << endl), \
  (void)0 \
 )

The (void)0 causes the statement to evaluate to one of void type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that MACRO(a++, b++) will increment a and b twice.

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

How do I install Python 3 on an AWS EC2 instance?

If you do a

sudo yum list | grep python3

you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:

sudo yum install python34 python34-pip

In Java, what is the best way to determine the size of an object?

long heapSizeBefore = Runtime.getRuntime().totalMemory();

// Code for object construction
...
long heapSizeAfter = Runtime.getRuntime().totalMemory();
long size = heapSizeAfter - heapSizeBefore;

size gives you the increase in memory usage of the jvm due to object creation and that typically is the size of the object.

What is correct content-type for excel files?

Do keep in mind that the file.getContentType could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.

Laravel 5 PDOException Could Not Find Driver

I have tried the following command on Ubuntu and its working for me sudo apt-get install php7.0-mysql

Thanks

Table Height 100% inside Div element

You need to have a height in the div <div style="overflow:hidden"> else it doesnt know what 100% is.

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path) directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

In Python how should I test if a variable is None, True or False

There are many good answers. I would like to add one more point. A bug can get into your code if you are working with numerical values, and your answer is happened to be 0.

a = 0 
b = 10 
c = None

### Common approach that can cause a problem

if not a:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if not b:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}")

if not c:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")
Answer is not found. Answer is 0.   
Answer is: 10.   
Answer is not found. Answer is None.
### Safer approach 
if a is None:
    print(f"Answer is not found. Answer is {str(a)}.") 
else:
    print(f"Answer is: {str(a)}.")

if b is None:
    print(f"Answer is not found. Answer is {str(b)}.") 
else:
    print(f"Answer is: {str(b)}.")

if c is None:
    print(f"Answer is not found. Answer is {str(c)}.") 
else:
    print(f"Answer is: {str(c)}.")

Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.

How do I close an Android alertdialog

alertDialog.setPositiveButton("SAVE",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        /*Write your code here */
                        dialog.dismiss();
                    }
                });
        alertDialog.setNegativeButton("CANCEL",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Insert new item in array on any position in PHP

$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)

no module named urllib.parse (How should I install it?)

The urlparse in Python 2.7.11 was renamed to urllib.parse in Python 3. So, if you have a code such from urlparse import urlparse, I suggest you change it to from urllib.parse import urlparse Since you are using python 2.7.5, using the below will solve your poblem

from urlparse import urlparse

Instead of from urllib.parse import urlparse

update listview dynamically with adapter

Most people recommend using notifyDataSetChanged(), but I found this link pretty useful. In fact using clear and add you can accomplish the same goal using less memory footprint, and more responsibe app.

For example:

notesListAdapter.clear();
notes = new ArrayList<Note>();
notesListAdapter.add(todayNote);
if (birthdayNote != null) notesListAdapter.add(birthdayNote);

/* no need to refresh, let the adaptor do its job */

Detailed 500 error message, ASP + IIS 7.5

If you're on a remote server you can configure your web.config file like so:

<configuration>
<system.webServer>
    <httpErrors errorMode="Detailed" />
    <asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
    <customErrors mode="Off"/>
    <compilation debug="true"/>
</system.web>

Can Windows' built-in ZIP compression be scripted?

to create a compressed archive you can use the utility MAKECAB.EXE

How to update a menu item shown in the ActionBar?

in my case: invalidateOptionsMenu just re-setted the text to the original one, but directly accessing the menu item and re-writing the desire text worked without problems:

if (mnuTopMenuActionBar_ != null) {
    MenuItem mnuPageIndex = mnuTopMenuActionBar_
        .findItem(R.id.menu_magazin_pageOfPage_text);

    if (mnuPageIndex != null) {
        if (getScreenOrientation() == 1) {
            mnuPageIndex.setTitle((i + 1) + " von " + pages);
        }
        else {
            mnuPageIndex.setTitle(
                (i + 1) + " + " + (i + 2) + " " + " von " + pages);
        }
        // invalidateOptionsMenu();
    }
}

due to the comment below, I was able to access the menu item via the following code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.magazine_swipe_activity, menu);
    mnuTopMenuActionBar_ = menu;
    return true;
}

Adding value labels on a matplotlib bar chart

If you only want to add Datapoints above the bars, you could easily do it with:

 for i in range(len(frequencies)): # your number of bars
    plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
    y = y_values[i]+1, #takes your y values as vertical positioning argument 
    s = data_labels[i], # the labels you want to add to the data
    size = 9) # font size of datalabels

ng-repeat :filter by single field

You must use filter:{color_name:by_colour} instead of

filter:by_colour

If you want to match with a single property of an object, then write that property instead of object, otherwise some other property will get match.

Method call if not null in C#

Maybe not better but in my opinion more readable is to create an extension method

public static bool IsNull(this object obj) {
 return obj == null;
}

Ruby on Rails: Where to define global constants?

Some options:

Using a constant:

class Card
  COLOURS = ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
end

Lazy loaded using class instance variable:

class Card
  def self.colours
    @colours ||= ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
  end
end

If it is a truly global constant (avoid global constants of this nature, though), you could also consider putting a top-level constant in config/initializers/my_constants.rb for example.

What is the python "with" statement designed for?

Again for completeness I'll add my most useful use-case for with statements.

I do a lot of scientific computing and for some activities I need the Decimal library for arbitrary precision calculations. Some part of my code I need high precision and for most other parts I need less precision.

I set my default precision to a low number and then use with to get a more precise answer for some sections:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

I use this a lot with the Hypergeometric Test which requires the division of large numbers resulting form factorials. When you do genomic scale calculations you have to be careful of round-off and overflow errors.

Generating unique random numbers (integers) between 0 and 'x'

Something like this

var limit = 10;
var amount = 3;
var nums = new Array();

for(int i = 0; i < amount; i++)
{
    var add = true;
    var n = Math.round(Math.random()*limit + 1;
    for(int j = 0; j < limit.length; j++)
    {
        if(nums[j] == n)
        {
            add = false;
        }
    }
    if(add)
    {
        nums.push(n)
    }
    else
    {
        i--;
    }
}

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

Test step/scenario:
1. Open a browser and navigate to TestURL
2. Maximize the browser

Maximize the browser with C# (.NET):

driver.Manage().Window.Maximize();

Maximize the browser with Java :

driver.manage().window().maximize();

Another way to do with Java:

Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenResolution = new Dimension((int) 
                    toolkit.getScreenSize().getWidth(), (int) 
                    toolkit.getScreenSize().getHeight());

driver.manage().window().setSize(screenResolution);

How to Call Controller Actions using JQuery in ASP.NET MVC

We can call Controller method using Javascript / Jquery very easily as follows:

Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'

public JsonResult SubMenu_Click(string param1, string param2)

    {
       A[] arr = null;
        try
        {
            Processing...
           Get Result and fill arr.

        }
        catch { }


        return Json(arr , JsonRequestBehavior.AllowGet);

    }

Following is the complex type (class)

 public class A
 {

  public string property1 {get ; set ;}

  public string property2 {get ; set ;}

 }

Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.

function callControllerMethod(value1 , value2) {
    var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 &param2=value2'
    $.getJSON(strMethodUrl, receieveResponse);
}


function receieveResponse(response) {

    if (response != null) {
        for (var i = 0; i < response.length; i++) {
           alert(response[i].property1);
        }
    }
}

In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.

receieveResponse is the callback function receiving the response or return value of the controllers method.

Here we made use of JSON , since we can't make use of the C# class object

directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:

Json(arr , JsonRequestBehavior.AllowGet);

and returned that Json object.

Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.

For more detaill click here

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Try writting the lambda with the same conditions as the delegate. like this:

  List<AnalysisObject> analysisObjects = 
    analysisObjectRepository.FindAll().Where(
    (x => 
       (x.ID == packageId)
    || (x.Parent != null && x.Parent.ID == packageId)
    || (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
    ).ToList();

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns refers to the XML namespace

When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

Note: The namespace URI is not used by the parser to look up information.

The purpose is to give the namespace a unique name. However, often companies use the namespace as a pointer to a web page containing namespace information.

How to deploy a React App on Apache web server

Firstly, in your react project go to your package.json and adjust this line line of code to match your destination domain address + folder:

"homepage": "https://yourwebsite.com/your_folder_name/",

Secondly, go to terminal in your react project and type:

npm run build

Now, take all files from that newly created build folder and upload them into your_folder_name, with filezilla in subfolder like this:

public_html/your_folder_name

Check in the browser!

Difference between Apache CXF and Axis

Keep in mind, I'm completely biased (PMC Chair of CXF), but my thoughts:

From a strictly "can the project do what I need it to do" perspective, both are pretty equivalent. There some "edge case" things that CXF can do that Axis 2 cannot and vice versa. But for 90% of the use cases, either will work fine.

Thus, it comes down to a bunch of other things other than "check box features".

  • API - CXF pushes "standards based" API's (JAX-WS compliant) whereas Axis2 general goes toward proprietary things. That said, even CXF may require uses of proprietary API's to configure/control various things outside the JAX-WS spec. For REST, CXF also uses standard API's (JAX-RS compliant) instead of proprietary things. (Yes, I'm aware of the JAX-WS runtime in Axis2, but the tooling and docs and everything doesn't target it)

  • Community aspects and supportability - CXF prides itself on responding to issues and making "fixpacks" available to users. CXF did 12 fixpacks for 2.0.x (released two years ago, so about every 2 months), 6 fixpacks to 2.1.x, and now 3 for 2.2.x. Axis2 doesn't really "support" older versions. Unless a "critical" issue is hit, you may need to wait till the next big release (they average about every 9-10 months or so) to get fixes. (although, with either, you can grab the source code and patch/fix yourself. Gotta love open source.)

  • Integration - CXF has much better Spring integration if you use Spring. All the configuration and such is done through Spring. Also, people tend to consider CXF as more "embeddable" (I've never looked at Axis2 from this perspective) into other applications. Not sure if things like that matter to you.

  • Performance - they both perform very well. I think Axis2's proprietary ADB databinding is a bit faster than CXF, but if you use JAXB (standards based API's again), CXF is a bit faster. When using more complex scenarios like WS-Security, the underlying security "engine" (WSS4J) is the same for both so the performance is completely comparable.

Not sure if that answers the question at all. Hope it at least provides some information.

:-)

Dan

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

What is Vim recording and how can it be disabled?

It sounds like you have macro recording turned on. To shut it off, press q.

Refer to ":help recording" for further information.

Related links:

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

How to set the JSTL variable value in javascript?

You can save the whole jstl object as a Javascript object by converting the whole object to json. It is possible by Jackson in java.

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil{
   public static String toJsonString(Object obj){
      ObjectMapper objectMapper = ...; // jackson object mapper
      return objectMapper.writeValueAsString(obj);
   }
}

/WEB-INF/tags/util-functions.tld:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" 
  version="2.1"> 

  <tlib-version>1.0</tlib-version>
  <uri>http://www.your.url/util-functions</uri>

  <function>
      <name>toJsonString</name>
      <function-class>your.package.JsonUtil</function-class>
      <function-signature>java.lang.String toJsonString(java.lang.Object)</function-signature>
  </function>  

</taglib> 

web.xml

<jsp-config>
  <tablib>
    <taglib-uri>http://www.your.url/util-functions</taglib-uri>
    <taglib-location>/WEB-INF/tags/util-functions.tld</taglib-location>
  </taglib>
</jsp-confi>

mypage.jsp:

<%@ taglib prefix="uf" uri="http://www.your.url/util-functions" %> 

<script>
   var myJavaScriptObject = JSON.parse('${uf:toJsonString(myJstlObject)}');
</script>

Input size vs width

You can resize using style and width to resize the textbox. Here is the code for it.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div align="center">_x000D_
_x000D_
    <form method="post">_x000D_
          <div class="w3-row w3-section">_x000D_
            <div class="w3-rest" align = "center">_x000D_
                <input name="lastName" type="text" id="myInput" style="width: 50%">_x000D_
            </div>_x000D_
        </div>_x000D_
    </form>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Use align to center the textbox.

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

In my case I have a Table Column name Path which datatype i set was varchar(200).After updating it to nvarchar(max), I have deleted the table from edmx and then again added the table and it wokred properly for me.

Find files in a folder using Java

Appache commons IO various

FilenameUtils.wildcardMatch

See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.

html <input type="text" /> onchange event not working

HTML5 defines an oninput event to catch all direct changes. it works for me.

Searching if value exists in a list of objects using Linq

The technique i used before discovering .Any():

var hasJohn = (from customer in list
      where customer.FirstName == "John"
      select customer).FirstOrDefault() != null;

Openssl : error "self signed certificate in certificate chain"

If you're running Charles and trying to build a container then you'll most likely get this error.

Make sure to disable Charles (macos) proxy under proxy -> macOS proxy

Charles is an

HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.

So anything similar may cause the same issue.

Implementing a Custom Error page on an ASP.Net website

<system.webServer>     
<httpErrors errorMode="DetailedLocalOnly">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
    </httpErrors>
</system.webServer>

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

The general rule-of-thumb is, if you can do it using a single SQL statement instead of using PL/SQL, you should. It will usually be more efficient.

However, if you need to add more procedural logic (for some reason), you might need to use PL/SQL, but you should use bulk operations instead of row-by-row processing. (Note: in Oracle 10g and later, your FOR loop will automatically use BULK COLLECT to fetch 100 rows at a time; however your insert statement will still be done row-by-row).

e.g.

DECLARE
   TYPE tA IS TABLE OF FOO.A%TYPE INDEX BY PLS_INTEGER;
   TYPE tB IS TABLE OF FOO.B%TYPE INDEX BY PLS_INTEGER;
   TYPE tC IS TABLE OF FOO.C%TYPE INDEX BY PLS_INTEGER;
   rA tA;
   rB tB;
   rC tC;
BEGIN
   SELECT * BULK COLLECT INTO rA, rB, rC FROM FOO;
   -- (do some procedural logic on the data?)
   FORALL i IN rA.FIRST..rA.LAST
      INSERT INTO BAR(A,
                      B,
                      C)
      VALUES(rA(i),
             rB(i),
             rC(i));
END;

The above has the benefit of minimising context switches between SQL and PL/SQL. Oracle 11g also has better support for tables of records so that you don't have to have a separate PL/SQL table for each column.

Also, if the volume of data is very great, it is possible to change the code to process the data in batches.

How to quietly remove a directory with content in PowerShell

2018 Update

In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName to silently delete the directory .\DirName with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.

Batch file to perform start, run, %TEMP% and delete all

@echo off
RD %TEMP%\. /S /Q

::pause
explorer %temp%

This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.

Submit HTML form on self page

Use ?:

<form action="?" method="post">

It will send the user back to the same page.

fs: how do I locate a parent folder?

The easiest way would be to use path.resolve:

path.resolve(__dirname, '..', '..');

How to load a UIView using a nib file created with Interface Builder

To programmatically load a view from a nib/xib in Swift 4:

// Load a view from a Nib given a placeholder view subclass
//      Placeholder is an instance of the view to load.  Placeholder is discarded.
//      If no name is provided, the Nib name is the same as the subclass type name
//
public func loadViewFromNib<T>(placeholder placeholderView: T, name givenNibName: String? = nil) -> T {

    let nib = loadNib(givenNibName, placeholder: placeholderView)
    return instantiateView(fromNib: nib, placeholder: placeholderView)
}

// Step 1: Returns a Nib
//
public func loadNib<T>(_ givenNibName: String? = nil, placeholder placeholderView: T) -> UINib {
    //1. Load and unarchive nib file
    let nibName = givenNibName ?? String(describing: type(of: placeholderView))

    let nib = UINib(nibName: nibName, bundle: Bundle.main)
    return nib
}

// Step 2: Instantiate a view given a nib
//
public func instantiateView<T>(fromNib nib: UINib, placeholder placeholderView: T) -> T {
    //1. Get top level objects
    let topLevelObjects = nib.instantiate(withOwner: placeholderView, options: nil)

    //2. Have at least one top level object
    guard let firstObject = topLevelObjects.first else {
        fatalError("\(#function): no top level objects in nib")
    }

    //3. Return instantiated view, placeholderView is not used
    let instantiatedView = firstObject as! T
    return instantiatedView
}

iOS: Convert UTC NSDate to local Timezone

Convert UTC time to current time zone.

call function

NSLocale *locale = [NSLocale autoupdatingCurrentLocale];

NSString *myLanguageCode = [locale objectForKey: NSLocaleLanguageCode];
NSString *myCountryCode = [locale objectForKey: NSLocaleCountryCode];

NSString *rfc3339DateTimeString = @"2015-02-15 00:00:00"];
NSDate *myDateTime = (NSDate*)[_myCommonFunctions _ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:myLanguageCode CountryCode:myCountryCode Formated:NO];

Function

-NSObject*)_ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString     LanguageCode:(NSString *)lgc CountryCode:(NSString *)ctc Formated:(BOOL) formated
{
    NSDateFormatter *sUserVisibleDateFormatter = nil;
    NSDateFormatter *sRFC3339DateFormatter = nil;

    NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];

    if (sRFC3339DateFormatter == nil)
    {
        sRFC3339DateFormatter = [[NSDateFormatter alloc] init];

        NSLocale *myPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:[NSString stringWithFormat:@"%@", timeZone]];

        [sRFC3339DateFormatter setLocale:myPOSIXLocale];
        [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
        [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    }

    // Convert the RFC 3339 date time string to an NSDate.
    NSDate *date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];

    if (formated == YES)
    {
        NSString *userVisibleDateTimeString;

        if (date != nil)
        {
            if (sUserVisibleDateFormatter == nil)
            {
                sUserVisibleDateFormatter = [[NSDateFormatter alloc] init];
                [sUserVisibleDateFormatter setDateStyle:NSDateFormatterMediumStyle];
                [sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
            }

            // Convert the date object to a user-visible date string.
            userVisibleDateTimeString = [sUserVisibleDateFormatter stringFromDate:date];

            return (NSObject*)userVisibleDateTimeString;
        }
    }

    return (NSObject*)date;
}

Convert file: Uri to File in Android

By the following code, I am able to get adobe application shared pdf file as a stream and saving into android application path

Android.Net.Uri fileuri =
    (Android.Net.Uri)Intent.GetParcelableExtra(Intent.ExtraStream);

    fileuri i am getting as {content://com.adobe.reader.fileprovider/root_external/
                                        data/data/com.adobe.reader/files/Downloads/sample.pdf}

    string filePath = fileuri.Path;

   filePath I am gettings as root_external/data/data/com.adobe.reader/files/Download/sample.pdf

      using (var stream = ContentResolver.OpenInputStream(fileuri))
      {
       byte[] fileByteArray = ToByteArray(stream); //only once you can read bytes from stream second time onwards it has zero bytes

       string fileDestinationPath ="<path of your destination> "
       convertByteArrayToPDF(fileByteArray, fileDestinationPath);//here pdf copied to your destination path
       }
     public static byte[] ToByteArray(Stream stream)
        {
            var bytes = new List<byte>();

            int b;
            while ((b = stream.ReadByte()) != -1)
                bytes.Add((byte)b);

            return bytes.ToArray();
        }

      public static string convertByteArrayToPDF(byte[] pdfByteArray, string filePath)
        {

            try
            {
                Java.IO.File data = new Java.IO.File(filePath);
                Java.IO.OutputStream outPut = new Java.IO.FileOutputStream(data);
                outPut.Write(pdfByteArray);
                return data.AbsolutePath;

            }
            catch (System.Exception ex)
            {
                return string.Empty;
            }
        }