Programs & Examples On #Hsl

HSV is cylindrical color model that determines colors by hue (0°-360°), saturation (color intensity) and lightness (from black over the color to white).

HSL to RGB color conversion

With H, S,and L in [0,1] range:

ConvertHslToRgb: function (iHsl)
{
    var min, sv, sextant, fract, vsf;

    var v = (iHsl.l <= 0.5) ? (iHsl.l * (1 + iHsl.s)) : (iHsl.l + iHsl.s - iHsl.l * iHsl.s);
    if (v === 0)
        return { Red: 0, Green: 0, Blue: 0 };

    min = 2 * iHsl.l - v;
    sv = (v - min) / v;
    var h = (6 * iHsl.h) % 6;
    sextant = Math.floor(h);
    fract = h - sextant;
    vsf = v * sv * fract;

    switch (sextant)
    {
        case 0: return { r: v, g: min + vsf, b: min };
        case 1: return { r: v - vsf, g: v, b: min };
        case 2: return { r: min, g: v, b: min + vsf };
        case 3: return { r: min, g: v - vsf, b: v };
        case 4: return { r: min + vsf, g: min, b: v };
        case 5: return { r: v, g: min, b: v - vsf };
    }
}

What is the significance of #pragma marks? Why do we need #pragma marks?

When we have a big/lengthy class say more than couple 100 lines of code we can't see everything on Monitor screen, hence we can't see overview (also called document items) of our class. Sometime we want to see overview of our class; its all methods, constants, properties etc at a glance. You can press Ctrl+6 in XCode to see overview of your class. You'll get a pop-up kind of Window aka Jump Bar.

By default, this jump bar doesn't have any buckets/sections. It's just one long list. (Though we can just start typing when jump Bar appears and it will search among jump bar items). Here comes the need of pragma mark

If you want to create sections in your Jump Bar then you can use pragma marks with relevant description. Now refer snapshot attached in question. There 'View lifeCycle' and 'A section dedicated ..' are sections created by pragma marks

IntelliJ and Tomcat.. Howto..?

In Netbeans you can right click on the project and run it, but in IntelliJ IDEA you have to select the index.jsp file or the welcome file to run the project.

this is because Netbeans generate the following tag in web.xml and IntelliJ do not.

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

Use PPK file in Mac Terminal to connect to remote connection over SSH

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

node.js require() cache - possible to invalidate?

I couldn't neatly add code in an answer's comment. But I would use @Ben Barkay's answer then add this to the require.uncache function.

    // see https://github.com/joyent/node/issues/8266
    // use in it in @Ben Barkay's require.uncache function or along with it. whatever
    Object.keys(module.constructor._pathCache).forEach(function(cacheKey) {
        if ( cacheKey.indexOf(moduleName) > -1 ) {
            delete module.constructor._pathCache[ cacheKey ];
        }
    }); 

Say you've required a module, then uninstalled it, then reinstalled the same module but used a different version that has a different main script in its package.json, the next require will fail because that main script does not exists because it's cached in Module._pathCache

Jupyter Notebook not saving: '_xsrf' argument missing from post

Open the developer setting and click console and type the following

JSON.parse(document.getElementById('jupyter-config-data').textContent).token

Then try saving the Notebook. The notebook that was not saving previously will save now.

how to read all files inside particular folder

using System.IO;

//...

  string[] files;

  if (Directory.Exists(Path)) {
    files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly);
    //...

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How to get the current directory in a C program?

To get current directory (where you execute your target program), you can use the following example code, which works for both Visual Studio and Linux/MacOS(gcc/clang), both C and C++:

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

#if defined(_MSC_VER)
#include <direct.h>
#define getcwd _getcwd
#elif defined(__GNUC__)
#include <unistd.h>
#endif

int main() {
    char* buffer;

    if( (buffer=getcwd(NULL, 0)) == NULL) {
        perror("failed to get current directory\n");
    } else {
        printf("%s \nLength: %zu\n", buffer, strlen(buffer));
        free(buffer);
    }

    return 0;
}

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Forbidden You don't have permission to access /wp-login.php on this server

Make sure your apache .conf files are correct -- then double check your .htaccess files. In this case, my .htaccess were incorrect! I removed some weird stuff no longer needed and it worked. Tada.

Using Javascript in CSS

IE supports CSS expressions:

width:expression(document.body.clientWidth > 955 ? "955px": "100%" );

but they are not standard and are not portable across browsers. Avoid them if possible. They are deprecated since IE8.

What are native methods in Java and where should they be used?

Java native code necessities:

  • h/w access and control.
  • use of commercial s/w and system services[h/w related].
  • use of legacy s/w that hasn't or cannot be ported to Java.
  • Using native code to perform time-critical tasks.

hope these points answers your question :)

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Following the instructions here http://help.loftware.com/pages/viewpage.action?pageId=27099554 I had to install the Microsoft Access Database Engine 2010 Redistributable before I had the Excel driver installed to use the DSN-less connection I wanted to use from perl.

Bootstrap get div to align in the center

In bootstrap you can use .text-centerto align center. also add .row and .col-md-* to your code.

align= is deprecated,

Added .col-xs-* for demo

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
  <div class="container">
    <div class="row">
      <div class="col-xs-4">
        <p>Hello there</p>
      </div>
      <div class="col-xs-4 text-center">
        <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
        <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
      </div>
      <div class="col-xs-4 text-right">
        <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
        <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
        <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
      </div>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

UPDATE(OCT 2017)

For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
  <div class="d-flex justify-content-between">
    <div class="p-1">
      <p>Hello there</p>
    </div>
    <div class="p-1">
      <a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
      <a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
    </div>
    <div class="p-1">
      <a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
      <a href="#"><i class="fa fa-twitter fa-2x"></i></a>
      <a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to debug Spring Boot application with Eclipse?

The best solution in my opinion is add a plugin in the pom.xml, and you don't need to do anything else all the time:

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>
                        -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9898
                    </jvmArguments>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Is there a common Java utility to break a list into batches?

import com.google.common.collect.Lists;

List<List<T>> batches = Lists.partition(List<T>,batchSize)

Use Lists.partition(List,batchSize). You need to import Lists from google common package (com.google.common.collect.Lists)

It will return List of List<T> with and the size of every element equal to your batchSize.

Check if a specific tab page is selected (active)

This can work as well.

if (tabControl.SelectedTab.Text == "tabText" )
{
    .. do stuff
}

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

AngularJS: How to clear query parameters in the URL?

The accepted answer worked for me, but I needed to dig a little deeper to fix the problems with the back button.

What I noticed is that if I link to a page using <a ui-sref="page({x: 1})">, then remove the query string using $location.search('x', null), I don't get an extra entry in my browser history, so the back button takes me back to where I started. Although I feel like this is wrong because I don't think that Angular should automatically remove this history entry for me, this is actually the desired behaviour for my particular use-case.

The problem is that if I link to the page using <a href="/page/?x=1"> instead, then remove the query string in the same way, I do get an extra entry in my browser history, so I have to click the back button twice to get back to where I started. This is inconsistent behaviour, but actually this seems more correct.

I can easily fix the problem with href links by using $location.search('x', null).replace(), but then this breaks the page when you land on it via a ui-sref link, so this is no good.

After a lot of fiddling around, this is the fix I came up with:

In my app's run function I added this:

$rootScope.$on('$locationChangeSuccess', function () {
    $rootScope.locationPath = $location.path();
});

Then I use this code to remove the query string parameter:

$location.search('x', null);

if ($location.path() === $rootScope.locationPath) {
    $location.replace();
}

Difference between JSON.stringify and JSON.parse

JSON.parse() is for "parsing" something that was received as JSON.
JSON.stringify() is to create a JSON string out of an object/array.

Is there a Public FTP server to test upload and download?

Currently, the link dlptest is working fine.

The files will only be stored for 30 minutes before being deleted.

How to find Control in TemplateField of GridView?

Try with below code.

Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.

<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
    OnRowDataBound="mainGrid_RowDataBound"  EmptyDataText="No Data Found.">
    <Columns>
        <asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
                <asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
                <a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
                <input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Handling RowDataBound event,

protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblName = (Label)e.Row.FindControl("lblName");
        LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
        HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
        HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
    }
}

Send POST request using NSURLSession

Teja Kumar Bethina's code changed for Swift 3:

    let urlStr = "http://url_to_manage_post_requests"
    let url = URL(string: urlStr)

    var request: URLRequest = URLRequest(url: url!)

    request.httpMethod = "POST"

    request.setValue("application/json", forHTTPHeaderField:"Content-Type")
    request.timeoutInterval = 60.0

    //additional headers
    request.setValue("deviceIDValue", forHTTPHeaderField:"DeviceId")

    let bodyStr = "string or data to add to body of request"
    let bodyData = bodyStr.data(using: String.Encoding.utf8, allowLossyConversion: true)
    request.httpBody = bodyData

    let task = URLSession.shared.dataTask(with: request) {
        (data: Data?, response: URLResponse?, error: Error?) -> Void in

        if let httpResponse = response as? HTTPURLResponse {
            print("responseCode \(httpResponse.statusCode)")
        }

        if error != nil {

            // You can handle error response here
            print("\(error)")
        } else {
            //Converting response to collection formate (array or dictionary)
            do {
                let jsonResult = (try JSONSerialization.jsonObject(with: data!, options:
                    JSONSerialization.ReadingOptions.mutableContainers))

                //success code
            } catch {
                //failure code
            }
        }
    }

    task.resume()

How to get DropDownList SelectedValue in Controller in MVC

I was having the same issue in asp.NET razor C#

I had a ComboBox filled with titles from an EventMessage, and I wanted to show the Content of this message with its selected value to show it in a label or TextField or any other Control...

My ComboBox was filled like this:

 @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })

In my EventController I had a function to go to the page, in which I wanted to show my ComboBox (which is of a different model type, so I had to use a partial view)?

The function to get from index to page in which to load the partial view:

  public ActionResult EventDetail(int id)
        {

            Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
            //  EventOrg eventOrg = db.EventOrgs.Find(id);
            if (eventOrg == null)
            {

                return HttpNotFound();
            }
            ViewBag.EventBerichten = GetEventBerichtenLijst(id);
            ViewBag.eventOrg = eventOrg;
            return View(eventOrg);
        }

The function for the partial view is here:

 public PartialViewResult InhoudByIdPartial(int id)
        {
            return PartialView(
                db.EventBericht.Where(r => r.EventID == id).ToList());

        }

The function to fill EventBerichten:

        public List<EventBerichten> GetEventBerichtenLijst(int id)
        {
            var eventLijst = db.EventBericht.ToList();
            var berLijst = new List<EventBerichten>();
            foreach (var ber in eventLijst)
            {
                if (ber.EventID == id )
                {
                    berLijst.Add(ber);
                }
            }
            return berLijst;
        }

The partialView Model looks like this:

@model  IEnumerable<STUVF_back_end.Models.EventBerichten>

<table>
    <tr>
        <th>
            EventID
        </th>
        <th>
            Titel
        </th>
        <th>
            Inhoud
        </th>
        <th>
            BerichtDatum
        </th>
        <th>
            BerichtTijd
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EventID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Titel)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Inhoud)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtDatum)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtTijd)
            </td>

        </tr>
    }
</table>

VIEUW: This is the script used to get my output in the view

<script type="text/javascript">
    $(document).ready(function () {
        $("#EventBerichten").change(function () {
            $("#log").ajaxError(function (event, jqxhr, settings, exception) {
                alert(exception);
            });

            var BerichtSelected = $("select option:selected").first().text();
            $.get('@Url.Action("InhoudByIdPartial")',
                { EventBerichtID: BerichtSelected }, function (data) {
                    $("#target").html(data);
                });
        });
    });
            </script>
@{
                    Html.RenderAction("InhoudByIdPartial", Model.EventID);
                } 

<fieldset>
                <legend>Berichten over dit Evenement</legend>
                <div>
                    @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
                </div>

                <br />
                <div id="target">

                </div>
                <div id="log">

                </div>
            </fieldset>

Rails 3 migrations: Adding reference column?

When adding a column you need to make that column an integer and if possible stick with rails conventions. So for your case I am assuming you already have a Tester and User models, and testers and users tables.

To add the foreign key you need to create an integer column with the name user_id (convention):

add_column :tester, :user_id, :integer

Then add a belongs_to to the tester model:

class Tester < ActiveRecord::Base
  belongs_to :user
end

And you might also want to add an index for the foreign key (this is something the references already does for you):

add_index :tester, :user_id

converting CSV/XLS to JSON?

Instead of hard-coded converters, how about CSV support for Jackson (JSON processor): https://github.com/FasterXML/jackson-dataformat-csv. So core Jackson can read JSON in as POJOs, Maps, JsonNode, almost anything. And CSV support can do the same with CSV. Combine the two and it's very powerful but simple converter between multiple formats (there are backends for XML, YAML already, and more being added).

An article that shows how to do this can be found here.

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

In regards to JavaScript:

The === operator works the same as the == operator, but it requires that its operands have not only the same value, but also the same data type.

For example, the sample below will display 'x and y are equal', but not 'x and y are identical'.

var x = 4;
var y = '4';
if (x == y) {
    alert('x and y are equal');
}
if (x === y) {
    alert('x and y are identical');
}

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

How to describe "object" arguments in jsdoc?

There's a new @config tag for these cases. They link to the preceding @param.

/** My function does X and Y.
    @params {object} parameters An object containing the parameters
    @config {integer} setting1 A required setting.
    @config {string} [setting2] An optional setting.
    @params {MyClass~FuncCallback} callback The callback function
*/
function(parameters, callback) {
    // ...
};

/**
 * This callback is displayed as part of the MyClass class.
 * @callback MyClass~FuncCallback
 * @param {number} responseCode
 * @param {string} responseMessage
 */

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

'gulp' is not recognized as an internal or external command

Go to My Computer>Properties>Advance System Settings>Environment Variables>

Under the variables of Administrator edit the PATH variable & change its value to "C:\Users\Username\AppData\Roaming\npm". Note: The username in the path will be the current Admin user's name that you have logged in with.

How to center a window on the screen in Tkinter?

This answer is better for understanding beginner

#
import tkinter as tk

win = tk.Tk()  # Creating instance of Tk class
win.title("Centering windows")
win.resizable(False, False)  # This code helps to disable windows from resizing

window_height = 500
window_width = 900

screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()

x_cordinate = int((screen_width/2) - (window_width/2))
y_cordinate = int((screen_height/2) - (window_height/2))

win.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))

win.mainloop()

Using Predicate in Swift

Example how to use in swift 2.0

let dataSource = [
    "Domain CheckService",
    "IMEI check",
    "Compliant about service provider",
    "Compliant about TRA",
    "Enquires",
    "Suggestion",
    "SMS Spam",
    "Poor Coverage",
    "Help Salim"
]
let searchString = "Enq"
let predicate = NSPredicate(format: "SELF contains %@", searchString)
let searchDataSource = dataSource.filter { predicate.evaluateWithObject($0) }

You will get (playground)

enter image description here

How to create a directory in Java?

Well to create Directory/folder in java we have two methods

Here makedirectory method creates single directory if it does not exist.

File dir = new File("path name");
boolean isCreated = dir.mkdir();

And

File dir = new File("path name");
boolean isCreated = dir.mkdirs();

Here makedirectories method will create all directories that are missing in the path which the file object represent.

For example refer link below (explained very well). Hope it helps!! https://www.flowerbrackets.com/create-directory-java-program/

How can I test a change made to Jenkinsfile locally?

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

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

User GETDATE() to put current date into SQL variable

SELECT @LastChangeDate = GETDATE()

How do I use a custom Serializer with Jackson?

If your only requirement in your custom serializer is to skip serializing the name field of User, mark it as transient. Jackson will not serialize or deserialize transient fields.

[ see also: Why does Java have transient fields? ]

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

How to set-up a favicon?

There is a very simple method to set a favicon, which had been around for a long time AFAIK. Place the favicon.ico file in the default location. i.e

http://www.yoursite.com/favicon.ico

This works in almost every browser without a <link> tag. However, this works only if it is an *.ico file. PNGs and other formats still have to be linked with a <link> tag

printing all contents of array in C#

If you do not want to use the Array function.

public class GArray
{
    int[] mainArray;
    int index;
    int i = 0;

    public GArray()
    {
        index = 0;
        mainArray = new int[4];
    }
    public void add(int addValue)
    {

        if (index == mainArray.Length)
        {
            int newSize = index * 2;
            int[] temp = new int[newSize];
            for (int i = 0; i < mainArray.Length; i++)
            {
                temp[i] = mainArray[i];
            }
            mainArray = temp;
        }
        mainArray[index] = addValue;
        index++;

    }
    public void print()
    {
        for (int i = 0; i < index; i++)
        {
            Console.WriteLine(mainArray[i]);
        }
    }
 }
 class Program
{
    static void Main(string[] args)
    {
        GArray myArray = new GArray();
        myArray.add(1);
        myArray.add(2);
        myArray.add(3);
        myArray.add(4);
        myArray.add(5);
        myArray.add(6);
        myArray.print();
        Console.ReadKey();
    }
}

How do you list all triggers in a MySQL database?

I hope following code will give you more information.

select * from information_schema.triggers where 
information_schema.triggers.trigger_schema like '%your_db_name%'

This will give you total 22 Columns in MySQL version: 5.5.27 and Above

TRIGGER_CATALOG 
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA 
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED 
SQL_MODE
DEFINER 
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION

Check if a value is within a range of numbers

If you must use a regexp (and really, you shouldn't!) this will work:

/^0\.00([1-8]\d*|90*)$/

should work, i.e.

  • ^ nothing before,
  • followed by 0.00 (nb: backslash escape for the . character)
  • followed by 1 through 8, and any number of additional digits
  • or 9, followed by any number of zeroes
  • $: followed by nothing else

CFNetwork SSLHandshake failed iOS 9

This error was showing up in the logs sometimes when I was using a buggy/crashy Cordova iOS version. It went away when I upgraded or downgraded cordova iOS.

The server I was connecting to was using TLSv1.2 SSL so I knew that was not the problem.

Bundling data files with PyInstaller (--onefile)

Perhaps i missed a step or did something wrong but the methods which are above, didn't bundle data files with PyInstaller into one exe file. Let me share the steps what i have done.

  1. step:Write one of the above methods into your py file with importing sys and os modules. I tried both of them. The last one is:

    def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        return os.path.join(base_path, relative_path)
    
  2. step: Write, pyi-makespec file.py, to the console, to create a file.spec file.

  3. step: Open, file.spec with Notepad++ to add the data files like below:

    a = Analysis(['C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.py'],
                 pathex=['C:\\Users\\TCK\\Desktop\\Projeler'],
                 binaries=[],
                 datas=[],
                 hiddenimports=[],
                 hookspath=[],
                 runtime_hooks=[],
                 excludes=[],
                 win_no_prefer_redirects=False,
                 win_private_assemblies=False,
                 cipher=block_cipher)
    #Add the file like the below example
    a.datas += [('Converter-GUI.ico', 'C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico', 'DATA')]
    pyz = PYZ(a.pure, a.zipped_data,
         cipher=block_cipher)
    exe = EXE(pyz,
              a.scripts,
              exclude_binaries=True,
              name='Converter-GUI',
              debug=False,
              strip=False,
              upx=True,
              #Turn the console option False if you don't want to see the console while executing the program.
              console=False,
              #Add an icon to the program.
              icon='C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico')
    
    coll = COLLECT(exe,
                   a.binaries,
                   a.zipfiles,
                   a.datas,
                   strip=False,
                   upx=True,
                   name='Converter-GUI')
    
  4. step: I followed the above steps, then saved the spec file. At last opened the console and write, pyinstaller file.spec (in my case, file=Converter-GUI).

Conclusion: There's still more than one file in the dist folder.

Note: I'm using Python 3.5.

EDIT: Finally it works with Jonathan Reinhart's method.

  1. step: Add the below codes to your python file with importing sys and os.

    def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
        base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
        return os.path.join(base_path, relative_path)
    
  2. step: Call the above function with adding the path of your file:

    image_path = resource_path("Converter-GUI.ico")
    
  3. step: Write the above variable that call the function to where your codes need the path. In my case it's:

        self.window.iconbitmap(image_path)
    
  4. step: Open the console in the same directory of your python file, write the codes like below:

        pyinstaller --onefile your_file.py
    
  5. step: Open the .spec file of the python file and append the a.datas array and add the icon to the exe class, which was given above before the edit in 3'rd step.
  6. step: Save and exit the path file. Go to your folder which include the spec and py file. Open again the console window and type the below command:

        pyinstaller your_file.spec
    

After the 6. step your one file is ready to use.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

How to display an image from a path in asp.net MVC 4 and Razor view?

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>

NuGet: 'X' already has a dependency defined for 'Y'

I was getting the issue 'Newtonsoft.Json' already has a dependency defined for 'Microsoft.CSharp' on the TeamCity build server. I changed the "Update Mode" of the Nuget Installer build step from solution file to packages.config and NuGet.exe to the latest version (I had 3.5.0) and it worked !!

Getting full JS autocompletion under Sublime Text

There are three approaches

  • Use SublimeCodeIntel plug-in

  • Use CTags plug-in

  • Generate .sublime-completion file manually

Approaches are described in detail in this blog post (of mine): http://opensourcehacker.com/2013/03/04/javascript-autocompletions-and-having-one-for-sublime-text-2/

Tooltips with Twitter Bootstrap

Simple use of this:

<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip">
   tooltip
</a>

Using jQuery:

$(document).ready(function(){
    $('#mytooltip').tooltip();
});

You can left side of tooltip u can simple add this->data-placement="left"

<a href="#" id="mytooltip" class="btn btn-praimary" data-toggle="tooltip" title="my tooltip" data-placement="left">tooltip</a>

Viewing unpushed Git commits

All the other answers talk about "upstream" (the branch you pull from).
But a local branch can push to a different branch than the one it pulls from.

master might not push to the remote tracking branch "origin/master".
The upstream branch for master might be origin/master, but it could push to the remote tracking branch origin/xxx or even anotherUpstreamRepo/yyy.
Those are set by branch.*.pushremote for the current branch along with the global remote.pushDefault value.

It is that remote-tracking branch which counts when seeking unpushed commits: the one that tracks the branch at the remote where the local branch would be pushed to.
The branch at the remote can be, again, origin/xxx or even anotherUpstreamRepo/yyy.

Git 2.5+ (Q2 2015) introduces a new shortcut for that: <branch>@{push}

See commit 29bc885, commit 3dbe9db, commit adfe5d0, commit 48c5847, commit a1ad0eb, commit e291c75, commit 979cb24, commit 1ca41a1, commit 3a429d0, commit a9f9f8c, commit 8770e6f, commit da66b27, commit f052154, commit 9e3751d, commit ee2499f [all from 21 May 2015], and commit e41bf35 [01 May 2015] by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit c4a8354, 05 Jun 2015)

Commit adfe5d0 explains:

sha1_name: implement @{push} shorthand

In a triangular workflow, each branch may have two distinct points of interest: the @{upstream} that you normally pull from, and the destination that you normally push to. There isn't a shorthand for the latter, but it's useful to have.

For instance, you may want to know which commits you haven't pushed yet:

git log @{push}..

Or as a more complicated example, imagine that you normally pull changes from origin/master (which you set as your @{upstream}), and push changes to your own personal fork (e.g., as myfork/topic).
You may push to your fork from multiple machines, requiring you to integrate the changes from the push destination, rather than upstream.
With this patch, you can just do:

git rebase @{push}

rather than typing out the full name.

Commit 29bc885 adds:

for-each-ref: accept "%(push)" format

Just as we have "%(upstream)" to report the "@{upstream}" for each ref, this patch adds "%(push)" to match "@{push}".
It supports the same tracking format modifiers as upstream (because you may want to know, for example, which branches have commits to push).

If you want to see how many commit your local branches are ahead/behind compared to the branch you are pushing to:

git for-each-ref --format="%(refname:short) %(push:track)" refs/heads

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

You cannot supply system properties to the jarsigner.exe tool, unfortunately.

I have submitted defect 7177232, referencing @eckes' defect 7127374 and explaining why it was closed in error.

My defect is specifically about the impact on the jarsigner tool, but perhaps it will lead them to reopening the other defect and addressing the issue properly.

UPDATE: Actually, it turns out that you CAN supply system properties to the Jarsigner tool, it's just not in the help message. Use jarsigner -J-Djsse.enableSNIExtension=false

How to open select file dialog via js?

READY TO USE FUNCTION (using Promise)

/**
 * Select file(s).
 * @param {String} contentType The content type of files you wish to select. For instance "image/*" to select all kinds of images.
 * @param {Boolean} multiple Indicates if the user can select multiples file.
 * @returns {Promise<File|File[]>} A promise of a file or array of files in case the multiple parameter is true.
 */
function (contentType, multiple){
    return new Promise(resolve => {
        let input = document.createElement('input');
        input.type = 'file';
        input.multiple = multiple;
        input.accept = contentType;

        input.onchange = _ => {
            let files = Array.from(input.files);
            if (multiple)
                resolve(files);
            else
                resolve(files[0]);
        };

        input.click();
    });
}

TEST IT

_x000D_
_x000D_
// Content wrapper element_x000D_
let contentElement = document.getElementById("content");_x000D_
_x000D_
// Button callback_x000D_
async function onButtonClicked(){_x000D_
    let files = await selectFile("image/*", true);_x000D_
    contentElement.innerHTML = files.map(file => `<img src="${URL.createObjectURL(file)}" style="width: 100px; height: 100px;">`).join('');_x000D_
}_x000D_
_x000D_
// ---- function definition ----_x000D_
function selectFile (contentType, multiple){_x000D_
    return new Promise(resolve => {_x000D_
        let input = document.createElement('input');_x000D_
        input.type = 'file';_x000D_
        input.multiple = multiple;_x000D_
        input.accept = contentType;_x000D_
_x000D_
        input.onchange = _ => {_x000D_
            let files = Array.from(input.files);_x000D_
            if (multiple)_x000D_
                resolve(files);_x000D_
            else_x000D_
                resolve(files[0]);_x000D_
        };_x000D_
_x000D_
        input.click();_x000D_
    });_x000D_
}
_x000D_
<button onclick="onButtonClicked()">Select images</button>_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

Error in installation a R package

There could be a few things happening here. Start by first figuring out your library location:

Sys.getenv("R_LIBS_USER")

or

.libPaths()

We already know yours from the info you gave: C:\Program Files\R\R-3.0.1\library

I believe you have a file in there called: 00LOCK. From ?install.packages:

Note that it is possible for the package installation to fail so badly that the lock directory is not removed: this inhibits any further installs to the library directory (or for --pkglock, of the package) until the lock directory is removed manually.

You need to delete that file. If you had the pacman package installed you could have simply used p_unlock() and the 00LOCK file is removed. You can't install pacman now until the 00LOCK file is removed.

To install pacman use:

install.packages("pacman")

There may be a second issue. This is where you somehow corrupted MASS. This can occur, in my experience, if you try to update a package while it is in use in another R session. I'm sure there's other ways to cause this as well. To solve this problem try:

  1. Close out of all R sessions (use task manager to ensure you're truly R session free) Ctrl + Alt + Delete
  2. Go to your library location Sys.getenv("R_LIBS_USER"). In your case this is: C:\Program Files\R\R-3.0.1\library
  3. Manually delete the MASS package
  4. Fire up a vanilla session of R
  5. Install MASS via install.packages("MASS")

If any of this works please let me know what worked.

configure: error: C compiler cannot create executables

I furiously read all of this page, hoping to find a solution for:

"configure: error: C compiler cannot create executables"

In the end nothing worked, because my problem was a "typing" one, and was related to CFLAGS. In my .bash_profile file I had:

export ARM_ARCH="arm64”
export CFLAGS="-arch ${ARM_ARCH}"

As you can observe --- export ARM_ARCH="arm64” --- the last quote sign is not the same with the first quote sign. The first one ( " ) is legal while the second one ( ” ) is not.
This happended because I made the mistake to use TextEdit (I'm working under MacOS), and this is apparently a feature called SmartQuotes: the quote sign CHANGES BY ITSELF TO THE ILLEGAL STYLE whenever you edit something just next to it.
Lesson learned: use a proper text editor...

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

How to regex in a MySQL query

I think you can use REGEXP instead of LIKE

SELECT trecord FROM `tbl` WHERE (trecord REGEXP '^ALA[0-9]')

How to get the class of the clicked element?

I saw this question so I thought I might expand on it a little more. This is an expansion of the idea that @SteveFenton had. Instead of binding a click event to each li element, it would be more efficient to delegate the events from the ul down.

For jQuery 1.7 and higher

$("ul.tabs").on('click', 'li', function(e) {
   alert($(this).attr("class"));
});

Documentation: .on()

For jQuery 1.4.2 - 1.7

$("ul.tabs").delegate('li', 'click', function(e) {
   alert($(this).attr("class"));
});

Documentation: .delegate()

As a last resort for jQuery 1.3 - 1.4

$("ul.tabs").children('li').live('click', function(e) {
   alert($(this).attr("class"));
});

or

$("ul.tabs > li").live('click', function(e) {
   alert($(this).attr("class"));
});

Documentation: .live()

How can I use std::maps with user-defined types as key?

You need to define operator < for the Class1.

Map needs to compare the values using operator < and hence you need to provide the same when user defined class are used as key.

class Class1
{
public:
    Class1(int id);

    bool operator <(const Class1& rhs) const
    {
        return id < rhs.id;
    }
private:
    int id;
};

super() in Java

For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

public class DeveloperSteps extends ScenarioSteps {

public DeveloperSteps(Pages pages) {
    super(pages);
}........

How do I add an existing directory tree to a project in Visual Studio?

In Visual Studio 2017, you switch between Solution View and Folder View back and forth. I think this is a better option, because it will keep the solution cleaner. I use this to edit .gitignore, .md files, etc.

Solution View and Folder View

Running python script inside ipython

How to run a script in Ipython

import os
filepath='C:\\Users\\User\\FolderWithPythonScript' 
os.chdir(filepath)
%run pyFileInThatFilePath.py

That should do it

What GRANT USAGE ON SCHEMA exactly do?

GRANTs on different objects are separate. GRANTing on a database doesn't GRANT rights to the schema within. Similiarly, GRANTing on a schema doesn't grant rights on the tables within.

If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table.

The rights tests are done in order:

Do you have `USAGE` on the schema? 
    No:  Reject access. 
    Yes: Do you also have the appropriate rights on the table? 
        No:  Reject access. 
        Yes: Check column privileges.

Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public, which every user/group is a member of. So everyone already has usage on that schema.

The phrase:

(assuming that the objects' own privilege requirements are also met)

Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.

It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists.

If you were to grant world-read rights on the file (mode rw-r--r--) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.

If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.

You need to set both permissions for people to actually be able to view the file.

Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table.

(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECTing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)

Pass C# ASP.NET array to Javascript array

For array of objects:

var array= JSON.parse('@Newtonsoft.Json.JsonConvert.SerializeObject(numbers)'.replace(/&quot;/g, "\""));

For array of int:

 var array= JSON.parse('@Newtonsoft.Json.JsonConvert.SerializeObject(numbers)');

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

Check if cookies are enabled

A transparent, clean and simple approach, checking cookies availability with PHP and taking advantage of AJAX transparent redirection, hence not triggering a page reload. It doesn't require sessions either.

Client-side code (JavaScript)

function showCookiesMessage(cookiesEnabled) {
    if (cookiesEnabled == 'true')
        alert('Cookies enabled');
    else
        alert('Cookies disabled');
}

$(document).ready(function() {
    var jqxhr = $.get('/cookiesEnabled.php');
    jqxhr.done(showCookiesMessage);
});

(JQuery AJAX call can be replaced with pure JavaScript AJAX call)

Server-side code (PHP)

if (isset($_COOKIE['cookieCheck'])) {
    echo 'true';
} else {
    if (isset($_GET['reload'])) {
        echo 'false';
    } else {
        setcookie('cookieCheck', '1', time() + 60);
        header('Location: ' . $_SERVER['PHP_SELF'] . '?reload');
        exit();
    }
}

First time the script is called, the cookie is set and the script tells the browser to redirect to itself. The browser does it transparently. No page reload takes place because it's done within an AJAX call scope.

The second time, when called by redirection, if the cookie is received, the script responds an HTTP 200 (with string "true"), hence the showCookiesMessage function is called.

If the script is called for the second time (identified by the "reload" parameter) and the cookie is not received, it responds an HTTP 200 with string "false" -and the showCookiesMessage function gets called.

ReactJS and images in public folder

You Could also use this.. it works assuming 'yourimage.jpg' is in your public folder.

<img src={'./yourimage.jpg'}/>

UIButton: set image for selected-highlighted state

I found the solution: need to add addition line

[button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateSelected | UIControlStateHighlighted];

How do I properly clean up Excel interop objects?

UPDATE: Added C# code, and link to Windows Jobs

I spent sometime trying to figure out this problem, and at the time XtremeVBTalk was the most active and responsive. Here is a link to my original post, Closing an Excel Interop process cleanly, even if your application crashes. Below is a summary of the post, and the code copied to this post.

  • Closing the Interop process with Application.Quit() and Process.Kill() works for the most part, but fails if the applications crashes catastrophically. I.e. if the app crashes, the Excel process will still be running loose.
  • The solution is to let the OS handle the cleanup of your processes through Windows Job Objects using Win32 calls. When your main application dies, the associated processes (i.e. Excel) will get terminated as well.

I found this to be a clean solution because the OS is doing real work of cleaning up. All you have to do is register the Excel process.

Windows Job Code

Wraps the Win32 API Calls to register Interop processes.

public enum JobObjectInfoType
{
    AssociateCompletionPortInformation = 7,
    BasicLimitInformation = 2,
    BasicUIRestrictions = 4,
    EndOfJobTimeInformation = 6,
    ExtendedLimitInformation = 9,
    SecurityLimitInformation = 5,
    GroupInformation = 11
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
    public int nLength;
    public IntPtr lpSecurityDescriptor;
    public int bInheritHandle;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
    public Int64 PerProcessUserTimeLimit;
    public Int64 PerJobUserTimeLimit;
    public Int16 LimitFlags;
    public UInt32 MinimumWorkingSetSize;
    public UInt32 MaximumWorkingSetSize;
    public Int16 ActiveProcessLimit;
    public Int64 Affinity;
    public Int16 PriorityClass;
    public Int16 SchedulingClass;
}

[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
    public UInt64 ReadOperationCount;
    public UInt64 WriteOperationCount;
    public UInt64 OtherOperationCount;
    public UInt64 ReadTransferCount;
    public UInt64 WriteTransferCount;
    public UInt64 OtherTransferCount;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
    public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
    public IO_COUNTERS IoInfo;
    public UInt32 ProcessMemoryLimit;
    public UInt32 JobMemoryLimit;
    public UInt32 PeakProcessMemoryUsed;
    public UInt32 PeakJobMemoryUsed;
}

public class Job : IDisposable
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    static extern IntPtr CreateJobObject(object a, string lpName);

    [DllImport("kernel32.dll")]
    static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

    private IntPtr m_handle;
    private bool m_disposed = false;

    public Job()
    {
        m_handle = CreateJobObject(null, null);

        JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
        info.LimitFlags = 0x2000;

        JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
        extendedInfo.BasicLimitInformation = info;

        int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
        IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
        Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

        if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
            throw new Exception(string.Format("Unable to set information.  Error: {0}", Marshal.GetLastWin32Error()));
    }

    #region IDisposable Members

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    #endregion

    private void Dispose(bool disposing)
    {
        if (m_disposed)
            return;

        if (disposing) {}

        Close();
        m_disposed = true;
    }

    public void Close()
    {
        Win32.CloseHandle(m_handle);
        m_handle = IntPtr.Zero;
    }

    public bool AddProcess(IntPtr handle)
    {
        return AssignProcessToJobObject(m_handle, handle);
    }

}

Note about Constructor code

  • In the constructor, the info.LimitFlags = 0x2000; is called. 0x2000 is the JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE enum value, and this value is defined by MSDN as:

Causes all processes associated with the job to terminate when the last handle to the job is closed.

Extra Win32 API Call to get the Process ID (PID)

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

Using the code

    Excel.Application app = new Excel.ApplicationClass();
    Job job = new Job();
    uint pid = 0;
    Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);
    job.AddProcess(Process.GetProcessById((int)pid).Handle);

How to use order by with union all in sql?

You don't really need to have parenthesis. You can sort directly:

SELECT *, 1 AS RN FROM TABLE_A
UNION ALL 
SELECT *, 2 AS RN FROM TABLE_B
ORDER BY RN, COLUMN_1

How to print the ld(linker) search path

The question is tagged Linux, but maybe this works as well under Linux?

gcc -Xlinker -v

Under Mac OS X, this prints:

@(#)PROGRAM:ld  PROJECT:ld64-224.1
configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 armv6m armv7m armv7em
Library search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib
Framework search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/
[...]

The -Xlinker option of gcc above just passes -v to ld. However:

ld -v

doesn't print the search path.

How can I detect the touch event of an UIImageView?

Add gesture on that view. Add an image into that view, and then it would be detecting a gesture on the image too. You could try with the delegate method of the touch event. Then in that case it also might be detecting.

Restart node upon changing a file

node-dev

node-dev is great alternative to both nodemon and supervisor for developers who like to get growl (or libnotify) notifications on their desktop whenever the server restarts or when there is an error or change occur in file.

Installation:

npm install -g node-dev

Use node-dev, instead of node:

node-dev app.js

Notification on Changing file so server start automatically

enter image description here

console out put

enter image description here

Add CSS to <head> with JavaScript?

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

<head>
  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  </script>
  # other stuff..
</head>

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!

http://jsbin.com/oqede3/edit

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Tapestry pages and components are simple POJO's(Plain Old Java Object) consisting of getters and setters for easy access to Java language features.

How to create a date and time picker in Android?

You can use one of DatePicker library wdullaer/MaterialDateTimePicker

  • First show DatePicker.

    private void showDatePicker() {
    Calendar now = Calendar.getInstance();
    DatePickerDialog dpd = DatePickerDialog.newInstance(
            HomeActivity.this,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
    );
    dpd.show(getFragmentManager(), "Choose Date:");
    }
    
  • Then onDateSet callback store date & show TimePicker

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, monthOfYear, dayOfMonth);
    filter.setDate(cal.getTime());
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            showTimePicker();
        }
    },500);
    }
    
  • On onTimeSet callback store time

     @Override
     public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
    Calendar cal = Calendar.getInstance();
    if(filter.getDate()!=null)
        cal.setTime(filter.getDate());
    cal.set(Calendar.HOUR_OF_DAY,hourOfDay);
    cal.set(Calendar.MINUTE,minute);
    }
    

jquery getting post action url

Clean and Simple:

$('#signup').submit(function(event) {

      alert(this.action);
});

How to decode viewstate

This is somewhat "native" .NET way of converting ViewState from string into StateBag Code is below:

public static StateBag LoadViewState(string viewState)
    {
        System.Web.UI.Page converterPage = new System.Web.UI.Page();
        HiddenFieldPageStatePersister persister = new HiddenFieldPageStatePersister(new Page());
        Type utilClass = typeof(System.Web.UI.BaseParser).Assembly.GetType("System.Web.UI.Util");
        if (utilClass != null && persister != null)
        {
            MethodInfo method = utilClass.GetMethod("DeserializeWithAssert", BindingFlags.NonPublic | BindingFlags.Static);
            if (method != null)
            {
                PropertyInfo formatterProperty = persister.GetType().GetProperty("StateFormatter", BindingFlags.NonPublic | BindingFlags.Instance);
                if (formatterProperty != null)
                {
                    IStateFormatter formatter = (IStateFormatter)formatterProperty.GetValue(persister, null);
                    if (formatter != null)
                    {
                        FieldInfo pageField = formatter.GetType().GetField("_page", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (pageField != null)
                        {
                            pageField.SetValue(formatter, null);
                            try
                            {
                                Pair pair = (Pair)method.Invoke(null, new object[] { formatter, viewState });
                                if (pair != null)
                                {
                                    MethodInfo loadViewState = converterPage.GetType().GetMethod("LoadViewStateRecursive", BindingFlags.Instance | BindingFlags.NonPublic);
                                    if (loadViewState != null)
                                    {
                                        FieldInfo postback = converterPage.GetType().GetField("_isCrossPagePostBack", BindingFlags.NonPublic | BindingFlags.Instance);
                                        if (postback != null)
                                        {
                                            postback.SetValue(converterPage, true);
                                        }
                                        FieldInfo namevalue = converterPage.GetType().GetField("_requestValueCollection", BindingFlags.NonPublic | BindingFlags.Instance);
                                        if (namevalue != null)
                                        {
                                            namevalue.SetValue(converterPage, new NameValueCollection());
                                        }
                                        loadViewState.Invoke(converterPage, new object[] { ((Pair)((Pair)pair.First).Second) });
                                        FieldInfo viewStateField = typeof(Control).GetField("_viewState", BindingFlags.NonPublic | BindingFlags.Instance);
                                        if (viewStateField != null)
                                        {
                                            return (StateBag)viewStateField.GetValue(converterPage);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ex != null)
                                {

                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

WordPress: get author info from post id

<?php
  $field = 'display_name';
  the_author_meta($field);
?>

Valid values for the $field parameter include:

  • admin_color
  • aim
  • comment_shortcuts
  • description
  • display_name
  • first_name
  • ID
  • jabber
  • last_name
  • nickname
  • plugins_last_view
  • plugins_per_page
  • rich_editing
  • syntax_highlighting
  • user_activation_key
  • user_description
  • user_email
  • user_firstname
  • user_lastname
  • user_level
  • user_login
  • user_nicename
  • user_pass
  • user_registered
  • user_status
  • user_url
  • yim

Selenium wait until document is ready

Here's my attempt at a completely generic solution, in Python:

First, a generic "wait" function (use a WebDriverWait if you like, I find them ugly):

def wait_for(condition_function):
    start_time = time.time()
    while time.time() < start_time + 3:
        if condition_function():
            return True
        else:
            time.sleep(0.1)
    raise Exception('Timeout waiting for {}'.format(condition_function.__name__))

Next, the solution relies on the fact that selenium records an (internal) id-number for all elements on a page, including the top-level <html> element. When a page refreshes or loads, it gets a new html element with a new ID.

So, assuming you want to click on a link with text "my link" for example:

old_page = browser.find_element_by_tag_name('html')

browser.find_element_by_link_text('my link').click()

def page_has_loaded():
    new_page = browser.find_element_by_tag_name('html')
    return new_page.id != old_page.id

wait_for(page_has_loaded)

For more Pythonic, reusable, generic helper, you can make a context manager:

from contextlib import contextmanager

@contextmanager
def wait_for_page_load(browser):
    old_page = browser.find_element_by_tag_name('html')

    yield

    def page_has_loaded():
        new_page = browser.find_element_by_tag_name('html')
        return new_page.id != old_page.id

    wait_for(page_has_loaded)

And then you can use it on pretty much any selenium interaction:

with wait_for_page_load(browser):
    browser.find_element_by_link_text('my link').click()

I reckon that's bulletproof! What do you think?

More info in a blog post about it here

Django values_list vs values

You can get the different values with:

set(Article.objects.values_list('comment_id', flat=True))

Python Turtle, draw text with on screen with larger font

You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..

But another question is this: How do you set the color of the text You write?

Answer: You use the turtle.color() method or turtle.fillcolor(), like this:

turtle.fillcolor("blue")

or just:

turtle.color("orange")

These calls must come before the turtle.write() command..

Open terminal here in Mac OS finder

I created a bundle with 3 apps for the finder toolbar. The other two apps do:

  • open Textmate with the current selection
  • open GitX with the current folder

For more information see here: http://nslog.de/posts/71

Foreign keys in mongo?

We can define the so-called foreign key in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: ['bio101', 'bio102']   // <= ids of the courses
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

The courses field contains _ids of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of student Jane, we need to perform another operation to retrieve the course document via _id.

If the course bio101 is removed, we need to perform another operation to update the courses field in the student document.

More: MongoDB Schema Design

The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:

Embedded document

  1. Suitable for one-to-few.
  2. Advantage: no need to perform additional queries to another document.
  3. Disadvantage: cannot manage the entity of embedded documents individually.

Example:

student
{
  name: 'Kate Monster',
  addresses : [
     { street: '123 Sesame St', city: 'Anytown', cc: 'USA' },
     { street: '123 Avenue Q', city: 'New York', cc: 'USA' }
  ]
}

Child referencing

Like the student/course example above.

Parent referencing

Suitable for one-to-squillions, such as log messages.

host
{
    _id : ObjectID('AAAB'),
    name : 'goofy.example.com',
    ipaddr : '127.66.66.66'
}

logmsg
{
    time : ISODate("2014-03-28T09:42:41.382Z"),
    message : 'cpu is on fire!',
    host: ObjectID('AAAB')       // Reference to the Host document
}

Virtually, a host is the parent of a logmsg. Referencing to the host id saves much space given that the log messages are squillions.

References:

  1. 6 Rules of Thumb for MongoDB Schema Design: Part 1
  2. 6 Rules of Thumb for MongoDB Schema Design: Part 2
  3. 6 Rules of Thumb for MongoDB Schema Design: Part 3
  4. Model One-to-Many Relationships with Document References

How to provide a mysql database connection in single file in nodejs

You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:

every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

You could create db.js:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database : 'chat'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

Then in your app.js, you would simply require it.

var express = require('express');
var app = express();
var db = require('./db');

app.get('/save',function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    db.query('INSERT INTO messages SET ?', post, function(err, result) {
      if (err) throw err;
    });
});

server.listen(3000);

This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db thanks to how node require works :)

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

(Just assumption, less info of Exception stacktrace)

I think, this line, incercari.setText(valIncercari); throws Exception because valIncercari is int

So it should be,

incercari.setText(valIncercari+"");

Or

incercari.setText(Integer.toString(valIncercari));

How to close the command line window after running a batch file?

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

Angular 2 Dropdown Options Default Value

Step: 1 Create Properties declare class

export class Task {
    title: string;
    priority: Array<any>;
    comment: string;

    constructor() {
        this.title      = '';
        this.priority   = [];
        this.comment    = '';
     }
}

Stem: 2 Your Component Class

import { Task } from './task';

export class TaskComponent implements OnInit {
  priorityList: Array<any> = [
    { value: 0, label: '?' },
    { value: 1, label: '?' },
    { value: 2, label: '??' },
    { value: 3, label: '???' },
    { value: 4, label: '????' },
    { value: 5, label: '?????' }
  ];
  taskModel: Task           = new Task();

  constructor(private taskService: TaskService) { }
  ngOnInit() {
    this.taskModel.priority     = [3]; // index number
  }
}

Step: 3 View File .html

<select class="form-control" name="priority" [(ngModel)]="taskModel.priority"  required>
    <option *ngFor="let list of priorityList" [value]="list.value">
      {{list.label}}
    </option>
</select>

Output:

enter image description here

How to link to a <div> on another page?

You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.

This is can done in this way:

add hash in the url of next_page : example.com#hashkey

$( document ).ready(function() {

  ##get hash code at next page
  var hashcode = window.location.hash;

  ## move page to any specific position of next page(let that is div with id "hashcode")
  $('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');

});

PostgreSQL: how to convert from Unix epoch to date?

The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:

SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;

For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214

How can I convert string to double in C++?

If it is a c-string (null-terminated array of type char), you can do something like:

#include <stdlib.h>
char str[] = "3.14159";
double num = atof(str);

If it is a C++ string, just use the c_str() method:

double num = atof( cppstr.c_str() );

atof() will convert the string to a double, returning 0 on failure. The function is documented here: http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html

How to convert <font size="10"> to px?

This cannot be answered that easily. It depends on the font used and the points per inch (ppi). This should give an overview of the problem.

Set today's date as default date in jQuery UI datepicker

try this:

$("#mydate").datepicker("setDate",'1d');

How to style CSS role

please use :

 #content[role=main]{
   your style here
}

MySQL JOIN ON vs USING?

Thought I would chip in here with when I have found ON to be more useful than USING. It is when OUTER joins are introduced into queries.

ON benefits from allowing the results set of the table that a query is OUTER joining onto to be restricted while maintaining the OUTER join. Attempting to restrict the results set through specifying a WHERE clause will, effectively, change the OUTER join into an INNER join.

Granted this may be a relative corner case. Worth putting out there though.....

For example:

CREATE TABLE country (
   countryId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
   country varchar(50) not null,
  UNIQUE KEY countryUIdx1 (country)
) ENGINE=InnoDB;

insert into country(country) values ("France");
insert into country(country) values ("China");
insert into country(country) values ("USA");
insert into country(country) values ("Italy");
insert into country(country) values ("UK");
insert into country(country) values ("Monaco");


CREATE TABLE city (
  cityId int(10) unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,
  countryId int(10) unsigned not null,
  city varchar(50) not null,
  hasAirport boolean not null default true,
  UNIQUE KEY cityUIdx1 (countryId,city),
  CONSTRAINT city_country_fk1 FOREIGN KEY (countryId) REFERENCES country (countryId)
) ENGINE=InnoDB;


insert into city (countryId,city,hasAirport) values (1,"Paris",true);
insert into city (countryId,city,hasAirport) values (2,"Bejing",true);
insert into city (countryId,city,hasAirport) values (3,"New York",true);
insert into city (countryId,city,hasAirport) values (4,"Napoli",true);
insert into city (countryId,city,hasAirport) values (5,"Manchester",true);
insert into city (countryId,city,hasAirport) values (5,"Birmingham",false);
insert into city (countryId,city,hasAirport) values (3,"Cincinatti",false);
insert into city (countryId,city,hasAirport) values (6,"Monaco",false);

-- Gah. Left outer join is now effectively an inner join 
-- because of the where predicate
select *
from country left join city using (countryId)
where hasAirport
; 

-- Hooray! I can see Monaco again thanks to 
-- moving my predicate into the ON
select *
from country co left join city ci on (co.countryId=ci.countryId and ci.hasAirport)
; 

Using AES encryption in C#

I've recently had to bump up against this again in my own project - and wanted to share the somewhat simpler code that I've been using, as this question and series of answers kept coming up in my searches.

I'm not going to get into the security concerns around how often to update things like your Salt and Initialization Vector - that's a topic for a security forum, and there are some great resources out there to look at. This is simply a block of code to implement AesManaged in C#.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Your.Namespace.Security {
    public static class Cryptography {
        #region Settings

        private static int _iterations = 2;
        private static int _keySize = 256;

        private static string _hash     = "SHA1";
        private static string _salt     = "aselrias38490a32"; // Random
        private static string _vector   = "8947az34awl34kjq"; // Random

        #endregion

        public static string Encrypt(string value, string password) {
            return Encrypt<AesManaged>(value, password);
        }
        public static string Encrypt<T>(string value, string password) 
                where T : SymmetricAlgorithm, new() {
            byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
            byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
            byte[] valueBytes = GetBytes<UTF8Encoding>(value);

            byte[] encrypted;
            using (T cipher = new T()) {
                PasswordDeriveBytes _passwordBytes = 
                    new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) {
                    using (MemoryStream to = new MemoryStream()) {
                        using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) {
                            writer.Write(valueBytes, 0, valueBytes.Length);
                            writer.FlushFinalBlock();
                            encrypted = to.ToArray();
                        }
                    }
                }
                cipher.Clear();
            }
            return Convert.ToBase64String(encrypted);
        }

        public static string Decrypt(string value, string password) {
            return Decrypt<AesManaged>(value, password);
        }
        public static string Decrypt<T>(string value, string password) where T : SymmetricAlgorithm, new() {
            byte[] vectorBytes = GetBytes<ASCIIEncoding>(_vector);
            byte[] saltBytes = GetBytes<ASCIIEncoding>(_salt);
            byte[] valueBytes = Convert.FromBase64String(value);

            byte[] decrypted;
            int decryptedByteCount = 0;

            using (T cipher = new T()) {
                PasswordDeriveBytes _passwordBytes = new PasswordDeriveBytes(password, saltBytes, _hash, _iterations);
                byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                try {
                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) {
                        using (MemoryStream from = new MemoryStream(valueBytes)) {
                            using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {
                                decrypted = new byte[valueBytes.Length];
                                decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                            }
                        }
                    }
                } catch (Exception ex) {
                    return String.Empty;
                }

                cipher.Clear();
            }
            return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
        }

    }
}

The code is very simple to use. It literally just requires the following:

string encrypted = Cryptography.Encrypt(data, "testpass");
string decrypted = Cryptography.Decrypt(encrypted, "testpass");

By default, the implementation uses AesManaged - but you could actually also insert any other SymmetricAlgorithm. A list of the available SymmetricAlgorithm inheritors for .NET 4.5 can be found at:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.aspx

As of the time of this post, the current list includes:

  • AesManaged
  • RijndaelManaged
  • DESCryptoServiceProvider
  • RC2CryptoServiceProvider
  • TripleDESCryptoServiceProvider

To use RijndaelManaged with the code above, as an example, you would use:

string encrypted = Cryptography.Encrypt<RijndaelManaged>(dataToEncrypt, password);
string decrypted = Cryptography.Decrypt<RijndaelManaged>(encrypted, password);

I hope this is helpful to someone out there.

Calling Python in Java?

It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.

Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.

see here how to use Python interpreter in Java.

Can I start the iPhone simulator without "Build and Run"?

The simulator is just an application, and as such you can run it like any other application.

To run the simulator straight from terminal prepend these locations with the open command

Xcode 7.x, 8.x, and 9.x

In Xcode 7.x, the iPhone Simulator has moved again: /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app.

Xcode 6.x

In Xcode 6.x, the iPhone Simulator has moved yet again, and now resides here: /Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app.


Xcode 4.x, 5.x

In Xcode 4.x (through 4.5 on Mountain Lion) and Xcode 5.0.x on Mavericks, it lives here: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/

In my version of Xcode (4.5.2), I find it quite convenient to use the Open Developer Tool menu from either the dock icon or the Xcode menu:

open iOS Simulator


Xcode 3.x

In Xcode 3.x, it lives here:

/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app


In some future version of Xcode, it will probably move again, it's a squirrelly little app.

Configure DataSource programmatically in Spring Boot

I customized Tomcat DataSource in Spring-Boot 2.

Dependency versions:

  • spring-boot: 2.1.9.RELEASE
  • tomcat-jdbc: 9.0.20

May be it will be useful for somebody.

application.yml

spring:
    datasource:
        driver-class-name: org.postgresql.Driver
        type: org.apache.tomcat.jdbc.pool.DataSource
        url: jdbc:postgresql://${spring.datasource.database.host}:${spring.datasource.database.port}/${spring.datasource.database.name}
        database:
            host: localhost
            port: 5432
            name: rostelecom
        username: postgres
        password: postgres
        tomcat:
            validation-query: SELECT 1
            validation-interval: 30000           
            test-on-borrow: true
            remove-abandoned: true
            remove-abandoned-timeout: 480
            test-while-idle: true
            time-between-eviction-runs-millis: 60000
            log-validation-errors: true
            log-abandoned: true

Java

@Bean
@Primary
@ConfigurationProperties("spring.datasource.tomcat")
public PoolConfiguration postgresDataSourceProperties() {
    return new PoolProperties();
}

@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
    PoolConfiguration properties = postgresDataSourceProperties();
    return new DataSource(properties);
}

The main reason why it had been done is several DataSources in application and one of them it is necessary to mark as a @Primary.

box-shadow on bootstrap 3 container

http://jsfiddle.net/Y93TX/2/

     @import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");

.row {
    height: 100px;
    background-color: green;
}
.container {
    margin-top: 50px;
    box-shadow: 0 0 30px black;
    padding:0 15px 0 15px;
}



    <div class="container">
        <div class="row">one</div>
        <div class="row">two</div>
        <div class="row">three</div>
    </div>
</body>

PHP send mail to multiple email addresses

Following code will do the task....

<?php

$contacts = array(
"[email protected]",
"[email protected]",
//....as many email address as you need
);

foreach($contacts as $contact) {

$to      =  $contact;
$subject = 'the subject';
$message = 'hello';
mail($to, $subject, $message, $headers);

}

?>

bundle install returns "Could not locate Gemfile"

  1. Make sure that the file name is Capitalized Gemfile instead of gemfile.
  2. Make sure you're in the same directory as the Gemfile.

Run local python script on remote server

I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).

So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec() built-in function on the decoded message. If I remember correctly my one-liner for this was:

stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]

It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.

The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.

For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.

Getting the error "Missing $ inserted" in LaTeX

I had the same problem - and I have read all these answers, but unfortunately none of them worked for me. Eventually I tried removing this line

%\usepackage[latin1]{inputenc}

and all errors disappeared.

Getting individual colors from a color map in matplotlib

I had precisely this problem, but I needed sequential plots to have highly contrasting color. I was also doing plots with a common sub-plot containing reference data, so I wanted the color sequence to be consistently repeatable.

I initially tried simply generating colors randomly, reseeding the RNG before each plot. This worked OK (commented-out in code below), but could generate nearly indistinguishable colors. I wanted highly contrasting colors, ideally sampled from a colormap containing all colors.

I could have as many as 31 data series in a single plot, so I chopped the colormap into that many steps. Then I walked the steps in an order that ensured I wouldn't return to the neighborhood of a given color very soon.

My data is in a highly irregular time series, so I wanted to see the points and the lines, with the point having the 'opposite' color of the line.

Given all the above, it was easiest to generate a dictionary with the relevant parameters for plotting the individual series, then expand it as part of the call.

Here's my code. Perhaps not pretty, but functional.

from matplotlib import cm
cmap = cm.get_cmap('gist_rainbow')  #('hsv') #('nipy_spectral')

max_colors = 31   # Constant, max mumber of series in any plot.  Ideally prime.
color_number = 0  # Variable, incremented for each series.

def restart_colors():
    global color_number
    color_number = 0
    #np.random.seed(1)

def next_color():
    global color_number
    color_number += 1
    #color = tuple(np.random.uniform(0.0, 0.5, 3))
    color = cmap( ((5 * color_number) % max_colors) / max_colors )
    return color

def plot_args():  # Invoked for each plot in a series as: '**(plot_args())'
    mkr = next_color()
    clr = (1 - mkr[0], 1 - mkr[1], 1 - mkr[2], mkr[3])  # Give line inverse of marker color
    return {
        "marker": "o",
        "color": clr,
        "mfc": mkr,
        "mec": mkr,
        "markersize": 0.5,
        "linewidth": 1,
    }

My context is JupyterLab and Pandas, so here's sample plot code:

restart_colors()  # Repeatable color sequence for every plot

fig, axs = plt.subplots(figsize=(15, 8))
plt.title("%s + T-meter"%name)

# Plot reference temperatures:
axs.set_ylabel("°C", rotation=0)
for s in ["T1", "T2", "T3", "T4"]:
    df_tmeter.plot(ax=axs, x="Timestamp", y=s, label="T-meter:%s" % s, **(plot_args()))

# Other series gets their own axis labels
ax2 = axs.twinx()
ax2.set_ylabel(units)

for c in df_uptime_sensors:
    df_uptime[df_uptime["UUID"] == c].plot(
        ax=ax2, x="Timestamp", y=units, label="%s - %s" % (units, c), **(plot_args())
    )

fig.tight_layout()
plt.show()

The resulting plot may not be the best example, but it becomes more relevant when interactively zoomed in. uptime + T-meter

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

ASP.NET Core Web API Authentication

As rightly said by previous posts, one of way is to implement a custom basic authentication middleware. I found the best working code with explanation in this blog: Basic Auth with custom middleware

I referred the same blog but had to do 2 adaptations:

  1. While adding the middleware in startup file -> Configure function, always add custom middleware before adding app.UseMvc().
  2. While reading the username, password from appsettings.json file, add static read only property in Startup file. Then read from appsettings.json. Finally, read the values from anywhere in the project. Example:

    public class Startup
    {
      public Startup(IConfiguration configuration)
      {
        Configuration = configuration;
      }
    
      public IConfiguration Configuration { get; }
      public static string UserNameFromAppSettings { get; private set; }
      public static string PasswordFromAppSettings { get; private set; }
    
      //set username and password from appsettings.json
      UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
      PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
    }
    

How to add an event after close the modal window?

$('.close').click(function() {
  //Code to be executed when close is clicked
  $('#result').html('yes,result');
});

Convert python datetime to timestamp in milliseconds

For those who searches for an answer without parsing and loosing milliseconds, given dt_obj is a datetime:

python3 only, elegant

int(dt_obj.timestamp() * 1000)

both python2 and python3 compatible:

import time

int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

I would recommend this to anyone looking for missing functionality:

http://code.google.com/p/ddr-ecma5/

It brings in most of the missing ecma5 functionality to older browers :)

Python: split a list based on a condition?

I'd take a 2-pass approach, separating evaluation of the predicate from filtering the list:

def partition(pred, iterable):
    xs = list(zip(map(pred, iterable), iterable))
    return [x[1] for x in xs if x[0]], [x[1] for x in xs if not x[0]]

What's nice about this, performance-wise (in addition to evaluating pred only once on each member of iterable), is that it moves a lot of logic out of the interpreter and into highly-optimized iteration and mapping code. This can speed up iteration over long iterables, as described in this answer.

Expressivity-wise, it takes advantage of expressive idioms like comprehensions and mapping.

Setting up an MS-Access DB for multi-user access

The correct way of building client/server Microsoft Access applications where the data is stored in a RDBMS is to use the Linked Table method. This ensures Data Isolation and Concurrency is maintained between the Microsoft Access client application and the RDBMS data with no additional and unnecessary programming logic and code which makes maintenance more difficult, and adds to development time.

see: http://claysql.blogspot.com/2014/08/normal-0-false-false-false-en-us-x-none.html

Save child objects automatically using JPA Hibernate

Following program describe how bidirectional relation work in hibernate.

When parent will save its list of child object will be auto save.

On Parent side:

    @Entity
    @Table(name="clients")
    public class Clients implements Serializable  {

         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)     
         @OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
          List<SmsNumbers> smsNumbers;
    }

And put the following annotation on the child side:

  @Entity
  @Table(name="smsnumbers")
  public class SmsNumbers implements Serializable {

     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     int id;
     String number;
     String status;
     Date reg_date;
     @ManyToOne
     @JoinColumn(name = "client_id")
     private Clients clients;

    // and getter setter.

 }

Main class:

 public static void main(String arr[])
 {
    Session session = HibernateUtil.openSession();
      //getting transaction object from session object
    session.beginTransaction();

    Clients cl=new Clients("Murali", "1010101010");
    SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
    SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
    SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
    List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
    lstSmsNumbers.add(sms1);
    lstSmsNumbers.add(sms2);
    lstSmsNumbers.add(sms3);
    cl.setSmsNumbers(lstSmsNumbers);
    session.saveOrUpdate(cl);
    session.getTransaction().commit(); 
    session.close();    

 }

How to make layout with rounded corners..?

Use CardView to get rounded edges for any layouts. Use card_view:cardCornerRadius="5dp" for cardview to get rounded layout edges.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:card_view="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

      <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="5dp">
          <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp"
                android:weightSum="1">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".3"
                    android:text="@string/quote_code"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".7"
                    android:text="@string/quote_details"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />
            </LinearLayout>
       </android.support.v7.widget.CardView>
   </LinearLayout>

How can I get the day of a specific date with PHP

$date = '2014-02-25';
date('D', strtotime($date));

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

If you want a "Null, empty or white space" check, you can avoid unnecessary string manipulation with LTRIM and RTRIM like this.

IF COALESCE(PATINDEX('%[^ ]%', @parameter), 0) > 0
    RAISERROR ...

How to stick text to the bottom of the page?

You might want to put the absolutely aligned div in a relatively aligned container - this way it will still be contained into the container rather than the browser window.

<div style="position: relative;background-color: blue; width: 600px; height: 800px;">    

    <div style="position: absolute; bottom: 5px; background-color: green">
    TEST (C) 2010
    </div>
</div>

Custom alert and confirm box in jquery

jQuery UI has it's own elements, but jQuery alone hasn't.

http://jqueryui.com/dialog/

Working example:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>


</body>
</html>

How can I show an element that has display: none in a CSS rule?

document.getElementById('mybox').style.display = "block";

Ignore invalid self-signed ssl certificate in node.js with https.request?

Adding to @Armand answer:

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0 e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0 (with great thanks to Juanra)

If you on windows usage:

set NODE_TLS_REJECT_UNAUTHORIZED=0

Thanks to: @weagle08

How do I remove trailing whitespace using a regular expression?

You can simply use it like this:

_x000D_
_x000D_
var regex = /( )/g;
_x000D_
_x000D_
_x000D_

Sample: click here

How can I select all elements without a given class in jQuery?

if (!$(row).hasClass("changed")) {
    // do your stuff
}

Can't create a docker image for COPY failed: stat /var/lib/docker/tmp/docker-builder error

Removing ./ from source path should resolve your issue:

 COPY test.json /home/test.json
 COPY test.py /home/test.py

How to get function parameter names/values dynamically?

I know this is an old question, but beginners have been copypasting this around as if this was good practice in any code. Most of the time, having to parse a function's string representation to use its parameter names just hides a flaw in the code's logic.

Parameters of a function are actually stored in an array-like object called arguments, where the first argument is arguments[0], the second is arguments[1] and so on. Writing parameter names in the parentheses can be seen as a shorthand syntax. This:

function doSomething(foo, bar) {
    console.log("does something");
}

...is the same as:

function doSomething() {
    var foo = arguments[0];
    var bar = arguments[1];

    console.log("does something");
}

The variables themselves are stored in the function's scope, not as properties in an object. There is no way to retrieve the parameter name through code as it is merely a symbol representing the variable in human-language.

I always considered the string representation of a function as a tool for debugging purposes, especially because of this arguments array-like object. You are not required to give names to the arguments in the first place. If you try parsing a stringified function, it doesn't actually tell you about extra unnamed parameters it might take.

Here's an even worse and more common situation. If a function has more than 3 or 4 arguments, it might be logical to pass it an object instead, which is easier to work with.

function saySomething(obj) {
  if(obj.message) console.log((obj.sender || "Anon") + ": " + obj.message);
}

saySomething({sender: "user123", message: "Hello world"});

In this case, the function itself will be able to read through the object it receives and look for its properties and get both their names and values, but trying to parse the string representation of the function would only give you "obj" for parameters, which isn't useful at all.

Chrome sendrequest error: TypeError: Converting circular structure to JSON

I resolve this problem on NodeJS like this:

var util = require('util');

// Our circular object
var obj = {foo: {bar: null}, a:{a:{a:{a:{a:{a:{a:{hi: 'Yo!'}}}}}}}};
obj.foo.bar = obj;

// Generate almost valid JS object definition code (typeof string)
var str = util.inspect(b, {depth: null});

// Fix code to the valid state (in this example it is not required, but my object was huge and complex, and I needed this for my case)
str = str
    .replace(/<Buffer[ \w\.]+>/ig, '"buffer"')
    .replace(/\[Function]/ig, 'function(){}')
    .replace(/\[Circular]/ig, '"Circular"')
    .replace(/\{ \[Function: ([\w]+)]/ig, '{ $1: function $1 () {},')
    .replace(/\[Function: ([\w]+)]/ig, 'function $1(){}')
    .replace(/(\w+): ([\w :]+GMT\+[\w \(\)]+),/ig, '$1: new Date("$2"),')
    .replace(/(\S+): ,/ig, '$1: null,');

// Create function to eval stringifyed code
var foo = new Function('return ' + str + ';');

// And have fun
console.log(JSON.stringify(foo(), null, 4));

Remove spaces from std::string in C++

Just for fun, as other answers are much better than this.

#include <boost/hana/functional/partial.hpp>
#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
int main() {
    using ranges::to;
    using ranges::views::filter;
    using boost::hana::partial;
    auto const& not_space = partial(std::not_equal_to<>{}, ' ');
    auto const& to_string = to<std::string>;

    std::string input = "2C F4 32 3C B9 DE";
    std::string output = input | filter(not_space) | to_string;
    assert(output == "2CF4323CB9DE");
}

PHP shell_exec() vs exec()

shell_exec returns all of the output stream as a string. exec returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.

See

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

try this,

$(".head h3").html("New header");

or

$(".head h3").text("New header");

remember class selectors returns all the matching elements.

Base 64 encode and decode example code

To encrypt:

byte[] encrpt= text.getBytes("UTF-8");
String base64 = Base64.encodeToString(encrpt, Base64.DEFAULT);

To decrypt:

byte[] decrypt= Base64.decode(base64, Base64.DEFAULT);
String text = new String(decrypt, "UTF-8");

How to export MySQL database with triggers and procedures?

May be it's obvious for expert users of MYSQL but I wasted some time while trying to figure out default value would not export functions. So I thought to mention here that --routines param needs to be set to true to make it work.

mysqldump --routines=true -u <user> my_database > my_database.sql

Turning off hibernate logging console output

There are several parts of hibernate logging you can control based on the logger hierarchy of the hibernate package (more on logger hierarchy here).

    <!-- Log everything in hibernate -->
    <Logger name="org.hibernate" level="info" additivity="false">
      <AppenderRef ref="Console" />
    </Logger>

    <!-- Log SQL statements -->
    <Logger name="org.hibernate.SQL" level="debug" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

    <!-- Log JDBC bind parameters -->
    <Logger name="org.hibernate.type.descriptor.sql" level="trace" additivity="false">
      <AppenderRef ref="Console" />
      <AppenderRef ref="File" />
    </Logger>

The above was taken from here.

Additionally you could have the property show-sql:true in your configuration file since that supersedes the logging framework settings. More on that here.

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

Java Currency Number format

I know this is an old question but...

import java.text.*;

public class FormatCurrency
{
    public static void main(String[] args)
    {
        double price = 123.4567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(price));
    }
}

VSCode Change Default Terminal

If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `

//with this you can select what type of console you want
{
    "key": "ctrl+shift+t",
    "command": "shellLauncher.launch"
},

//and this will help you quickly change console
{ 
    "key": "ctrl+shift+j", 
    "command": "workbench.action.terminal.focusNext" 
},
{
    "key": "ctrl+shift+k", 
    "command": "workbench.action.terminal.focusPrevious" 
}`

Update some specific field of an entity in android Room

You could try this, but performance may be worse a little:

@Dao
public abstract class TourDao {

    @Query("SELECT * FROM Tour WHERE id == :id")
    public abstract Tour getTour(int id);

    @Update
    public abstract int updateTour(Tour tour);

    public void updateTour(int id, String end_address) {
        Tour tour = getTour(id);
        tour.end_address = end_address;
        updateTour(tour);
    }
}

run a python script in terminal without the python command

You use a shebang line at the start of your script:

#!/usr/bin/env python

make the file executable:

chmod +x arbitraryname

and put it in a directory on your PATH (can be a symlink):

cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname

Why is there no Char.Empty like String.Empty?

If you want to remove characters that satisfy a specific condition, you may use this:

string s = "SoMEthInG";
s = new string(s.Where(c => char.IsUpper(c)).ToArray());

(This will leave only the uppercase characters in the string.)

In other words, you may "use" the string as an IEnumerable<char>, make changes on it and then convert it back to a string as shown above.

Again, this enables to not only remove a specific char because of the lambda expression, although you can do so if you change the lambda expression like this: c => c != 't'.

Java: How to read a text file

This example code shows you how to read file in Java.

import java.io.*;

/**
 * This example code shows you how to read file in Java
 *
 * IN MY CASE RAILWAY IS MY TEXT FILE WHICH I WANT TO DISPLAY YOU CHANGE WITH YOUR   OWN      
 */

 public class ReadFileExample 
 {
    public static void main(String[] args) 
    {
       System.out.println("Reading File from Java code");
       //Name of the file
       String fileName="RAILWAY.txt";
       try{

          //Create object of FileReader
          FileReader inputFile = new FileReader(fileName);

          //Instantiate the BufferedReader Class
          BufferedReader bufferReader = new BufferedReader(inputFile);

          //Variable to hold the one line data
          String line;

          // Read file line by line and print on the console
          while ((line = bufferReader.readLine()) != null)   {
            System.out.println(line);
          }
          //Close the buffer reader
          bufferReader.close();
       }catch(Exception e){
          System.out.println("Error while reading file line by line:" + e.getMessage());                      
       }

     }
  }

Google Maps JS API v3 - Simple Multiple Marker Example

The recent simplest after modification in current map markers and clusterer algorithm:

Modification on: https://developers.google.com/maps/documentation/javascript/marker-clustering[![enter image description here]1]1

<!DOCTYPE Html>
<html>

<head>
<meta Content-Security-Policy="default-src  'self'; script-src 'self' 'unsafe-eval' https://*/;">
<link type="text/css" href="http://www.mapsmarker.com/wp-content/uploads/leaflet-maps-marker-icons/bar_coktail.png">
<link rel="icon" href="data:,">
<title>App</title>
</head>
<style type="text/css">
   #map {
    height: 500
}
</style>

<body>
<div id='map' style="width:100%; height:400px"></div>
<script type='text/javascript'>
    function initMap() {
        maps = new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(12.9824855, 77.637094),
            zoom: 5,
            disableDefaultUI: false,
            mapTypeId: google.maps.MapTypeId.HYBRID
        });
        var labels='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var markerImage = 'http://www.mapsmarker.com/wp-content/uploads/leaflet-maps-marker-icons/bar_coktail.png';
        marker = locations.map(function (location, i) {
            return new google.maps.Marker({
                position: new google.maps.LatLng(location.lat, location.lng),
                map: maps,
                title: "Map",
                label: labels[i % labels.length],
                icon: markerImage
            });
        });

        var markerCluster = new MarkerClusterer(maps, marker, {
            imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
        });
    }
    var locations = [
            { lat: 12.9824855, lng: 77.637094},
            { lat: 11.9824855, lng: 77.154312 },
            { lat: 12.8824855, lng: 77.637094},
            { lat: 10.8824855, lng: 77.054312 },
            { lat: 12.9824855, lng: 77.637094},
            { lat: 11.9824855, lng: 77.154312 },
            { lat: 12.8824855, lng: 77.637094},
            { lat: 13.8824855, lng: 77.054312 },
            { lat: 14.9824855, lng: 54.637094},
            { lat: 15.9824855, lng: 54.154312 },
            { lat: 16.8824855, lng: 53.637094},
            { lat: 17.8824855, lng: 52.054312 },
            { lat: 18.9824855, lng: 51.637094},
            { lat: 19.9824855, lng: 69.154312 },
            { lat: 20.8824855, lng: 68.637094},
            { lat: 21.8824855, lng: 67.054312 },
            { lat: 12.9824855, lng: 76.637094},
            { lat: 11.9824855, lng: 75.154312 },
            { lat: 12.8824855, lng: 74.637094},
            { lat: 10.8824855, lng: 74.054312 },
            { lat: 12.9824855, lng: 73.637094},
            { lat: 3.9824855, lng: 72.154312 },
            { lat: 2.8824855, lng: 71.637094},
            { lat: 1.8824855, lng: 70.054312 }
        ];

</script>
<script src="https://unpkg.com/@google/[email protected]/dist/markerclustererplus.min.js">
</script>
<script src="https:maps.googleapis.com/maps/api/js?key=AIzaSyDWu6_Io9xA1oerfOxE77YAv31etN4u3Dw&callback=initMap">
</script>
<script type='text/javascript'></script>

How to set null to a GUID property

Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff") but that's a lot uglier IMHO.

How do I install SciPy on 64 bit Windows?

As the transcript for SciPy told you, SciPy isn't really supposed to work on Win64:

Warning: Windows 64 bits support is experimental, and only available for
testing. You are advised not to use it for production.

So I would suggest to install the 32-bit version of Python, and stop attempting to build SciPy yourself. If you still want to try anyway, you first need to compile BLAS and LAPACK, as PiotrLegnica says. See the transcript for the places where it was looking for compiled versions of these libraries.

Most efficient way to check if a file is empty in Java on Windows

Stolen from http://www.coderanch.com/t/279224/Streams/java/Checking-empty-file

FileInputStream fis = new FileInputStream(new File("file_name"));  
int b = fis.read();  
if (b == -1)  
{  
  System.out.println("!!File " + file_name + " emty!!");  
}  

Updated: My first answer was premature and contained a bug.

How are POST and GET variables handled in Python?

They are stored in the CGI fieldstorage object.

import cgi
form = cgi.FieldStorage()

print "The user entered %s" % form.getvalue("uservalue")

How to check if a number is between two values?

I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values

if (500 < size && size < 600) { doStuff(); }

Page redirect with successful Ajax request

I think you can do that with:

window.location = "your_url";

How to only find files in a given directory, and ignore subdirectories using bash

find /dev -maxdepth 1 -name 'abc-*'

Does not work for me. It return nothing. If I just do '.' it gives me all the files in directory below the one I'm working in on.

find /dev -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls

Return nothing with '.' instead I get list of all 'big' files in my directory as well as the rootfiles/ directory where I store old ones.

Continuing. This works.

find ./ -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls
564751   71 -rw-r--r--   1 snyder   bfactory   115739 May 21 12:39 ./R24eTightPiPi771052-55.root
565197  105 -rw-r--r--   1 snyder   bfactory   150719 May 21 14:27 ./R24eTightPiPi771106-2.root
565023   94 -rw-r--r--   1 snyder   bfactory   134180 May 21 12:59 ./R24eTightPiPi77999-109.root
719678   82 -rw-r--r--   1 snyder   bfactory   121149 May 21 12:42 ./R24eTightPiPi771098-10.root
564029  140 -rw-r--r--   1 snyder   bfactory   170181 May 21 14:14 ./combo77v.root

Apparently /dev means directory of interest. But ./ is needed, not just .. The need for the / was not obvious even after I figured out what /dev meant more or less.

I couldn't respond as a comment because I have no 'reputation'.

How do I calculate square root in Python?

You can use NumPy to calculate square roots of arrays:

 import numpy as np
 np.sqrt([1, 4, 9])

jQuery - selecting elements from inside a element

....but $('span', $('#foo')); doesn't work?

This method is called as providing selector context.

In this you provide a second argument to the jQuery selector. It can be any css object string just like you would pass for direct selecting or a jQuery element.

eg.

$("span",".cont1").css("background", '#F00');

The above line will select all spans within the container having the class named cont1.

DEMO

Can PHP cURL retrieve response headers AND body in a single request?

is this what are you looking to?

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
$response = curl_exec($ch); 
list($header, $body) = explode("\r\n\r\n", $response, 2);

PowerShell - Start-Process and Cmdline Switches

I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)

cmd /C "$msbuild $args" >> $outputfile

Difference between logical addresses, and physical addresses?

logical address is address relative to program. It tells how much memory a particular process will take, not tell what will the exact location of the process and this exact location will we generated by using some mapping, and is known as physical address.

$(...).datepicker is not a function - JQuery - Bootstrap

Not the right function name I think

$(document).ready(function() {

    $('.datepicker').datetimepicker({
        format: 'dd/mm/yyyy'
    });
});

Can't install gems on OS X "El Capitan"

Reinstalling RVM worked for me, but I had to reinstall all of my gems afterward:

rvm implode
\curl -sSL https://get.rvm.io | bash -s stable --ruby
rvm reload

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

JQuery - Call the jquery button click event based on name property

You have to use the jquery attribute selector. You can read more here:

http://api.jquery.com/attribute-equals-selector/

In your case it should be:

$('input[name="btnName"]')

Change MySQL root password in phpMyAdmin

you can use this command

 mysql> UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';

check the links http://www.kirupa.com/forum/showthread.php?279644-How-to-reset-password-in-WAMP-server http://www.phpmytutor.com/blogs/2012/08/27/change-mysql-root-password-in-wamp-server/

Find your config.inc.php file under the phpMyAdmin installation directory and update the line that looks like
this:

$cfg['Servers'][$i]['password']      = 'password';

... to this:

 $cfg['Servers'][$i]['password']      = 'newpassword';

How to shutdown a Spring Boot Application in a correct way?

Spring Boot provided several application listener while try to create application context one of them is ApplicationFailedEvent. We can use to know weather the application context initialized or not.

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.context.event.ApplicationFailedEvent; 
    import org.springframework.context.ApplicationListener;

    public class ApplicationErrorListener implements 
                    ApplicationListener<ApplicationFailedEvent> {

        private static final Logger LOGGER = 
        LoggerFactory.getLogger(ApplicationErrorListener.class);

        @Override
        public void onApplicationEvent(ApplicationFailedEvent event) {
           if (event.getException() != null) {
                LOGGER.info("!!!!!!Looks like something not working as 
                                expected so stoping application.!!!!!!");
                         event.getApplicationContext().close();
                  System.exit(-1);
           } 
        }
    }

Add to above listener class to SpringApplication.

    new SpringApplicationBuilder(Application.class)
            .listeners(new ApplicationErrorListener())
            .run(args);  

How to reference a local XML Schema file correctly?

Maybe can help to check that the path to the xsd file has not 'strange' characters like 'é', or similar: I was having the same issue but when I changed to a path without the 'é' the error dissapeared.

How do I return the SQL data types from my query?

There MUST be en easier way to do this... Low and behold, there is...!

"sp_describe_first_result_set" is your friend!

Now I do realise the question was asked specifically for SQL Server 2000, but I was looking for a similar solution for later versions and discovered some native support in SQL to achieve this.

In SQL Server 2012 onwards cf. "sp_describe_first_result_set" - Link to BOL

I had already implemented a solution using a technique similar to @Trisped's above and ripped it out to implement the native SQL Server implementation.

In case you're not on SQL Server 2012 or Azure SQL Database yet, here's the stored proc I created for pre-2012 era databases:

CREATE PROCEDURE [fn].[GetQueryResultMetadata] 
    @queryText VARCHAR(MAX)
AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    --SET NOCOUNT ON;

    PRINT @queryText;

    DECLARE
                @sqlToExec NVARCHAR(MAX) = 
                    'SELECT TOP 1 * INTO #QueryMetadata FROM ('
                    +
                    @queryText
                    +
                    ') T;'
                    + '
                        SELECT
                                    C.Name                          [ColumnName],
                                    TP.Name                         [ColumnType],
                                    C.max_length                    [MaxLength],
                                    C.[precision]                   [Precision],
                                    C.[scale]                       [Scale],
                                    C.[is_nullable]                 IsNullable
                        FROM
                                    tempdb.sys.columns              C
                                        INNER JOIN
                                    tempdb.sys.types                TP
                                                                                ON
                                                                                        TP.system_type_id = C.system_type_id
                                                                                            AND
                                                                                        -- exclude custom types
                                                                                        TP.system_type_id = TP.user_type_id
                        WHERE
                                    [object_id] = OBJECT_ID(N''tempdb..#QueryMetadata'');
            '

    EXEC sp_executesql @sqlToExec

END

Create a folder if it doesn't already exist

if (!is_dir('path_directory')) {
    @mkdir('path_directory');
}

How to hide TabPage from TabControl

Hide TabPage and Remove the Header:

this.tabPage1.Hide();
this.tabPage3.Hide();
this.tabPage5.Hide();
tabControl1.TabPages.Remove(tabPage1);
tabControl1.TabPages.Remove(tabPage3);
tabControl1.TabPages.Remove(tabPage5);

Show TabPage and Visible the Header:

tabControl1.TabPages.Insert(0,tabPage1);
tabControl1.TabPages.Insert(2, tabPage3);
tabControl1.TabPages.Insert(4, tabPage5);
this.tabPage1.Show();
this.tabPage3.Show();
this.tabPage5.Show();
tabControl1.SelectedTab = tabPage1;

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

Cleaning `Inf` values from an R dataframe

Option 1

Use the fact that a data.frame is a list of columns, then use do.call to recreate a data.frame.

do.call(data.frame,lapply(DT, function(x) replace(x, is.infinite(x),NA)))

Option 2 -- data.table

You could use data.table and set. This avoids some internal copying.

DT <- data.table(dat)
invisible(lapply(names(DT),function(.name) set(DT, which(is.infinite(DT[[.name]])), j = .name,value =NA)))

Or using column numbers (possibly faster if there are a lot of columns):

for (j in 1:ncol(DT)) set(DT, which(is.infinite(DT[[j]])), j, NA)

Timings

# some `big(ish)` data
dat <- data.frame(a = rep(c(1,Inf), 1e6), b = rep(c(Inf,2), 1e6), 
                  c = rep(c('a','b'),1e6),d = rep(c(1,Inf), 1e6),  
                  e = rep(c(Inf,2), 1e6))
# create data.table
library(data.table)
DT <- data.table(dat)

# replace (@mnel)
system.time(na_dat <- do.call(data.frame,lapply(dat, function(x) replace(x, is.infinite(x),NA))))
## user  system elapsed 
#  0.52    0.01    0.53 

# is.na (@dwin)
system.time(is.na(dat) <- sapply(dat, is.infinite))
# user  system elapsed 
# 32.96    0.07   33.12 

# modified is.na
system.time(is.na(dat) <- do.call(cbind,lapply(dat, is.infinite)))
#  user  system elapsed 
# 1.22    0.38    1.60 


# data.table (@mnel)
system.time(invisible(lapply(names(DT),function(.name) set(DT, which(is.infinite(DT[[.name]])), j = .name,value =NA))))
# user  system elapsed 
# 0.29    0.02    0.31 

data.table is the quickest. Using sapply slows things down noticeably.

How many threads is too many?

As Pax rightly said, measure, don't guess. That what I did for DNSwitness and the results were suprising: the ideal number of threads was much higher than I thought, something like 15,000 threads to get the fastest results.

Of course, it depends on many things, that's why you must measure yourself.

Complete measures (in French only) in Combien de fils d'exécution ?.

How to add local .jar file dependency to build.gradle file?

The solution which worked for me is the usage of fileTree in build.gradle file. Keep the .jar which need to add as dependency in libs folder. The give the below code in dependenices block in build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Alter a MySQL column to be AUTO_INCREMENT

You can apply the atuto_increment constraint to the data column by the following query:

ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;

But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:

SET foreign_key_checks = 0;

Therefore, use the following query instead:

SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;

Change background color for selected ListBox item

You have to create a new template for item selection like this.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
            <Border
                BorderThickness="{TemplateBinding Border.BorderThickness}"
                Padding="{TemplateBinding Control.Padding}"
                BorderBrush="{TemplateBinding Border.BorderBrush}"
                Background="{TemplateBinding Panel.Background}"
                SnapsToDevicePixels="True">
                <ContentPresenter
                    Content="{TemplateBinding ContentControl.Content}"
                    ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                    HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                    VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
                    SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </Border>
        </ControlTemplate>
    </Setter.Value>
</Setter>

Rollback to last git commit

An easy foolproof way to UNDO local file changes since the last commit is to place them in a new branch:

git branch changes
git checkout changes
git add .
git commit

This leaves the changes in the new branch. Return to the original branch to find it back to the last commit:

git checkout master

The new branch is a good place to practice different ways to revert changes without risk of messing up the original branch.

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

  1. Copy the DLL to C:\Windows\SysWoW64\
  2. In elevated cmd: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

  1. Copy the DLL to C:\Windows\System32\
  2. In elevated cmd: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

Does Hive have a String split function?

Just a clarification on the answer given by Bkkbrad.

I tried this suggestion and it did not work for me.

For example,

split('aa|bb','\\|')

produced:

["","a","a","|","b","b",""]

But,

split('aa|bb','[|]')

produced the desired result:

["aa","bb"]

Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.

For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html

Javascript array value is undefined ... how do I test for that

try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)

How do I parse JSON with Objective-C?

With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.

So, for example:

NSData *returnedData = ...JSON data, probably from a web request...

// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?

if(NSClassFromString(@"NSJSONSerialization"))
{
    NSError *error = nil;
    id object = [NSJSONSerialization
                      JSONObjectWithData:returnedData
                      options:0
                      error:&error];

    if(error) { /* JSON was malformed, act appropriately here */ }

    // the originating poster wants to deal with dictionaries;
    // assuming you do too then something like this is the first
    // validation step:
    if([object isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *results = object;
        /* proceed with results as you like; the assignment to
        an explicit NSDictionary * is artificial step to get 
        compile-time checking from here on down (and better autocompletion
        when editing). You could have just made object an NSDictionary *
        in the first place but stylistically you might prefer to keep
        the question of type open until it's confirmed */
    }
    else
    {
        /* there's no guarantee that the outermost object in a JSON
        packet will be a dictionary; if we get here then it wasn't,
        so 'object' shouldn't be treated as an NSDictionary; probably
        you need to report a suitable error condition */
    }
}
else
{
    // the user is using iOS 4; we'll need to use a third-party solution.
    // If you don't intend to support iOS 4 then get rid of this entire
    // conditional and just jump straight to
    // NSError *error = nil;
    // [NSJSONSerialization JSONObjectWithData:...
}

node.js - request - How to "emitter.setMaxListeners()"?

Although adding something to nodejs module is possible, it seems to be not the best way (if you try to run your code on other computer, the program will crash with the same error, obviously).

I would rather set max listeners number in your own code:

var options = {uri:headingUri, headers:headerData, maxRedirects:100};
request.setMaxListeners(0);
request.get(options, function (error, response, body) {
}

Forwarding port 80 to 8080 using NGINX

You can define an upstream and use it in proxy_pass

http://rohanambasta.blogspot.com/2016/02/redirect-nginx-request-to-upstream.html

server {  
   listen        8082;

   location ~ /(.*) {  
       proxy_pass  test_server;  
       proxy_set_header Host $host;  
       proxy_set_header X-Real-IP $remote_addr;  
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
       proxy_set_header X-Forwarded-Proto $scheme;  
       proxy_redirect    off;  
   }  

}   

  upstream test_server  
     {  
         server test-server:8989  
}  

How do I declare and assign a variable on a single line in SQL

on sql 2008 this is valid

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

on sql server 2005, you need to do this

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

Appropriate datatype for holding percent values?

Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2) with an appropriate CHECK constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

Android disable screen timeout while app is running

I used:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

to disable the screen timeout and

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

to re-enable it.

Make the current Git branch a master branch

My way of doing things is the following

#Backup branch
git checkout -b master_backup
git push origin master_backup
git checkout master
#Hard Reset master branch to the last common commit
git reset --hard e8c8597
#Merge
git merge develop

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

Make sure that the database is created. I got the same error when I applied the migration to the wrong project in the solution. When I applied the migration to the right project, it created the database and that solved the error.

How do I show multiple recaptchas on a single page?

To add a bit to raphadko's answer: since you have multiple captchas (on one page), you can't use the (universal) g-recaptcha-response POST parameter (because it holds only one captcha's response). Instead, you should use grecaptcha.getResponse(opt_widget_id) call for each captcha. Here's my code (provided each captcha is inside its form):

HTML:

<form ... />

<div id="RecaptchaField1"></div>

<div class="field">
  <input type="hidden" name="grecaptcha" id="grecaptcha" />
</div>

</form>

and

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>

JavaScript:

var CaptchaCallback = function(){
    var widgetId;

    $('[id^=RecaptchaField]').each(function(index, el) {

         widgetId = grecaptcha.render(el.id, {'sitekey' : 'your_site_key'});

         $(el).closest("form").submit(function( event ) {

            this.grecaptcha.value = "{\"" + index + "\" => \"" + grecaptcha.getResponse(widgetId) + "\"}"

         });
    });
};

Notice that I apply the event delegation (see refresh DOM after append element ) to all the dynamically modified elements. This binds every individual captha's response to its form submit event.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

Google Chrome display JSON AJAX response as tree and not as a plain text

There was an issue with a build of Google Chrome Dev build 24.0.1312.5 that caused the preview panel to no longer display a json object tree but rather flat text. It should be fixed in the next dev

See more here: http://code.google.com/p/chromium/issues/detail?id=160733

Python vs. Java performance (runtime speed)

If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?

For example:

  • Does it count when Java executes an empty loop faster than Python?
  • Or is Python faster when it notices that the loop body is empty, the loop header has no side effects and it optimizes the whole loop away?
  • Or is that "a language characteristic"?
  • Do you want to know how many bytecodes each language can execute per second?
  • Which ones? Only the fast ones or all of them?
  • How do you count the Java VM JIT compiler which turns bytecode into CPU-specific assembler code at runtime?
  • Do you include code compilation times (which are extra in Java but always included in Python)?

Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.

Check if Python Package is installed

In the Terminal type

pip show some_package_name

Example

pip show matplotlib

PHP UML Generator

phUML

phUML is fully automatic UML class diagramm generator written in PHP, licensed under the BSD license. It is capable of parsing any PHP5 object oriented source code and create an appropriate image representation of the oo structure based on the UML specification.

UML Example

./phuml -r /var/www/my_project -graphviz -createAssociations false -neato out.png

Step by step guide

Removing duplicate rows in Notepad++

If the rows are immediately after each other then you can use a regex replace:

Search Pattern: ^(.*\r?\n)(\1)+

Replace with: \1

How to loop in excel without VBA or macros?

You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.

Aggregate the results from that table into a results cell.

The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.

Get all LI elements in array

If you want all the li tags in an array even when they are in different ul tags then you can simply do

var lis = document.getElementByTagName('li'); 

and if you want to get particular div tag li's then:

var lis = document.getElementById('divID').getElementByTagName('li'); 

else if you want to search a ul first and then its li tags then you can do:

var uls = document.getElementsByTagName('ul');
for(var i=0;i<uls.length;i++){
    var lis=uls[i].getElementsByTagName('li');
    for(var j=0;j<lis.length;j++){
        console.log(lis[j].innerHTML);
    }
}

mysql_config not found when installing mysqldb python interface

In CentOS 7 instead of yum install mysql-devel do yum install mysql-community-devel

This does not require you to add the mysql repo.