Programs & Examples On #Eager loading

Eager loading is a way to load objects of a certain class and a number of named associations in the same request.

Entity Framework - Include Multiple Levels of Properties

I also had to use multiple includes and at 3rd level I needed multiple properties

(from e in context.JobCategorySet
                      where e.Id == id &&
                            e.AgencyId == agencyId
                      select e)
                      .Include(x => x.JobCategorySkillDetails)
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.DurationType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RuleType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RateType))
                      .FirstOrDefaultAsync();

This may help someone :)

Dynamic Web Module 3.0 -- 3.1

  1. Go to Workspace location
  2. select your project folder
  3. .setting folder
  4. edit "org.eclipse.wst.common.project.facet.core"
  5. change installed facet="jst.web" version="3.0"

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

A beginner's guide to SQL database design

These are questions which, in my opionion, requires different knowledge from different domains.

  1. You just can't know in advance "which" tables to build, you have to know the problem you have to solve and design the schema accordingly;
  2. This is a mix of database design decision and your database vendor custom capabilities (ie. you should check the documentation of your (r)dbms and eventually learn some "tips & tricks" for scaling), also the configuration of your dbms is crucial for scaling (replication, data partitioning and so on);
  3. again, almost every rdbms comes with a particular "dialect" of the SQL language, so if you want efficient queries you have to learn that particular dialect --btw. much probably write elegant query which are also efficient is a big deal: elegance and efficiency are frequently conflicting goals--

That said, maybe you want to read some books, personally I've used this book in my datbase university course (and found a decent one, but I've not read other books in this field, so my advice is to check out for some good books in database design).

Plotting multiple curves same graph and same scale

points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19)

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

Get host domain from URL?

Use Uri class and use Host property

Uri url = new Uri(@"http://support.domain.com/default.aspx?id=12345");
Console.WriteLine(url.Host);

PHP function to generate v4 UUID

Taken from this comment on the PHP manual, you could use this:

function gen_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}

Send JSON data with jQuery

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Check if String / Record exists in DataTable

I think that if your "item_manuf_id" is the primary key of the DataTable you could use the Find method ...

string s = "stringValue";
DataRow foundRow = dtPs.Rows.Find(s);
if(foundRow != null) {
 //You have it ...
 }

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Bootstrap.yml is used to fetch config from the server. It can be for a Spring cloud application or for others. Typically it looks like:

spring:
  application:
    name: "app-name"
  cloud:
    config:
      uri: ${config.server:http://some-server-where-config-resides}

When we start the application it tries to connect to the given server and read the configuration based on spring profile mentioned in run/debug configuration. bootstrap.yml loads the first

If the server is unreachable application might even be unable to proceed further. However, if configurations matching the profile are present locally the server configs get overridden.

Good approach:

Maintain a separate profile for local and run the app using different profiles.

jQuery’s .bind() vs. .on()

These snippets all perform exactly the same thing:

element.on('click', function () { ... });
element.bind('click', function () { ... });
element.click(function () { ... });

However, they are very different from these, which all perform the same thing:

element.on('click', 'selector', function () { ... });
element.delegate('click', 'selector', function () { ... });
$('selector').live('click', function () { ... });

The second set of event handlers use event delegation and will work for dynamically added elements. Event handlers that use delegation are also much more performant. The first set will not work for dynamically added elements, and are much worse for performance.

jQuery's on() function does not introduce any new functionality that did not already exist, it is just an attempt to standardize event handling in jQuery (you no longer have to decide between live, bind, or delegate).

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

Filename too long in Git for Windows

I had this error too, but in my case the cause was using an outdated version of npm, v1.4.28.

Updating to npm v3 followed by

rm -rf node_modules
npm -i

worked for me. npm issue 2697 has details of the "maximally flat" folder structure included in npm v3 (released 2015-06-25).

Angular.js programmatically setting a form field to dirty

Since AngularJS 1.3.4 you can use $setDirty() on fields (source). For example, for each field with error and marked required you can do the following:

angular.forEach($scope.form.$error.required, function(field) {
    field.$setDirty();
});

Creating multiline strings in JavaScript

Update:

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

A template literal is delimited by backticks:

var html = `
  <div>
    <span>Some HTML here</span>
  </div>
`;

(Note: I'm not advocating to use HTML in strings)

Browser support is OK, but you can use transpilers to be more compatible.


Original ES5 answer:

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

"foo \
bar"

How can I filter a date of a DateTimeField in Django?

Model.objects.filter(datetime__year=2011, datetime__month=2, datetime__day=30)

How to put two divs on the same line with CSS in simple_form in rails?

why not use flexbox ? so wrap them into another div like that

_x000D_
_x000D_
.flexContainer { _x000D_
   _x000D_
  margin: 2px 10px;_x000D_
  display: flex;_x000D_
} _x000D_
_x000D_
.left {_x000D_
  flex-basis : 30%;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  flex-basis : 30%;_x000D_
}
_x000D_
<form id="new_production" class="simple_form new_production" novalidate="novalidate" method="post" action="/projects/1/productions" accept-charset="UTF-8">_x000D_
    <div style="margin:0;padding:0;display:inline">_x000D_
        <input type="hidden" value="?" name="utf8">_x000D_
        <input type="hidden" value="2UQCUU+tKiKKtEiDtLLNeDrfBDoHTUmz5Sl9+JRVjALat3hFM=" name="authenticity_token">_x000D_
    </div>_x000D_
    <div class="flexContainer">_x000D_
      <div class="left">Proj Name:</div>_x000D_
      <div class="right">must have a name</div>_x000D_
    </div>_x000D_
    <div class="input string required"> </div>_x000D_
 </form>
_x000D_
_x000D_
_x000D_

feel free to play with flex-basis percentage to get more customized space.

Best way to find os name and version in Unix/Linux platform

The "lsb_release" command provides certain Linux Standard Base and distribution-specific information. So using the below command we can get Operating system name and operating system version.

"lsb_release -a"

How to parse json string in Android?

Below is the link which guide in parsing JSON string in android.

http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE

Also according to your json string code snippet must be something like this:-

JSONObject mainObject = new JSONObject(yourstring);

JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");  
JSONString url = universityObject.getString("url");

Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)

Same for other object.

How to get the list of all printers in computer

Get Network and Local Printer List in ASP.NET

This method uses the Windows Management Instrumentation or the WMI interface. It’s a technology used to get information about various systems (hardware) running on a Windows Operating System.

private void GetAllPrinterList()
        {
            ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
            objScope.Connect();

            SelectQuery selectQuery = new SelectQuery();
            selectQuery.QueryString = "Select * from win32_Printer";
            ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
            ManagementObjectCollection MOC = MOS.Get();
            foreach (ManagementObject mo in MOC)
            {
                lstPrinterList.Items.Add(mo["Name"].ToString());
            }
        }

Click here to download source and application demo

Demo of application which listed network and local printer

enter image description here

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

What I did was to create an extension to UITextField and added a Designer editable property. Setting this property to any color would change the border (bottom) to that color (setting other borders to none).

Since this also requires to change the place holder text color, I also added that to the extension.

    extension UITextField {

    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }


    @IBInspectable var bottomBorderColor: UIColor? {
        get {
            return self.bottomBorderColor
        }
        set {
            self.borderStyle = UITextBorderStyle.None;
            let border = CALayer()
            let width = CGFloat(0.5)
            border.borderColor = newValue?.CGColor
            border.frame = CGRect(x: 0, y: self.frame.size.height - width,   width:  self.frame.size.width, height: self.frame.size.height)

            border.borderWidth = width
            self.layer.addSublayer(border)
            self.layer.masksToBounds = true

        }
    }
}

Android - running a method periodically using postDelayed() call

Why don't you create service and put logic in onCreate(). In this case even if you press back button service will keep on executing. and once you enter into application it will not call onCreate() again. Rather it will call onStart()

JavaFX 2.1 TableView refresh items

You just need to clear the table and call the function that generates the filling of the table.

ButtonRefresh.setOnAction((event) -> {
            tacheTable.getItems().clear();
            PopulateTable();
        });

What does EntityManager.flush do and why do I need to use it?

So when you call EntityManager.persist(), it only makes the entity get managed by the EntityManager and adds it (entity instance) to the Persistence Context. An Explicit flush() will make the entity now residing in the Persistence Context to be moved to the database (using a SQL).

Without flush(), this (moving of entity from Persistence Context to the database) will happen when the Transaction to which this Persistence Context is associated is committed.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

How to undo a git merge with conflicts

There are two things you can do first undo merge by command

git merge --abort

or

you can go to your previous commit state temporarily by command

git checkout 0d1d7fc32 

How can I set the default value for an HTML <select> element?

I came across this question, but the accepted and highly upvoted answer didn't work for me. It turns out that if you are using React, then setting selected doesn't work.

Instead you have to set a value in the <select> tag directly as shown below:

<select value="B">
  <option value="A">Apple</option>
  <option value="B">Banana</option>
  <option value="C">Cranberry</option>
</select>

Read more about why here on the React page.

in a "using" block is a SqlConnection closed on return or exception?

I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.

     try
     {
       using (var con = new SqlConnection(@"Data Source=..."))
       {
         var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";

         using (var insertCommand = new SqlCommand(cad, con))
         {
           insertCommand.Parameters.AddWithValue("@r1", atxt);
           insertCommand.Parameters.AddWithValue("@r2", btxt);
           insertCommand.Parameters.AddWithValue("@r3", ctxt);
           con.Open();
           insertCommand.ExecuteNonQuery();
         }
       }
     }
     catch (Exception ex)
     {
       MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }

No matter where's the try/catch placed, the exception will be caught without issues.

Parse DateTime string in JavaScript

If you are using jQuery UI, you can format any date with:

<html>
    <body>
        Your date formated: <span id="date1"></span><br/>
    </body>
</html>

 

var myDate = '30.11.2011';
var parsedDate = $.datepicker.parseDate('dd.mm.yy', myDate);

$('#date1').text($.datepicker.formatDate('M d, yy', parsedDate));

http://jsfiddle.net/mescalito2345/ND2Qg/14/

how to set font size based on container size?

You can also try this pure CSS method:

font-size: calc(100% - 0.3em);

for each loop in groovy

Your code works fine.

def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]

for (objKey in tmpHM.keySet()) {   
    HashMap objHM = (HashMap) list.get(objKey);
    print("objHM: ${objHM}  , ")
}

prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

IndexOf function in T-SQL

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

TortoiseGit-git did not exit cleanly (exit code 1)

Right-click folder -> TortiseGit -> Clean up.. -> click OK

None of the above solutions worked for me but this one did.

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I replaced the "localhost" with IP Address (Database server's public IP Address) in the jdbc Url then it worked.

jdbcUrl = "jdbc:oracle:thin:<user>@//localhost:1521/<Service Name>";

??

jdbcUrl = "jdbc:oracle:thin:<user>@//<Public IP Address>:1521/<Service Name>";

Check a collection size with JSTL

use ${fn:length(companies) > 0} to check the size. This returns a boolean

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Well, after some struggling, what worked for me was completely removing the current JDK, as described here:

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.JavaUpdateHelper.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

Then installed 1.7.0_21, which was downloaded from here.

Now java -version prompts:

java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b12)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

Update multiple tables in SQL Server using INNER JOIN

You can update with a join if you only affect one table like this:

UPDATE table1 
SET table1.name = table2.name 
FROM table1, table2 
WHERE table1.id = table2.id 
AND table2.foobar ='stuff'

But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.

However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.

SQL JOINS

But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.

Allow anything through CORS Policy

Try configuration at /config/application.rb:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
  end
end

How to roundup a number to the closest ten?

You could also use CEILING which rounds up to an integer or desired multiple of significance

ie
=CEILING(A1,10)
rounds up to a multiple of 10

12340.0001 will become 12350

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

What is the printf format specifier for bool?

If you like C++ better than C, you can try this:

#include <ios>
#include <iostream>

bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;

Run as java application option disabled in eclipse

I had this same problem. For me, the reason turned out to be that I had a mismatch in the name of the class and the name of the file. I declared class "GenSig" in a file called "SignatureTester.java".

I changed the name of the class to "SignatureTester", and the "Run as Java Application" option showed up immediately.

How to search in an array with preg_match?

In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.

How do I see what elements in an array that matches my regular expression?

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

See the below example:

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

output

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

Documentation


But I just want to get the value of the specified groups. How?

array_reduce with preg_match can solve this issue in clean manner; see the snippet below.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher ($m, $str) {
  if (preg_match ('/^hello (\w+)/i', $str, $matches))
    $m[] = $matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

output

Array
(
    [0] => stackoverflow
    [1] => world
)

Documentation


Using array_reduce seems tedious, isn't there another way?

Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_* or preg_* function.

Wrap it in a function if you are going to use this method more than once.

$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', $str, $m))
    $matches[] = $m[1];

Documentation

Passing an array by reference

It's just the required syntax:

void Func(int (&myArray)[100])

^ Pass array of 100 int by reference the parameters name is myArray;

void Func(int* myArray)

^ Pass an array. Array decays to a pointer. Thus you lose size information.

void Func(int (*myFunc)(double))

^ Pass a function pointer. The function returns an int and takes a double. The parameter name is myFunc.

How can I start PostgreSQL on Windows?

After a lot of search and tests i found the solution : if you are in windows :

1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools

$ show data_directory;

result :

------------------------
- D:/PG_DATA/data      -
------------------------

2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"

and open a command prompt (CMD) and execute this command :

pg_ctl -D "D:\PSG_SQL\data" restart

This should do it.

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

You can try using jquery.pep.js:

jquery.pep.js is a lightweight jQuery plugin which turns any DOM element into a draggable object. It works across mostly all browsers, from old to new, from touch to click. I built it to serve a need in which jQuery UI’s draggable was not fulfilling, since it didn’t work on touch devices (without some hackery).

Website, GitHub link

"static const" vs "#define" vs "enum"

In C #define is much more popular. You can use those values for declaring array sizes for example:

#define MAXLEN 5

void foo(void) {
   int bar[MAXLEN];
}

ANSI C doesn't allow you to use static consts in this context as far as I know. In C++ you should avoid macros in these cases. You can write

const int maxlen = 5;

void foo() {
   int bar[maxlen];
}

and even leave out static because internal linkage is implied by const already [in C++ only].

MySQL Error: #1142 - SELECT command denied to user

This error happened on my server when I imported a view with an invalid definer.

Removing the faulty view fixed the error.

The error message didn't say anything about the view in question, but was "complaining" about one of the tables, that was used in the view.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

Display rows with one or more NaN values in pandas dataframe

Use df[df.isnull().any(axis=1)] for python 3.6 or above.

How to test if parameters exist in rails

use blank? http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F

unless params[:one].blank? && params[:two].blank?

will return true if its empty or nil

also... that will not work if you are testing boolean values.. since

>> false.blank?
=> true

in that case you could use

unless params[:one].to_s.blank? && params[:two].to_s.blank?

What is an NP-complete in computer science?

NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

Found out that there's no bug there. Just add:

<base href="/" />

to your <head />.

How Can I Resolve:"can not open 'git-upload-pack' " error in eclipse?

I got this Error after re-creating a Repository on my Server (Codebeamer) - the User in Question lacked some permissions, after granting them, everything worked fine.

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Mac OS apps cannot read bash environment variables. Look at this question Setting environment variables in OS X? to expose M2_HOME to all applications including IntelliJ. You do need to restart after doing this.

mysql datatype for telephone number and address

I'm not sure whether it's a good idea to use integers at all. Some numbers might contain special characters (# as part of the extension for example) which you should be able to handle too. So I would suggest using varchars instead.

Check if list is empty in C#

Why not...

bool isEmpty = !list.Any();
if(isEmpty)
{
    // error message
}
else
{
    // show grid
}

The GridView has also an EmptyDataTemplate which is shown if the datasource is empty. This is an approach in ASP.NET:

<emptydatarowstyle backcolor="LightBlue" forecolor="Red"/>

<emptydatatemplate>

  <asp:image id="NoDataErrorImg"
    imageurl="~/images/NoDataError.jpg" runat="server"/>

    No Data Found!  

</emptydatatemplate> 

How to pause in C?

You could also just use system("pause");

Most efficient way to prepend a value to an array

There is special method:

a.unshift(value);

But if you want to prepend several elements to array it would be faster to use such a method:

var a = [1, 2, 3],
    b = [4, 5];

function prependArray(a, b) {
    var args = b;
    args.unshift(0);
    args.unshift(0);
    Array.prototype.splice.apply(a, args);
}

prependArray(a, b);
console.log(a); // -> [4, 5, 1, 2, 3]

cast class into another class or convert class to another

You could change your class structure to:

public class maincs : sub1
{
   public int d; 
}

public class sub1
{
   public int a;
   public int b;
   public int c;
}

Then you could keep a list of sub1 and cast some of them to mainc.

How to create PDFs in an Android app?

A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.

Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

Array length in angularjs returns undefined

use:

$scope.users.length;

Instead of:

$scope.users.lenght;

And next time "spell-check" your code.

What is stdClass in PHP?

is a way in which the avoid stopping interpreting the script when there is some data must be put in a class , but unfortunately this class was not defined

Example :

 return $statement->fetchAll(PDO::FETCH_CLASS  , 'Tasks');

Here the data will be put in the predefined 'Tasks' . But, if we did the code as this :

 return $statement->fetchAll(PDO::FETCH_CLASS );

then the will put the results in .

simply says that : look , we have a good KIDS[Objects] Here but without Parents . So , we will send them to a infant child Care Home :)

SmartGit Installation and Usage on Ubuntu

What it correct way of installing SmartGit on Ubuntu? Thus I can have normal icon

In smartgit/bin folder, there's a shell script waiting for you: add-menuitem.sh. It does just that.

Python Script Uploading files via FTP

Try this:

#!/usr/bin/env python

import os
import paramiko 
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

How to inherit constructors?

Don't forget that you can also redirect constructors to other constructors at the same level of inheritance:

public Bar(int i, int j) : this(i) { ... }
                            ^^^^^

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

How can I find the number of days between two Date objects in Ruby?

irb(main):005:0> a = Date.parse("12/1/2010")
=> #<Date: 4911063/2,0,2299161>

irb(main):007:0> b = Date.parse("12/21/2010")
=> #<Date: 4911103/2,0,2299161>

irb(main):016:0> c = b.mjd - a.mjd
=> 20

This uses a Modified Julian Day Number.

From wikipedia:

The Julian date (JD) is the interval of time in days and fractions of a day since January 1, 4713 BC Greenwich noon, Julian proleptic calendar.

select rows in sql with latest date for each ID repeated multiple times

You can do this with a Correlated Subquery (That is a subquery wherein you reference a field in the main query). In this case:

SELECT * 
FROM yourtable t1
WHERE date = (SELECT max(date) from yourtable WHERE id = t1.id)

Here we give the yourtable table an alias of t1 and then use that alias in the subquery grabbing the max(date) from the same table yourtable for that id.

Tried to Load Angular More Than Once

Seems like nobody has mentioned this anywhere so here is what triggered it for me: I had the ng-view directive on my body. Changing it like so

<body layout="column">
<div ng-view></div>
...
</body>

stopped the error.

Batchfile to create backup and rename with timestamp

Renames all .pdf files based on current system date. For example a file named Gross Profit.pdf is renamed to Gross Profit 2014-07-31.pdf. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf.

You could replace the ? with the report name Gross Profit, but it will only rename the one report. The ? renames everything in the Conduit folder. The reason there are so many ?, is that some .pdfs have long names. If you just put 12 ?s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?, then try it with many ?s. The ? length should be a little longer or as long as the longest report name.

@ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"

How to cast an object in Objective-C

((SelectionListViewController *)myEditController).list

More examples:

int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly

In Firebase, is there a way to get the number of children of a node without loading all the node data?

write a cloud function to and update the node count.

// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.userscount = functions.database.ref('/users/')
    .onWrite(event => {

      console.log('users number : ', event.data.numChildren());


      return event.data.ref.parent.child('count/users').set(event.data.numChildren());
    }); 

Refer :https://firebase.google.com/docs/functions/database-events

root--| |-users ( this node contains all users list) |
|-count |-userscount : (this node added dynamically by cloud function with the user count)

Hide div element when screen size is smaller than a specific size

@media only screen and (min-width: 1140px)

should do his job, show us your css file

Redirect within component Angular 2

This worked for me Angular cli 6.x:

import {Router} from '@angular/router';

constructor(private artistService: ArtistService, private router: Router) { }

  selectRow(id: number): void{
       this.router.navigate([`./artist-detail/${id}`]);

  }

How to remove indentation from an unordered list item?

Live demo: https://jsfiddle.net/h8uxmoj4/

ol, ul {
  padding-left: 0;
}

li {
  list-style: none;
  padding-left: 1.25rem;
  position: relative;
}

li::before {
  left: 0;
  position: absolute;
}

ol {
  counter-reset: counter;
}

ol li::before {
  content: counter(counter) ".";
  counter-increment: counter;
}

ul li::before {
  content: "?";
}

Since the original question is unclear about its requirements, I attempted to solve this problem within the guidelines set by other answers. In particular:

  • Align list bullets with outside paragraph text
  • Align multiple lines within the same list item

I also wanted a solution that didn't rely on browsers agreeing on how much padding to use. I've added an ordered list for completeness.

Calculating time difference in Milliseconds

I do not know how does your PersonalizationGeoLocationServiceClientHelper works. Probably it performs some sort of caching, so requests for the same IP address may return extremely fast.

How to use Python's pip to download and keep the zipped files for a package?

The --download-cache option should do what you want:

pip install --download-cache="/pth/to/downloaded/files" package

However, when I tested this, the main package downloaded, saved and installed ok, but the the dependencies were saved with their full url path as the name - a bit annoying, but all the tar.gz files were there.

The --download option downloads the main package and its dependencies and does not install any of them. (Note that prior to version 1.1 the --download option did not download dependencies.)

pip install package --download="/pth/to/downloaded/files"

The pip documentation outlines using --download for fast & local installs.

How to clean old dependencies from maven repositories?

Short answer - Deleted .m2 folder in {user.home}. E.g. in windows 10 user home is C:\Users\user1. Re-build your project using mvn clean package. Only those dependencies would remain, which are required by the projects.

Long Answer - .m2 folder is just like a normal folder and the content of the folder is built from different projects. I think there is no way to figure out automatically that which library is "old". In fact old is a vague word. There could be so many reasons when a previous version of a library is used in a project, hence determining which one is unused is not possible.

All you could do, is to delete the .m2 folder and re-build all of your projects and then the folder would automatically build with all the required library.

If you are concern about only a particular version of a library to be used in all the projects; it is important that the project's pom should also update to latest version. i.e. if different POMs refer different versions of the library, all will get downloaded in .m2.

Is it possible to start a shell session in a running container (without ssh)

Just do

docker attach container_name

As mentioned in the comments, to detach from the container without stopping it, type Ctrlpthen Ctrlq.

How to use breakpoints in Eclipse

Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-

http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/

Is there a way to reset IIS 7.5 to factory settings?

This link has some useful suggestions: http://forums.iis.net/t/1085990.aspx

It depends on where you have the config settings stored. By default IIS7 will have all of it's configuration settings stored in a file called "ApplicationHost.Config". If you have delegation configured then you will see site/app related config settings getting written to web.config file for the site/app. With IIS7 on vista there is an automatica backup file for master configuration is created. This file is called "application.config.backup" and it resides inside "C:\Windows\System32\inetsrv\config" You could rename this file to applicationHost.config and replace it with the applicationHost.config inside the config folder. IIS7 on server release will have better configuration back up story, but for now I recommend using APPCMD to backup/restore your configuration on regualr basis. Example: APPCMD ADD BACK "MYBACKUP" Another option (really the last option) is to uninstall/reinstall IIS along with WPAS (Windows Process activation service).

Can I embed a custom font in an iPhone application?

As all the previous answers indicated, it's very well possible, and pretty easy in newer iOS versions.

I know this is not a technical answer, but since a lot of people do make it wrong (thus effectively violating licenses which may cost you a lot of money if you're being sued), let me strengthen one caveat here: Embedding a custom font in an iOS (or any other kind) app is basically redistributing the font. Most licenses for commercial fonts do forbid redistribution, so please make sure you're acting according to the license.

Best programming based games

I used to have a lot of fun coding my own robot with Robocode in college.

It is Java based, the API is detailled and it's pretty easy to get a challenging robot up and running.

Here is an example :

 public class MyFirstRobot extends Robot {
     public void run() {
         while (true) {
             ahead(100);
             turnGunRight(360);
             back(100);
             turnGunRight(360);
         }
     }

     public void onScannedRobot(ScannedRobotEvent e) {
         fire(1);
     }
 }

Assigning the output of a command to a variable

You can use a $ sign like:

OUTPUT=$(expression)

Does Google Chrome work with Selenium IDE (as Firefox does)?

If you want to harness Selenium IDE record & playback capabilities for Chrome browser there is an equivalent extension for Chrome called Scirocco. You can add it to Chrome by visiting here using your Chrome browser https://chrome.google.com/webstore/search/scirocco

Scirocco is created by Sonix Asia and is not as polished as Selenium IDE for Firefox. It is in fact quite buggy in places. But it does what you ask.

Declare and initialize a Dictionary in Typescript

I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string) and remove(key: string) method. I suspect that this could be simplified once generics are available in the 0.9 release.

First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.

interface IDictionary {
    add(key: string, value: any): void;
    remove(key: string): void;
    containsKey(key: string): bool;
    keys(): string[];
    values(): any[];
}

class Dictionary {

    _keys: string[] = new string[];
    _values: any[] = new any[];

    constructor(init: { key: string; value: any; }[]) {

        for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
        }
    }

    add(key: string, value: any) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): any[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
            return false;
        }

        return true;
    }

    toLookup(): IDictionary {
        return this;
    }
}

Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values() and toLookup() to return the correct types.

interface IPerson {
    firstName: string;
    lastName: string;
}

interface IPersonDictionary extends IDictionary {
    [index: string]: IPerson;
    values(): IPerson[];
}

class PersonDictionary extends Dictionary {
    constructor(init: { key: string; value: IPerson; }[]) {
        super(init);
    }

    values(): IPerson[]{
        return this._values;
    }

    toLookup(): IPersonDictionary {
        return this;
    }
}

And here is a simple initialization and usage example:

var persons = new PersonDictionary([
    { key: "p1", value: { firstName: "F1", lastName: "L2" } },
    { key: "p2", value: { firstName: "F2", lastName: "L2" } },
    { key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();


alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2

persons.remove("p2");

if (!persons.containsKey("p2")) {
    alert("Key no longer exists");
    // alert: Key no longer exists
}

alert(persons.keys().join(", "));
// alert: p1, p3

How to compare two dates along with time in java

Since Date implements Comparable<Date>, it is as easy as:

date1.compareTo(date2);

As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).

Note that Date has also .after() and .before() methods which will return booleans instead.

Where does Visual Studio look for C++ header files?

Visual Studio looks for headers in this order:

  • In the current source directory.
  • In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
  • In the Visual Studio C++ Include directories under Tools ? Options ? Projects and Solutions ? VC++ Directories.
  • In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties ? Configuration ? VC++ Directories

In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).

Pointer vs. Reference

If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.

A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.

// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& optional_str)
{
    if (optional_str)
    {
       cout << *optional_str << std::endl;
    }
    else
    {
       cout << "(no string)" << std::endl;
    }
}

// Sample method using optional as return value
boost::optional<int> ReturnOptional(bool return_nothing)
{
    if (return_nothing)
    {
       return boost::optional<int>();
    }

    return boost::optional<int>(42);
}

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

tl;dr

  • Use modern java.time classes.
  • Never use Date/Calendar/SimpleDateFormat classes.

Example:

ZonedDateTime                                // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now(                                        // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )              // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo(                                // Lop off finer part of this value.
    ChronoUnit.MILLIS                        // Specify level of truncation via `ChronoUnit` enum object.
)                                            // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format(                                     // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME    // This standard ISO 8601 format is close to your desired output.
)                                            // Returns a `String`.
.replace( "T" , " " )                        // Replace `T` in middle with a SPACE.

java.time

The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.

want current date and time

Capture the current moment in UTC using Instant.

Instant instant = Instant.now() ;

To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.

ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;

The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.

ZonedDateTime
.now( 
    ZoneId.of( "Pacific/Auckland" ) 
)
.truncatedTo(
    ChronoUnit.MILLIS
)

in “dd/MM/yyyy HH:mm:ss.SS” format

I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.

But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.

String output = 
    zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
    .replace( "T" , " " )  
;

sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");

Date date = sdf1.parse(strDate);

Never exchange date-time values using text intended for presentation to humans.

Instead, use the standard formats defined for this very purpose, found in ISO 8601.

The java.time use these ISO 8601 formats by default when parsing/generating strings.

Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.

Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;

2018-01-23T01:23:45.123456789Z

This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Spring schemaLocation fails when there is no internet connection

You need to add schema locations to your bean definition, and then they can be found in classpath instead of fetched over the net. Given your formatting problems, I'm not 100% sure that you aren't doing this already.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- empty: the beans we use are in the base class's context. -->
</beans>

Apply .gitignore on an existing repository already tracking large number of files

If you added your .gitignore too late, git will continue to track already commited files regardless. To fix this, you can always remove all cached instances of the unwanted files.

First, to check what files are you actually tracking, you can run:

git ls-tree --name-only --full-tree -r HEAD

Let say that you found unwanted files in a directory like cache/ so, it's safer to target that directory instead of all of your files.

So instead of:

git rm -r --cached .

It's safer to target the unwanted file or directory:

git rm -r --cached cache/

Then proceed to add all changes,

git add .

and commit...

git commit -m ".gitignore is now working"

Reference: https://amyetheredge.com/code/13.html

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

Use of *args and **kwargs

Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:

>>> import operator
>>> def multiply(*args):
...  return reduce(operator.mul, args)

Then you use this function like:

>>> multiply(1,2,3)
6

or

>>> numbers = [1,2,3]
>>> multiply(*numbers)
6

How can I write data attributes using Angular?

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

jQuery: select all elements of a given class, except for a particular Id

I'll just throw in a JS (ES6) answer, in case someone is looking for it:

Array.from(document.querySelectorAll(".myClass:not(#myId)")).forEach((el,i) => {
    doSomething(el);
}

Update (this may have been possible when I posted the original answer, but adding this now anyway):

document.querySelectorAll(".myClass:not(#myId)").forEach((el,i) => {
    doSomething(el);
});

This gets rid of the Array.from usage.

document.querySelectorAll returns a NodeList.
Read here to know more about how to iterate on it (and other things): https://developer.mozilla.org/en-US/docs/Web/API/NodeList

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Updating address bar with new URL without hash or reloading the page

Changing only what's after hash - old browsers

document.location.hash = 'lookAtMeNow';

Changing full URL. Chrome, Firefox, IE10+

history.pushState('data to be passed', 'Title of the page', '/test');

The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use

history.replaceState('data to be passed', 'Title of the page', '/test');

Try running these in the console now!

Compare two files and write it to "match" and "nomatch" files

//STEP01   EXEC SORT90MB                        
//SORTJNF1 DD DSN=INPUTFILE1,   
//            DISP=SHR                          
//SORTJNF2 DD DSN=INPUTFILE2,   
//            DISP=SHR                          
//SORTOUT  DD DSN=MISMATCH_OUTPUT_FILE, 
//            DISP=(,CATLG,DELETE),             
//            UNIT=TAPE,                        
//            DCB=(RECFM=FB,BLKSIZE=0),         
//            DSORG=PS                          
//SYSOUT   DD SYSOUT=*                          
//SYSIN    DD *                                 
  JOINKEYS FILE=F1,FIELDS=(1,79,A)              
  JOINKEYS FILE=F2,FIELDS=(1,79,A)              
  JOIN UNPAIRED,F1,ONLY                         
  SORT FIELDS=COPY                              
/*                                              

Unstaged changes left after git reset --hard

I had the same problem and it was related to the .gitattributes file. However the file type that caused the problem was not specified in the .gitattributes.

I was able to solve the issue by simply running

git rm .gitattributes
git add -A
git reset --hard

What is the difference between <section> and <div>?

Using <section> may be neater, help screen readers and SEO while <div> is smaller in bytes and quicker to type

Overall very little difference.

Also, would not recommend putting <section> in a <section>, instead place a <div> inside a <section>

Run Python script at startup in Ubuntu

Create file ~/.config/autostart/MyScript.desktop with

[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=

X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0

It helps me!

How to stop C# console applications from closing automatically?

Ctrl + F5 is better, because you don't need additional lines. And you can, in the end, hit enter and exit running mode.

But, when you start a program with F5 and put a break-point, you can debug your application and that gives you other advantages.

How to remove "href" with Jquery?

Your title question and your example are completely different. I'll start by answering the title question:

$("a").removeAttr("href");

And as far as not requiring an href, the generally accepted way of doing this is:

<a href"#" onclick="doWork(); return false;">link</a>

The return false is necessary so that the href doesn't actually go anywhere.

How to set the locale inside a Debian/Ubuntu Docker container?

I dislike having Docker environment variables when I do not expect user of a Docker image to change them.

Just put it somewhere in one RUN. If you do not have UTF-8 locales generated, then you can do the following set of commands:

export DEBIAN_FRONTEND=noninteractive
apt-get update -q -q
apt-get install --yes locales
locale-gen --no-purge en_US.UTF-8
update-locale LANG=en_US.UTF-8
echo locales locales/locales_to_be_generated multiselect en_US.UTF-8 UTF-8 | debconf-set-selections
echo locales locales/default_environment_locale select en_US.UTF-8 | debconf-set-selections
dpkg-reconfigure locales

How to edit Docker container files from the host?

The way I am doing is using Emacs with docker package installed. I would recommend Spacemacs version of Emacs. I would follow the following steps:

1) Install Emacs (Instruction) and install Spacemacs (Instruction)

2) Add docker in your .spacemacs file

3) Start Emacs

4) Find file (SPC+f+f) and type /docker:<container-id>:/<path of dir/file in the container>

5) Now your emacs will use the container environment to edit the files

How to run an external program, e.g. notepad, using hyperlink?

Make a batch file and call the bacth file in Window.open. Here how it works

  1. make a file in notepad
  2. write your script : start wmplayer "\dotnet\sc\1234.mp4" /fullscreen
  3. save as : test.bat in \dotnet\sc\test.bat

in html

window.open('file://dotnet/sc/test.bat')

Enjoy..

passing form data to another HTML page

Using pure JavaScript.It's very easy using local storage.
The first page form:

_x000D_
_x000D_
function getData()
{
    //gettting the values
    var email = document.getElementById("email").value;
    var password= document.getElementById("password").value; 
    var telephone= document.getElementById("telephone").value; 
    var mobile= document.getElementById("mobile").value; 
    //saving the values in local storage
    localStorage.setItem("txtValue", email);
    localStorage.setItem("txtValue1", password);
    localStorage.setItem("txtValue2", mobile);
    localStorage.setItem("txtValue3", telephone);   
}
_x000D_
  input{
    font-size: 25px;
  }
  label{
    color: rgb(16, 8, 46);
    font-weight: bolder;
  }
  #data{

  }
_x000D_
   <fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
        <form action="action.html">
        <legend>Sign Up Form</legend>
        <label>Email:<br />
        <input type="text" name="email" id="email"/></label><br />
        <label>Password<br />
        <input type="text" name="password" id="password"/></label><br>
        <label>Mobile:<br />
        <input type="text" name="mobile" id="mobile"/></label><br />
        <label>Telephone:<br />
        <input type="text" name="telephone" id="telephone"/></label><br> 
        <input type="submit" value="Submit" onclick="getData()">
    </form>
    </fieldset>
_x000D_
_x000D_
_x000D_

This is the second page:

_x000D_
_x000D_
//displaying the value from local storage to another page by their respective Ids
document.getElementById("data").innerHTML=localStorage.getItem("txtValue");
document.getElementById("data1").innerHTML=localStorage.getItem("txtValue1");
document.getElementById("data2").innerHTML=localStorage.getItem("txtValue2");
document.getElementById("data3").innerHTML=localStorage.getItem("txtValue3");
_x000D_
 <div style=" font-size: 30px;  color: rgb(32, 7, 63); text-align: center;">
    <div style="font-size: 40px; color: red; margin: 0 auto;">
        Here's Your data
    </div>
    The Email is equal to: <span id="data"> Email</span><br> 
    The Password is equal to <span id="data1"> Password</span><br>
    The Mobile is equal to <span id="data2"> Mobile</span><br>
    The Telephone is equal to <span id="data3"> Telephone</span><br>
    </div>
_x000D_
_x000D_
_x000D_

Important Note:

Please don't forget to give name "action.html" to the second html file to work the code properly. I can't use multiple pages in a snippet, that's why its not working here try in the browser in your editor where it will surely work.

Append text to input field

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style type="text/css">
        *{
            font-family: arial;
            font-size: 15px;
        }
    </style>
</head>
<body>
    <button id="more">More</button><br/><br/>
    <div>
        User Name : <input type="text" class="users"/><br/><br/>
    </div>
    <button id="btn_data">Send Data</button>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#more').on('click',function(x){
                var textMore = "User Name : <input type='text' class='users'/><br/><br/>";
                $("div").append(textMore);
            });

            $('#btn_data').on('click',function(x){
                var users=$(".users");
                $(users).each(function(i, e) {
                    console.log($(e).val());
                });
            })
        });
    </script>
</body>
</html>

Output enter image description here

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Java: Find .txt files in specified folder

It's really useful, I used it with a slight change:

filename=directory.list(new FilenameFilter() { 
    public boolean accept(File dir, String filename) { 
        return filename.startsWith(ipro); 
    }
});

AWS S3: how do I see how much disk space is using

On linux box that have python (with pip installer), grep and awk, install AWS CLI (command line tools for EC2, S3 and many other services)

sudo pip install awscli

then create a .awssecret file in your home folder with content as below (adjust key, secret and region as needed):

[default]
aws_access_key_id=<YOUR_KEY_HERE>
aws_secret_access_key=<YOUR_SECRET_KEY_HERE>
region=<AWS_REGION>

Make this file read-write to your user only:

sudo chmod 600 .awssecret

and export it to your environment

 export AWS_CONFIG_FILE=/home/<your_name>/.awssecret

then run in the terminal (this is a single line command, separated by \ for easy reading here):

aws s3 ls s3://<bucket_name>/foo/bar | \
grep -v -E "(Bucket: |Prefix: |LastWriteTime|^$|--)" | \
awk 'BEGIN {total=0}{total+=$3}END{print total/1024/1024" MB"}'
  • the aws part lists the bucket (or optionally a 'sub-folder')
  • the grep part removes (using -v) the lines that match the Regular Expression (using -E). ^$ is for blank line, -- is for the separator lines in the output of aws s3 ls
  • the last awk simply add to total the 3rd colum of the resulting output (the size in KB) then display it at the end

NOTE this command works for the current bucket or 'folder', not recursively

'xmlParseEntityRef: no name' warnings while loading xml into a php file

Found this here ...

Problem: An XML parser returns the error “xmlParseEntityRef: noname”

Cause: There is a stray ‘&’ (ampersand character) somewhere in the XML text eg. some text & some more text

Solution:

  • Solution 1: Remove the ampersand.
  • Solution 2: Encode the ampersand (that is replace the & character with &amp; ). Remember to Decode when reading the XML text.
  • Solution 3: Use CDATA sections (text inside a CDATA section will be ignored by the parser.) eg. <![CDATA[some text & some more text]]>

Note: ‘&’ ‘<' '>‘ will all give problems if not handled correctly.

return string with first match Regex

Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost.

def return_first_match(text):
    result = re.findall('\d+',text)
    result = result[0] if result else ""
    return result

FormsAuthentication.SignOut() does not log the user out

This started happening to me when I set the authentication > forms > Path property in Web.config. Removing that fixed the problem, and a simple FormsAuthentication.SignOut(); again removed the cookie.

Page redirect after certain time PHP

You can use this javascript code to redirect after a specific time. Hope it will work.

setRedirectTime(function () 
{
   window.location.href= 'https://www.google.com'; // the redirect URL will be here

},10000); // 10 seconds

comparing 2 strings alphabetically for sorting purposes

"a".localeCompare("b") should actually return -1 since a sorts before b

http://www.w3schools.com/jsref/jsref_localecompare.asp

"Error: Main method not found in class MyClass, please define the main method as..."

The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.

It

  • must be static
  • must have exactly one String array argument (which may be named anything)
  • must be spelled m-a-i-n in lowercase.

Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.

Add one year in current date PYTHON

Look at this:

#!/usr/bin/python

import datetime

def addYears(date, years):
    result = date + datetime.timedelta(366 * years)
    if years > 0:
        while result.year - date.year > years or date.month < result.month or date.day < result.day:
            result += datetime.timedelta(-1)
    elif years < 0:
        while result.year - date.year < years or date.month > result.month or date.day > result.day:
            result += datetime.timedelta(1)
    print "input: %s output: %s" % (date, result)
    return result

Example usage:

addYears(datetime.date(2012,1,1), -1)
addYears(datetime.date(2012,1,1), 0)
addYears(datetime.date(2012,1,1), 1)
addYears(datetime.date(2012,1,1), -10)
addYears(datetime.date(2012,1,1), 0)
addYears(datetime.date(2012,1,1), 10)

And output of this example:

input: 2012-01-01 output: 2011-01-01
input: 2012-01-01 output: 2012-01-01
input: 2012-01-01 output: 2013-01-01
input: 2012-01-01 output: 2002-01-01
input: 2012-01-01 output: 2012-01-01
input: 2012-01-01 output: 2022-01-01

Java difference between FileWriter and BufferedWriter

BufferedWriter is more efficient. It saves up small writes and writes in one larger chunk if memory serves me correctly. If you are doing lots of small writes then I would use BufferedWriter. Calling write calls to the OS which is slow so having as few writes as possible is usually desirable.

Hosting ASP.NET in IIS7 gives Access is denied?

Checking the Application Pool Identity in Anonymous Authentication and enabling Forms Authentication would solve problem for access denied error.

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Greek would need UTF-8 on N column types: aß? ;)

How to run a cronjob every X minutes?

Your CRON should look like this:

*/5 * * * *

CronWTF is really usefull when you need to test out your CRON settings.

Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.

Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:

#!/usr/bin/php

that way you can call the whole thing like this

*/5 * * * * php /path/to/script.php > /path/to/logfile.log

How to move up a directory with Terminal in OS X

Typing cd will take you back to your home directory. Whereas typing cd .. will move you up only one directory (the direct parent of the current directory).

Correct way to initialize empty slice

As an addition to @ANisus' answer...

below is some information from the "Go in action" book, which I think is worth mentioning:

Difference between nil & empty slices

If we think of a slice like this:

[pointer] [length] [capacity]

then:

nil slice:   [nil][0][0]
empty slice: [addr][0][0] // points to an address

nil slice

They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.

// Create a nil slice of integers.
var slice []int

empty slice

Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.

// Use make to create an empty slice of integers.
slice := make([]int, 0)

// Use a slice literal to create an empty slice of integers.
slice := []int{}

Regardless of whether you’re using a nil slice or an empty slice, the built-in functions append, len, and cap work the same.


Go playground example:

package main

import (
    "fmt"
)

func main() {

    var nil_slice []int
    var empty_slice = []int{}

    fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
    fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))

}

prints:

true 0 0
false 0 0

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

Material UI and Grid system

Below is made by purely MUI Grid system,

MUI - Grid Layout

With the code below,

// MuiGrid.js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary,
    backgroundColor: "#b5b5b5",
    margin: "10px"
  }
}));

export default function FullWidthGrid() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Grid container spacing={0}>
        <Grid item xs={12}>
          <Paper className={classes.paper}>xs=12</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={12} sm={6}>
          <Paper className={classes.paper}>xs=12 sm=6</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
        <Grid item xs={6} sm={3}>
          <Paper className={classes.paper}>xs=6 sm=3</Paper>
        </Grid>
      </Grid>
    </div>
  );
}

↓ CodeSandbox ↓

Edit MUI-Grid system

How can I make a ComboBox non-editable in .NET?

To add a Visual Studio GUI reference, you can find the DropDownStyle options under the Properties of the selected ComboBox:

enter image description here

Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent(), like so:

this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;

Reset IntelliJ UI to Default

Recent Versions

Window -> Restore Default Layout

(Thanks to Seven4X's answer)

Older Versions

You can simply delete the whole configuration folder ${user.home}/.IntelliJIdea60/config while IntelliJ IDEA is not running. Next time it restarts, everything is restored from the default settings.

It depends on the OS:

https://intellij-support.jetbrains.com/entries/23358108

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

How to insert a value that contains an apostrophe (single quote)?

Use a backtick (on the ~ key) instead;

`O'Brien`

Change background color of R plot

After combining the information in this thread with the R-help ?rect, I came up with this nice graph for circadian rhythm data (24h plot). The script for the background rectangles is this:

root script:

>rect(xleft, ybottom, xright, ytop, col = NA, border = NULL)

My script:

>i <- 24*(0:8)
>rect(8+i, 1, 24+i, 130, col = "lightgrey", border=NA)
>rect(8+i, -10, 24+i, 0.1, col = "black", border=NA)

The idea is to represent days of 24 hours with 8 h light and 16 h dark.

Cheers,

Romário

Validation error: "No validator could be found for type: java.lang.Integer"

As stated in problem, to solve this error you MUST use correct annotations. In above problem, @NotBlank or @NotEmpty annotation must be applied on any String field only.

To validate long type field, use annotation @NotNull.

How do I find out which process is locking a file using .NET?

Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked.

I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.

using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Collections.Generic;

static public class FileUtil
{
    [StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);
        if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

Using from Limited Permission (e.g. IIS)

This call accesses the registry. If the process does not have permission to do so, you will get ERROR_WRITE_FAULT, meaning An operation was unable to read or write to the registry. You could selectively grant permission to your restricted account to the necessary part of the registry. It is more secure though to have your limited access process set a flag (e.g. in the database or the file system, or by using an interprocess communication mechanism such as queue or named pipe) and have a second process call the Restart Manager API.

Granting other-than-minimal permissions to the IIS user is a security risk.

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

I would add to the accepted answer that you would also want to add the Accept header to the httpClient:

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

How to specify a port to run a create-react-app based project?

Changing in my package.json file "start": "export PORT=3001 && react-scripts start" worked for me too and I'm on macOS 10.13.4

Reverse HashMap keys and values in Java

To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value.

But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.

Java balanced expressions check {[()]}

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    import java.util.Stack;
    public class BalancedParenthesisWithStack {

    /*This is purely Java Stack based solutions without using additonal 
      data structure like array/Map */

    public static void main(String[] args) throws IOException {

        Scanner sc = new Scanner(System.in);

        /*Take list of String inputs (parenthesis expressions both valid and 
         invalid from console*/

        List<String> inputs=new ArrayList<>();
        while (sc.hasNext()) {

            String input=sc.next();
            inputs.add(input);

        }

        //For every input in above list display whether it is valid or 
         //invalid parenthesis expression

        for(String input:inputs){



        System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
        (input));
        }
    }

    //This method identifies whether expression is valid parenthesis or not

    public static boolean isBalancedParenthesis(String expression){

        //sequence of opening parenthesis according to its precedence
         //i.e. '[' has higher precedence than '{' or '('
        String openingParenthesis="[{(";

        //sequence of closing parenthesis according to its precedence
        String closingParenthesis=")}]";

        //Stack will be pushed on opening parenthesis and popped on closing.
        Stack<Character> parenthesisStack=new Stack<>();


          /*For expression to be valid :
          CHECK :
          1. it must start with opening parenthesis [()...
          2. precedence of parenthesis  should be proper (eg. "{[" invalid  
                                                              "[{(" valid  ) 


          3. matching pair if(  '(' => ')')  i.e. [{()}(())] ->valid [{)]not 
          */
         if(closingParenthesis.contains
         (((Character)expression.charAt(0)).toString())){
            return false;
        }else{
        for(int i=0;i<expression.length();i++){

        char ch= (Character)expression.charAt(i);

        //if parenthesis is opening(ie any of '[','{','(') push on stack
        if(openingParenthesis.contains(ch.toString())){
                parenthesisStack.push(ch);
            }else if(closingParenthesis.contains(ch.toString())){
        //if parenthesis is closing (ie any of ']','}',')') pop stack
        //depending upon check-3 
                if(parenthesisStack.peek()=='(' && (ch==')') || 
                    parenthesisStack.peek()=='{' && (ch=='}') ||    
                    parenthesisStack.peek()=='[' && (ch==']')
                        ){
                parenthesisStack.pop();
                }
            }
        }

        return (parenthesisStack.isEmpty())? true : false;
        }
    }

Using OpenGl with C#?

SharpGL is a project that lets you use OpenGL in your Windows Forms or WPF applications.

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

To add to what others posted:

ExecuteScalar conceptually returns the leftmost column from the first row of the resultset from the query; you could ExecuteScalar a SELECT * FROM staff, but you'd only get the first cell of the resulting rows Typically used for queries that return a single value. I'm not 100% sure about SQLServer but in Oracle, you wouldnt use it to run a FUNCTION (a database code that returns a single value) and expect it to give you the return value of the function even though functions return single values.. However, if youre running the function as part of a query, e.g. SELECT SUBSTR('abc', 1, 1) FROM DUAL then it would give the return value by virtue of the fact that the return value is stored in the top leftmost cell of the resulting rowset

ExecuteNonQuery would be used to run database stored procedures, functions and queries that modify data (INSERT/UPDATE/DELETE) or modify database structure (CREATE TABLE...). Typically the return value of the call is an indication of how many rows were affected by the operation but check the DB documentation to guarantee this

how to define variable in jquery

In jquery, u can delcare variable two styles.

One is,

$.name = 'anirudha';
alert($.name);

Second is,

var hText = $("#head1").text();

Second is used when you read data from textbox, label, etc.

case statement in SQL, how to return multiple variables?

Depending on your use case, instead of using a case statement, you can use the union of multiple select statements, one for each condition.

My goal when I found this question was to select multiple columns conditionally. I didn't necessarily need the case statement, so this is what I did.

For example:

  SELECT
    a1,
    a2,
    a3,
    ...
  WHERE <condition 1>
    AND (<other conditions>)
  UNION
  SELECT
    b1,
    b2,
    b3,
    ...
  WHERE <condition 2>
    AND (<other conditions>)
  UNION
  SELECT
  ...
-- and so on

Be sure that exactly one condition evaluates to true at a time.

I'm using Postgresql, and the query planner was smart enough to not run a select statement at all if the condition in the where clause evaluated to false (i.e. only one of the select statement actually runs), so this was also performant for me.

jQuery Scroll To bottom of the page

You can try this

var scroll=$('#scroll');
scroll.animate({scrollTop: scroll.prop("scrollHeight")});

Html table tr inside td

You can solve without nesting tables.

_x000D_
_x000D_
<table border="1">_x000D_
    <thead>_x000D_
        <tr>_x000D_
            <th>ABC</th>_x000D_
            <th>ABC</th>_x000D_
            <th colspan="2">ABC</th>_x000D_
            <th>ABC</th>_x000D_
        </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td rowspan="4">Item1</td>_x000D_
            <td rowspan="4">Item1</td>_x000D_
            <td colspan="2">Item1</td>_x000D_
            <td rowspan="4">Item1</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>Name1</td>_x000D_
            <td>Price1</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>Name2</td>_x000D_
            <td>Price2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>Name3</td>_x000D_
            <td>Price3</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>Item2</td>_x000D_
            <td>Item2</td>_x000D_
            <td colspan="2">Item2</td>_x000D_
            <td>Item2</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

How do I search a Perl array for a matching string?

If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

my @strings = qw( aAa Bbb cCC DDD eee );

my %string_lut;

# Init via slice:
@string_lut{ map uc, @strings } = ();

# or use a for loop:
#    for my $string ( @strings ) {
#        $string_lut{ uc($string) } = undef;
#    }


#Look for a string:

my $search = 'AAa';

print "'$string' ", 
    ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
    " in the array\n";

Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

base64 encode in MySQL

create table encrypt(username varchar(20),password varbinary(200))

insert into encrypt values('raju',aes_encrypt('kumar','key')) select *,cast(aes_decrypt(password,'key') as char(40)) from encrypt where username='raju';

Finding median of list in Python

A simple function to return the median of the given list:

def median(lst):
    lst.sort()  # Sort the list first
    if len(lst) % 2 == 0:  # Checking if the length is even
        # Applying formula which is sum of middle two divided by 2
        return (lst[len(lst) // 2] + lst[(len(lst) - 1) // 2]) / 2
    else:
        # If length is odd then get middle value
        return lst[len(lst) // 2]

Some examples with the medain function:

>>> median([9, 12, 20, 21, 34, 80])  # Even
20.5
>>> median([9, 12, 80, 21, 34])  # Odd
21

If you want to use library you can just simply do:

>>> import statistics
>>> statistics.median([9, 12, 20, 21, 34, 80])  # Even
20.5
>>> statistics.median([9, 12, 80, 21, 34])  # Odd
21

How do I Sort a Multidimensional Array in PHP

With usort. Here's a generic solution, that you can use for different columns:

class TableSorter {
  protected $column;
  function __construct($column) {
    $this->column = $column;
  }
  function sort($table) {
    usort($table, array($this, 'compare'));
    return $table;
  }
  function compare($a, $b) {
    if ($a[$this->column] == $b[$this->column]) {
      return 0;
    }
    return ($a[$this->column] < $b[$this->column]) ? -1 : 1;
  }
}

To sort by first column:

$sorter = new TableSorter(0); // sort by first column
$mdarray = $sorter->sort($mdarray);

How do I grab an INI value within a shell script?

one of more possible solutions

dbver=$(sed -n 's/.*database_version *= *\([^ ]*.*\)/\1/p' < parameters.ini)
echo $dbver

Input type DateTime - Value format?

with momentjs i use

moment(value).format("YYYY-MM-DDTHH:mm:ss")

How to loop through a HashMap in JSP?

Depending on what you want to accomplish within the loop, iterate over one of these instead:

  • countries.keySet()
  • countries.entrySet()
  • countries.values()

How to avoid 'cannot read property of undefined' errors?

What you are doing raises an exception (and rightfully so).

You can always do

try{
   window.a.b.c
}catch(e){
   console.log("YO",e)
}

But I wouldn't, instead think of your use case.

Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?

Usually, you'd like to actually validate what sort of object you're dealing with.

Also, on a side note you should not use statements like if(a.b) because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined

Run bash script from Windows PowerShell

You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish

sh myscriptfile

Disable asp.net button after click to prevent double clicking

This solution works if you are using asp.net validators:

<script language="javascript" type="text/javascript">
function disableButton(sender,group)
{
    Page_ClientValidate(group);
    if (Page_IsValid)
    {
        sender.disabled = "disabled";
        __doPostBack(sender.name, '');
    }
}</script>

and change the button:

<asp:Button runat="server" ID="btnSendMessage" Text="Send" OnClick="btnSendMessage_OnClick" OnClientClick="disableButton(this,'theValidationGroup')" CausesValidation="true" ValidationGroup="theValidationGroup" />

What's the difference between using "let" and "var"?

ECMAScript 6 added one more keyword to declare variables other the "const" other than "let".

The primary goal of introduction of "let" and "const" over "var" is to have block scoping instead of traditional lexical scoping. This article explains very briefly difference between "var" and "let" and it also covers the discussion on "const".

RedirectToAction with parameter

If one want to Show error message for [httppost] then he/she can try by passing an ID using

return RedirectToAction("LogIn", "Security", new { @errorId = 1 });

for Details like this

 public ActionResult LogIn(int? errorId)
        {
            if (errorId > 0)
            {
                ViewBag.Error = "UserName Or Password Invalid !";
            }
            return View();
        }

[Httppost]
public ActionResult LogIn(FormCollection form)
        {
            string user= form["UserId"];
            string password = form["Password"];
            if (user == "admin" && password == "123")
            {
               return RedirectToAction("Index", "Admin");
            }
            else
            {
                return RedirectToAction("LogIn", "Security", new { @errorId = 1 });
            }
}

Hope it works fine.

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

How to convert file to base64 in JavaScript?

JavaScript btoa() function can be used to convert data into base64 encoded string

Find oldest/youngest datetime object in a list

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

Check if application is on its first run

There is no way to know that through the Android API. You have to store some flag by yourself and make it persist either in a SharedPreferenceEditor or using a database.

If you want to base some licence related stuff on this flag, I suggest you use an obfuscated preference editor provided by the LVL library. It's simple and clean.

Regards, Stephane

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

Easiest way to read/write a file's content in Python

This isn't Perl; you don't want to force-fit multiple lines worth of code onto a single line. Write a function, then calling the function takes one line of code.

def read_file(fn):
    """
    >>> import os
    >>> fn = "/tmp/testfile.%i" % os.getpid()
    >>> open(fn, "w+").write("testing")
    >>> read_file(fn)
    'testing'
    >>> os.unlink(fn)
    >>> read_file("/nonexistant")
    Traceback (most recent call last):
        ...
    IOError: [Errno 2] No such file or directory: '/nonexistant'
    """
    with open(fn) as f:
        return f.read()

if __name__ == "__main__":
    import doctest
    doctest.testmod()

How to change style of a default EditText

You have a few options.

  1. Use Android assets studios Android Holo colors generator to generate the resources, styles and themes you need to add to your app to get the holo look across all devices.

  2. Use holo everywhere library.

  3. Use the PNG for the holo text fields and set them as background images yourself. You can get the images from the Android assets studios holo color generator. You'll have to make a drawable and define the normal, selected and disabled states.

UPDATE 2016-01-07

This answer is now outdated. Android has tinting API and ability to theme on controls directly now. A good reference for how to style or theme any element is a site called materialdoc.

What is an Intent in Android?

An Android application can contain zero or more activities. When your application has more than one activity, you often need to navigate from one to another. In Android, you navigate between activities through what is known as an intent. You can pass some data to the activity which you want to start through intent, by using putExtra().

Installing a pip package from within a Jupyter Notebook not working

The problem is that pyarrow is saved by pip into dist-packages (in your case /usr/local/lib/python2.7/dist-packages). This path is skipped by Jupyter so pip won't help.

As a solution I suggest adding in the first block

import sys
sys.path.append('/usr/local/lib/python2.7/dist-packages')

or whatever is path or python version. In case of Python 3.5 this is

import sys
sys.path.append("/usr/local/lib/python3.5/dist-packages")

How should I declare default values for instance variables in Python?

You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:

>>> class TestClass(object):
...     t = None
... 
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>

Also if you need defaults:

>>> class TestClassDefaults(object):
...    t = None
...    def __init__(self, t=None):
...       self.t = t
... 
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>

Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__.

How do I clone a specific Git branch?

Create a branch on the local system with that name. e.g. say you want to get the branch named branch-05142011

git branch branch-05142011 origin/branch-05142011

It'll give you a message:

$ git checkout --track origin/branch-05142011
Branch branch-05142011 set up to track remote branch refs/remotes/origin/branch-05142011.
Switched to a new branch "branch-05142011"

Now just checkout the branch like below and you have the code

git checkout branch-05142011

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

How do I replace multiple spaces with a single space in C#?

Consolodating other answers, per Joel, and hopefully improving slightly as I go:

You can do this with Regex.Replace():

string s = Regex.Replace (
    "   1  2    4 5", 
    @"[ ]{2,}", 
    " "
    );

Or with String.Split():

static class StringExtensions
{
    public static string Join(this IList<string> value, string separator)
    {
        return string.Join(separator, value.ToArray());
    }
}

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Use Message.get_payload

b = email.message_from_string(a)
if b.is_multipart():
    for payload in b.get_payload():
        # if payload.is_multipart(): ...
        print payload.get_payload()
else:
    print b.get_payload()

What's the best way to get the last element of an array without deleting it?

Use the end() function.

$array = [1,2,3,4,5];
$last = end($array); // 5

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

Why can't I duplicate a slice with `copy()`?

NOTE: This is an incorrect solution as @benlemasurier proved

Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

package main

import "fmt"

func main() {
    var foo = []int{1, 2, 3, 4, 5}
    fmt.Println("foo:", foo)
    var bar = append(foo)
    fmt.Println("bar:", bar)
    bar = append(bar, 6)
    fmt.Println("foo after:", foo)
    fmt.Println("bar after:", bar)
}

Outputs this:

foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]

Official reasons for "Software caused connection abort: socket write error"

The java.net.SocketException is thrown when there is an error creating or accessing a socket (such as TCP). This usually can be caused when the server has terminated the connection (without properly closing it), so before getting the full response. In most cases this can be caused either by the timeout issue (e.g. the response takes too much time or server is overloaded with the requests), or the client sent the SYN, but it didn't receive ACK (acknowledgment of the connection termination). For timeout issues, you can consider increasing the timeout value.

The Socket Exception usually comes with the specified detail message about the issue.

Example of detailed messages:

  • Software caused connection abort: recv failed.

    The error indicates an attempt to send the message and the connection has been aborted by your server. If this happened while connecting to the database, this can be related to using not compatible Connector/J JDBC driver.

    Possible solution: Make sure you've proper libraries/drivers in your CLASSPATH.

  • Software caused connection abort: connect.

    This can happen when there is a problem to connect to the remote. For example due to virus-checker rejecting the remote mail requests.

    Possible solution: Check Virus scan service whether it's blocking the port for the outgoing requests for connections.

  • Software caused connection abort: socket write error.

    Possible solution: Make sure you're writing the correct length of bytes to the stream. So double check what you're sending. See this thread.

  • Connection reset by peer: socket write error / Connection aborted by peer: socket write error

    The application did not check whether keep-alive connection had been timed out on the server side.

    Possible solution: Ensure that the HttpClient is non-null before reading from the connection.E13222_01

  • Connection reset by peer.

    The connection has been terminated by the peer (server).

  • Connection reset.

    The connection has been either terminated by the client or closed by the server end of the connection due to request with the request.

    See: What's causing my java.net.SocketException: Connection reset?

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

Passing $_POST values with cURL

Check out this page which has an example of how to do it.

How to get number of rows inserted by a transaction

@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:

DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]

OUTPUT:

(2 row(s) affected)
Rows        ROWCOUNT
----------- -----------
2           1

(1 row(s) affected)

you get Rows value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT command affected 1 row

if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:

--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal  int
DECLARE @PeachTotal  int

SELECT @AppleTotal=0,@PeachTotal=0

BEGIN TRANSACTION

INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

COMMIT

SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal

How to update only one field using Entity Framework?

I know this is an old thread but I was also looking for a similar solution and decided to go with the solution @Doku-so provided. I'm commenting to answer the question asked by @Imran Rizvi , I followed @Doku-so link that shows a similar implementation. @Imran Rizvi's question was that he was getting an error using the provided solution 'Cannot convert Lambda expression to Type 'Expression> [] ' because it is not a delegate type'. I wanted to offer a small modification I made to @Doku-so's solution that fixes this error in case anyone else comes across this post and decides to use @Doku-so's solution.

The issue is the second argument in the Update method,

public int Update(T entity, Expression<Func<T, object>>[] properties). 

To call this method using the syntax provided...

Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn); 

You must add the 'params' keyword in front of the second arugment as so.

public int Update(T entity, params Expression<Func<T, object>>[] properties)

or if you don't want to change the method signature then to call the Update method you need to add the 'new' keyword, specify the size of the array, then finally use the collection object initializer syntax for each property to update as seen below.

Update(Model, new Expression<Func<T, object>>[3] { d=>d.Name }, { d=>d.SecondProperty }, { d=>d.AndSoOn });

In @Doku-so's example he is specifying an array of Expressions so you must pass the properties to update in an array, because of the array you must also specify the size of the array. To avoid this you could also change the expression argument to use IEnumerable instead of an array.

Here is my implementation of @Doku-so's solution.

public int Update<TEntity>(LcmsEntities dataContext, DbEntityEntry<TEntity> entityEntry, params Expression<Func<TEntity, object>>[] properties)
     where TEntity: class
    {
        entityEntry.State = System.Data.Entity.EntityState.Unchanged;

        properties.ToList()
            .ForEach((property) =>
            {
                var propertyName = string.Empty;
                var bodyExpression = property.Body;
                if (bodyExpression.NodeType == ExpressionType.Convert
                    && bodyExpression is UnaryExpression)
                {
                    Expression operand = ((UnaryExpression)property.Body).Operand;
                    propertyName = ((MemberExpression)operand).Member.Name;
                }
                else
                {
                    propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);
                }

                entityEntry.Property(propertyName).IsModified = true;
            });

        dataContext.Configuration.ValidateOnSaveEnabled = false;

        return dataContext.SaveChanges();
    }

Usage:

this.Update<Contact>(context, context.Entry(modifiedContact), c => c.Active, c => c.ContactTypeId);

@Doku-so provided a cool approach using generic's, I used the concept to solve my issue but you just can't use @Doku-so's solution as is and in both this post and the linked post no one answered the usage error questions.

What is a regular expression which will match a valid domain name without a subdomain?

I know that this is a bit of an old post, but all of the regular expressions here are missing one very important component: the support for IDN domain names.

IDN domain names start with xn--. They enable extended UTF-8 characters in domain names. For example, did you know "?.com" is a valid domain name? Yeah, "love heart dot com"! To validate the domain name, you need to let http://xn--c6h.com/ pass the validation.

Note, to use this regex, you will need to convert the domain to lower case, and also use an IDN library to ensure you encode domain names to ACE (also known as "ASCII Compatible Encoding"). One good library is GNU-Libidn.

idn(1) is the command line interface to the internationalized domain name library. The following example converts the host name in UTF-8 into ACE encoding. The resulting URL https://nic.xn--flw351e/ can then be used as ACE-encoded equivalent of https://nic.??/.

  $ idn --quiet -a nic.??
  nic.xn--flw351e

This magic regular expression should cover most domains (although, I am sure there are many valid edge cases that I have missed):

^((?!-))(xn--)?[a-z0-9][a-z0-9-_]{0,61}[a-z0-9]{0,1}\.(xn--)?([a-z0-9\-]{1,61}|[a-z0-9-]{1,30}\.[a-z]{2,})$

When choosing a domain validation regex, you should see if the domain matches the following:

  1. xn--stackoverflow.com
  2. stackoverflow.xn--com
  3. stackoverflow.co.uk

If these three domains do not pass, your regular expression may be not allowing legitimate domains!

Check out The Internationalized Domain Names Support page from Oracle's International Language Environment Guide for more information.

Feel free to try out the regex here: http://www.regexr.com/3abjr

ICANN keeps a list of tlds that have been delegated which can be used to see some examples of IDN domains.


Edit:

 ^(((?!-))(xn--|_{1,1})?[a-z0-9-]{0,61}[a-z0-9]{1,1}\.)*(xn--)?([a-z0-9][a-z0-9\-]{0,60}|[a-z0-9-]{1,30}\.[a-z]{2,})$

This regular expression will stop domains that have '-' at the end of a hostname as being marked as being valid. Additionally, it allows unlimited subdomains.

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

Make child div stretch across width of page

you can pull it out of the flow by setting position:absolute on it, but you'll have different display issues to deal with. Or you can explicitly set the width to > 960.

How to define several include path in Makefile

You have to prepend every directory with -I:

INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public

How to set the JSTL variable value in javascript?

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

import com.fasterxml.jackson.databind.ObjectMapper;

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

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

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

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

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

</taglib> 

web.xml

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

mypage.jsp:

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

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

Access to the path denied error in C#

Did you try specifing some file name?

eg:

string route="D:\\somefilename.txt";

How to check if all inputs are not empty with jQuery

var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
}); 
console.log(isValid);

How to create a simple map using JavaScript/JQuery

var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']

Regex number between 1 and 100

This is very simple logic, So no need of regx.

Instead go for using ternary operator

var num = 89;
var isValid = (num <=  100 && num > 0 ) ? true : false;

It will do the magic for you!!

How can I calculate the time between 2 Dates in typescript

// TypeScript

const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);

// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Get Specific Columns Using “With()” Function in Laravel Eloquent

Now you can use the pluckmethod on a Collection instance:

This will return only the uuid attribute of the Post model

App\Models\User::find(2)->posts->pluck('uuid')
=> Illuminate\Support\Collection {#983
     all: [
       "1",
       "2",
       "3",
     ],
   }

make iframe height dynamic based on content inside- JQUERY/Javascript

Add this to the iframe, this worked for me:

onload="this.height=this.contentWindow.document.body.scrollHeight;"

And if you use jQuery try this code:

onload="$(this).height($(this.contentWindow.document.body).find(\'div\').first().height());"

How to dump a table to console?

This is my version that supports excluding tables and userdata

-- Lua Table View by Elertan
table.print = function(t, exclusions)
    local nests = 0
    if not exclusions then exclusions = {} end
    local recurse = function(t, recurse, exclusions)
        indent = function()
            for i = 1, nests do
                io.write("    ")
            end
        end
        local excluded = function(key)
            for k,v in pairs(exclusions) do
                if v == key then
                    return true
                end
            end
            return false
        end
        local isFirst = true
        for k,v in pairs(t) do
            if isFirst then
                indent()
                print("|")
                isFirst = false
            end
            if type(v) == "table" and not excluded(k) then
                indent()
                print("|-> "..k..": "..type(v))
                nests = nests + 1
                recurse(v, recurse, exclusions)
            elseif excluded(k) then
                indent()
                print("|-> "..k..": "..type(v))
            elseif type(v) == "userdata" or type(v) == "function" then
                indent()
                print("|-> "..k..": "..type(v))
            elseif type(v) == "string" then
                indent()
                print("|-> "..k..": ".."\""..v.."\"")
            else
                indent()
                print("|-> "..k..": "..v)
            end
        end
        nests = nests - 1
    end

    nests = 0
    print("### START TABLE ###")
    for k,v in pairs(t) do
        print("root")
        if type(v) == "table" then
            print("|-> "..k..": "..type(v))
            nests = nests + 1
            recurse(v, recurse, exclusions)
        elseif type(v) == "userdata" or type(v) == "function" then
            print("|-> "..k..": "..type(v))
        elseif type(v) == "string" then
            print("|-> "..k..": ".."\""..v.."\"")
        else
            print("|-> "..k..": "..v)
        end
    end
    print("### END TABLE ###")
end

This is an example

t = {
    location = {
       x = 10,
       y = 20
    },
    size = {
      width = 100000000,
      height = 1000,
    },
    name = "Sidney",
    test = {
        hi = "lol",
    },
    anotherone = {
        1, 
        2, 
        3
    }
}

table.print(t, { "test" })

Prints:

   ### START TABLE ###
root
|-> size: table
    |
    |-> height: 1000
    |-> width: 100000000
root
|-> location: table
    |
    |-> y: 20
    |-> x: 10
root
|-> anotherone: table
    |
    |-> 1: 1
    |-> 2: 2
    |-> 3: 3
root
|-> test: table
    |
    |-> hi: "lol"
root
|-> name: "Sidney"
### END TABLE ###

Notice that the root doesn't remove exclusions

How to delete specific rows and columns from a matrix in a smarter way?

You can use

t1<- t1[-4:-6,-7:-9]  

or

t1 <- t1[-(4:6), -(7:9)]

or

t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]

You can pass vectors to select rows/columns to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns.

> t1 <- array(1:20, dim=c(10,10));

> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   12    2   12    2   12
[2,]    3   13    3   13    3   13
[3,]    5   15    5   15    5   15
[4,]    8   18    8   18    8   18
[5,]   10   20   10   20   10   20

using awk with column value conditions

This method uses regexp, it should work:

awk '$2 ~ /findtext/ {print $3}' <infile>

Editing the date formatting of x-axis tick labels in matplotlib

In short:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

TensorFlow: "Attempting to use uninitialized value" in variable initialization

It's not 100% clear from the code example, but if the list initial_parameters_of_hypothesis_function is a list of tf.Variable objects, then the line session.run(init) will fail because TensorFlow isn't (yet) smart enough to figure out the dependencies in variable initialization. To work around this, you should change the loop that creates parameters to use initial_parameters_of_hypothesis_function[i].initialized_value(), which adds the necessary dependency:

parameters = []
for i in range(0, number_of_attributes, 1):
    parameters.append(tf.Variable(
        initial_parameters_of_hypothesis_function[i].initialized_value()))