Programs & Examples On #Jump table

A jump table (also known as a branch table) is used to transfer program control (branching) to another part of the program by storing a table of branch instructions.

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Blocking device rotation on mobile web pages

In JavaScript-enabled browsers it should be easy to determine if the screen is in landscape or portrait mode and compensate using CSS. It may be helpful to give users the option to disable this or at least warn them that device rotation will not work properly.

Edit

The easiest way to detect the orientation of the browser is to check the width of the browser versus the height of the browser. This also has the advantage that you'll know if the game is being played on a device that is naturally oriented in landscape mode (as some mobile devices like the PSP are). This makes more sense than trying to disable device rotation.

Edit 2

Daz has shown how you can detect device orientation, but detecting orientation is only half of the solution. If want to reverse the automatic orientation change, you'll need to rotate everything either 90° or 270°/-90°, e.g.

$(window).bind('orientationchange resize', function(event){
  if (event.orientation) {
    if (event.orientation == 'landscape') {
      if (window.rotation == 90) {
        rotate(this, -90);
      } else {
        rotate(this, 90);
      }
    }
  }
});

function rotate(el, degs) {
  iedegs = degs/90;
  if (iedegs < 0) iedegs += 4;
  transform = 'rotate('+degs+'deg)';
  iefilter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+iedegs+')';
  styles = {
    transform: transform,
    '-webkit-transform': transform,
    '-moz-transform': transform,
    '-o-transform': transform,
    filter: iefilter,
    '-ms-filter': iefilter
  };
  $(el).css(styles);
}

Note: if you want to rotate in IE by an arbitrary angle (for other purposes), you'll need to use matrix transform, e.g.

rads = degs * Math.PI / 180;
m11 = m22 = Math.cos(rads);
m21 = Math.sin(rads);
m12 = -m21;
iefilter = "progid:DXImageTransform.Microsoft.Matrix("
  + "M11 = " + m11 + ", "
  + "M12 = " + m12 + ", "
  + "M21 = " + m21 + ", "
  + "M22 = " + m22 + ", sizingMethod = 'auto expand')";
styles['filter'] = styles['-ms-filter'] = iefilter;

—or use CSS Sandpaper. Also, this applies the rotation style to the window object, which I've never actually tested and don't know if works or not. You may need to apply the style to a document element instead.

Anyway, I would still recommend simply displaying a message that asks the user to play the game in portrait mode.

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

Python: access class property from string

A picture's worth a thousand words:

>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'

Can't access to HttpContext.Current

This is because you are referring to property of controller named HttpContext. To access the current context use full class name:

System.Web.HttpContext.Current

However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current as being deprecated inside ASP.NET MVC. The correct way to access current context is

this.ControllerContext.HttpContext

or if you are inside a Controller, just use member

this.HttpContext

iOS Remote Debugging

The selected answer is only for Safari. At the moment it's not possible to do real remote debugging in Chrome on iOS, but as with most mobile browsers you can use WeInRe for some simple debugging. It's a bit work to set up, but lets you inspect the DOM, see styling, change DOM and play with the console.

enter image description here

To setup:

  • Install nodejs
  • npm install -g weinre
  • weinre --boundHost -all-
  • Open http://{wifi-ip-address}:8080/ and copy the target script code
  • Paste the script tag into your page (or use the bookmarklet)
  • Click on the link to the debug client user interface (http://{wifi-ip-address}:8080/client/#anonymous)
  • When you get a green line under Clients the browser is connected

The bookmarklet is a bit more of an hassle to install. It's easiest if you have bookmark-sync turned on for both desktop and mobile Chrome. Copy the bookmarklet url from the local weinre server (same as above). Unfortunately it doesn't work because it's not url-encoded properly. So open the JavaScript console and type in:

copy(encodeURI('')); // paste bookmarklet inside quotes

You should now have the url-encoded bookmarklet in your clipboard. Paste it into a new bookmark under Mobile Bookmarks. Call it weinre or something simple to type. It should be synced to your mobile pretty fast, so load the page you want to inspect. Then type in the bookmark name in the url-bar, and you should see the bookmarklet as an auto-complete-suggestion. Click it to run bookmarklet code :)

enter image description here

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

How to convert unix timestamp to calendar date moment.js

moment(timestamp).format('''any format''')

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

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

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

How to Retrieve value from JTextField in Java Swing?

Just use event.getSource() frim within actionPerformed

Cast it to the component

for Ex, if you need combobox

JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();

use appropriate api to get the value,

for Ex.

Object selected = comboBox.getSelectedItem();  etc.

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

byte[] to file in Java

Without any libraries:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

Files.write(bytes, new File(path));

With Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

6 digits regular expression

You can use range quantifier {min,max} to specify minimum of 1 digit and maximum of 6 digits as:

^[0-9]{1,6}$

Explanation:

^     : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$     : End anchor

Why did your regex not work ?

You were almost close on the regex:

^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$

Since you had escaped the ? by preceding it with the \, the ? was no more acting as a regex meta-character ( for 0 or 1 repetitions) but was being treated literally.

To fix it just remove the \ and you are there.

See it on rubular.

The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.

Your second regex:

^[0-999999]$

is equivalent to:

^[0-9]$

which matches strings with exactly one digit. They are equivalent because a character class [aaaab] is same as [ab].

How can I tell what edition of SQL Server runs on the machine?

You can get just the edition (plus under individual properties) using SERVERPROPERTY

e.g.

SELECT SERVERPROPERTY('Edition')

Quote (for "Edition"):

Installed product edition of the instance of SQL Server. Use the value of this property to determine the features and the limits, such as maximum number of CPUs, that are supported by the installed product.
Returns:
'Desktop Engine' (Not available for SQL Server 2005.)
'Developer Edition'
'Enterprise Edition'
'Enterprise Evaluation Edition'
'Personal Edition'(Not available for SQL Server 2005.)
'Standard Edition'
'Express Edition'
'Express Edition with Advanced Services'
'Workgroup Edition'
'Windows Embedded SQL'
Base data type: nvarchar(128)

psycopg2: insert multiple rows with one query

The cursor.copyfrom solution as provided by @jopseph.sheedy (https://stackoverflow.com/users/958118/joseph-sheedy) above (https://stackoverflow.com/a/30721460/11100064) is indeed lightning fast.

However, the example he gives are not generically usable for a record with any number of fields and it took me while to figure out how to use it correctly.

The IteratorFile needs to be instantiated with tab-separated fields like this (r is a list of dicts where each dict is a record):

    f = IteratorFile("{0}\t{1}\t{2}\t{3}\t{4}".format(r["id"],
        r["type"],
        r["item"],
        r["month"],
        r["revenue"]) for r in records)

To generalise for an arbitrary number of fields we will first create a line string with the correct amount of tabs and field placeholders : "{}\t{}\t{}....\t{}" and then use .format() to fill in the field values : *list(r.values())) for r in records:

        line = "\t".join(["{}"] * len(records[0]))

        f = IteratorFile(line.format(*list(r.values())) for r in records)

complete function in gist here.

Check if input is integer type in C

I found a way to check whether the input given is an integer or not using atoi() function .

Read the input as a string, and use atoi() function to convert the string in to an integer.

atoi() function returns the integer number if the input string contains integer, else it will return 0. You can check the return value of the atoi() function to know whether the input given is an integer or not.

There are lot more functions to convert a string into long, double etc., Check the standard library "stdlib.h" for more.

Note : It works only for non-zero numbers.

#include<stdio.h>
#include<stdlib.h>

int main() {
    char *string;
    int number;

    printf("Enter a number :");
    string = scanf("%s", string);

    number = atoi(string);

    if(number != 0)
        printf("The number is %d\n", number);
    else
        printf("Not a number !!!\n");
    return 0;
}

Using Git with Visual Studio

In Jan 2013, Microsoft announced that they are adding full Git support into all their ALM products. They have published a plugin for Visual Studio 2012 that adds Git source control integration.

Alternatively, there is a project called Git Extensions that includes add-ins for Visual Studio 2005, 2008, 2010 and 2012, as well as Windows Explorer integration. It's regularly updated and having used it on a couple of projects, I've found it very useful.

Another option is Git Source Control Provider.

TextFX menu is missing in Notepad++

For Notepad++ 64-bit:

There is an unreleased 64-bit version of this plugin. You can download the DLL from here, drop it under Notepad++/plugins/NppTextFX directory and restart Notepad++. You will need to create the NppTextFX directory first though.

As per this GitHub issue, there might be some bugs lurking around. If you run into any, feel free to raise a GitHub ticket for each, as the author (HQJaTu) is recommending. As per the author, the code behind this binary is found on this branch.

enter image description here

Tested on Notepad++ v7.5.8 (64-bit, Build time: Jul 23 2018)

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

private void btnSent_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

        mail.From = new MailAddress(txtAcc.Text);
        mail.To.Add(txtToAdd.Text);
        mail.Subject = txtSub.Text;
        mail.Body = txtContent.Text;
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
        mail.Attachments.Add(attachment);

        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);

        SmtpServer.EnableSsl = true;

        SmtpServer.Send(mail);
        MessageBox.Show("mail send");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MailMessage mail = new MailMessage();
    openFileDialog1.ShowDialog();
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
    mail.Attachments.Add(attachment);
    txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}

How do I declare a two dimensional array?

atli's answer really helped me understand this. Here is an example of how to iterate through a two-dimensional array. This sample shows how to find values for known names of an array and also a foreach where you just go through all of the fields you find there. I hope it helps someone.

$array = array(
    0 => array(
        'name' => 'John Doe',
        'email' => '[email protected]'
    ),
    1 => array(
        'name' => 'Jane Doe',
        'email' => '[email protected]'
    ),
);

foreach ( $array  as $groupid => $fields) {
    echo "hi element ". $groupid . "\n";
    echo ". name is ". $fields['name'] . "\n";
    echo ". email is ". $fields['email'] . "\n";
    $i = 0;
    foreach ($fields as $field) {
         echo ". field $i is ".$field . "\n";
        $i++;
    }
}

Outputs:

hi element 0
. name is John Doe
. email is [email protected]
. field 0 is John Doe
. field 1 is [email protected]
hi element 1
. name is Jane Doe
. email is [email protected]
. field 0 is Jane Doe
. field 1 is [email protected]

Create folder with batch but only if it doesn't already exist

This should work for you:

IF NOT EXIST "\path\to\your\folder" md \path\to\your\folder

However, there is another method, but it may not be 100% useful:

md \path\to\your\folder >NUL 2>NUL

This one creates the folder, but does not show the error output if folder exists. I highly recommend that you use the first one. The second one is if you have problems with the other.

What is [Serializable] and when should I use it?

Serialization

Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization

Uses of Serialization

  1. To save the state of an object into a file, database etc. and use it latter.
  2. To send an object from one process to another (App Domain) on the same machine and also send it over wire to a process running on another machine.
  3. To create a clone of the original object as a backup while working on the main object.
  4. A set of objects can easily be copied to the system’s clipboard and then pasted into the same or another application

Below are some useful custom attributes that are used during serialization of an object

[Serializable] -> It is used when we mark an object’s serializable [NonSerialized] -> It is used when we do not want to serialize an object’s field. [OnSerializing] -> It is used when we want to perform some action while serializing an object [OnSerialized] -> It is used when we want to perform some action after serialized an object into stream.

Below is the example of serialization

[Serializable]
    internal class DemoForSerializable
    {
        internal string Fname = string.Empty;
        internal string Lname = string.Empty;

        internal Stream SerializeToMS(DemoForSerializable demo)
        {
            DemoForSerializable objSer = new DemoForSerializable();
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, objSer);
            return ms;
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext context) {
            Fname = "sheo";
            Lname = "Dayal";
        }
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
       // Do some work after serialized object
        }

    }

Here is the calling code

class Program
    {
        string fname = string.Empty;
        string Lname = string.Empty; 

       static void Main(string[] args)
        {
            DemoForSerializable demo = new DemoForSerializable();

            Stream ms = demo.SerializeToMS(demo);
            ms.Position = 0;

            DemoForSerializable demo1 = new BinaryFormatter().Deserialize(ms) as DemoForSerializable;

            Console.WriteLine(demo1.Fname);
            Console.WriteLine(demo1.Lname);
            Console.ReadLine();
        }

    }

sendKeys() in Selenium web driver

For python selenium,

Importing the library,

from selenium.webdriver.common.keys import Keys

Use this code to press any key you want,

Anyelement.send_keys(Keys.RETURN)

You can find all the key names by searching this selenium.webdriver.common.keys.

Creating a textarea with auto-resize

Has anyone considered contenteditable? No messing around with scrolling,a nd the only JS I like about it is if you plan on saving the data on blur... and apparently, it's compatible on all of the popular browsers : http://caniuse.com/#feat=contenteditable

Just style it to look like a text box, and it autosizes... Make its min-height the preferred text height and have at it.

What's cool about this approach is that you can save and tags on some of the browsers.

http://jsfiddle.net/gbutiri/v31o8xfo/

_x000D_
_x000D_
var _auto_value = '';
$(document).on('blur', '.autosave', function(e) {
  var $this = $(this);
  if ($this.text().trim() == '') {
    $this.html('');
  }

  // The text is here. Do whatever you want with it.
  $this.addClass('saving');

  if (_auto_value !== $this.html() || $this.hasClass('error')) {

    // below code is for example only.
    $.ajax({
      url: '/echo/json/?action=xyz_abc',
      data: 'data=' + $this.html(),
      type: 'post',
      datatype: 'json',
      success: function(d) {
        console.log(d);
        $this.removeClass('saving error').addClass('saved');
        var k = setTimeout(function() {
          $this.removeClass('saved error')
        }, 500);
      },
      error: function() {
        $this.removeClass('saving').addClass('error');
      }
    });
  } else {
    $this.removeClass('saving');
  }
}).on('focus mouseup', '.autosave', function() {
  var $this = $(this);
  if ($this.text().trim() == '') {
    $this.html('');
  }
  _auto_value = $this.html();
}).on('keyup', '.autosave', function(e) {
  var $this = $(this);
  if ($this.text().trim() == '') {
    $this.html('');
  }
});
_x000D_
body {
  background: #3A3E3F;
  font-family: Arial;
}

label {
  font-size: 11px;
  color: #ddd;
}

.autoheight {
  min-height: 16px;
  font-size: 16px;
  margin: 0;
  padding: 10px;
  font-family: Arial;
  line-height: 20px;
  box-sizing: border-box;
  -o-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  overflow: hidden;
  display: block;
  resize: none;
  border: 0;
  outline: none;
  min-width: 200px;
  background: #ddd;
  max-height: 400px;
  overflow: auto;
}

.autoheight:hover {
  background: #eee;
}

.autoheight:focus {
  background: #fff;
}

.autosave {
  -webkit-transition: all .2s;
  -moz-transition: all .2s;
  transition: all .2s;
  position: relative;
  float: none;
}

.autoheight * {
  margin: 0;
  padding: 0;
}

.autosave.saving {
  background: #ff9;
}

.autosave.saved {
  background: #9f9;
}

.autosave.error {
  background: #f99;
}

.autosave:hover {
  background: #eee;
}

.autosave:focus {
  background: #fff;
}

[contenteditable=true]:empty:before {
  content: attr(placeholder);
  color: #999;
  position: relative;
  top: 0px;
  /*
    For IE only, do this:
    position: absolute;
    top: 10px;
    */
  cursor: text;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Your Name</label>
<div class="autoheight autosave contenteditable" contenteditable="true" placeholder="Your Name"></div>
_x000D_
_x000D_
_x000D_

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Explicitly specifying the max_iter resolves the warning as the default max_iter is 100. [For Logistic Regression].

 logreg = LogisticRegression(max_iter=1000)

How can I check if a string represents an int, without using try/except?

Uh.. Try this:

def int_check(a):
    if int(a) == a:
        return True
    else:
        return False

This works if you don't put a string that's not a number.

And also (I forgot to put the number check part. ), there is a function checking if the string is a number or not. It is str.isdigit(). Here's an example:

a = 2
a.isdigit()

If you call a.isdigit(), it will return True.

Click events on Pie Charts in Chart.js

To successfully track click events and on what graph element the user clicked, I did the following in my .js file I set up the following variables:

vm.chartOptions = {
    onClick: function(event, array) {
        let element = this.getElementAtEvent(event);
        if (element.length > 0) {
            var series= element[0]._model.datasetLabel;
            var label = element[0]._model.label;
            var value = this.data.datasets[element[0]._datasetIndex].data[element[0]._index];
        }
    }
};
vm.graphSeries = ["Series 1", "Serries 2"];
vm.chartLabels = ["07:00", "08:00", "09:00", "10:00"];
vm.chartData = [ [ 20, 30, 25, 15 ], [ 5, 10, 100, 20 ] ];

Then in my .html file I setup the graph as follows:

<canvas id="releaseByHourBar" 
    class="chart chart-bar"
    chart-data="vm.graphData"
    chart-labels="vm.graphLabels" 
    chart-series="vm.graphSeries"
    chart-options="vm.chartOptions">
</canvas>

Horizontal line using HTML/CSS

This might be your problem:

height: .05em;

Chrome is a bit funky with decimals, so try a fixed-pixel height:

height: 2px;

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

If you are running cmake to generate SomeLib yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG mode of the find_packages() command, you'll see that the User Package Registry is one of elements.

Brief how-to

Associate the targets of SomeLib that you need outside of that external project by adding them to an export set in the CMakeLists.txt files where they are created:

add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)

Create a XXXConfig.cmake file for SomeLib in its ${CMAKE_CURRENT_BUILD_DIR} and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt associated with SomeLib:

export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib)                                                    # Store location of SomeLibConfig.cmake

Issue your find_package(SomeLib REQUIRED) commmand in the CMakeLists.txt file of the project that depends on SomeLib without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH.

When it might be the right approach

This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.

But if you're never actually installing SomeLib in your workflow, calling EXPORT(PACKAGE <name>) allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib, you probably know your platform, CMAKE_MODULE_PATH, etc, so @user2288008's excellent answer will have you covered.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Just try to do this one (through root access) - "chmod -R 777 /home/username/git"

List of strings to one string

String.Join() is implemented quite fast, and as you already have a collection of the strings in question, is probably the best choice. Above all, it shouts "I'm joining a list of strings!" Always nice.

Angular get object from array by Id

You can use .filter() or .find(). One difference that filter will iterate over all items and returns any which passes the condition as array while find will return the first matched item and break the iteration.

Example

_x000D_
_x000D_
var questions = [_x000D_
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},_x000D_
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},_x000D_
      {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},_x000D_
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},_x000D_
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},_x000D_
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},_x000D_
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},_x000D_
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},_x000D_
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},_x000D_
      {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},_x000D_
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},_x000D_
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},_x000D_
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},_x000D_
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},_x000D_
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}_x000D_
];_x000D_
_x000D_
function getDimensionsByFilter(id){_x000D_
  return questions.filter(x => x.id === id);_x000D_
}_x000D_
_x000D_
function getDimensionsByFind(id){_x000D_
  return questions.find(x => x.id === id);_x000D_
}_x000D_
_x000D_
var test = getDimensionsByFilter(10);_x000D_
console.log(test);_x000D_
_x000D_
test = getDimensionsByFind(10);_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

How to have jQuery restrict file types on upload?

    $("input[name='btnsubmit']").attr('disabled', true);
    $('input[name="filphoto"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) 
    {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'bmp':
        $("input[name='btnsubmit']").attr('disabled', false);
    break;
    default:
        alert('This is not an allowed file type.');
        $("input[name='btnsubmit']").attr('disabled', true);
        this.value = '';

How to undo a SQL Server UPDATE query?

Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.

Then you can just review the contents pre-update and write a SQL script to do the update.

Is there a way to run Python on Android?

Pygame Subset for Android

Pygame is a 2D game engine for Python (on desktop) that is popular with new programmers. The Pygame Subset for Android describes itself as...

...a port of a subset of Pygame functionality to the Android platform. The goal of the project is to allow the creation of Android-specific games, and to ease the porting of games from PC-like platforms to Android.

The examples include a complete game packaged as an APK, which is pretty interesting.

Python, remove all non-alphabet chars from string

Try:

s = ''.join(filter(str.isalnum, s))

This will take every char from the string, keep only alphanumeric ones and build a string back from them.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Plotting lines connecting points

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

enter image description here

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I've solved the problem , and I will explain how :

  1. Download Github For Windows client and install it.
  2. After The client successfully installed , connect it with your github account.It should be easy , just follow the wizard.
  3. Then you should add git.exe location to your "Path Variable". The location you should add will probably be something like : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin

Alternatively , if you don't want to add to environment variables. You can open the android studio and go to : Settings -> Version Control -> Git In text box next to "Path to Git Executable" you will see "git.exe" , just give it a full path like so : C:\Users\Your_Username\AppData\Local\GitHub\PortableGit_ca477551eeb4aea0e4ae9fcd3358bd96720bb5c8\bin\git.exe

Hope it saved your time . Happy coding :)

EDIT : For latest Github for windows versions some can find the git.exe under "...\cmd\git.exe" rather than "...\bin\git.exe".

setImmediate vs. nextTick

I recommend you to check docs section dedicated for Loop to get better understanding. Some snippet taken from there:

We have two calls that are similar as far as users are concerned, but their names are confusing.

  • process.nextTick() fires immediately on the same phase

  • setImmediate() fires on the following iteration or 'tick' of the
    event loop

In essence, the names should be swapped. process.nextTick() fires more immediately than setImmediate(), but this is an artifact of the past which is unlikely to change.

jQuery animate margin top

use 'marginTop' instead of MarginTop

$(this).find('.info').animate({ 'marginTop': '-50px', opacity: 0.5 }, 1000);

Post order traversal of binary tree without recursion

It's very nice to see so many spirited approaches to this problem. Quite inspiring indeed!

I came across this topic searching for a simple iterative solution for deleting all nodes in my binary tree implementation. I tried some of them, and I tried something similar found elsewhere on the Net, but none of them were really to my liking.

The thing is, I am developing a database indexing module for a very specific purpose (Bitcoin Blockchain indexing), and my data is stored on disk, not in RAM. I swap in pages as needed, doing my own memory management. It's slower, but fast enough for the purpose, and with having storage on disk instead of RAM, I have no religious bearings against wasting space (hard disks are cheap).

For that reason my nodes in my binary tree have parent pointers. That's (all) the extra space I'm talking about. I need the parents because I need to iterate both ascending and descending through the tree for various purposes.

Having that in my mind, I quickly wrote down a little piece of pseudo-code on how it could be done, that is, a post-order traversal deleting nodes on the fly. It's implemented and tested, and became a part of my solution. And it's pretty fast too.

The thing is: It gets really, REALLY, simple when nodes have parent pointers, and furthermore since I can null out the parent's link to the "just departed" node.

Here's the pseudo-code for iterative post-order deletion:

Node current = root;
while (current)
{
  if (current.left)       current = current.left;  // Dive down left
  else if (current.right) current = current.right; // Dive down right
  else
  {
    // Node "current" is a leaf, i.e. no left or right child
    Node parent = current.parent; // assuming root.parent == null
    if (parent)
    {
      // Null out the parent's link to the just departing node
      if (parent.left == current) parent.left = null;
      else                        parent.right = null;
    }
    delete current;
    current = parent;
  }
}
root = null;

If you are interested in a more theoretical approach to coding complex collections (such as my binary tree, which is really a self-balancing red-black-tree), then check out these links:

http://opendatastructures.org/versions/edition-0.1e/ods-java/6_2_BinarySearchTree_Unbala.html http://opendatastructures.org/versions/edition-0.1e/ods-java/9_2_RedBlackTree_Simulated_.html https://www.cs.auckland.ac.nz/software/AlgAnim/red_black.html

Happy coding :-)

Søren Fog http://iprotus.eu/

Playing .mp3 and .wav in Java?

I have other methods for that, the first is :

public static void playAudio(String filePath){

    try{
        InputStream mus = new FileInputStream(new File(filePath));
        AudioStream aud = new AudioStream(mus);
    }catch(Exception e){
        JOptionPane.showMessageDialig(null, "You have an Error");
    }

And the second is :

try{
    JFXPanel x = JFXPanel();
    String u = new File("021.mp3").toURI().toString();
    new MediaPlayer(new Media(u)).play();
} catch(Exception e){
    JOPtionPane.showMessageDialog(null, e);
}

And if we want to make loop to this audio we use this method.

try{
    AudioData d = new AudioStream(new FileInputStream(filePath)).getData();
    ContinuousAudioDataStream s = new ContinuousAudioDataStream(d);
    AudioPlayer.player.start(s);
} catch(Exception ex){
    JOPtionPane.showMessageDialog(null, ex);
}

if we want to stop this loop we add this libreries in the try:

AudioPlayer.player.stop(s);

for this third method we add the folowing imports :

import java.io.FileInputStream;
import sun.audio.AudioData;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;

AngularJS : ng-click not working

Just add the function reference to the $scope in the controller:

for example if you want the function MyFunction to work in ng-click just add to the controller:

app.controller("MyController", ["$scope", function($scope) {
   $scope.MyFunction = MyFunction;
}]);

Is it possible to have SSL certificate for IP address, not domain name?

According to this answer, it is possible, but rarely used.

As for how to get it: I would tend to simply try and order one with the provider of your choice, and enter the IP address instead of a domain during the ordering process.

However, running a site on an IP address to avoid the DNS lookup sounds awfully like unnecessary micro-optimization to me. You will save a few milliseconds at best, and that is per visit, as DNS results are cached on multiple levels.

I don't think your idea makes sense from an optimization viewpoint.

How do I compare strings in Java?

String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true

Make sure you understand why. It's because the == comparison only compares references; the equals() method does a character-by-character comparison of the contents.

When you call new for a and b, each one gets a new reference that points to the "foo" in the string table. The references are different, but the content is the same.

Specifying trust store information in spring boot application.properties

If you are in Spring, try just add properties for it (use needed properties), and it should work for total JVM

javax:
  net:
    ssl:
      key-store-password: ${KEYSTORE_SECRET}
      key-store-type: PKCS12
      trust-store-password: ${TRUSTSTORE_SECRET}
      trust-store-type: PKCS12

Failed to decode downloaded font

In my case -- using React with Gatsby -- the issue was solved with double-checking all of my paths. I was using React/Gatsby with Sass and the Gatsby source files were looking for the fonts in a different place than the compiled files. Once I duplicated the files into each path this problem was gone.

Shell Scripting: Using a variable to define a path

Don't use spaces...

(Incorrect)

SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'

(Correct)

SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'

How to make a div with no content have a width?

Too late to answer, but nevertheless.

While using CSS, to style the div (content-less), the min-height property must be set to "n"px to make the div visible (works with webkits and chrome, while not sure if this trick will work on IE6 and lower)

Code:

_x000D_
_x000D_
.shape-round{_x000D_
  width: 40px;_x000D_
  min-height: 40px;_x000D_
  background: #FF0000;_x000D_
  border-radius: 50%;_x000D_
}
_x000D_
<div class="shape-round"></div>
_x000D_
_x000D_
_x000D_

Git in Visual Studio - add existing project?

On Visual Studio 2015 the only way I finally got it to work was to run git init from the root of my directory using the command line. Then I went into Team Explorer and added a local git repository. Then I selected that local git repository, went to Settings->Repository Settings, and added my Remote Repo. That's how I was finally able to integrate Visual Studio to use my existing project with git.

I read all of the answers but none of them worked for me. I went to File->Add To Source Control, which was suppose to basically do the same as git init, but it didn't seem to initialize my project because when I would then go to Team Explorer all of the options were grayed out. Also nothing would show up in the Changes dialog either. Another answer stated that I just had to create a local repo in Team Explorer and then my changes would show up, but that didn't work either. All the Git options on Team Explorer only worked after I initialized my project through the command line.

I'm new to Visual Studio so I don't know if I just missed something obvious, but it seems like my project wasn't initializing from Visual Studio.

How to manually trigger click event in ReactJS?

How about just plain old js ? example:

autoClick = () => {
 if (something === something) {
    var link = document.getElementById('dashboard-link');
    link.click();
  }
};
  ......      
var clickIt = this.autoClick();            
return (
  <div>
     <Link id="dashboard-link" to={'/dashboard'}>Dashboard</Link>
  </div>
);

Node.js: get path from the request

Based on @epegzz suggestion for the regex.

( url ) => {
  return url.match('^[^?]*')[0].split('/').slice(1)
}

returns an array with paths.

Calculate relative time in C#

I would recommend computing this on the client side too. Less work for the server.

The following is the version that I use (from Zach Leatherman)

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 * 
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification 
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 * 
 * Licensed under the MIT license.
 */

function humane_date(date_str){
        var time_formats = [
                [60, 'just now'],
                [90, '1 minute'], // 60*1.5
                [3600, 'minutes', 60], // 60*60, 60
                [5400, '1 hour'], // 60*60*1.5
                [86400, 'hours', 3600], // 60*60*24, 60*60
                [129600, '1 day'], // 60*60*24*1.5
                [604800, 'days', 86400], // 60*60*24*7, 60*60*24
                [907200, '1 week'], // 60*60*24*7*1.5
                [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
                [3942000, '1 month'], // 60*60*24*(365/12)*1.5
                [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
                [47304000, '1 year'], // 60*60*24*365*1.5
                [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
                [4730400000, '1 century'] // 60*60*24*365*100*1.5
        ];

        var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
                dt = new Date,
                seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
                token = ' ago',
                i = 0,
                format;

        if (seconds < 0) {
                seconds = Math.abs(seconds);
                token = '';
        }

        while (format = time_formats[i++]) {
                if (seconds < format[0]) {
                        if (format.length == 2) {
                                return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
                        } else {
                                return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
                        }
                }
        }

        // overflow for centuries
        if(seconds > 4730400000)
                return Math.round(seconds / 4730400000) + ' centuries' + token;

        return date_str;
};

if(typeof jQuery != 'undefined') {
        jQuery.fn.humane_dates = function(){
                return this.each(function(){
                        var date = humane_date(this.title);
                        if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
                                jQuery(this).text(date);
                });
        };
}

How can I use onItemSelected in Android?

Another thing: When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (parent.getId()){
        case R.id.sp_alarmSelection:
            //Do something
            Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.sp_optionSelection:
            //Do another thing 
            Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
    }
}

How do I close a single buffer (out of many) in Vim?

Those using a buffer or tree navigation plugin, like Buffergator or NERDTree, will need to toggle these splits before destroying the current buffer - else you'll send your splits into wonkyville

I use:

"" Buffer Navigation                                                                                                                                                                                        
" Toggle left sidebar: NERDTree and BufferGator                                                                                                                                                             
fu! UiToggle()                                                                                                                                                                                              
  let b = bufnr("%")                                                                                                                                                                                        
  execute "NERDTreeToggle | BuffergatorToggle"                                                                                                                                                              
  execute ( bufwinnr(b) . "wincmd w" )                                                                                                                                                                      
  execute ":set number!"                                                                                                                                                                                    
endf                                                                                                                                                                                                        
map  <silent> <Leader>w  <esc>:call UiToggle()<cr>   

Where "NERDTreeToggle" in that list is the same as typing :NERDTreeToggle. You can modify this function to integrate with your own configuration.

Can we update primary key values of a table?

From a relational database theory point of view, there should be absolutely no problem on updating the primary key of a table, provided that there are no duplicates among the primary keys and that you do not try to put a NULL value in any of the primary key columns.

<DIV> inside link (<a href="">) tag

As of HTML5 it is OK to wrap <a> elements around a <div> (or any other block elements):

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).

Just have to make sure you don't put an <a> within your <a> ( or a <button>).

How to detect when an Android app goes to the background and come back to the foreground

There are three ways through which you can achieve this:

  • Single Activity architecture
  • ActivityLifecycleCallback
  • LifecycleObserver and ProcessLifecycleOwner

Have written an article in detail on this over here. Hope it helps.

Output array to CSV in Ruby

Struggling with this myself. This is my take:

https://gist.github.com/2639448:

require 'csv'

class CSV
  def CSV.unparse array
    CSV.generate do |csv|
      array.each { |i| csv << i }
    end
  end
end

CSV.unparse [ %w(your array), %w(goes here) ]

How to make div go behind another div?

http://jsfiddle.net/f2znvn4f/


HTML

<div class="box-left-mini">
    <div class="front"><span>this is in front</span></div>
    <div class="behind_container">
        <div class="behind">behind</div>        
    </div>
</div>

CSS

.box-left-mini{
    float:left;
    background-image:url(website-content/hotcampaign.png);
    width:292px;
    height:141px;
}

.box-left-mini .front {
    display: block;
    z-index: 5;
    position: relative;
}
.box-left-mini .front span {
    background: #fff
}

.box-left-mini .behind_container {
    background-color: #ff0;
    position: relative;
    top: -18px;
}
.box-left-mini .behind {
    display: block;
    z-index: 3;
}

The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve

Adding values to Arraylist

You are getting the warning because ArrayList is part of java generics. Essentially, it's a way to catch your type errors at compile time. For example, if you declare your array list with types Integer (ArrrayList<Integer>) and then try to add Strings to it, you'll get an error at compile time - avoiding nasty crashes at runtime.

The first syntax is there for backward compatibility and should be avoided whenever possible (note that generics were not there in older versions of java).

Second and third examples are pretty much equivalent. As you need to pass an object and not a primitive type to add method, your 3 is internally converted to Integer(3). By writing a string in double-quotes you effectively are creating a String object. When calling String("ss") you are creating a new String object with value being the same as the parameter ("ss").

Unless you really do need to store different types in your List, I would suggest actually using a proper type declaration, e.g. ArrayList<Integer> = new ArrayList<Integer>() - it'll save you a lot of headache in the long run.

If you do need multiple datatypes in the list, then the second example is better.

Tools for making latex tables in R

I'd like to add a mention of the "brew" package. You can write a brew template file which would be LaTeX with placeholders, and then "brew" it up to create a .tex file to \include or \input into your LaTeX. Something like:

\begin{tabular}{l l}
A & <%= fit$A %> \\
B & <%= fit$B %> \\
\end{tabular}

The brew syntax can also handle loops, so you can create a table row for each row of a dataframe.

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Where does gcc look for C and C++ header files?

These are the directories that gcc looks in by default for the specified header files ( given that the header files are included in chevrons <>); 1. /usr/local/include/ --used for 3rd party header files. 2. /usr/include/ -- used for system header files.

If in case you decide to put your custom header file in a place other than the above mentioned directories, you can include them as follows: 1. using quotes ("./custom_header_files/foo.h") with files path, instead of chevrons in the include statement. 2. using the -I switch when compiling the code. gcc -I /home/user/custom_headers/ -c foo.c -p foo.o Basically the -I switch tells the compiler to first look in the directory specified with the -I switch ( before it checks the standard directories).When using the -I switch the header files may be included using chevrons.

Finding element's position relative to the document

http://www.quirksmode.org/js/findpos.html Explains the best way to do it, all in all, you are on the right track you have to find the offsets and traverse up the tree of parents.

If statement for strings in python?

Python is case sensitive and needs proper indentation. You need to use lowercase "if", indent your conditions properly and the code has a bug. proceed will evaluate to y

How to use ng-if to test if a variable is defined

I edited your plunker to include ABOS's solution.

<body ng-controller="MainCtrl">
    <ul ng-repeat='item in items'>
      <li ng-if='item.color'>The color is {{item.color}}</li>
      <li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
    </ul>
  </body>

plunkerFork

How to make a input field readonly with JavaScript?

document.getElementById("").readOnly = true

C# using streams

Stream is just an abstraction (or a wrapper) over a physical stream of bytes. This physical stream is called the base stream. So there is always a base stream over which a stream wrapper is created and thus the wrapper is named after the base stream type ie FileStream, MemoryStream etc.

The advantage of the stream wrapper is that you get a unified api to interact with streams of any underlying type usb, file etc.

Why would you treat data as stream - because data chunks are loaded on-demand, we can inspect/process the data as chunks rather than loading the entire data into memory. This is how most of the programs deal with big files, for eg encrypting an OS image file.

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

TIP:

comment out pid and socket file, if you can't connect to server.. mysql could be connecting with incorrect pid and/or socket file, so when you try to connect to server trough command-line it "looks" at the incorrect pid/socket file...

### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock

Multi-line bash commands in makefile

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)

How to delete items from a dictionary while iterating over it?

You could also do it in two steps:

remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]

My favorite approach is usually to just make a new dict:

# Python 2.7 and 3.x
mydict = { k:v for k,v in mydict.items() if k!=val }
# before Python 2.7
mydict = dict((k,v) for k,v in mydict.iteritems() if k!=val)

How do I customize Facebook's sharer.php

It appears the following answer no longer works, and Facebook no longer accepts parameters on the Feed Dialog links

You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:

1) Create a link like:

   http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
        '&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
        '&picture=[LINK_TO_IMAGE]' +
        '&name=' + encodeURIComponent('[CONTENT_TITLE]') +
        '&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
        '&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
        '&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
        '&display=popup';

(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)

2) Open that link in a popup window with JavaScript on click of the share link

3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script> to close the popup window

The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Calculate date from week number

I used one of the solutions but it gave me wrong results, simply because it counts Sunday as a first day of the week.

I changed:

var firstDay = new DateTime(DateTime.Now.Year, 1, 1).AddDays((weekNumber - 1) * 7);
var lastDay = firstDay.AddDays(6);

to:

var lastDay = new DateTime(DateTime.Now.Year, 1, 1).AddDays((weekNumber) * 7);
var firstDay = lastDay.AddDays(-6);

and now it is working as a charm.

How to read data from a file in Lua

There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.

How to align a <div> to the middle (horizontally/width) of the page

body, html {
    display: table;
    height: 100%;
    width: 100%;
}
.container {
    display: table-cell;
    vertical-align: middle;
}
.container .box {
    width: 100px;
    height: 100px;
    background: red;
    margin: 0 auto;
}

http://jsfiddle.net/NPV2E/

"width:100%" for the "body" tag is only for an example. In a real project you may remove this property.

Copy Data from a table in one Database to another separate database

We can three part naming like database_name..object_name

The below query will create the table into our database(with out constraints)

SELECT * 
INTO DestinationDB..MyDestinationTable 
FROM SourceDB..MySourceTable 

Alternatively you could:

INSERT INTO DestinationDB..MyDestinationTable 
SELECT * FROM SourceDB..MySourceTable

If your destination table exists and is empty.

MySQL/SQL: Group by date only on a Datetime column

Or:

SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;

More efficient (I think.) Because you don't have to cast mydate twice per row.

Set cookies for cross origin requests

Pim's answer is very helpful. In my case, I have to use

Expires / Max-Age: "Session"

If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:

Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"

Hope it is helpful for future people who may meet same issue.

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

ngModel

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

This directive executes at priority level 1.

Example Plunker

JAVASCRIPT

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

CSS

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

HTML

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

ngModel is responsible for:

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

ngBind

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

This directive executes at priority level 0.

Example Plunker

JAVASCRIPT

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

HTML

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

ngBind is responsible for:

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

PHP upload image

<?php
include("config.php");

if(isset($_POST['but_upload'])){
 
  $name = $_FILES['file']['name'];
  $target_dir = "upload/";
  $target_file = $target_dir . basename($_FILES["file"]["name"]);

  // Select file type
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  // Valid file extensions
  $extensions_arr = array("jpg","jpeg","png","gif");

  // Check extension
  if( in_array($imageFileType,$extensions_arr) ){
 
     // Insert record
     $query = "insert into images(name) values('".$name."')";
     mysqli_query($con,$query);
  
     // Upload file
     move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);

  }
 
}
?>
<form method="post" action="" enctype='multipart/form-data'>
  <input type='file' name='file' />
  <input type='submit' value='Save name' name='but_upload'>
</form>

Select the name or path of the image which you have stored in the database table and use it in the image source. Read More

 <?php
    $sql = "select name from images where id=1";
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_array($result)){
          $image = $row['name'];
          $image_src = "upload/".$image; 
          <img src='<?php echo $image_src;  ?>' > echo '<br>';
    }
    ?>

source code: https://www.phpcodingstuff.com/blog/how-to-insert-image-in-php.html

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:

void testAbc(){
     myClass.myObj = myInteface;
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

although it would be a wiser choice to extract all initialization code into @Before

@Before
void setUp(){
     myClass = new myClass();
     myClass.myObj = myInteface;
}

@Test
void testAbc(){
     myClass.abc();
     verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}

How to have a a razor action link open in a new tab?

<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" type="submit" id="runReport" target="_blank" class="button Secondary"> @Reports.RunReport </a>

Load HTML File Contents to Div [without the use of iframes]

2019
Using fetch

<script>
fetch('page.html')
  .then(data => data.text())
  .then(html => document.getElementById('elementID').innerHTML = html);
</script>

<div id='elementID'> </div>

fetch needs to receive a http or https link, this means that it won't work locally.

Note: As Altimus Prime said, it is a feature for modern browsers

Correct use of flush() in JPA/Hibernate

Probably the exact details of em.flush() are implementation-dependent. In general anyway, JPA providers like Hibernate can cache the SQL instructions they are supposed to send to the database, often until you actually commit the transaction. For example, you call em.persist(), Hibernate remembers it has to make a database INSERT, but does not actually execute the instruction until you commit the transaction. Afaik, this is mainly done for performance reasons.

In some cases anyway you want the SQL instructions to be executed immediately; generally when you need the result of some side effects, like an autogenerated key, or a database trigger.

What em.flush() does is to empty the internal SQL instructions cache, and execute it immediately to the database.

Bottom line: no harm is done, only you could have a (minor) performance hit since you are overriding the JPA provider decisions as regards the best timing to send SQL instructions to the database.

How to set dropdown arrow in spinner?

Copy and paste this xml to show as a Dropdown and change your Dropdown color

 <?xml version="1.0" encoding="UTF-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp" 
    android:background="@drawable/red">

    <Spinner android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:dropDownWidth="fill_parent" 
        android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"

     />

</LinearLayout>

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignLeft="@+id/linearLayout1"
    android:layout_alignRight="@+id/linearLayout1"
    android:layout_below="@+id/linearLayout1"
    android:layout_marginTop="25dp"
    android:background="@drawable/red"
    android:ems="10"
    android:hint="enter card number" >

    <requestFocus />
</EditText>

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignLeft="@+id/editText1"
    android:layout_alignRight="@+id/editText1"
    android:layout_below="@+id/editText1"
    android:layout_marginTop="33dp"
    android:orientation="horizontal" 
    android:background="@drawable/red">

    <Spinner
        android:id="@+id/spinner3"
        android:layout_width="72dp"
        android:layout_height="wrap_content"
         android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"
         />

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="72dp"
        android:layout_height="wrap_content" 
        android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"
        />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="22dp"
        android:layout_height="match_parent"
        android:layout_weight="0.18"
        android:ems="10"
        android:hint="enter cvv" />

</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout3"
    android:layout_width="wrap_content"
    android:layout_height="55dp"
    android:layout_alignParentLeft="true"
    android:layout_alignRight="@+id/linearLayout2"
    android:layout_below="@+id/linearLayout2"
    android:layout_marginTop="26dp"
    android:orientation="vertical"
    android:background="@drawable/red" >
</LinearLayout>

<Spinner
    android:id="@+id/spinner4"
    android:layout_width="15dp"
    android:layout_height="18dp"
    android:layout_alignBottom="@+id/linearLayout3"
    android:layout_alignLeft="@+id/linearLayout3"
    android:layout_alignRight="@+id/linearLayout3"
    android:layout_alignTop="@+id/linearLayout3"
    android:popupBackground="@drawable/textbox"
        android:spinnerMode="dropdown"
        android:background="@drawable/drop_down_large"/>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/linearLayout3"
    android:layout_marginTop="18dp"
    android:text="Add Amount"
    android:background="@drawable/buttonsty"/>

Converting Integer to String with comma for thousands

First you need to include the JSTL tags :-

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 

at the start of the page

HTML Form Redirect After Submit

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

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

How to include *.so library in Android Studio?

Android NDK official hello-libs CMake example

https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs

Just worked for me on Ubuntu 17.10 host, Android Studio 3, Android SDK 26, so I strongly recommend that you base your project on it.

The shared library is called libgperf, the key code parts are:

  • hello-libs/app/src/main/cpp/CMakeLists.txt:

    // -L
    add_library(lib_gperf SHARED IMPORTED)
    set_target_properties(lib_gperf PROPERTIES IMPORTED_LOCATION
              ${distribution_DIR}/gperf/lib/${ANDROID_ABI}/libgperf.so)
    
    // -I
    target_include_directories(hello-libs PRIVATE
                               ${distribution_DIR}/gperf/include)
    // -lgperf
    target_link_libraries(hello-libs
                          lib_gperf)
    
  • app/build.gradle:

    android {
        sourceSets {
            main {
                // let gradle pack the shared library into apk
                jniLibs.srcDirs = ['../distribution/gperf/lib']
    

    Then, if you look under /data/app on the device, libgperf.so will be there as well.

  • on C++ code, use: #include <gperf.h>

  • header location: hello-libs/distribution/gperf/include/gperf.h

  • lib location: distribution/gperf/lib/arm64-v8a/libgperf.so

  • If you only support some architectures, see: Gradle Build NDK target only ARM

The example git tracks the prebuilt shared libraries, but it also contains the build system to actually build them as well: https://github.com/googlesamples/android-ndk/tree/840858984e1bb8a7fab37c1b7c571efbe7d6eb75/hello-libs/gen-libs

How to fill Matrix with zeros in OpenCV?

If You are more into programming with templates, You may also do it this way...

template<typename _Tp>
... some algo ...
cv::Mat mat = cv::Mat_<_Tp>::zeros(rows, cols);
mat.at<_Tp>(i, j) = val;

PyLint "Unable to import" error - how to set PYTHONPATH?

The solution to alter path in init-hook is good, but I dislike the fact that I had to add absolute path there, as result I can not share this pylintrc file among the developers of the project. This solution using relative path to pylintrc file works better for me:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

Note that pylint.config.PYLINTRC also exists and has the same value as find_pylintrc().

How to check if memcache or memcached is installed for PHP?

The best approach in this case is to use extension_loaded() or function_exists() they are equally as fast.

You can see evidence here:

https://github.com/dragoonis/ppi-framework/blob/master/Cache/Memcached.php#L140

Bear in mind that some PHP extensions such as APC have php.ini settings that can disable them even though the extension may be loaded. Here is an example of how to check against that also:

https://github.com/dragoonis/ppi-framework/blob/master/Cache/Apc.php#L79

Hope this helps.

SOAP or REST for Web Services?

Answering the 2012 refreshed (by the second bounty) question, and reviewing the today's results (other answers).


SOAP, pros and cons

About SOAP 1.2, advantages and drawbacks when comparing with "REST"... Well, since 2007 you can describe REST Web services with WSDL, and using SOAP protocol... That is, if you work a little harder, all W3C standards of the web services protocol stack can be REST!

It is a good starting point, because we can imagine a scenario in which all the philosophical and methodological discussions are temporarily avoided. We can compare technically "SOAP-REST" with "NON-SOAP-REST" in similar services,

  • SOAP-REST (="REST-SOAP"): as showed by L.Mandel, WSDL2 can describe a REST webservice, and, if we suppose that exemplified XML can be enveloped in SOAP, all the implementation will be "SOAP-REST".

  • NON-SOAP-REST: any REST web service that can not be SOAP... That is, "90%" of the well-knowed REST examples. Some not use XML (ex. typical AJAX RESTs use JSON instead), some use another XML strucutures, without the SOAP headers or rules. PS: to avoid informality, we can suppose REST level 2 in the comparisons.

Of course, to compare more conceptually, compare "NON-REST-SOAP" with "NON-SOAP-REST", as different modeling approaches. So, completing this taxonomy of web services:

  • NON-REST-SOAP: any SOAP web service that can not be REST... That is, "90%" of the well-knowed SOAP examples.

  • NON-REST-NEITHER-SOAP: yes, the universe of "web services modeling" comprises other things (ex. XML-RPC).

SOAP in the REST condictions

Comparing comparable things: SOAP-REST with NON-SOAP-REST.

PROS

Explaining some terms,

  • Contractual stability: for all kinds of contracts (as "written agreements"),

    • By the use of standars: all levels of the W3C stack are mutually compliant. REST, by other hand, is not a W3C or ISO standard, and have no normatized details about service's peripherals. So, as I, @DaveWoldrich(20 votes), @cynicalman(5), @Exitos(0) said before, in a context where are NEED FOR STANDARDS, you need SOAP.

    • By the use of best practices: the "verbose aspect" of the W3C stack implementations, translates relevant human/legal/juridic agreements.

  • Robustness: the safety of SOAP structure and headers. With metada communication (with the full expressiveness of XML) and verification you have an "insurance policy" against any changes or noise.
    SOAP have "transactional reliability (...) deal with communication failures. SOAP has more controls around retry logic and thus can provide more end-to-end reliability and service guarantees", E. Terman.

Sorting pros by popularity,

  • Better tools (~70 votes): SOAP currently has the advantage of better tools, since 2007 and still 2012, because it is a well-defined and widely accepted standard. See @MarkCidade(27 votes), @DaveWoldrich(20), @JoshM(13), @TravisHeseman(9).

  • Standars compliance (25 votes): as I, @DaveWoldrich(20 votes), @cynicalman(5), @Exitos(0) said before, in a context where are NEED FOR STANDARDS, you need SOAP.

  • Robustness: insurance of SOAP headers, @JohnSaunders (8 votes).

CONS

  • SOAP strucuture is more complex (more than 300 votes): all answers here, and sources about "SOAP vs REST", manifest some degree of dislike with SOAP's redundancy and complexity. This is a natural consequence of the requirements for formal verification (see below), and for robustness (see above). "REST NON-SOAP" (and XML-RPC, the SOAP originator) can be more simple and informal.

  • The "only XML" restriction is a performance obstacle when using tiny services (~50 votes): see json.org/xml and this question, or this other one. This point is showed by @toluju(41), and others.
    PS: as JSON is not a IETF standard, but we can consider a de facto standard for web software community.


Modeling services with SOAP

Now, we can add SOAP-NON-REST with NON-SOAP-REST comparisons, and explain when is better to use SOAP:

  • Need for standards and stable contracts (see "PROS" section). PS: see a typical "B2B need for standards" described by @saille.

  • Need for tools (see "PROS" section). PS: standards, and the existence of formal verifications (see bellow), are important issues for the tools automation.

  • Parallel heavy processing (see "Context/Foundations" section below): with bigger and/or slower processes, no matter with a bit more complexity of SOAP, reliability and stability are the best investments.

  • Need more security: when more than HTTPS is required, and you really need additional features for protection, SOAP is a better choice (see @Bell, 32 votes). "Sending the message along a path more complicated than request/response or over a transport that does not involve HTTP", S. Seely. XML is a core issue, offering standards for XML Encryption, XML Signature, and XML Canonicalization, and, only with SOAP you can to embed these mechanisms into a message by a well-accepted standard as WS-Security.

  • Need more flexibility (less restrictions): SOAP not need exact correspondence with an URI; not nedd restrict to HTTP; not need to restrict to 4 verbs. As @TravisHeseman (9 votes) says, if you wanted something "flexible for an arbitrary number of client technologies and uses", use SOAP.
    PS: remember that XML is more universal/expressive than JSON (et al).

  • Need for formal verifications: important to understand that W3C stack uses formal methods, and REST is more informal. Your WSDL (a formal language) service description is a formal specification of your web services interfaces, and SOAP is a robust protocol that accept all possible WSDL prescriptions.

CONTEXT

Historical

To assess trends is necessary historical perspective. For this subject, a 10 or 15 years perspective...

Before the W3C standardization, there are some anarchy. Was difficult to implement interoperable services with different frameworks, and more difficult, costly, and time consuming to implement something interoperable between companys. The W3C stack standards has been a light, a north for interoperation of sets of complex web services.

For day-by-day tasks, like to implement AJAX, SOAP is heavy... So, the need for simple approaches need to elect a new theory-framework... And big "Web software players", as Google, Amazon, Yahoo, et al, elected the best alternative, that is the REST approach. Was in this context that REST concept arrived as a "competing framework", and, today (2012's), this alternative is a de facto standard for programmers.

Foundations

In a context of Parallel Computing the web services provides parallel subtasks; and protocols, like SOAP, ensures good synchronization and communication. Not "any task": web services can be classified as
coarse-grained and embarrassing parallelism.

As the task gets bigger, it becomes less significant "complexity debate", and becomes more relevant the robustness of the communication and the solidity of the contracts.

Display two fields side by side in a Bootstrap Form

The problem is that .form-control class renders like a DIV element which according to the normal-flow-of-the-page renders on a new line.

One way of fixing issues like this is to use display:inline property. So, create a custom CSS class with display:inline and attach it to your component with a .form-control class. You have to have a width for your component as well.

There are other ways of handling this issue (like arranging your form-control components inside any of the .col classes), but the easiest way is to just make your .form-control an inline element (the way a span would render)

How to upload files to server using JSP/Servlet?

For Spring MVC I have been trying for hours to do this and managed to have a simpler version that worked for taking form input both data and image.

<form action="/handleform" method="post" enctype="multipart/form-data">
  <input type="text" name="name" />
  <input type="text" name="age" />
  <input type="file" name="file" />
  <input type="submit" />
</form>

Controller to handle

@Controller
public class FormController {
    @RequestMapping(value="/handleform",method= RequestMethod.POST)
    ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
            throws ServletException, IOException {

        System.out.println(name);
        System.out.println(age);
        if(!file.isEmpty()){
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();
            BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
            stream.write(bytes);
            stream.flush();
            stream.close();
        }
        return new ModelAndView("index");
    }
}

Hope it helps :)

Tomcat - maxThreads vs maxConnections

From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections is the value of maxThreads unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads.

Oracle Add 1 hour in SQL

Old way:

SELECT DATE_COLUMN + 1 is adding a day
SELECT DATE_COLUMN + N /24 to add hour(s) - N being number of hours
SELECT DATE_COLUMN + N /1440 to add minute(s) - N being number of minutes
SELECT DATE_COLUMN + N /86400 to add second(s) - N being number of seconds

Using INTERVAL:

SELECT DATE_COLUMN + INTERVAL 'N' HOUR or MINUTE or SECOND - N being a number of hours or minutes or seconds.

JavaScript: How do I print a message to the error console?

This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:

just do:

alert("message");

Setting a minimum/maximum character count for any character using a regular expression

Like this: .

The . means any character except newline (which sometimes is but often isn't included, check your regex flavour).

You can rewrite your expression as ^.{1,35}$, which should match any line of length 1-35.

Task continuation on UI thread

I just wanted to add this version because this is such a useful thread and I think this is a very simple implementation. I have used this multiple times in various types if multithreaded application:

 Task.Factory.StartNew(() =>
      {
        DoLongRunningWork();
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
              { txt.Text = "Complete"; }));
      });

How to use passive FTP mode in Windows command prompt?

The Windows FTP command-line client (ftp.exe) does not support the passive mode, on any version of Windows. It makes it pretty useless nowadays due to ubiquitous firewalls and NATs.

Using the quote pasv won't help. It switches only the server to the passive mode, but not the client.


Use any thirdparty Windows FTP command-line client instead. Most other support the passive mode.

For example WinSCP defaults to the passive mode and there's a guide available for converting Windows FTP script to WinSCP script. If you are starting from the scratch, see the guide to automating file transfers to FTP using WinSCP. Also, WinSCP GUI can generate a script template for you.

(I'm the author of WinSCP)

What is the difference between smoke testing and sanity testing?

Smoke testing

Suppose a new build of an app is ready from the development phase.

We check if we are able to open the app without a crash. We login to the app. We check if the user is redirected to the proper URL and that the environment is stable. If the main aim of the app is to provide a "purchase" functionality to the user, check if the user's ID is redirected to the buying page.

After the smoke testing we confirm the build is in a testable form and is ready to go through sanity testing.

Sanity testing

In this phase, we check the basic functionalities, like

  1. login with valid credentials,
  2. login with invalid credentials,
  3. user's info are properly displayed after logging in,
  4. making a purchase order with a certain user's id,
  5. the "thank you" page is displayed after the purchase

What is the Regular Expression For "Not Whitespace and Not a hyphen"

In Java:

    String regex = "[^-\\s]";

    System.out.println("-".matches(regex)); // prints "false"
    System.out.println(" ".matches(regex)); // prints "false"
    System.out.println("+".matches(regex)); // prints "true"

The regex [^-\s] works as expected. [^\s-] also works.

See also

How to show Page Loading div until the page has finished loading?

Based on @mehyaa answer, but much shorter:

HTML (right after <body>):

<img id = "loading" src = "loading.gif" alt = "Loading indicator">

CSS:

#loading {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 32px;
  height: 32px;
  /* 1/2 of the height and width of the actual gif */
  margin: -16px 0 0 -16px;
  z-index: 100;
  }

Javascript (jQuery, since I'm already using it):

$(window).load(function() {
  $('#loading').remove();
  });

How to set RelativeLayout layout params in code not in xml?

I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.

package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;     
    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Layout
            RelativeLayout atulsLayout = new RelativeLayout(this);
            atulsLayout.setBackgroundColor(Color.GREEN);

            //Button
            Button redButton = new Button(this);
            redButton.setText("Log In");
            redButton.setBackgroundColor(Color.RED);

            //Username input
            EditText username =  new EditText(this);

            redButton.setId(1);
            username.setId(2);

            RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
            );

            //give rules to position widgets
            usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
            usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            usernameDetails.setMargins(0,0,0,50);

            buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
            buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);

            Resources r = getResources();
            int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
            username.setWidth(px);

            //Add widget to layout(button is now a child of layout)
            atulsLayout.addView(redButton,buttonDetails);
            atulsLayout.addView(username,usernameDetails);

            //Set these activities content/display to this view
            setContentView(atulsLayout);
        }
    }

Best way to get application folder path

For a web application, to get the current web application root directory, generally call by web page for the current incoming request:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Above code description

Can we instantiate an abstract class directly?

According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.

    public class MyCustomClass extends YourAbstractClass {

/// attributes, methods ,...
}
  1. work with interfaces.

Including another class in SCSS

Looks like @mixin and @include are not needed for a simple case like this.

One can just do:

.myclass {
  font-weight: bold;
  font-size: 90px;
}

.myotherclass {
  @extend .myclass;
  color: #000000;
}

Letsencrypt add domain to existing certificate

Apache on Ubuntu, using the Apache plugin:

sudo certbot certonly --cert-name example.com -d m.example.com,www.m.example.com

The above command is vividly explained in the Certbot user guide on changing a certificate's domain names. Note that the command for changing a certificate's domain names applies to adding new domain names as well.

Edit

If running the above command gives you the error message

Client with the currently selected authenticator does not support any combination of challenges that will satisfy the CA.

follow these instructions from the Let's Encrypt Community

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

Access a global variable in a PHP function

Another way to do it:

<?php

$data = 'My data';

$menugen = function() use ($data) {

    echo "[".$data."]";
};

$menugen();

UPDATE 2020-01-13: requested by Peter Mortensen

As of PHP 5.3.0 we have anonymous functions support that can create closures. A closure can access the variable which is created outside of its scope.

In the example, the closure is able to access $data because it was declared in the use clause.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.

I'd prefer to use OneJar for this issue.

How to add a second x-axis in matplotlib

I'm forced to post this as an answer instead of a comment due to low reputation. I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata. I was able to use Dhara's answer to do this with a modification:

ax2.lines = []

instead of using:

ax2.cla()

When in use also cleared my plot from ax1.

How can I find where I will be redirected using cURL?

The answer above didn't work for me on one of my servers, something to to with basedir, so I re-hashed it a little. The code below works on all my servers.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
curl_close( $ch ); 
// the returned headers
$headers = explode("\n",$a);
// if there is no redirection this will be the final url
$redir = $url;
// loop through the headers and check for a Location: str
$j = count($headers);
for($i = 0; $i < $j; $i++){
// if we find the Location header strip it and fill the redir var       
if(strpos($headers[$i],"Location:") !== false){
        $redir = trim(str_replace("Location:","",$headers[$i]));
        break;
    }
}
// do whatever you want with the result
echo redir;

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

Solved, just renamed the Global.asax or delete it fixed the problem :/

Other known related bugs I found on the web:

  1. Global.asax.cs: must inherit from HttpApplication -> public class MvcApplication : HttpApplication
  2. Project output must be the bin folder and not Bin/Debug, etc.
  3. Iss application pool is not in the correct .net version.

How to remove an element from an array in Swift

If you don't know the index of the element that you want to remove, and the element is conform the Equatable protocol, you can do:

animals.remove(at: animals.firstIndex(of: "dogs")!)

See Equatable protocol answer:How do I do indexOfObject or a proper containsObject

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

converting date time to 24 hour format

You should take a look at Java date formatting, in particular SimpleDateFormat. There's some examples here: http://download.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html - but you can also find a lot more with a quick google.

Adding a simple UIAlertView

This page shows how to add an UIAlertController if you are using Swift.

Select elements by attribute

A couple ideas were tossed around using "typeof", jQuery ".is" and ".filter" so I thought I would post up a quick perf compare of them. The typeof appears to be the best choice for this. While the others will work, there appears to be a clear performance difference when invoking the jq library for this effort.

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

Entity Framework vs LINQ to SQL

If your database is straightforward and simple, LINQ to SQL will do. If you need logical/abstracted entities on top of your tables, then go for Entity Framework.

CSS3 Spin Animation

You haven't specified any keyframes. I made it work here.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation: spin 4s infinite linear;
}

@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

You can actually do lots of really cool stuff with this. Here is one I made earlier.

:)

N.B. You can skip having to write out all the prefixes if you use -prefix-free.

Read .csv file in C

A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// adjust BUFFER_SIZE to suit longest line 
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1

// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP          0
#define IMIE        1
#define NAZWISKo    2
#define ULICA       3
#define NUMER       4
#define KOD         5
#define MIEJSCOw    6
#define TELEFON     7
#define EMAIL       8
#define DATA_UR     9

long loadFile(FILE *pFile, long *errcount);
static int  loadValues(char *line, long lineno);
static char delim;

long loadFile(FILE *pFile, long *errcount){

    char sInputBuf [BUFFER_SIZE];
    long lineno = 0L;

    if(pFile == NULL)
        return RET_FAIL;

    while (!feof(pFile)) {

        // load line into static buffer
        if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
            break;

        // skip first line (headers)
        if(++lineno==1)
            continue;

        // jump over empty lines
        if(strlen(sInputBuf)==0)
            continue;
        // set pFields array pointers to null-terminated string fields in sInputBuf
        if(loadValues(sInputBuf,lineno)==RET_FAIL){
           (*errcount)++;
            if(*errcount > MAXERRS)
                break;
        } else {    
            // On return pFields array pointers point to loaded fields ready for load into DB or whatever
            // Fields can be accessed via pFields, e.g.
            printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
        }
    }
    return lineno;
}


static int  loadValues(char *line, long lineno){
    if(line == NULL)
        return RET_FAIL;

    // chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
    // can be removed if sure fgets has removed both CR and LF from end of line
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
        *(line + strlen(line)-1) = '\0';
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
        *(line + strlen(line)-1) = '\0';

    char *cptr = line;
    int fld = 0;
    int inquote = FALSE;
    char ch;

    pFields[fld]=cptr;
    while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
        if(ch == '"') {
            if(! inquote)
                pFields[fld]=cptr+1;
            else {
                *cptr = '\0';               // zero out " and jump over it
            }
            inquote = ! inquote;
        } else if(ch == delim && ! inquote){
            *cptr = '\0';                   // end of field, null terminate it
            pFields[++fld]=cptr+1;
        }
        cptr++;
    }   
    if(fld > NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;
    } else if (fld < NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;    
    }
    return RET_OK;
}

int main(int argc, char **argv)
{
   FILE *fp;
   long errcount = 0L;
   long lines = 0L;

   if(argc!=3){
       printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
       return (RET_FAIL);
   }   
   if((delim=argv[2][0])=='\0'){
       fprintf(stderr,"delimiter must be specified\n");
       return (RET_FAIL);
   }
   fp = fopen(argv[1] , "r");
   if(fp == NULL) {
      fprintf(stderr,"Error opening file: %d\n",errno);
      return(RET_FAIL);
   }
   lines=loadFile(fp,&errcount);
   fclose(fp);
   printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
   if(errcount>0)
        return(RET_FAIL);
    return(RET_OK); 
}

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

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

Here's another. It's a Chrome Extension

Once installed you can run it by creating a new tab in Chrome and clicking the apps button near the top left

It has a simple gui. Click choose folder, then click the http://127.0.0.1:8887 link

enter image description here

https://www.youtube.com/watch?v=AK6swHiPtew

Cannot find R.layout.activity_main

Check if you not imported android.R accidentally.

Access props inside quotes in React JSX

React (or JSX) doesn't support variable interpolation inside an attribute value, but you can put any JS expression inside curly braces as the entire attribute value, so this works:

<img className="image" src={"images/" + this.props.image} />

How to download a Nuget package without nuget.exe or Visual Studio extension?

Based on Xavier's answer, I wrote a Google chrome extension NuTake to add links to the Nuget.org package pages.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Try to set

this.MinimumSize = new Size(140, 480);
this.MaximumSize = new Size(140, 480);

How to generate xsd from wsdl

You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.

SoapUI can do many things though!

Return outside function error in Python

You have a return statement that isn't in a function. Functions are started by the def keyword:

def function(argument):
    return "something"

print function("foo")  #prints "something"

return has no meaning outside of a function, and so python raises an error.

How to add row in JTable?

For the sake of completeness, first make sure you have the correct import so you can use the addRow function:

import javax.swing.table.*;

Assuming your jTable is already created, you can proceed and create your own add row method which will accept the parameters that you need:

public void yourAddRow(String str1, String str2, String str3){
  DefaultTableModel yourModel = (DefaultTableModel) yourJTable.getModel();
  yourModel.addRow(new Object[]{str1, str2, str3});
}

SQL Server Management Studio, how to get execution time down to milliseconds

I don't know about expanding the information bar.

But you can get the timings set as a default for all queries showing in the "Messages" tab.

When in a Query window, go to the Query Menu item, select "query options" then select "advanced" in the "Execution" group and check the "set statistics time" / "set statistics IO" check boxes. These values will then show up in the messages area for each query without having to remember to put in the set stats on and off.

You could also use Shift + Alt + S to enable client statistics at any time

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

String to Dictionary in Python

This data is JSON! You can deserialize it using the built-in json module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson module.

import json    # or `import simplejson as json` if on Python < 2.6

json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string)    # obj now contains a dict of the data

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

Visual c++ can't open include file 'iostream'

I had this exact same problem in VS 2015. It looks like as of VS 2010 and later you need to include #include "stdafx.h" in all your projects.

#include "stdafx.h"
#include <iostream>
using namespace std;

The above worked for me. The below did not:

#include <iostream>
using namespace std;

This also failed:

#include <iostream>
using namespace std;
#include "stdafx.h"

Python glob multiple filetypes

You could also use reduce() like so:

import glob
file_types = ['*.txt', '*.mdown', '*.markdown']
project_files = reduce(lambda list1, list2: list1 + list2, (glob.glob(t) for t in file_types))

this creates a list from glob.glob() for each pattern and reduces them to a single list.

Get full URL and query string in Servlet for both HTTP and HTTPS requests

I know this is a Java question, but if you're using Kotlin you can do this quite nicely:

val uri = request.run {
    if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}

Is this very likely to create a memory leak in Tomcat?

I added the following to @PreDestroy method in my CDI @ApplicationScoped bean, and when I shutdown TomEE 1.6.0 (tomcat7.0.39, as of today), it clears the thread locals.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pf;

import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Administrator
 * 
 * google-gson issue # 402: Memory Leak in web application; comment # 25
 * https://code.google.com/p/google-gson/issues/detail?id=402
 */
public class ThreadLocalImmolater {

    final Logger logger = LoggerFactory.getLogger(ThreadLocalImmolater.class);

    Boolean debug;

    public ThreadLocalImmolater() {
        debug = true;
    }

    public Integer immolate() {
        int count = 0;
        try {
            final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            threadLocalsField.setAccessible(true);
            final Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals");
            inheritableThreadLocalsField.setAccessible(true);
            for (final Thread thread : Thread.getAllStackTraces().keySet()) {
                    count += clear(threadLocalsField.get(thread));
                    count += clear(inheritableThreadLocalsField.get(thread));
            }
            logger.info("immolated " + count + " values in ThreadLocals");
        } catch (Exception e) {
            throw new Error("ThreadLocalImmolater.immolate()", e);
        }
        return count;
    }

    private int clear(final Object threadLocalMap) throws Exception {
        if (threadLocalMap == null)
                return 0;
        int count = 0;
        final Field tableField = threadLocalMap.getClass().getDeclaredField("table");
        tableField.setAccessible(true);
        final Object table = tableField.get(threadLocalMap);
        for (int i = 0, length = Array.getLength(table); i < length; ++i) {
            final Object entry = Array.get(table, i);
            if (entry != null) {
                final Object threadLocal = ((WeakReference)entry).get();
                if (threadLocal != null) {
                    log(i, threadLocal);
                    Array.set(table, i, null);
                    ++count;
                }
            }
        }
        return count;
    }

    private void log(int i, final Object threadLocal) {
        if (!debug) {
            return;
        }
        if (threadLocal.getClass() != null &&
            threadLocal.getClass().getEnclosingClass() != null &&
            threadLocal.getClass().getEnclosingClass().getName() != null) {

            logger.info("threadLocalMap(" + i + "): " +
                        threadLocal.getClass().getEnclosingClass().getName());
        }
        else if (threadLocal.getClass() != null &&
                 threadLocal.getClass().getName() != null) {
            logger.info("threadLocalMap(" + i + "): " + threadLocal.getClass().getName());
        }
        else {
            logger.info("threadLocalMap(" + i + "): cannot identify threadlocal class name");
        }
    }

}

How to sum data.frame column values?

to order after the colsum :

order(colSums(people),decreasing=TRUE)

if more than 20+ columns

order(colSums(people[,c(5:25)],decreasing=TRUE) ##in case of keeping the first 4 columns remaining.

Get the element with the highest occurrence in an array

a=['pear', 'apple', 'orange', 'apple'];
b={};
max='', maxi=0;
for(let k of a) {
  if(b[k]) b[k]++; else b[k]=1;
  if(maxi < b[k]) { max=k; maxi=b[k] }
}

How to change the height of a <br>?

Here is the correct solution that actually has cross-browser support:

  br {
        line-height: 150%;
     }

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

Ubuntu - Run command on start-up with "sudo"

You can add the command in the /etc/rc.local script that is executed at the end of startup.

Write the command before exit 0. Anything written after exit 0 will never be executed.

round() doesn't seem to be rounding properly

You can switch the data type to an integer:

>>> n = 5.59
>>> int(n * 10) / 10.0
5.5
>>> int(n * 10 + 0.5)
56

And then display the number by inserting the locale's decimal separator.

However, Jimmy's answer is better.

jQuery Ajax PUT with parameters

Use:

$.ajax({
    url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
        console.log(data);
    }
});

Always remember to use _METHOD=PUT.

Remove Duplicate objects from JSON Array

Reviving an old question, but I wanted to post an iteration on @adeneo's answer. That answer is completely general, but for this use case it could be more efficient (it's slow on my machine with an array of a few thousand objects). If you know the specific properties of the objects you need to compare, just compare them directly:

var sl = standardsList;
var out = [];

for (var i = 0, l = sl.length; i < l; i++) {
    var unique = true;
    for (var j = 0, k = out.length; j < k; j++) {
        if ((sl[i].Grade === out[j].Grade) && (sl[i].Domain === out[j].Domain)) {
            unique = false;
        }
    }
    if (unique) {
        out.push(sl[i]);
    }
}

console.log(sl.length); // 10
console.log(out.length); // 5

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

Try downloading apache-jmeter-2.6.zip from http://www.apache.org/dist/jmeter/binaries/

This contains the proper ApacheJMeter.jar that is needed to initiate.

Go to bin folder in the command prompt and try java -jar ApacheJMeter.jar if the download is correct this should open the GUI.

Edit on 23/08/2018:

Program to find largest and second largest number in array

Getting the second largest number from an array is pretty easy in python, I have done with simple steps and put various ways of test cases and it gave the right answer every time. PS. I know it's for c but I just gave a simple solution to the question if done in python

n = int(input()) #taking number of elements in array
arr = map(int, input().split()) #taking differet elements
l=[]
s=set()
for i in arr: #putting all the elemnents in set to remove any duplicate number
    s.add(i)
for j in s:  #putting all element from the set in the list to sort and get the second largest number
    l.append(j)
l.sort()
c=len(l)
print(l[c-2]) #printing second largest number

Change user-agent for Selenium web-driver

This is a short solution to change the request UserAgent on the fly.

Change UserAgent of a request with Chrome

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome(driver_path)
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent":"python 2.7", "platform":"Windows"})
driver.get('http://amiunique.org')

then return your useragent:

agent = driver.execute_script("return navigator.userAgent")

Some sources

The source code of webdriver.py from SeleniumHQ (https://github.com/SeleniumHQ/selenium/blob/11c25d75bd7ed22e6172d6a2a795a1d195fb0875/py/selenium/webdriver/chrome/webdriver.py) extends its functionalities through the Chrome Devtools Protocol

def execute_cdp_cmd(self, cmd, cmd_args):
        """
        Execute Chrome Devtools Protocol command and get returned result

We can use the Chrome Devtools Protocol Viewer to list more extended functionalities (https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setUserAgentOverride) as well as the parameters type to use.

Trigger validation of all fields in Angular Form submit

What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.

In the click event where I wanted to trigger the validation, I did the following:

vm.triggerSubmit = function() {
    vm.homeForm.$setSubmitted();
    ...
}

That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.

Display fullscreen mode on Tkinter

I think if you are looking for fullscreen only, no need to set geometry or maxsize etc.

You just need to do this:

-If you are working on ubuntu:

root=tk.Tk()
root.attributes('-zoomed', True)

-and if you are working on windows:

root.state('zoomed')

Now for toggling between fullscreen, for minimising it to taskbar you can use:

Root.iconify()

Failed binder transaction when putting an bitmap dynamically in a widget

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

How can I make a thumbnail <img> show a full size image when clicked?

alt is text that is displayed when the image can't be loaded or the user's browser doesn't support images (e.g. readers for blind people).

Try using something like lightbox:

http://www.lokeshdhakar.com/projects/lightbox2/

update: This library maybe better as its based on jQuery which you have said your using http://leandrovieira.com/projects/jquery/lightbox/

Angular 5 Scroll to top on every Route click

From Angular Version 6+ No need to use window.scroll(0,0)

For Angular version 6+ from @docs
Represents options to configure the router.

interface ExtraOptions {
  enableTracing?: boolean
  useHash?: boolean
  initialNavigation?: InitialNavigation
  errorHandler?: ErrorHandler
  preloadingStrategy?: any
  onSameUrlNavigation?: 'reload' | 'ignore'
  scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
  anchorScrolling?: 'disabled' | 'enabled'
  scrollOffset?: [number, number] | (() => [number, number])
  paramsInheritanceStrategy?: 'emptyOnly' | 'always'
  malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  urlUpdateStrategy?: 'deferred' | 'eager'
  relativeLinkResolution?: 'legacy' | 'corrected'
}

One can use scrollPositionRestoration?: 'disabled' | 'enabled' | 'top' in

Example:

RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'|'top' 
});

And if one requires to manually control the scrolling, No need to use window.scroll(0,0) Instead from Angular V6 common package has introduced ViewPortScoller.

abstract class ViewportScroller {
  static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
  abstract setOffset(offset: [number, number] | (() => [number, number])): void
  abstract getScrollPosition(): [number, number]
  abstract scrollToPosition(position: [number, number]): void
  abstract scrollToAnchor(anchor: string): void
  abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}

Usage is pretty Straightforward Example:

import { Router } from '@angular/router';
import {  ViewportScroller } from '@angular/common'; //import
export class RouteService {

  private applicationInitialRoutes: Routes;
  constructor(
    private router: Router;
    private viewPortScroller: ViewportScroller//inject
  )
  {
   this.router.events.pipe(
            filter(event => event instanceof NavigationEnd))
            .subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

I got the solution for the Android Studio installation after trying everything that I could find on the Internet. If you're using Android Studio and getting this error:

Find [Path_to_Android_SDK]\sdk\tools\android.bat. In my case, it was in C:\Users\Nathan\AppData\Local\Android\android-studio\sdk\tools\android.bat.

Right-click it, hit Edit, and scroll all the way down to the bottom.

Find where it says: call %java_exe% %REMOTE_DEBUG% ...

Replace that with call %java_exe% -Djava.net.preferIPv4Stack=true %REMOTE_DEBUG% ...

Restart Android Studio/SDK and everything works. This fixed many issues for me, including being unable to fetch XML files or create new projects.

What is the GAC in .NET?

Exe Application, first of all, references from a current directory to a subdirectory. And then, system directory. VS6.0 system directory was ..windows/system32. .NET system directory is like the below GAC path.

  1. GAC path

    1) C:\Windows\Assembly (for .NET 2.0 ~ 3.5)

    2) C:\Windows\Microsoft.NET\assembly (for .NET 4.0)

  2. How to install an assembly into GAC (as Administrator)

    1) Drag and Drop

    2) Use GacUtil.exe with Visual Studio Command Prompt

     gacutil -i [Path][Assembly Name].dll
    
    • Note: To install an assembly into the GAC, the assembly must be strongly named. Otherwise you get an error like this: Failure adding assembly to the cache: Attempt to install an assembly without a strong name.
  3. How to uninstall an assembly from GAC (as Administrator)

     gacutil -u [Assembly Name], Version=1.0.0.0, PublickeyToken=7896a3567gh
    
    • Note: has no extention, .dll. Version and PublickeyToken can be omitted and be checked in GAC assembly.

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat

Got the solution and it's working fine. Set the environment variables as:

  • CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59 (path where your Apache Tomcat is)
  • JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25; (path where your JDK is)
  • JRE_Home=C:\Program Files\Java\jre1.8.0_25; (path where your JRE is)
  • CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

How can I load the contents of a text file into a batch file variable?

Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...

set FileContents=

Then in your batch file do something like this...

   @echo off
   copy SetFile.bat + %1 $tmp$.bat > nul
   call $tmp$.bat
   del $tmp$.bat

%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.

Get Selected value of a Combobox

You can use the below change event to which will trigger when the combobox value will change.

Private Sub ComboBox1_Change()
'your code here
End Sub

Also you can get the selected value using below

ComboBox1.Value

Why is there no xrange function in Python3?

Python3's range is Python2's xrange. There's no need to wrap an iter around it. To get an actual list in Python3, you need to use list(range(...))

If you want something that works with Python2 and Python3, try this

try:
    xrange
except NameError:
    xrange = range

Determining the size of an Android view at runtime

This works for me in my onClickListener:

yourView.postDelayed(new Runnable() {               
    @Override
    public void run() {         
        yourView.invalidate();
        System.out.println("Height yourView: " + yourView.getHeight());
        System.out.println("Width yourView: " + yourView.getWidth());               
    }
}, 1);

Java foreach loop: for (Integer i : list) { ... }

Another way, you can use a pass-through object to capture the last value and then do something with it:

List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
    // do stuff
    lastValue = i;
}
// do stuff with last value

Draw a connecting line between two elements

D3 has hundreds of examples, some of which are suitable for this question.

Examples without drag and drop, that are fixed:

Examples without drag and drop, that are interactive:

Examples with dragging and dropping:

This answer is based off of Glenn Dayton's answer.

How to print to console using swift playground?

In Xcode 6.3 and later (including Xcode 7 and 8), console output appears in the Debug area at the bottom of the playground window (similar to where it appears in a project). To show it:

  • Menu: View > Debug Area > Show Debug Area (??Y)

  • Click the middle button of the workspace-layout widget in the toolbar

    workspace layout widget

  • Click the triangle next to the timeline at the bottom of the window

    triangle for console

Anything that writes to the console, including Swift's print statement (renamed from println in Swift 2 beta) shows up there.


In earlier Xcode 6 versions (which by now you probably should be upgrading from anyway), show the Assistant editor (e.g. by clicking the little circle next to a bit in the output area). Console output appears there.

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

OSError: [Errno 8] Exec format error

It wouldn't be wrong to mention that Pexpect does throw a similar error

#python -c "import pexpect; p=pexpect.spawn('/usr/local/ssl/bin/openssl_1.1.0f  version'); p.interact()"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/pexpect.py", line 430, in __init__
    self._spawn (command, args)
  File "/usr/lib/python2.7/site-packages/pexpect.py", line 560, in _spawn
    os.execv(self.command, self.args)
OSError: [Errno 8] Exec format error

Over here, the openssl_1.1.0f file at the specified path has exec command specified in it and is running the actual openssl binary when called.

Usually, I wouldn't mention this unless I have the root cause, but this problem was not there earlier. Unable to find the similar problem, the closest explanation to make it work is the same as the one provided by @jfs above.

what worked for me is both

  • adding /bin/bash at the beginning of the command or file you are
    facing the problem with, or
  • adding shebang #!/bin/sh as the first line.

for ex.

#python -c "import pexpect; p=pexpect.spawn('/bin/bash /usr/local/ssl/bin/openssl_1.1.0f  version'); p.interact()"
OpenSSL 1.1.0f  25 May 2017

"Find next" in Vim

When I was beginning I needed to watch a demo.

How to search in Vim

  1. type /
  2. type search term e.g. "var"
  3. press enter
  4. for next instance press n (for previous N)

Pass by pointer & Pass by reference

In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.

Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.

Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.

References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.

How to use HTML Agility pack

I don't know if this will be of any help to you, but I have written a couple of articles which introduce the basics.

The next article is 95% complete, I just have to write up explanations of the last few parts of the code I have written. If you are interested then I will try to remember to post here when I publish it.

How to iterate through a list of dictionaries in Jinja template?

Data:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:

Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py. If the dict is unicode object, you have to encode into utf-8.

Youtube iframe wmode issue

If you are using the new asynchronous API, you will need to add the parameter like so:

<!-- YOUTUBE -->
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
var initialVideo = 'ApkM4t9L5jE'; // YOUR YOUTUBE VIDEO ID
function onYouTubePlayerAPIReady() {
    console.log("onYouTubePlayerAPIReady" + initialVideo);
    player = new YT.Player('player', {
      height: '381',
      width: '681',
      wmode: 'transparent', // SECRET SAUCE HERE
      videoId: initialVideo,      
       playerVars: { 'autoplay': 1, 'rel': 0, 'wmode':'transparent' },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
}

This is based on the google documentation and example here: http://code.google.com/apis/youtube/iframe_api_reference.html

Pass variables between two PHP pages without using a form or the URL of page

Here are brief list:

  • JQuery with JSON stuff. (http://www.w3schools.com/xml/xml_http.asp)

  • $_SESSION - probably best way

  • Custom cookie - will not *always* work.

  • HTTP headers - some proxy can block it.

  • database such MySQL, Postgres or something else such Redis or Memcached (e.g. similar to home-made session, "locked" by IP address)

  • APC - similar to database, will not *always* work.

  • HTTP_REFERRER

  • URL hash parameter , e.g. http://domain.com/page.php#param - you will need some JavaScript to collect the hash. - gmail heavy use this.

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command.it is working for me.

if "$(OutDir)"=="bin\Debug\"  goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit

How to find and replace with regex in excel

Use Google Sheets instead of Excel - this feature is built in, so you can use regex right from the find and replace dialog.

To answer your question:

  1. Copy the data from Excel and paste into Google Sheets
  2. Use the find and replace dialog with regex
  3. Copy the data from Google Sheets and paste back into Excel

How to change FontSize By JavaScript?

JavaScript is case sensitive.

So, if you want to change the font size, you have to go:

span.style.fontSize = "25px";

How to query the permissions on an Oracle directory?

Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.

As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.

Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.

How to update the constant height constraint of a UIView programmatically?

You can update your constraint with a smooth animation if you want, see the chunk of code below:

heightOrWidthConstraint.constant = 100
UIView.animate(withDuration: animateTime, animations:{
self.view.layoutIfNeeded()
})

Removing duplicates from a String in Java

Using Stream makes it easy.

noDuplicates = Arrays.asList(myString.split(""))
                     .stream()
                     .distinct()
                     .collect(Collectors.joining());

Here is some more documentation about Stream and all you can do with it : https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

The 'description' part is very instructive about the benefits of Streams.

Static variables in JavaScript

I use static function variables a lot and it's a real shame JS doesn't have a built-in mechanism for that. Too often I see code where variables and functions are defined in an outer scope even though they're just used inside one function. This is ugly, error prone and just asking for trouble...

I came up with the following method:

if (typeof Function.prototype.statics === 'undefined') {
  Function.prototype.statics = function(init) {
    if (!this._statics) this._statics = init ? init() : {};
    return this._statics;
  }
}

This adds a 'statics' method to all functions (yes, just relax about it), when called it will add an empty object (_statics) to the function object and return it. If an init function is supplied _statics will be set to init() result.

You can then do:

function f() {
  const _s = f.statics(() => ({ v1=3, v2=somefunc() });

  if (_s.v1==3) { ++_s.v1; _s.v2(_s.v1); }
} 

Comparing this to an IIFE which is the other correct answer, this has the disadvantage of adding one assignment and one if on every function call and adding a '_statics' member to the function, however there are a few advantages: the arguments are there at the top not in the internal function, using a 'static' in the internal function code is explicit with an '_s.' prefix, and it is overall simpler to look at and understand.

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.

The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"