Programs & Examples On #Widescreen

Font scaling based on width of container

Try http://simplefocus.com/flowtype/. This is what I use for my sites, and it has worked perfectly.

if else statement in AngularJS templates

Angularjs (versions below 1.1.5) does not provide the if/else functionality . Following are a few options to consider for what you want to achieve:

(Jump to the update below (#5) if you are using version 1.1.5 or greater)

1. Ternary operator:

As suggested by @Kirk in the comments, the cleanest way of doing this would be to use a ternary operator as follows:

<span>{{isLarge ? 'video.large' : 'video.small'}}</span>

2. ng-switch directive:

can be used something like the following.

<div ng-switch on="video">
    <div ng-switch-when="video.large">
        <!-- code to render a large video block-->
    </div>
    <div ng-switch-default>
        <!-- code to render the regular video block -->
    </div>
</div>

3. ng-hide / ng-show directives

Alternatively, you might also use ng-show/ng-hide but using this will actually render both a large video and a small video element and then hide the one that meets the ng-hide condition and shows the one that meets ng-show condition. So on each page you'll actually be rendering two different elements.

4. Another option to consider is ng-class directive.

This can be used as follows.

<div ng-class="{large-video: video.large}">
    <!-- video block goes here -->
</div>

The above basically will add a large-video css class to the div element if video.large is truthy.

UPDATE: Angular 1.1.5 introduced the ngIf directive

5. ng-if directive:

In the versions above 1.1.5 you can use the ng-if directive. This would remove the element if the expression provided returns false and re-inserts the element in the DOM if the expression returns true. Can be used as follows.

<div ng-if="video == video.large">
    <!-- code to render a large video block-->
</div>
<div ng-if="video != video.large">
    <!-- code to render the regular video block -->
</div>

How to detect iPhone 5 (widescreen devices)?

This has been answered a hundred times but this solution worked the best for me and helped address the issue when new devices are introduced and I don't have a size defined.

Swift 5 Helper:

extension UIScreen {
    func phoneSizeInInches() -> CGFloat {
        switch (self.nativeBounds.size.height) {
        case 960, 480:
            return 3.5  //iPhone 4
        case 1136:
            return 4    //iPhone 5
        case 1334:
            return 4.7  //iPhone 6
        case 2208:
            return 5.5  //iPhone 6 Plus
        case 2436:
            return 5.8  //iPhone X
        case 1792:
            return 6.1  //iPhone XR
        case 2688:
            return 6.5  //iPhone XS Max
        default:
            let scale = self.scale
            let ppi = scale * 163
            let width = self.bounds.size.width * scale
            let height = self.bounds.size.height * scale
            let horizontal = width / ppi, vertical = height / ppi
            let diagonal = sqrt(pow(horizontal, 2) + pow(vertical, 2))
            return diagonal
        }
    }
}

This is because it's easy to memorize a phone's inch sizes, like, "5.5 inch" or "4.7 inch" device but difficult to remember the exact pixel sizes.

if UIScreen.main.phoneSizeInInches() == 4 {
  //do something with only 4 inch iPhones
}

This also gives you the opportunity to do something like this:

if UIScreen.main.phoneSizeInInches() < 5.5 {
  //do something on all iPhones smaller than the plus
}

The default: tries to uses the screen size and scale to try and calculate the diagonal inches. This is in case some new device size appears, it will try its best to determine and code, such as the last example, should still work.

How to develop or migrate apps for iPhone 5 screen resolution?

Use the Auto Layout feature for views. It will adjust automatically to all resolutions.

Create two xibs for a controller having controller name with suffix either ~iphone or ~ipad. At compile time, Xcode will take the right xib based on the device.

Use size classes, if you want to create a single xib for both iPhone and iPad, if the view is simple enough to port to iPhone and iPad.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

I use WinSplit Revolution for the keyboard arrangement capability and I use bblean as a replacement for Explorer. It has multiple workspace capabilities built right in and it allows you to customize it exactly how you want it to look.

android edittext onchange listener

 myTextBox.addTextChangedListener(new TextWatcher() {  

    public void afterTextChanged(Editable s) {}  

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 

    public void onTextChanged(CharSequence s, int start, int before, int count) {  

    TextView myOutputBox = (TextView) findViewById(R.id.myOutputBox);  
    myOutputBox.setText(s);  

    }  
});  

Inserting HTML into a div

Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:

$('#yourDivName').html('yourtHTML');

You may also consider using:

$('#yourDivName').append('yourtHTML');

This will add your gallery as the last item in the selected div. Or:

$('#yourDivName').prepend('yourtHTML');

This will add it as the first item in the selected div.

See the JQuery docs for these functions:

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

adb command for getting ip address assigned by operator

Try:

adb shell ip addr show rmnet0

It will return something like that:

3: rmnet0: <UP,LOWER_UP> mtu 1500 qdisc htb state UNKNOWN qlen 1000
    link/[530]
    inet 172.22.1.100/29 scope global rmnet0
    inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc/64 scope global dynamic
       valid_lft forever preferred_lft forever
    inet6 fe80::8099:af3f:2af2:8bc/64 scope link
       valid_lft forever preferred_lft forever 

This part is your IPV4 assigned by the operator

inet 172.22.1.100

This part is your IPV6 assigned by the operator

inet6 fc01:abab:cdcd:efe0:8099:af3f:2af2:8bc

Laravel check if collection is empty

I prefer

(!$mentor)

Is more effective and accurate

How to solve "Connection reset by peer: socket write error"?

The socket has been closed by the client (browser).

A bug in your code:

byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
   output.write(outputByte,0,4096);
}

The last packet read, then write may have a length < 4096, so I suggest:

byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
   output.write( outputByte, 0, len );
}

It's not your question, but it's my answer... ;-)

IFRAMEs and the Safari on the iPad, how can the user scroll the content?

-webkit-overflow-scrolling:touch as mentioned in the answer is infact the possible solution.

<div style="overflow:scroll !important; -webkit-overflow-scrolling:touch !important;">
     <iframe src="YOUR_PAGE_URL" width="600" height="400"></iframe>
</div>

But if you are unable to scroll up and down inside the iframe as shown in image below, enter image description here

you could try scrolling with 2 fingers diagonally like this,

enter image description here

This actually worked in my case, so just sharing it if you haven't still found a solution for this.

Password encryption at client side

This won't be secure, and it's simple to explain why:

If you hash the password on the client side and use that token instead of the password, then an attacker will be unlikely to find out what the password is.

But, the attacker doesn't need to find out what the password is, because your server isn't expecting the password any more - it's expecting the token. And the attacker does know the token because it's being sent over unencrypted HTTP!

Now, it might be possible to hack together some kind of challenge/response form of encryption which means that the same password will produce a different token each request. However, this will require that the password is stored in a decryptable format on the server, something which isn't ideal, but might be a suitable compromise.

And finally, do you really want to require users to have javascript turned on before they can log into your website?

In any case, SSL is neither an expensive or especially difficult to set up solution any more

How to generate .angular-cli.json file in Angular Cli?

As far as I know Angular-cli file can't be created via a command like Package-lock file, If you want to create it, you have to do it manually.

  1. You can type ng new to create a new angular project

  2. Locate its .angular-cli.json file

  3. Copy all its content

  4. Create a folder in your original project, and name it .angular-cli.json

  5. Paste what copied from new project in newly created angular cli file of original project.

  6. Locate this line in angular cli file you created, and change the name field to original project's name. You can find the project name in package.json file

project": {
  "name": "<name of the project>"
},

However, in newer angular version now it uses angular.json instead of angular-cli.json.

Get the last day of the month in SQL

Using SQL Server, here is another way to find last day of month :

SELECT DATEADD(MONTH,1,GETDATE())- day(DATEADD(MONTH,1,GETDATE()))

How to add an extra source directory for maven to compile and include in the build jar?

You can use the Build Helper Plugin, e.g:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.2.0</version>
        <executions>
          <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>some directory</source>
                ...
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

How to change Angular CLI favicon

Make sure when you use icon image it is not manipulated extension, like if you download a png image and then manually change its extension from png to icon. In this case, your image will be corrupted. And browser does not understand.

I did this mistake, but after using original icon image its start working.

How can I format a nullable DateTime with ToString()?

Console.WriteLine(dt2 != null ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "n/a"); 

EDIT: As stated in other comments, check that there is a non-null value.

Update: as recommended in the comments, extension method:

public static string ToString(this DateTime? dt, string format)
    => dt == null ? "n/a" : ((DateTime)dt).ToString(format);

And starting in C# 6, you can use the null-conditional operator to simplify the code even more. The expression below will return null if the DateTime? is null.

dt2?.ToString("yyyy-MM-dd hh:mm:ss")

Call two functions from same onclick

put a semicolon between the two functions as statement terminator.

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

In my case setting folowing options helpet me out

enter image description here

Changing plot scale by a factor in matplotlib

To set the range of the x-axis, you can use set_xlim(left, right), here are the docs

Update:

It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:

ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)

Attach a body onload event with JS

jcalfee314's idea worked for me - I had a window.onload = onLoad which meant that the functions in <body onload="..."> were not being called (which I don't have control over).

This fixed it:

oldOnLoad = window.onload
window.onload = onLoad;

function onLoad()
{
oldOnLoad();
...
}

Edit: Firefox didn't like oldOnLoad = document.body.onload;, so replaced with oldOnLoad = window.onload.

How to center a WPF app on screen?

What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.

But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?

Reset the Value of a Select Box

What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});   

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

ConcurrentHashMap was presented as alternative to Hashtable in Java 1.5 as part of concurrency package. With ConcurrentHashMap, you have a better choice not only if it can be safely used in the concurrent multi-threaded environment but also provides better performance than Hashtable and synchronizedMap. ConcurrentHashMap performs better because it locks a part of Map. It allows concurred read operations and the same time maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented

ConcurrentHashMap was developed as alternative of Hashtable and support all functionality of Hashtable with additional ability, so called concurrency level. ConcurrentHashMap allows multiple readers to read simultaneously without using blocks. It becomes possible by separating Map to different parts and blocking only part of Map in updates. By default, concurrency level is 16, so Map is spitted to 16 parts and each part is managed by separated block. It means, that 16 threads can work with Map simultaneously, if they work with different parts of Map. It makes ConcurrentHashMap hight productive, and not to down thread-safety.

If you are interested in some important features of ConcurrentHashMap and when you should use this realization of Map - I just put a link to a good article - How to use ConcurrentHashMap in Java

Load Image from javascript

If you are loading the image via AJAX you could use a callback to check if the image is loaded and do the hiding and src attribute assigning. Something like this:

$.ajax({ 
  url: [image source],
  success: function() {
  // Do the hiding here and the attribute setting
  }
});

For more reading refer to this JQuery AJAX

What exactly is a Maven Snapshot and why do we need it?

This is how a snapshot looks like for a repository and in this case is not enabled, which means that the repository referred in here is stable and there's no need for updates.

<project>
    ...
    <repositories>
        <repository>
            <id>lds-main</id>
            <name>LDS Main Repo</name>
            <url>http://code.lds.org/nexus/content/groups/main-repo</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

Another case would be for:

<snapshots>
        <enabled>true</enabled>
</snapshots>

which means that Maven will look for updates for this repository. You can also specify an interval for the updates with tag.

How to Select Top 100 rows in Oracle?

To select top n rows updated recently

SELECT * 
FROM (
   SELECT * 
   FROM table 
   ORDER BY UpdateDateTime DESC
)
WHERE ROWNUM < 101;

Authorize a non-admin developer in Xcode / Mac OS

For me, I found the suggestion in the following thread helped:

Stop "developer tools access needs to take control of another process for debugging to continue" alert

It suggested running the following command in the Terminal application:

sudo /usr/sbin/DevToolsSecurity --enable

Mongoose limit/offset and count query

I suggest you to use 2 queries:

  1. db.collection.count() will return total number of items. This value is stored somewhere in Mongo and it is not calculated.

  2. db.collection.find().skip(20).limit(10) here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too.

I think that you shouldn't query all items and than perform skip and take, cause later when you have big data you will have problems with data transferring and processing.

Create two-dimensional arrays and access sub-arrays in Ruby

Here's a 3D array case

class Array3D
   def initialize(d1,d2,d3)
    @data = Array.new(d1) { Array.new(d2) { Array.new(d3) } }
   end

  def [](x, y, z)
    @data[x][y][z]
  end

  def []=(x, y, z, value)
    @data[x][y][z] = value
  end
end

You can access subsections of each array just like any other Ruby array. @data[0..2][3..5][8..10] = 0 etc

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

I did the following to resolve mine:

  1. Open VirtualBox and check the new machine that is created for you by GenyMotion
  2. Right Click on it and choose Settings then go to the Network section/tab
  3. In Adapter 1 tab, It should be attached to Host-Only Adapter. Check what is the name of the used adapter Name then close it.

  4. Open File|Preferences in Virtualbox, then go to Network section/tab

  5. Under Host-only Networks tab, find the same name you have already gotten in step 3.

  6. Double click on that name and apple the following configuration

    • Adapter Tab:
    • IPv4 Adapter: 192.168.65.1
    • IPV4 Network Mask: 255.255.255.0

    • DHCP Server:

    • Check "Enable Server"
    • Server Address: 192.168.65.100
    • Server Mask: 255.255.255.0
    • Lower Address Bound: 192.168.65.101
    • Higher Address Bound: 192.168.65.255

Android XXHDPI resources

xxhdpi was not specified before but now new devices S4, HTC one are surely comes inside xxhdpi .These device dpi are around 440. I do not know exact limit for xxhdpi See how to develop android application for xxhdpi device Samsung S4 I know this is late answer but as thing had change since the question asked

Note Google Nexus 10 need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

How to escape braces (curly brackets) in a format string in .NET

Escaping curly brackets AND using string interpolation makes for an interesting challenge. You need to use quadruple brackets to escape the string interpolation parsing and string.format parsing.

Escaping Brackets: String Interpolation $("") and String.Format

string localVar = "dynamic";
string templateString = $@"<h2>{0}</h2><div>this is my {localVar} template using a {{{{custom tag}}}}</div>";
string result = string.Format(templateString, "String Interpolation");

// OUTPUT: <h2>String Interpolation</h2><div>this is my dynamic template using a {custom tag}</div>

Pandas join issue: columns overlap but no suffix specified

This error indicates that the two tables have the 1 or more column names that have the same column name. The error message translates to: "I can see the same column in both tables but you haven't told me to rename either before bringing one of them in"

You either want to delete one of the columns before bringing it in from the other on using del df['column name'], or use lsuffix to re-write the original column, or rsuffix to rename the one that is being brought it.

df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')

Rails create or update magic?

You can do it in one statement like this:

CachedObject.where(key: "the given key").first_or_create! do |cached|
   cached.attribute1 = 'attribute value'
   cached.attribute2 = 'attribute value'
end

What is the ultimate postal code and zip regex?

This looks like a good reference although it's not in Regex.

Really, unless you're actually shipping something to your users, I don't think it's worth the effort. And if you are shipping it, there are address cleaning tools/services you can look into to make it way easier on yourself.

Want to make Font Awesome icons clickable

I found this worked best for my usecase:

<i class="btn btn-light fa fa-dribbble fa-4x" href="#"></i>
<i class="btn btn-light fa fa-behance-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-linkedin-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-twitter-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-facebook-square fa-4x" href="#"></i>

Redirect to specified URL on PHP script completion?

Here's a solution to the "headers were already sent" problem. Assume you are validating and emailing a form. Make sure the php code is the first thing on your page... before any of the doctype and head tags and all that jazz. Then, when the POST arrives back at the page the php code will come first and not encounter the headers already sent problem.

sql set variable using COUNT

You want:

DECLARE @times int

SELECT @times =  COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

You also don't need the 'as' clause.

How to update a claim in ASP.NET Identity?

To remove claim details from database we can use below code. Also, we need to sign in again to update the cookie values

 // create a new identity 
            var identity = new ClaimsIdentity(User.Identity);

            // Remove the existing claim value of current user from database
            if(identity.FindFirst("NameOfUser")!=null)
                await UserManager.RemoveClaimAsync(applicationUser.Id, identity.FindFirst("NameOfUser"));

            // Update customized claim 
            await UserManager.AddClaimAsync(applicationUser.Id, new Claim("NameOfUser", applicationUser.Name));

            // the claim has been updates, We need to change the cookie value for getting the updated claim
            AuthenticationManager.SignOut(identity.AuthenticationType);
            await SignInManager.SignInAsync(Userprofile, isPersistent: false, rememberBrowser: false);

            return RedirectToAction("Index", "Home");

Using Python String Formatting with Lists

The same as @neobot's answer but a little more modern and succinct.

>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'

.htaccess File Options -Indexes on Subdirectories

htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.

http://www.javascriptkit.com/howto/htaccess.shtml

MySQL vs MySQLi when using PHP

There is a manual page dedicated to help choosing between mysql, mysqli and PDO at

The PHP team recommends mysqli or PDO_MySQL for new development:

It is recommended to use either the mysqli or PDO_MySQL extensions. It is not recommended to use the old mysql extension for new development. A detailed feature comparison matrix is provided below. The overall performance of all three extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

The page also has a feature matrix comparing the extension APIs. The main differences between mysqli and mysql API are as follows:

                               mysqli     mysql
Development Status             Active     Maintenance only
Lifecycle                      Active     Long Term Deprecation Announced*
Recommended                    Yes        No
OOP API                        Yes        No
Asynchronous Queries           Yes        No
Server-Side Prep. Statements   Yes        No
Stored Procedures              Yes        No
Multiple Statements            Yes        No
Transactions                   Yes        No
MySQL 5.1+ functionality       Yes        No

* http://news.php.net/php.internals/53799

There is an additional feature matrix comparing the libraries (new mysqlnd versus libmysql) at

and a very thorough blog article at

Can I install Python 3.x and 2.x on the same Windows computer?

Here is a neat and clean way to install Python2 & Python3 on windows.

https://datascience.com.co/how-to-install-python-2-7-and-3-6-in-windows-10-add-python-path-281e7eae62a

My case: I had to install Apache cassandra. I already had Python3 installed in my D: drive. With loads of development work under process i didn't wanted to mess my Python3 installation. And, i needed Python2 only for Apache cassandra.

So i took following steps:

  1. Downloaded & Installed Python2.
  2. Added Python2 entries to classpath (C:\Python27;C:\Python27\Scripts)
  3. Modified python.exe to python2.exe (as shown in image below)

enter image description here

  1. Now i am able to run both. For Python 2(python2 --version) & Python 3 (python --version). enter image description here

So, my Python3 installation remained intact.

Adding timestamp to a filename with mv in BASH

Well, it's not a direct answer to your question, but there's a tool in GNU/Linux whose job is to rotate log files on regular basis, keeping old ones zipped up to a certain limit. It's logrotate

Change Button color onClick

1.

function setColor(e) {
  var target = e.target,
      count = +target.dataset.count;

   target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
   target.dataset.count = count === 1 ? 0 : 1;
   /* 

   () : ? - this is conditional (ternary) operator - equals 

   if (count === 1) {
      target.style.backgroundColor = "#7FFF00";
      target.dataset.count = 0;
   } else {
      target.style.backgroundColor = "#FFFFFF";
      target.dataset.count = 1;
   } 
   target.dataset - return all "data attributes" for current element, 
   in the form of object, 
   and you don't need use global variable in order to save the state 0 or 1
  */ 
}


<input 
  type="button" 
  id="button" 
  value="button" 
  style="color:white" 
  onclick="setColor(event)"; 
  data-count="1" 
/>

2.

function setColor(e) {
   var target = e.target,
       status = e.target.classList.contains('active');

   e.target.classList.add(status ? 'inactive' : 'active');
   e.target.classList.remove(status ? 'active' : 'inactive'); 
}

.active {
  background-color: #7FFF00;  
}

.inactive {
  background-color: #FFFFFF;
}

<input 
  type="button" 
  id="button" 
  value="button" 
  style="color:white" 
  onclick="setColor(event)" 
/>

([conditional (ternary) operator])

Example-1

Example-2

How to display HTML tags as plain text

you may use htmlspecialchars()

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Concatenating Files And Insert New Line In Between Files

That's how I just did it on OsX 10.10.3

for f in *.txt; do (cat $f; echo '') >> fullData.txt; done

since the simple 'echo' command with no params ended up in no new lines inserted.

Transform DateTime into simple Date in Ruby on Rails

For old Ruby (1.8.x):

myDate = Date.parse(myDateTime.to_s)

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

How to make Python speak

There may not be anything 'Python specific', but the KDE and GNOME desktops offer text-to-speech as a part of their accessibility support, and also offer python library bindings. It may be possible to use the python bindings to control the desktop libraries for text to speech.

If using the Jython implementation of Python on the JVM, the FreeTTS system may be usable.

Finally, OSX and Windows have native APIs for text to speech. It may be possible to use these from python via ctypes or other mechanisms such as COM.

Convert a object into JSON in REST service by Spring MVC


The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:

<bean id="contentNegotiationManager"
      class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="useJaf" value="false" />
     <property name="defaultContentType" value="application/json" />

      <property name="mediaTypes">
         <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
         </map>
      </property>
   </bean>

   <mvc:annotation-driven
      content-negotiation-manager="contentNegotiationManager" />

   <context:annotation-config />

Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.

Looping through a hash, or using an array in PowerShell

Here is another quick way, just using the key as an index into the hash table to get the value:

$hash = @{
    'a' = 1;
    'b' = 2;
    'c' = 3
};

foreach($key in $hash.keys) {
    Write-Host ("Key = " + $key + " and Value = " + $hash[$key]);
}

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

create a text file using javascript

Try this:

<SCRIPT LANGUAGE="JavaScript">
 function WriteToFile(passForm) {

    set fso = CreateObject("Scripting.FileSystemObject");  
    set s = fso.CreateTextFile("C:\test.txt", True);
    s.writeline("HI");
    s.writeline("Bye");
    s.writeline("-----------------------------");
    s.Close();
 }
  </SCRIPT>

</head>

<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form> 

This will work only on IE

Replacing values from a column using a condition in R

I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful

library(dplyr)
iris %>% 
  mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))

Bootstrap Modal before form Submit

So if I get it right, on click of a button, you want to open up a modal that lists the values entered by the users followed by submitting it.

For this, you first change your input type="submit" to input type="button" and add data-toggle="modal" data-target="#confirm-submit" so that the modal gets triggered when you click on it:

<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />

Next, the modal dialog:

<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Confirm Submit
            </div>
            <div class="modal-body">
                Are you sure you want to submit the following details?

                <!-- We display the details entered by the user here -->
                <table class="table">
                    <tr>
                        <th>Last Name</th>
                        <td id="lname"></td>
                    </tr>
                    <tr>
                        <th>First Name</th>
                        <td id="fname"></td>
                    </tr>
                </table>

            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a href="#" id="submit" class="btn btn-success success">Submit</a>
            </div>
        </div>
    </div>
</div>

Lastly, a little bit of jQuery:

$('#submitBtn').click(function() {
     /* when the button in the form, display the entered values in the modal */
     $('#lname').text($('#lastname').val());
     $('#fname').text($('#firstname').val());
});

$('#submit').click(function(){
     /* when the submit button in the modal is clicked, submit the form */
    alert('submitting');
    $('#formfield').submit();
});

You haven't specified what the function validateForm() does, but based on this you should restrict your form from being submitted. Or you can run that function on the form's button #submitBtn click and then load the modal after the validations have been checked.

DEMO

How to resolve Value cannot be null. Parameter name: source in linq?

Error message clearly says that source parameter is null. Source is the enumerable you are enumerating. In your case it is ListMetadataKor object. And its definitely null at the time you are filtering it second time. Make sure you never assign null to this list. Just check all references to this list in your code and look for assignments.

What is the difference between aggregation, composition and dependency?

One object may contain another as a part of its attribute.

  1. document contains sentences which contain words.
  2. Computer system has a hard disk, ram, processor etc.

So containment need not be physical. e.g., computer system has a warranty.

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

Font is not available to the JVM with Jasper Reports

can make your custom fonts via iReport and converting like jars files

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

A static library(.a) is a library that can be linked directly into the final executable produced by the linker,it is contained in it and there is no need to have the library into the system where the executable will be deployed.

A shared library(.so) is a library that is linked but not embedded in the final executable, so will be loaded when the executable is launched and need to be present in the system where the executable is deployed.

A dynamic link library on windows(.dll) is like a shared library(.so) on linux but there are some differences between the two implementations that are related to the OS (Windows vs Linux) :

A DLL can define two kinds of functions: exported and internal. The exported functions are intended to be called by other modules, as well as from within the DLL where they are defined. Internal functions are typically intended to be called only from within the DLL where they are defined.

An SO library on Linux doesn't need special export statement to indicate exportable symbols, since all symbols are available to an interrogating process.

Jquery Ajax Loading image

Try something like this:

<div id="LoadingImage" style="display: none">
  <img src="" />
</div>

<script>
  function ajaxCall(){
    $("#LoadingImage").show();
      $.ajax({ 
        type: "GET", 
        url: surl, 
        dataType: "jsonp", 
        cache : false, 
        jsonp : "onJSONPLoad", 
        jsonpCallback: "newarticlescallback", 
        crossDomain: "true", 
        success: function(response) { 
          $("#LoadingImage").hide();
          alert("Success"); 
        }, 
        error: function (xhr, status) {  
          $("#LoadingImage").hide();
          alert('Unknown error ' + status); 
        }    
      });  
    }
</script>

WebSockets protocol vs HTTP

For the TL;DR, here are 2 cents and a simpler version for your questions:

  1. WebSockets provides these benefits over HTTP:

    • Persistent stateful connection for the duration of the connection
    • Low latency: near-real-time communication between server/client due to no overhead of reestablishing connections for each request as HTTP requires.
    • Full duplex: both server and client can send/receive simultaneously
  2. WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.

How to darken a background using CSS?

For me the filter/gradient approach didn't work (perhaps due to the existing CSS) so I have used :before pseudo styling trick instead:

.eventBannerContainer {
    position: relative;
}
.eventBannerContainer:before {
    background-color: black;
    height: 100%;
    width: 100%;
    content: "";
    opacity: 0.5;
    position: absolute;
    display: block;
}
/* make any immediate child elements above our darkening mask */
.eventBannerContainer > * {
    position: relative;
}

What Process is using all of my disk IO

Have you considered lsof (list open files)?

Easiest way to rotate by 90 degrees an image using OpenCV?

Here is my python cv2 implementation:

import cv2

img=cv2.imread("path_to_image.jpg")

# rotate ccw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=0)

# rotate cw
out=cv2.transpose(img)
out=cv2.flip(out,flipCode=1)

cv2.imwrite("rotated.jpg", out)

How to delete all files and folders in a folder by cmd call

I think the easiest way to do it is:

rmdir /s /q "C:\FolderToNotToDelete\"

The last "\" in the path is the important part.

How to run multiple SQL commands in a single SQL connection?

Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.

// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();

// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();

Formatting html email for Outlook

To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.

Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.

From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:

  • Various types of more sophisticated selectors, e.g. E:first-child, E:hover, E > F (Child combinator), E + F (Adjacent sibling combinator), E ~ F (General sibling combinator). This unfortunately means resorting to workarounds like inline styles.
  • Some font properties, e.g. white-space won't work.
  • The background-image property won't work.
  • There are several issues with the Box Model properties, most importantly height, width, and the max- versions are either not usable or have bugs for certain elements.
  • Positioning and Display issues (e.g. display, floats and position are all out).

In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.

PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top" where you probably meant to use vertical-align. Also: cell-padding for tds doesn't exist.

How to use std::sort to sort an array in C++

you can use,

 std::sort(v.begin(),v.end());

What can be the reasons of connection refused errors?

There could be many reasons, but the most common are:

  1. The port is not open on the destination machine.

  2. The port is open on the destination machine, but its backlog of pending connections is full.

  3. A firewall between the client and server is blocking access (also check local firewalls).

After checking for firewalls and that the port is open, use telnet to connect to the ip/port to test connectivity. This removes any potential issues from your application.

Expanding a parent <div> to the height of its children

Using something like self-clearing div is perfect for a situation like this. Then you'll just use a class on the parent... like:

<div id="parent" class="clearfix">

How to suppress Update Links warning?

UPDATE:

After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all is.

Preparations

First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).

Then, I changed only the following Excel options (i.e. all the other are left as is after installation):

  • Advanced > General > Ask to update automatic links checked:

Ask to update automatic links

  • Trust Center > Trust Center Settings... > External Content > Enable All... (although that one that relates to Data Connections is most likely not important for the case):

External Content

Preconditions

I prepared and placed to C:\ a workbook exactly as per @Siddharth Rout suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).

Manual Opening

The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:

WARNING #1

This workbook contains links to other data sources

After click on Update I expectedly got another:

WARNING #2

This workbook contains one or more links that cannot be updated

So, I suppose my testing environment is now pretty much similar to OP's) So far so good, we finally go to

VBA Opening

Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).

1. Simple Application.Workbooks.Open

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"

No surprise - this produces BOTH warnings, as for manual opening above.

2. Application.DisplayAlerts = False

Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True

This code ends up with WARNING #1, and either option clicked (Update / Don't Update) produces NO further warnings, i.e. Application.DisplayAlerts = False suppresses WARNING #2.

3. Application.AskToUpdateLinks = False

Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True

Opposite to DisplayAlerts, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False suppresses WARNING #1.

4. Double False

Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

Apparently, this code ends up with suppressing BOTH WARNINGS.

5. UpdateLinks:=False

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False

Finally, this 1-line solution (originally proposed by @brettdj) works the same way as Double False: NO WARNINGS are shown!

Conclusions

Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:

  1. Excel options DO matter, regardless of version - especially when we come to VBA solutions.
  2. Every trouble has short and elegant solution - together with not obvious and complicated one. Just one more proof for that!)

Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)

Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Original answer (tested for Excel 2007 with certain options):

This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder:

Sub WorkbookOpening2007()

Dim InputFolder As String
Dim LoopFileNameExt As String

InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!

LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""

Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True

LoopFileNameExt = Dir
Loop

End Sub

I tried it with books with unavailable external links - no warnings.

Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

Finding Number of Cores in Java

This works on Windows with Cygwin installed:

System.getenv("NUMBER_OF_PROCESSORS")

How to show full object in Chrome console?

this worked perfectly for me:

for(a in array)console.log(array[a])

you can extract any array created in console for find/replace cleanup and posterior usage of this data extracted

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

How to hide the Google Invisible reCAPTCHA badge

A slight variant of Matthew Dowell's post which avoids the short flash, but displays whenever the contact form 7 form is visible:

div.grecaptcha-badge{
    width:0 !important;
}

div.grecaptcha-badge.show{
    width:256px !important; 
}

I then added the following to the header.php in my child theme:

<script>
jQuery( window ).load(function () { 
    if( jQuery( '.wpcf7' ).length ){ 
        jQuery( '.grecaptcha-badge' ).addClass( 'show' );
    }
});
</script>

Disable asp.net button after click to prevent double clicking

<script type = "text/javascript">
function DisableButtons() {
    var inputs = document.getElementsByTagName("INPUT");
    for (var i in inputs) {
        if (inputs[i].type == "button" || inputs[i].type == "submit") {
            inputs[i].disabled = true;
        }
    }
}
window.onbeforeunload = DisableButtons;
</script>

Convert double to float in Java

To answer your query on "How to convert 2.3423424666767E13 to 23423424666767"

You can use a decimal formatter for formatting decimal numbers.

     double d = 2.3423424666767E13;
     DecimalFormat decimalFormat = new DecimalFormat("#");
     System.out.println(decimalFormat.format(d));

Output : 23423424666767

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

How do I get a list of all subdomains of a domain?

You can only do this if you are connecting to a DNS server for the domain -and- AXFR is enabled for your IP address. This is the mechanism that secondary systems use to load a zone from the primary. In the old days, this was not restricted, but due to security concerns, most primary name servers have a whitelist of: secondary name servers + a couple special systems.

If the nameserver you are using allows this then you can use dig or nslookup.

For example:

#nslookup

>ls domain.com

NOTE: because nslookup is being deprecated for dig and other newere tools, some versions of nslookup do not support "ls", most notably Mac OS X's bundled version.

Get only the date in timestamp in mysql

You can convert that time in Unix timestamp by using

select UNIX_TIMESTAMP('2013-11-26 01:24:34')

then convert it in the readable format in whatever format you need

select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");

For in detail you can visit link

In android how to set navigation drawer header image and name programmatically in class file?

val navigationView: NavigationView =  findViewById(R.id.nv)
val header: View = navigationView.getHeaderView(0)
val tv: TextView = header.findViewById(R.id.profilename)
tv.text = "Your_Text"

This will fix your problem <3

Accessing a Dictionary.Keys Key through a numeric index

One alternative would be a KeyedCollection if the key is embedded in the value.

Just create a basic implementation in a sealed class to use.

So to replace Dictionary<string, int> (which isn't a very good example as there isn't a clear key for a int).

private sealed class IntDictionary : KeyedCollection<string, int>
{
    protected override string GetKeyForItem(int item)
    {
        // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.
        return item.ToString();
    }
}

KeyedCollection<string, int> intCollection = new ClassThatContainsSealedImplementation.IntDictionary();

intCollection.Add(7);

int valueByIndex = intCollection[0];

Hide Utility Class Constructor : Utility classes should not have a public or default constructor

Best practice is to throw an error if the class is constructed.

Example:

/**
 * The Class FooUtilityService.
 */
final class FooUtilityService{

/**
* Instantiates a new FooUtilityService. Private to prevent instantiation
*/
private FooUtilityService() {

    // Throw an exception if this ever *is* called
    throw new AssertionError("Instantiating utility class.");
}

What is output buffering?

ob_start();  // turns on output buffering
$foo->bar();  // all output goes only to buffer
ob_clean();  // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents();  // buffer content is now an empty string
ob_end_clean();  // turn off output buffering

Buffers can be nested, so while one buffer is active, another ob_start() activates a new buffer. So ob_end_flush() and ob_flush() are not really sending the buffer to the output, but to the parent buffer. And only when there is no parent buffer, contents is sent to browser or terminal.

Nicely explained here: https://phpfashion.com/everything-about-output-buffering-in-php

Unsuccessful append to an empty NumPy array

numpy.append always copies the array before appending the new values. Your code is equivalent to the following:

import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)

Perhaps you mean to do this?

import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])

Link to "pin it" on pinterest without generating a button

You can create a custom link as described here using a small jQuery script

$('.linkPinIt').click(function(){
    var url = $(this).attr('href');
    var media = $(this).attr('data-image');
    var desc = $(this).attr('data-desc');
    window.open("//www.pinterest.com/pin/create/button/"+
    "?url="+url+
    "&media="+media+
    "&description="+desc,"_blank","top=0,right=0,width=750,height=320");
    return false; 
});

this will work for all links with class linkPinItwhich have the image and the description stored in the HTML 5 data attributes data-image and data-desc

<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F" 
   data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg" 
   data-desc="Title for Pinterest Photo" class="linkPinIt">
    Pin it!
</a> 

see this jfiddle example

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

Is it valid to have a html form inside another html form?

As workaround you could use formaction attribute on submit button. And just use different names on your inputs.

<form action="a">
<input.../>
    <!-- Form 2 inputs -->
    <input.../>
    <input.../>
    <input.../>
    <input type="submit" formaction="b">

</form>
<input.../>

How to use enums in C++

You are looking for strongly typed enumerations, a feature available in the C++11 standard. It turns enumerations into classes with scope values.

Using your own code example, it is:

  enum class Days {Saturday, Sunday, Tuesday,Wednesday, Thursday, Friday};
  Days day = Days::Saturday;

  if (day == Days::Saturday)  {
    cout << " Today is Saturday !" << endl;
  }
  //int day2 = Days::Sunday; // Error! invalid

Using :: as accessors to enumerations will fail if targeting a C++ standard prior C++11. But some old compilers doesn't supported it, as well some IDEs just override this option, and set a old C++ std.

If you are using GCC, enable C+11 with -std=c++11 or -std=gnu11 .

Be happy!

IIS7 Cache-Control

If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.

You can however drop this web.config in the root of the folder or site where you want to set it:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
    </staticContent>
  </system.webServer>
</configuration>

That will inform the client to cache content for 7 days in that folder and all subfolders.

You can also do this by editing the IIS7 metabase via appcmd.exe, like so:

\Windows\system32\inetsrv\appcmd.exe 
  set config "Default Web Site/folder" 
  -section:system.webServer/staticContent 
  -clientCache.cacheControlMode:UseMaxAge

\Windows\system32\inetsrv\appcmd.exe 
  set config "Default Web Site/folder" 
  -section:system.webServer/staticContent 
  -clientCache.cacheControlMaxAge:"7.00:00:00"

Can I give the col-md-1.5 in bootstrap?

You cloud also simply override the width of the Column...

<div class="col-md-1" style="width: 12.499999995%"></div>

Since col-md-1 is of width 8.33333333%; simply multiply 8.33333333 * 1.5 and set it as your width.

in bootstrap 4, you will have to override flex and max-width property too:

<div class="col-md-1" style="width: 12.499999995%;
    flex: 0 0 12.499%;max-width: 12.499%;"></div>

Close a MessageBox after several seconds

I know this question is 8 year old, however there was and is a better solution for this purpose. It's always been there, and still is: User32.dll!MessageBoxTimeout.

This is an undocumented function used by Microsoft Windows, and it does exactly what you want and even more. It supports different languages as well.

C# Import:

[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();

How to use it in C#:

uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/  0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;

NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);

Work smarter, not harder.

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

Syntax error: Illegal return statement in JavaScript

in javascript return statement only used inside function block. if you try to use return statement inside independent if else block it trigger syntax error : Illegal return statement in JavaScript

Here is my example code to avoid such error :

<script type = 'text/javascript'>
(function(){
    var ss= 'no';
    if(getStatus(ss)){
        alert('Status return true');   
    }else{
        alert('Status return false'); 
    }

    function getStatus(ask){
        if(ask=='yes')
        {
        return true;     
        }
        else
        {
        return false;
        }
    }
})();
</script>

Please check Jsfiddle example

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                              
/*                                              

creating batch script to unzip a file without additional zip tools

Try this:

@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b

:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%

Revision

To have it perform the unzip on each zip file creating a folder for each use:

@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
    Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b

If you don't want it to create a folder for each zip, change Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa" to Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

VBA to copy a file from one directory to another

Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:

Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")

Then you could use

Call fso.CopyFile(source, destination[, overwrite] )

where source and destination are the full names (including paths) of the file.

See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method

How to uncompress a tar.gz in another directory

You can use for loop to untar multiple .tar.gz files to another folder. The following code will take /destination/folder/path as an argument to the script and untar all .tar.gz files present at the current location in /destination/folder/path.

if [ $# -ne 1 ];
 then
 echo "invalid argument/s"
 echo "Usage: ./script-file-name.sh /target/directory"
 exit 0
fi
for file in *.tar.gz
do
    tar -zxvf "$file" --directory $1
done

Forking / Multi-Threaded Processes | Bash

Let me try example

for x in 1 2 3 ; do { echo a $x ; sleep 1 ; echo b $x ; } &  done ; sleep 10

And use jobs to see what's running.

How to get equal width of input and select fields

create another class and increase the with size with 2px example

.enquiry_fld_normal{
width:278px !important; 
}

.enquiry_fld_normal_select{
width:280px !important; 
 }

how to run mysql in ubuntu through terminal

If you want to run your scripts, then

mysql -u root -p < yourscript.sql

Command to delete all pods in all kubernetes namespaces

Here is a one-liner that can be extended with grep to filter by name.

kubectl get pods -o jsonpath="{.items[*].metadata.name}" | \
tr " " "\n" | \
xargs -i -P 0 kubectl delete pods {}

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

How to "wait" a Thread in Android

You need the sleep method of the Thread class.

public static void sleep (long time)

Causes the thread which sent this message to sleep for the given interval of time (given in milliseconds). The precision is not guaranteed - the Thread may sleep more or less than requested.

Parameters

time The time to sleep in milliseconds.

Remove Style on Element

You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to '' instead of null (see comments).

var element = document.getElementById('sample_id');

element.style.width = null;
element.style.height = null;

For more information, you can refer to HTMLElement.style documentation on MDN.

Sieve of Eratosthenes - Finding Primes Python

By combining contributions from many enthusiasts (including Glenn Maynard and MrHIDEn from above comments), I came up with following piece of code in python 2:

def simpleSieve(sieveSize):
    #creating Sieve.
    sieve = [True] * (sieveSize+1)
    # 0 and 1 are not considered prime.
    sieve[0] = False
    sieve[1] = False
    for i in xrange(2,int(math.sqrt(sieveSize))+1):
        if sieve[i] == False:
            continue
        for pointer in xrange(i**2, sieveSize+1, i):
            sieve[pointer] = False
    # Sieve is left with prime numbers == True
    primes = []
    for i in xrange(sieveSize+1):
        if sieve[i] == True:
            primes.append(i)
    return primes

sieveSize = input()
primes = simpleSieve(sieveSize)

Time taken for computation on my machine for different inputs in power of 10 is:

  • 3 : 0.3 ms
  • 4 : 2.4 ms
  • 5 : 23 ms
  • 6 : 0.26 s
  • 7 : 3.1 s
  • 8 : 33 s

How to print a query string with parameter values when using Hibernate

I like this for log4j:

log4j.logger.org.hibernate.SQL=trace
log4j.logger.org.hibernate.engine.query=trace
log4j.logger.org.hibernate.type=trace
log4j.logger.org.hibernate.jdbc=trace
log4j.logger.org.hibernate.type.descriptor.sql.BasicExtractor=error 
log4j.logger.org.hibernate.type.CollectionType=error 

Why does Git say my master branch is "already up to date" even though it is not?

As the other posters say, pull merges changes from upstream into your repository. If you want to replace what is in your repository with what is in upstream, you have several options. Off the cuff, I'd go with

git checkout HEAD^1  # Get off your repo's master.. doesn't matter where you go, so just go back one commit
git branch -d master  # Delete your repo's master branch
git checkout -t upstream/master  # Check out upstream's master into a local tracking branch of the same name

How to embed a video into GitHub README.md?

I combine Alexandre Jasmin and Gab Le Roux answers like this:

[![Demo CountPages alpha](https://share.gifyoutube.com/KzB6Gb.gif)](https://www.youtube.com/watch?v=ek1j272iAmc)

Demo:

Demo CountPages alpha

You can see this demo on github.

I used gifyoutube here, but I recommend using a local gif converter (like ffmpeg, see how) instead of an online one.

To record your screen to gif directly, you may want to check ScreenToGif.

How to say no to all "do you want to overwrite" prompts in a batch file copy?

Here's a workaround. If you want to copy everything from A that does not already exist in B:

Copy A to a new directory C. Copy B to C, overwriting anything that overlaps with A. Copy C to B.

HTML5 Audio Looping

Simplest way is:

bgSound = new Audio("sounds/background.mp3");
bgSound.loop = true;
bgSound.play();

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

How to delete images from a private docker registry?

Problem 1

You mentioned it was your private docker registry, so you probably need to check Registry API instead of Hub registry API doc, which is the link you provided.

Problem 2

docker registry API is a client/server protocol, it is up to the server's implementation on whether to remove the images in the back-end. (I guess)

DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)

Detailed explanation

Below I demo how it works now from your description as my understanding for your questions.

I run a private docker registry. I use the default one, and listen on port 5000.

docker run -d -p 5000:5000 registry

Then I tag the local image and push into it.

$ docker tag ubuntu localhost:5000/ubuntu
$ docker push localhost:5000/ubuntu
The push refers to a repository [localhost:5000/ubuntu] (len: 1)
Sending image list
Pushing repository localhost:5000/ubuntu (1 tags)
511136ea3c5a: Image successfully pushed
d7ac5e4f1812: Image successfully pushed
2f4b4d6a4a06: Image successfully pushed
83ff768040a0: Image successfully pushed
6c37f792ddac: Image successfully pushed
e54ca5efa2e9: Image successfully pushed
Pushing tag for rev [e54ca5efa2e9] on {http://localhost:5000/v1/repositories/ubuntu/tags/latest}

After that I can use Registry API to check it exists in your private docker registry

$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags
{"latest": "e54ca5efa2e962582a223ca9810f7f1b62ea9b5c3975d14a5da79d3bf6020f37"}

Now I can delete the tag using that API !!

$ curl -X DELETE localhost:5000/v1/repositories/ubuntu/tags/latest
true

Check again, the tag doesn't exist in my private registry server

$ curl -X GET localhost:5000/v1/repositories/ubuntu/tags/latest
{"error": "Tag not found"}

Jquery get form field value

var textValue = $("input[type=text]").val()

this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.

How to set radio button checked as default in radiogroup?

It's a bug of RadioGroup

RadioButton radioBtn2 = new RadioButton(context);

radioBtn2 without viewId, and generateViewId is in onChildViewAdded()

public void onChildViewAdded(View parent, View child) {
    if (parent == RadioGroup.this && child instanceof RadioButton) {
        int id = child.getId();
        // generates an id if it's missing
        if (id == View.NO_ID) {
            id = View.generateViewId();
            child.setId(id);
        }
        ((RadioButton) child).setOnCheckedChangeWidgetListener(
                mChildOnCheckedChangeListener);
    }

    if (mOnHierarchyChangeListener != null) {
        mOnHierarchyChangeListener.onChildViewAdded(parent, child);
    }
}

so, first radioGroup.addView(radioBtn2), then radioBtn2.setChecked(true);

Like this:

RadioGroup radioGroup = new RadioGroup(context);
RadioButton radioBtn1 = new RadioButton(context);
RadioButton radioBtn2 = new RadioButton(context);
RadioButton radioBtn3 = new RadioButton(context);

radioBtn1.setText("Less");
radioBtn2.setText("Normal");
radioBtn3.setText("More");

radioGroup.addView(radioBtn1);
radioGroup.addView(radioBtn2);
radioGroup.addView(radioBtn3);

radioBtn2.setChecked(true);

Jquery validation plugin - TypeError: $(...).validate is not a function

It looks like the JavaScript error your getting is probably being caused by

password: {
    required:true,
    rangelenght:[4.20]
},

As the [4.20] should be [4,20], which i'd guess is throwing off the validation code in additional-methods hence giving the type error's you posted.

Edit: As others have noted in the below comments rangelenght is also misspelled & jquery.validate.js library appears to be missing (assuming its not compiled in to one of your other assets)

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just in case this helps anyone else; this error can occur in Visual Studio if you have a View as the open tab, and that tab depends on a parameter.

Close the current view and start your application and the app will start 'Normally'; if you have a view open, Visual Studio interprets this as you want to run the current view.

Fastest way to flatten / un-flatten nested JSON objects

You can try out the package jpflat.

It flattens, inflates, resolves promises, flattens arrays, has customizable path creation and customizable value serialization.

The reducers and serializers receive the whole path as an array of it's parts, so more complex operations can be done to the path instead of modifying a single key or changing the delimiter.

Json path is the default, hence "jp"flat.

https://www.npmjs.com/package/jpflat

let flatFoo = await require('jpflat').flatten(foo)

How can I get a count of the total number of digits in a number?

If its only for validating you could do: 887979789 > 99999999

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

How to convert string to char array in C++?

Well I know this maybe rather dumb than and simple, but I think it should work:

string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
    b[i] = n[i];
    cout<< b[i]<< " ";
}

How to uninstall Eclipse?

The steps are very simple and it'll take just few mins. 1.Go to your C drive and in that go to the 'USER' section. 2.Under 'USER' section go to your 'name(e.g-'user1') and then find ".eclipse" folder and delete that folder 3.Along with that folder also delete "eclipse" folder and you can find that you're work has been done completely.

VB.NET: how to prevent user input in a ComboBox

Use KeyPressEventArgs,

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
    e.Handled = True
End Sub

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

In typescript you can do the following to suppress the error:

let subString?: string;

subString > !null; - Note the added exclamation mark before null.

How do I set a column value to NULL in SQL Server Management Studio?

I think @Zack properly answered the question but just to cover all the bases:

Update myTable set MyColumn = NULL

This would set the entire column to null as the Question Title asks.

To set a specific row on a specific column to null use:

Update myTable set MyColumn = NULL where Field = Condition.

This would set a specific cell to null as the inner question asks.

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

How to write character & in android strings.xml

This may be very old. But for those whose looking for a quick code.

 public String handleEscapeCharacter( String str ) {
    String[] escapeCharacters = { "&gt;", "&lt;", "&amp;", "&quot;", "&apos;" };
    String[] onReadableCharacter = {">", "<", "&", "\"\"", "'"};
    for (int i = 0; i < escapeCharacters.length; i++) {
        str = str.replace(escapeCharacters[i], onReadableCharacter[i]);
    } return str;
 }

That handles escape characters, you can add characters and symbols on their respective arrays.

-Cheers

Fill remaining vertical space with CSS using display:flex

Make it simple : DEMO

_x000D_
_x000D_
section {_x000D_
  display: flex;_x000D_
  flex-flow: column;_x000D_
  height: 300px;_x000D_
}_x000D_
_x000D_
header {_x000D_
  background: tomato;_x000D_
  /* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
  flex: 1;  /* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;  /* min-height has its purpose :) , unless you meant height*/_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br/>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- uncomment to see it break -->_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- -->_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Full screen version

_x000D_
_x000D_
section {_x000D_
  display: flex;_x000D_
  flex-flow: column;_x000D_
  height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
  background: tomato;_x000D_
  /* no flex rules, it will grow */_x000D_
}_x000D_
_x000D_
div {_x000D_
  flex: 1;_x000D_
  /* 1 and it will fill whole space left if no flex value are set to other children*/_x000D_
  background: gold;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
  /* min-height has its purpose :) , unless you meant height*/_x000D_
}_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br/>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- uncomment to see it break -->_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br> x_x000D_
    <br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    <!-- -->_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

SQL Query Multiple Columns Using Distinct on One Column Only

You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType value. If I have two rows with the same FruitType value but different Fruit_Id values for example, what should the system do?

Select Min(tblFruit_id) As tblFruit_id
    , tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType

SQL Fiddle example

iCheck check if checkbox is checked

To know if the iCheck box is checked

var isChecked = $("#myicheckboxid").prop("checked");

Which language uses .pde extension?

pde is extesion for:

  • Processing: Java derived language

  • Wiring: C/C++ derived language (Wiring is derived from Processing)

  • Early versions of Arduino: C/C++ derived (Arduino IDE is derived from Wiring)

For Arduino for example the IDE preprocessor is adding some #defines and some C/C++ files before giving all to gcc.

How to time Java program execution speed

public class someClass
{
   public static void main(String[] args) // your app start point
   {
       long start = java.util.Calendar.getInstance().getTimeInMillis();

       ... your stuff ...

       long end = java.util.Calendar.getInstance().getTimeInMillis();
       System.out.println("it took this long to complete this stuff: " + (end - start) + "ms");
   }
}

How do I add items to an array in jQuery?

You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.

The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.

Convert laravel object to array

Object to array

$array = (array) $players_Obj;  

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

Output:

array(2) {
    'foo' => int(1)
    'bar' => int(2)
}

How to pass variable from jade template file to a script file?

It's a little late but...

script.
  loginName="#{login}";

This is working fine in my script. In Express, I am doing this:

exports.index = function(req, res){
  res.render( 'index',  { layout:false, login: req.session.login } );
};

I guess the latest jade is different?

Merc.

edit: added "." after script to prevent Jade warning.

How to Apply Mask to Image in OpenCV?

While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:

inputMat.copyTo(outputMat, maskMat);

All objects are of type cv::Mat.

Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.

Also be aware that the .copyTo() function does not clear the output before copying.

If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

Securing a password in a properties file

Actually, this is a duplicate of Encrypt Password in Configuration Files?.

The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977

Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.

Submit form on pressing Enter with AngularJS

you can simply bind @Hostlistener with the component, and rest will take care by it. It won't need binding of any method from its HTML template.

@HostListener('keydown',['$event'])
onkeydown(event:keyboardEvent){
  if(event.key == 'Enter'){
           // TODO do something here
           // form.submit() OR API hit for any http method
  }
}

The above code should work with Angular 1+ version

Is there any publicly accessible JSON data source to test with real world data?

Tumblr has a public API that provides JSON. You can get a dump of posts using a simple url like http://puppygifs.tumblr.com/api/read/json.

How to fire AJAX request Periodically?

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

removing html element styles via javascript

you can just do:

element.removeAttribute("style")

Remove all child elements of a DOM node in JavaScript

There are couple of options to achieve that:

The fastest ():

while (node.lastChild) {
  node.removeChild(node.lastChild);
}

Alternatives (slower):

while (node.firstChild) {
  node.removeChild(node.firstChild);
}

while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}

Benchmark with the suggested options

Full width layout with twitter bootstrap

Update:

Bootstrap 3 has been released since this question was originally answered in January, so if you are a BS3 user, please refer to the BS3 documentation. For those still on BS2, the original answer still applies. If you are interested in switching from 2 to 3, see the migration guide.

Original answer:

From the bootstrap 2 docs:

Make any row "fluid" by changing .row to .row-fluid. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.

Code

<div class="row-fluid">
  <div class="span4">...</div>
  <div class="span8">...</div>
</div>

This, in conjunction with setting the width of your container to a fluid value, should allow you to get your desired layout.

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

Android Studio: Module won't show up in "Edit Configuration"

It was fixed for me after removing and re-adding the Android and Android-Gradle Facets in the Module Settings dialog.

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

How to create empty text file from a batch file?

Techniques I gathered from other answers:

Makes a 0 byte file a very clear, backward-compatible way:

type nul >EmptyFile.txt

idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP's work

A 0 byte file another way, it's backward-compatible-looking:

REM. >EmptyFile.txt

idea via: Johannes

A 0 byte file 3rd way backward-compatible-looking, too:

echo. 2>EmptyFile.txt

idea via: TheSmurf

A 0 byte file the systematic way probably available since Windows 2000:

fsutil file createnew EmptyFile.txt 0

idea via: Emm

A 0 bytes file overwriting readonly files

ATTRIB -R filename.ext>NUL
(CD.>filename.ext)2>NUL

idea via: copyitright

A single newline (2 bytes: 0x0D 0x0A in hex notation, alternatively written as \r\n):

echo.>AlmostEmptyFile.txt

Note: no space between echo, . and >.

idea via: How can you echo a newline in batch files?


edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature! compatibility: uknown

TheInvisibleFeature <nul >EmptyFile.txt

A 0 bytes file: invalid command/ with a random name (compatibility: uknown):

%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt

via: great source for random by Hung Huynh

edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command

A 0 bytes file: invalid command/ the funky way (compatibility: unknown)

*>EmptyFile.txt

idea via: Andriy M

A 0 bytes file 4th-coming way:

break > file.txt

idea via: foxidrive thanks to comment of Double Gras!

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

You can use attributes of html tag instead of validation from html input type ="date" can be used instead of validating it. That's the benifits html 5 gives you

Convert sqlalchemy row object to python dict

The 1.3 docs offer a very simple solution: KeyedTuple._asdict()

def to_array(rows):
    return [r._asdict() for r in rows]

def query():
    data = session.query(Table).all()
    return to_array(data)

What resources are shared between threads?

Thread share the heap (there is a research about thread specific heap) but current implementation share the heap. (and of course the code)

How can I determine if an image has loaded, using Javascript/jQuery?

Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.

<img id="photo"
     onload='loaded(this.id)'
     src="a_really_big_file.jpg"
     alt="this is some alt text"
     title="this is some title text" />

Copy Image from Remote Server Over HTTP

PHP has a built-in function file_get_contents(), which reads the content of a file into a string.

<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");

//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?>

If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.

PHP + curl, HTTP POST sample code?

If you try to login on site with cookies.

This code:

if ($server_output == "OK") { ... } else { ... }

May not works if you try to login, because many sites returns status 200, but the post is not successful.

Easy way to check if the login post is successful is check if it setting cookies again. If in output have Set-Cookies string, this means the posts is not successful and it starts new session.

Also the post can be successful, but the status can be redirect instead 200.

To be sure the post is successful try this:

Follow location after the post, so it will go to the page where the post do redirect to:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

And than check if new cookies existing in the request:

if (!preg_match('/^Set-Cookie:\s*([^;]*)/mi', $server_output)) 

{echo 'post successful'; }

else { echo 'not successful'; }

Convert array into csv

Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...

After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.

$resp = array();
foreach ($entries as $entry) {
    $row = array();
    foreach ($entry as $key => $value) {
        array_push($row, $value);
    }
    array_push($resp, implode(',', $row));
}
echo implode(PHP_EOL, $resp);

Note that for the $key => $value to work, your object's attributes must be public, the private ones will not get fetched.

The end result is that you get something like this:

blah,blah,blah
blah,blah,blah

Unsafe JavaScript attempt to access frame with URL

The problem is even if you create a proxy or load the content and inject it as if it's local, any scripts that that content defines will be loaded from the other domain and cause cross-domain problems.

Draw in Canvas by finger, Android

Regarding the beautiful code of Raghunandan above.

Many have asked how to "clear" the drawing. Here's how to do that:

public void clearDrawing()
    {
    Utils.Log("RaghunandanDraw, how to clear....");

    setDrawingCacheEnabled(false);
    // don't forget that one and the match below,
    // or you just keep getting a duplicate when you save.

    onSizeChanged(width, height, width, height);
    invalidate();

    setDrawingCacheEnabled(true);
    }

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
    super.onSizeChanged(w, h, oldw, oldh);

    width = w;      // don't forget these
    height = h;

    mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(mBitmap);
    }

Many have asked how to "save" the drawing. Here's how to do that:

public DrawingView(Context c)
  {
  circlePaint.setStrokeJoin(Paint.Join.MITER);
  circlePaint.setStrokeWidth(4f); 
  etc...

  // in the class where you set up the view, add this:
  setDrawingCacheEnabled( true );
  }

public void saveDrawing()
  {
  Bitmap whatTheUserDrewBitmap = getDrawingCache();
  // don't forget to clear it (see above) or you just get duplicates

  // almost always you will want to reduce res from the very high screen res
  whatTheUserDrewBitmap =
         ThumbnailUtils.extractThumbnail(whatTheUserDrewBitmap, 256, 256);
  // NOTE that's an incredibly useful trick for cropping/resizing squares
  // while handling all memory problems etc
  // http://stackoverflow.com/a/17733530/294884

  // you can now save the bitmap to a file, or display it in an ImageView:
  ImageView testArea = ...
  testArea.setImageBitmap( whatTheUserDrewBitmap );

  // these days you often need a "byte array". for example,
  // to save to parse.com or other cloud services
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  whatTheUserDrewBitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
  byte[] yourByteArray;
  yourByteArray = baos.toByteArray();
  }

Hope it helps someone as this has helped me.

How to check if an integer is in a given range?

if you are using Spring data you can also use the Range object from Spring.

range = new org.springframework.data.domain.Range(3, 8); range.contains(5) will return true.

HTML Form Redirect After Submit

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

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

Java Read Large Text File With 70million line of text

enter image description hereI actually did a research in this topic for months in my free time and came up with a benchmark and here is a code to benchmark all the different ways to read a File line by line.The individual performance may vary based on the underlying system. I ran on a windows 10 Java 8 Intel i5 HP laptop:Here is the code.

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class ReadComplexDelimitedFile {
    private static long total = 0;
    private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\^\\|\\^");

    @SuppressWarnings("unused")
    private void readFileUsingScanner() {

        String s;
        try (Scanner stdin = new Scanner(new File(this.getClass().getResource("input.txt").getPath()))) {
            while (stdin.hasNextLine()) {
                s = stdin.nextLine();
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total = total + fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }

    //Winner
    private void readFileUsingCustomBufferedReader() {

        try (CustomBufferedReader stdin = new CustomBufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }


    private void readFileUsingBufferedReader() {

        try (BufferedReader stdin = new BufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }
    }

    private void readFileUsingLineReader() {

        try (LineNumberReader stdin = new LineNumberReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }
    }

    private void readFileUsingStreams() {

        try (Stream<String> stream = Files.lines((new File(this.getClass().getResource("input.txt").getPath())).toPath())) {
            total += stream.mapToInt(s -> FIELD_DELIMITER_PATTERN.split(s, 0).length).sum();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    private void readFileUsingBufferedReaderFileChannel() {
        try (FileInputStream fis = new FileInputStream(this.getClass().getResource("input.txt").getPath())) {
            try (FileChannel inputChannel = fis.getChannel()) {
                try (CustomBufferedReader stdin = new CustomBufferedReader(Channels.newReader(inputChannel, "UTF-8"))) {
                    String s;
                    while ((s = stdin.readLine()) != null) {
                        String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                        total = total + fields.length;
                    }
                }
            } catch (Exception e) {
                System.err.println("Error");
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }


    public static void main(String args[]) {
        //JVM wamrup
        for (int i = 0; i < 100000; i++) {
            total += i;
        }
        // We know scanner is slow-Still warming up
        ReadComplexDelimitedFile readComplexDelimitedFile = new ReadComplexDelimitedFile();
        List<Long> longList = new ArrayList<>(50);
        for (int i = 0; i < 50; i++) {
            total = 0;
            long startTime = System.nanoTime();
            //readComplexDelimitedFile.readFileUsingScanner();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingScanner");
        longList.forEach(System.out::println);
        // Actual performance test starts here

        longList = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingBufferedReaderFileChannel();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingBufferedReaderFileChannel");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingBufferedReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingBufferedReader");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingStreams();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingStreams");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingCustomBufferedReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingCustomBufferedReader");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingLineReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingLineReader");
        longList.forEach(System.out::println);

    }
}

I had to rewrite BufferedReader to avoid synchronized and a couple of boundary conditions that is not needed.(Atleast that's what I felt.It is not unit tested so use it at your own risk.)

import com.sun.istack.internal.NotNull;

import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * Reads text from a character-input stream, buffering characters so as to
 * provide for the efficient reading of characters, arrays, and lines.
 * <p>
 * <p> The buffer size may be specified, or the default size may be used.  The
 * default is large enough for most purposes.
 * <p>
 * <p> In general, each read request made of a Reader causes a corresponding
 * read request to be made of the underlying character or byte stream.  It is
 * therefore advisable to wrap a CustomBufferedReader around any Reader whose read()
 * operations may be costly, such as FileReaders and InputStreamReaders.  For
 * example,
 * <p>
 * <pre>
 * CustomBufferedReader in
 *   = new CustomBufferedReader(new FileReader("foo.in"));
 * </pre>
 * <p>
 * will buffer the input from the specified file.  Without buffering, each
 * invocation of read() or readLine() could cause bytes to be read from the
 * file, converted into characters, and then returned, which can be very
 * inefficient.
 * <p>
 * <p> Programs that use DataInputStreams for textual input can be localized by
 * replacing each DataInputStream with an appropriate CustomBufferedReader.
 *
 * @author Mark Reinhold
 * @see FileReader
 * @see InputStreamReader
 * @see java.nio.file.Files#newBufferedReader
 * @since JDK1.1
 */

public class CustomBufferedReader extends Reader {

    private final Reader in;

    private char cb[];
    private int nChars, nextChar;

    private static final int INVALIDATED = -2;
    private static final int UNMARKED = -1;
    private int markedChar = UNMARKED;
    private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

    /**
     * If the next character is a line feed, skip it
     */
    private boolean skipLF = false;

    /**
     * The skipLF flag when the mark was set
     */
    private boolean markedSkipLF = false;

    private static int defaultCharBufferSize = 8192;
    private static int defaultExpectedLineLength = 80;
    private ReadWriteLock rwlock;


    /**
     * Creates a buffering character-input stream that uses an input buffer of
     * the specified size.
     *
     * @param in A Reader
     * @param sz Input-buffer size
     * @throws IllegalArgumentException If {@code sz <= 0}
     */
    public CustomBufferedReader(@NotNull final Reader in, int sz) {
        super(in);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this.in = in;
        cb = new char[sz];
        nextChar = nChars = 0;
        rwlock = new ReentrantReadWriteLock();
    }

    /**
     * Creates a buffering character-input stream that uses a default-sized
     * input buffer.
     *
     * @param in A Reader
     */
    public CustomBufferedReader(@NotNull final Reader in) {
        this(in, defaultCharBufferSize);
    }


    /**
     * Fills the input buffer, taking the mark into account if it is valid.
     */
    private void fill() throws IOException {
        int dst;
        if (markedChar <= UNMARKED) {
            /* No mark */
            dst = 0;
        } else {
            /* Marked */
            int delta = nextChar - markedChar;
            if (delta >= readAheadLimit) {
                /* Gone past read-ahead limit: Invalidate mark */
                markedChar = INVALIDATED;
                readAheadLimit = 0;
                dst = 0;
            } else {
                if (readAheadLimit <= cb.length) {
                    /* Shuffle in the current buffer */
                    System.arraycopy(cb, markedChar, cb, 0, delta);
                    markedChar = 0;
                    dst = delta;
                } else {
                    /* Reallocate buffer to accommodate read-ahead limit */
                    char ncb[] = new char[readAheadLimit];
                    System.arraycopy(cb, markedChar, ncb, 0, delta);
                    cb = ncb;
                    markedChar = 0;
                    dst = delta;
                }
                nextChar = nChars = delta;
            }
        }

        int n;
        do {
            n = in.read(cb, dst, cb.length - dst);
        } while (n == 0);
        if (n > 0) {
            nChars = dst + n;
            nextChar = dst;
        }
    }

    /**
     * Reads a single character.
     *
     * @return The character read, as an integer in the range
     * 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
     * end of the stream has been reached
     * @throws IOException If an I/O error occurs
     */
    public char readChar() throws IOException {
        for (; ; ) {
            if (nextChar >= nChars) {
                fill();
                if (nextChar >= nChars)
                    return (char) -1;
            }
            return cb[nextChar++];
        }
    }

    /**
     * Reads characters into a portion of an array, reading from the underlying
     * stream if necessary.
     */
    private int read1(char[] cbuf, int off, int len) throws IOException {
        if (nextChar >= nChars) {
            /* If the requested length is at least as large as the buffer, and
               if there is no mark/reset activity, and if line feeds are not
               being skipped, do not bother to copy the characters into the
               local buffer.  In this way buffered streams will cascade
               harmlessly. */
            if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
                return in.read(cbuf, off, len);
            }
            fill();
        }
        if (nextChar >= nChars) return -1;
        int n = Math.min(len, nChars - nextChar);
        System.arraycopy(cb, nextChar, cbuf, off, n);
        nextChar += n;
        return n;
    }

    /**
     * Reads characters into a portion of an array.
     * <p>
     * <p> This method implements the general contract of the corresponding
     * <code>{@link Reader#read(char[], int, int) read}</code> method of the
     * <code>{@link Reader}</code> class.  As an additional convenience, it
     * attempts to read as many characters as possible by repeatedly invoking
     * the <code>read</code> method of the underlying stream.  This iterated
     * <code>read</code> continues until one of the following conditions becomes
     * true: <ul>
     * <p>
     * <li> The specified number of characters have been read,
     * <p>
     * <li> The <code>read</code> method of the underlying stream returns
     * <code>-1</code>, indicating end-of-file, or
     * <p>
     * <li> The <code>ready</code> method of the underlying stream
     * returns <code>false</code>, indicating that further input requests
     * would block.
     * <p>
     * </ul> If the first <code>read</code> on the underlying stream returns
     * <code>-1</code> to indicate end-of-file then this method returns
     * <code>-1</code>.  Otherwise this method returns the number of characters
     * actually read.
     * <p>
     * <p> Subclasses of this class are encouraged, but not required, to
     * attempt to read as many characters as possible in the same fashion.
     * <p>
     * <p> Ordinarily this method takes characters from this stream's character
     * buffer, filling it from the underlying stream as necessary.  If,
     * however, the buffer is empty, the mark is not valid, and the requested
     * length is at least as large as the buffer, then this method will read
     * characters directly from the underlying stream into the given array.
     * Thus redundant <code>CustomBufferedReader</code>s will not copy data
     * unnecessarily.
     *
     * @param cbuf Destination buffer
     * @param off  Offset at which to start storing characters
     * @param len  Maximum number of characters to read
     * @return The number of characters read, or -1 if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     */
    public int read(char cbuf[], int off, int len) throws IOException {
        int n = read1(cbuf, off, len);
        if (n <= 0) return n;
        while ((n < len) && in.ready()) {
            int n1 = read1(cbuf, off + n, len - n);
            if (n1 <= 0) break;
            n += n1;
        }
        return n;
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @param ignoreLF If true, the next '\n' will be skipped
     * @return A String containing the contents of the line, not including
     * any line-termination characters, or null if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     * @see java.io.LineNumberReader#readLine()
     */
    String readLine(boolean ignoreLF) throws IOException {
        StringBuilder s = null;
        int startChar;



        bufferLoop:
        for (; ; ) {

            if (nextChar >= nChars)
                fill();
            if (nextChar >= nChars) { /* EOF */
                if (s != null && s.length() > 0)
                    return s.toString();
                else
                    return null;
            }
            boolean eol = false;
            char c = 0;
            int i;

            /* Skip a leftover '\n', if necessary */



            charLoop:
            for (i = nextChar; i < nChars; i++) {
                c = cb[i];
                if ((c == '\n')) {
                    eol = true;
                    break charLoop;
                }
            }

            startChar = nextChar;
            nextChar = i;

            if (eol) {
                String str;
                if (s == null) {
                    str = new String(cb, startChar, i - startChar);
                } else {
                    s.append(cb, startChar, i - startChar);
                    str = s.toString();
                }
                nextChar++;
                return str;
            }

            if (s == null)
                s = new StringBuilder(defaultExpectedLineLength);
            s.append(cb, startChar, i - startChar);
        }
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @return A String containing the contents of the line, not including
     * any line-termination characters, or null if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     * @see java.nio.file.Files#readAllLines
     */
    public String readLine() throws IOException {
        return readLine(false);
    }

    /**
     * Skips characters.
     *
     * @param n The number of characters to skip
     * @return The number of characters actually skipped
     * @throws IllegalArgumentException If <code>n</code> is negative.
     * @throws IOException              If an I/O error occurs
     */
    public long skip(long n) throws IOException {
        if (n < 0L) {
            throw new IllegalArgumentException("skip value is negative");
        }
        rwlock.readLock().lock();
            long r = n;
            try{
            while (r > 0) {
                if (nextChar >= nChars)
                    fill();
                if (nextChar >= nChars) /* EOF */
                    break;
                if (skipLF) {
                    skipLF = false;
                    if (cb[nextChar] == '\n') {
                        nextChar++;
                    }
                }
                long d = nChars - nextChar;
                if (r <= d) {
                    nextChar += r;
                    r = 0;
                    break;
                } else {
                    r -= d;
                    nextChar = nChars;
                }
            }
        } finally {
            rwlock.readLock().unlock();
        }
        return n - r;
    }

    /**
     * Tells whether this stream is ready to be read.  A buffered character
     * stream is ready if the buffer is not empty, or if the underlying
     * character stream is ready.
     *
     * @throws IOException If an I/O error occurs
     */
    public boolean ready() throws IOException {
        rwlock.readLock().lock();
        try {
            /*
             * If newline needs to be skipped and the next char to be read
             * is a newline character, then just skip it right away.
             */
            if (skipLF) {
                /* Note that in.ready() will return true if and only if the next
                 * read on the stream will not block.
                 */
                if (nextChar >= nChars && in.ready()) {
                    fill();
                }
                if (nextChar < nChars) {
                    if (cb[nextChar] == '\n')
                        nextChar++;
                    skipLF = false;
                }
            }
        } finally {
            rwlock.readLock().unlock();
        }
        return (nextChar < nChars) || in.ready();

    }

    /**
     * Tells whether this stream supports the mark() operation, which it does.
     */
    public boolean markSupported() {
        return true;
    }

    /**
     * Marks the present position in the stream.  Subsequent calls to reset()
     * will attempt to reposition the stream to this point.
     *
     * @param readAheadLimit Limit on the number of characters that may be
     *                       read while still preserving the mark. An attempt
     *                       to reset the stream after reading characters
     *                       up to this limit or beyond may fail.
     *                       A limit value larger than the size of the input
     *                       buffer will cause a new buffer to be allocated
     *                       whose size is no smaller than limit.
     *                       Therefore large values should be used with care.
     * @throws IllegalArgumentException If {@code readAheadLimit < 0}
     * @throws IOException              If an I/O error occurs
     */
    public void mark(int readAheadLimit) throws IOException {
        if (readAheadLimit < 0) {
            throw new IllegalArgumentException("Read-ahead limit < 0");
        }
        rwlock.readLock().lock();
        try {
            this.readAheadLimit = readAheadLimit;
            markedChar = nextChar;
            markedSkipLF = skipLF;
        } finally {
            rwlock.readLock().unlock();
        }
    }

    /**
     * Resets the stream to the most recent mark.
     *
     * @throws IOException If the stream has never been marked,
     *                     or if the mark has been invalidated
     */
    public void reset() throws IOException {
        rwlock.readLock().lock();
        try {
            if (markedChar < 0)
                throw new IOException((markedChar == INVALIDATED)
                        ? "Mark invalid"
                        : "Stream not marked");
            nextChar = markedChar;
            skipLF = markedSkipLF;
        } finally {
            rwlock.readLock().unlock();
        }
    }

    public void close() throws IOException {
        rwlock.readLock().lock();
        try {
            in.close();
        } finally {
            cb = null;
            rwlock.readLock().unlock();
        }

    }

    public Stream<String> lines() {
        Iterator<String> iter = new Iterator<String>() {
            String nextLine = null;

            @Override
            public boolean hasNext() {
                if (nextLine != null) {
                    return true;
                } else {
                    try {
                        nextLine = readLine();
                        return (nextLine != null);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            }

            @Override
            public String next() {
                if (nextLine != null || hasNext()) {
                    String line = nextLine;
                    nextLine = null;
                    return line;
                } else {
                    throw new NoSuchElementException();
                }
            }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
    }
}

And now the results:

Time taken for readFileUsingBufferedReaderFileChannel 2902690903 1845190694 1894071377 1815161868 1861056735 1867693540 1857521371 1794176251 1768008762 1853089582

Time taken for readFileUsingBufferedReader 2022837353 1925901163 1802266711 1842689572 1899984555 1843101306 1998642345 1821242301 1820168806 1830375108

Time taken for readFileUsingStreams 1992855461 1930827034 1850876033 1843402533 1800378283 1863581324 1810857226 1798497108 1809531144 1796345853

Time taken for readFileUsingCustomBufferedReader 1759732702 1765987214 1776997357 1772999486 1768559162 1755248431 1744434555 1750349867 1740582606 1751390934

Time taken for readFileUsingLineReader 1845307174 1830950256 1829847321 1828125293 1827936280 1836947487 1832186310 1820276327 1830157935 1829171481

Process finished with exit code 0

Inference: The test was run on a 200 MB file. The test was repeated several times. The data looked like this

Start Date^|^Start Time^|^End Date^|^End Time^|^Event Title ^|^All Day Event^|^No End Time^|^Event Description^|^Contact ^|^Contact Email^|^Contact Phone^|^Location^|^Category^|^Mandatory^|^Registration^|^Maximum^|^Last Date To Register
9/5/2011^|^3:00:00 PM^|^9/5/2011^|^^|^Social Studies Dept. Meeting^|^N^|^Y^|^Department meeting^|^Chris Gallagher^|^[email protected]^|^814-555-5179^|^High School^|^2^|^N^|^N^|^25^|^9/2/2011

Bottomline not much difference between BufferedReader and my CustomReader and it is very miniscule and hence you can use this to read your file.

Trust me you don't have to break your head.use BufferedReader with readLine,it is properly tested.At worst if you feel you can improve it just override and change it to StringBuilder instead of StringBuffer just to shave off half a second

Sorting a list with stream.sorted() in Java

It seems to be working fine:

List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);

Example Input/Output

Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]

Are you sure you are not verifying list instead of sortedList [in above example] i.e. you are storing the result of stream() in a new List object and verifying that object?

Parsing a JSON string in Ruby

Don't see any answers here that mention parsing directly to an object other than a Hash, but it is possible using the poorly-documented object_class option(see https://ruby-doc.org/stdlib-2.7.1/libdoc/json/rdoc/JSON.html):

JSON.parse('{"foo":{"bar": 2}}', object_class: OpenStruct).foo.bar
=> 2

The better way to read that option is "The ruby class that a json object turns into", which explains why it defaults to Hash. Likewise, there is an array_class option for json arrays.

Test whether string is a valid integer

Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case statement.

case ${variable#[-+]} in
  *[!0-9]* | '') echo Not a number ;;
  * ) echo Valid number ;;
esac

The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.

How can I update my ADT in Eclipse?

You have updated the android sdk but not updated the adt to match with it.

You can update the adt from here

You might need to update the software source for your adt update

Go to eclipse > help > Check for updates.

It should list the latest update of adt. If it is not working try the same *Go to eclipse > help > Install new software * but now please do the follwing:

It will list the updates available- which should ideally be adt 20.xx

Eclipse will restart and hopefully everything should work fine for you.

android - save image into gallery

Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ), 
    getAlbumName()
);

The picture doesn't go to the album. To do this, you need to call a scan:

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery

Git merge is not possible because I have unmerged files

Another potential cause for this (Intellij was involved in my case, not sure that mattered though): trying to merge in changes from a main branch into a branch off of a feature branch.

In other words, merging "main" into "current" in the following arrangement:

main
  |
  --feature
      |
      --current

I resolved all conflicts and GiT reported unmerged files and I was stuck until I merged from main into feature, then feature into current.

pandas: find percentile stats of a given column

assume series s

s = pd.Series(np.arange(100))

Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]

s.quantile(np.linspace(.1, 1, 9, 0))

0.1     9.9
0.2    19.8
0.3    29.7
0.4    39.6
0.5    49.5
0.6    59.4
0.7    69.3
0.8    79.2
0.9    89.1
dtype: float64

OR

s.quantile(np.linspace(.1, 1, 9, 0), 'lower')

0.1     9
0.2    19
0.3    29
0.4    39
0.5    49
0.6    59
0.7    69
0.8    79
0.9    89
dtype: int32

Typescript: React event types

The SyntheticEvent interface is generic:

interface SyntheticEvent<T> {
    ...
    currentTarget: EventTarget & T;
    ...
}

(Technically the currentTarget property is on the parent BaseSyntheticEvent type.)

And the currentTarget is an intersection of the generic constraint and EventTarget.
Also, since your events are caused by an input element you should use the ChangeEvent (in definition file, the react docs).

Should be:

update = (e: React.ChangeEvent<HTMLInputElement>): void => {
    this.props.login[e.currentTarget.name] = e.currentTarget.value
}

(Note: This answer originally suggested using React.FormEvent. The discussion in the comments is related to this suggestion, but React.ChangeEvent should be used as shown above.)

Extract Number from String in Python

There may be a little problem with code from Vishnu's answer. If there is no digits in the string it will return ValueError. Here is my suggestion avoid this:

>>> digit = lambda x: int(filter(str.isdigit, x) or 0)
>>> digit('3158 reviews')
3158
>>> digit('reviews')
0

Could not open ServletContext resource

Put the things like /src/main/resources/foo/bar.properties and then reference them as classpath:/foo/bar.properties.

ASP.NET postback with JavaScript

Per Phairoh: Use this in the Page/Component just in case the panel name changes

<script type="text/javascript">
     <!--
     //must be global to be called by ExternalInterface
         function JSFunction() {
             __doPostBack('<%= myUpdatePanel.ClientID  %>', '');
         }
     -->
     </script>

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

If the answers must be constrained to Google Sheets, this answer works but it has limitations and is clumsy enough UX that it may be hard to get others to adopt. In trying to solve this problem I've found that, for many applications, Airtable solves this by allowing for multi-select columns and the UX is worlds better.

Uncaught TypeError: Cannot read property 'value' of null

Instead of document or $(document) to avoid JQuery, you can add a TimeOut to validate the objects. TimeOut is executed after loading all objects within the page and other events...

setTimeout(function () { 

var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
....
....
....

}, 0);

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

Configure Log4Net in web application

often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.

Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.

What are the First and Second Level caches in (N)Hibernate?

There's a pretty good explanation of first level caching on the Streamline Logic blog.

Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.

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

Of course AJAX is the solution,

To perform an AJAX request (for easiness we can use jQuery library).

Step1.

Include jQuery library in your web page

a. you can download jQuery library from jquery.com and keep it locally.

b. or simply paste the following code,

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Step 2.

Call a javascript function on button click

<button type="button" onclick="foo()">Click Me</button>

Step 3.

and finally the function

 function foo () {
      $.ajax({
        url:"test.php", //the page containing php script
        type: "POST", //request type
        success:function(result){
         alert(result);
       }
     });
 }

it will make an AJAX request to test.php when ever you clicks the button and alert the response.

For example your code in test.php is,

<?php echo 'hello'; ?>

then it will alert "hello" when ever you clicks the button.

Setting DEBUG = False causes 500 Error

I had a problem similar to this and I will report how I solved mine because it could be that someone is also experiencing the same.

In my case, the error was caused because the server was not finding some static files from the homepage.

So make sure the error only occurs in the index or occurs on another page. If the problem is only occurring in the index very probably you need to check the static files. I recommend opening the Chrome preview console and checking for any errors.

In my case, the server couldn't find favicon.ico and two other CSS.

To fix this I passed python manage.py collectstatic and it worked.

CSS - make div's inherit a height

As already mentioned this can't be done with floats, they can't inherit heights, they're unaware of their siblings so for example the side two floats don't know the height of the centre content, so they can't inherit from anything.

Usually inherited height has to come from either an element which has an explicit height or if height: 100%; has been passed down through the display tree to it.. The only thing I'm aware of that passes on height which hasn't come from top of the "tree" is an absolutely positioned element - so you could for example absolutely position all the top right bottom left sides and corners (you know the height and width of the corners anyway) And as you seem to know the widths (of left/right borders) and heights of top/bottom) borders, and the widths of the top/bottom centers, are easy at 100% - the only thing that needs calculating is the height of the right/left sides if the content grows -

This you can do, even without using all four positioning co-ordinates which IE6 /7 doesn't support

I've put up an example based on what you gave, it does rely on a fixed width (your frame), but I think it could work with a flexible width too? the uses of this could be cool for those fancy image borders we can't get support for until multiple background images or image borders become fully available.. who knows, I was playing, so just sticking it out there!

proof of concept example is here

How to do INSERT into a table records extracted from another table

You have two syntax options:

Option 1

CREATE TABLE Table1 (
    id int identity(1, 1) not null,
    LongIntColumn1 int,
    CurrencyColumn money
)

CREATE TABLE Table2 (
    id int identity(1, 1) not null,
    LongIntColumn2 int,
    CurrencyColumn2 money
)

INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)

INSERT INTO Table2
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1

Option 2

CREATE TABLE Table1 (
    id int identity(1, 1) not null,
    LongIntColumn1 int,
    CurrencyColumn money
)

INSERT INTO Table1 VALUES(12, 12.00)
INSERT INTO Table1 VALUES(11, 13.00)


SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1
INTO Table2
FROM Table1
GROUP BY LongIntColumn1

Bear in mind that Option 2 will create a table with only the columns on the projection (those on the SELECT).

Vue 2 - Mutating props vue-warn

Vue.js props are not to be mutated as this is considered an Anti-Pattern in Vue.

The approach you will need to take is creating a data property on your component that references the original prop property of list

props: ['list'],
data: () {
  return {
    parsedList: JSON.parse(this.list)
  }
}

Now your list structure that is passed to the component is referenced and mutated via the data property of your component :-)

If you wish to do more than just parse your list property then make use of the Vue component' computed property. This allow you to make more in depth mutations to your props.

props: ['list'],
computed: {
  filteredJSONList: () => {
    let parsedList = JSON.parse(this.list)
    let filteredList = parsedList.filter(listItem => listItem.active)
    console.log(filteredList)
    return filteredList
  }
}

The example above parses your list prop and filters it down to only active list-tems, logs it out for schnitts and giggles and returns it.

note: both data & computed properties are referenced in the template the same e.g

<pre>{{parsedList}}</pre>

<pre>{{filteredJSONList}}</pre>

It can be easy to think that a computed property (being a method) needs to be called... it doesn't

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

A good workaround to remind you that m2e could be better configured, without the project inheriting a false positive error marker, is to just downgrade those errors to warnings:

Window -> Preferences -> Maven -> Errors/Warnings -> Plugin execution not covered by lifecycle configuration = Warning

How can I change or remove HTML5 form validation default error messages?

As you can see here:

html5 oninvalid doesn't work after fixed the input field

Is good to you put in that way, for when you fix the error disapear the warning message.

<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />

Add UIPickerView & a Button in Action sheet - How?

One more solution:

  • no toolbar but a segmented control (eyecandy)

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                        delegate:nil
                                                        cancelButtonTitle:nil
                                                        destructiveButtonTitle:nil
                                                        otherButtonTitles:nil];
    
    [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    
    [actionSheet addSubview:pickerView];
    [pickerView release];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [actionSheet addSubview:closeButton];
    [closeButton release];
    
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];
    

Simple export and import of a SQLite database on Android

To export db rather it is SQLITE or ROOM:

Firstly, add this permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Secondly, we drive to code the db functions:

private void exportDB() {
    try {
        File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = DirectoryName + File.separator +
                DATABASE_NAME + ".db";

        // Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);

        // Transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        // Close the streams
        output.flush();
        output.close();
        fis.close();


    } catch (IOException e) {
        Log.e("dbBackup:", e.getMessage());
    }
}

Create Folder on Daily basis with name of folder is Current date:

public void createBackup() {

    sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
    editor = sharedPref.edit();

    String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

    if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
        editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

        editor.commit();
    }

    File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
    if (success) {

        DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
        folder = new File(DirectoryName);
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (success) {
            exportDB();
        }
    } else {
        Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
    }

}

Assign the DATABASE_NAME without .db extension and its data type is string

Calling a method inside another method in same class

The add method that takes a String and a Person is calling a different add method that takes a Position. The one that takes Position is inherited from the ArrayList class.

Since your class Staff extends ArrayList<Position>, it automatically has the add(Position) method. The new add(String, Person) method is one that was written particularly for the Staff class.

What does axis in pandas mean?

Arrays are designed with so-called axis=0 and rows positioned vertically versus axis=1 and columns positioned horizontally. Axis refers to the dimension of the array. Illustration

What does "request for member '*******' in something not a structure or union" mean?

I have enumerated possibly all cases where this error may occur in code and its comments below. Please add to it, if you come across more cases.

#include<stdio.h>
#include<malloc.h>

typedef struct AStruct TypedefedStruct;

struct AStruct
{
    int member;
};

void main()
{
    /*  Case 1
        ============================================================================
        Use (->) operator to access structure member with structure pointer, instead
        of dot (.) operator. 
    */
    struct AStruct *aStructObjPtr = (struct AStruct *)malloc(sizeof(struct AStruct));
    //aStructObjPtr.member = 1;      //Error: request for member ‘member’ in something not 
                                      //a structure or union. 
                                      //It should be as below.
    aStructObjPtr->member = 1;
    printf("%d",aStructObjPtr->member); //1


    /*  Case 2
        ============================================================================
        We can use dot (.) operator with struct variable to access its members, but 
        not with with struct pointer. But we have to ensure we dont forget to wrap 
        pointer variable inside brackets.
    */
    //*aStructObjPtr.member = 2;     //Error, should be as below.
    (*aStructObjPtr).member = 2;
    printf("%d",(*aStructObjPtr).member); //2


    /* Case 3
       =============================================================================
       Use (->) operator to access structure member with typedefed structure pointer, 
       instead of dot (.) operator. 
    */
    TypedefedStruct *typedefStructObjPtr = (TypedefedStruct *)malloc(sizeof(TypedefedStruct));
    //typedefStructObjPtr.member=3;  //Error, should be as below.
    typedefStructObjPtr->member=3;
    printf("%d",typedefStructObjPtr->member);  //3


    /*  Case 4
        ============================================================================
        We can use dot (.) operator with struct variable to access its members, but 
        not with with struct pointer. But we have to ensure we dont forget to wrap 
        pointer variable inside brackets.
    */
    //*typedefStructObjPtr.member = 4;  //Error, should be as below.    
    (*typedefStructObjPtr).member=4;
    printf("%d",(*typedefStructObjPtr).member);  //4


    /* Case 5
       ============================================================================
       We have to be extra carefull when dealing with pointer to pointers to 
       ensure that we follow all above rules.
       We need to be double carefull while putting brackets around pointers.
    */

    //5.1. Access via struct_ptrptr and  ->
    struct AStruct **aStructObjPtrPtr = &aStructObjPtr;
    //*aStructObjPtrPtr->member = 5;  //Error, should be as below.
    (*aStructObjPtrPtr)->member = 5;
    printf("%d",(*aStructObjPtrPtr)->member); //5

    //5.2. Access via struct_ptrptr and .
    //**aStructObjPtrPtr.member = 6;  //Error, should be as below.
    (**aStructObjPtrPtr).member = 6;
    printf("%d",(**aStructObjPtrPtr).member); //6

    //5.3. Access via typedefed_strct_ptrptr and ->
    TypedefedStruct **typedefStructObjPtrPtr = &typedefStructObjPtr;
    //*typedefStructObjPtrPtr->member = 7;  //Error, should be as below.
    (*typedefStructObjPtrPtr)->member = 7;
    printf("%d",(*typedefStructObjPtrPtr)->member); //7

    //5.4. Access via typedefed_strct_ptrptr and .
    //**typedefStructObjPtrPtr->member = 8;  //Error, should be as below.
    (**typedefStructObjPtrPtr).member = 8;
    printf("%d",(**typedefStructObjPtrPtr).member); //8

    //5.5. All cases 5.1 to 5.4 will fail if you include incorrect number of *
    //     Below are examples of such usage of incorrect number *, correspnding
    //     to int values assigned to them

    //(aStructObjPtrPtr)->member = 5; //Error
    //(*aStructObjPtrPtr).member = 6; //Error 
    //(typedefStructObjPtrPtr)->member = 7; //Error 
    //(*typedefStructObjPtrPtr).member = 8; //Error
}

The underlying ideas are straight:

  • Use . with structure variable. (Cases 2 and 4)
  • Use -> with pointer to structure. (Cases 1 and 3)
  • If you reach structure variable or pointer to structure variable by following pointer, then wrap the pointer inside bracket: (*ptr). and (*ptr)-> vs *ptr. and *ptr-> (All cases except case 1)
  • If you are reaching by following pointers, ensure you have correctly reached pointer to struct or struct whichever is desired. (Case 5, especially 5.5)

How can I work with command line on synology?

for my example:

Windows XP ---> Synology:DS218+

  • Step1:
        > DNS: Control Panel (???)
             > Terminal & SNMP(??? & SNMP)
  • Step2:
        Enable Telnet service (?? Telnet ??)
        or Enable SSH Service (?? SSH ??)


    enter image description here
    enter image description here


  • Step3: Launch the terminal on Windows (or via executing

        cmd
    to launch the terminal)
    enter image description here


  • Step4: type: telnet your_nas_ip_or_domain_name, like below

        telnet 192.168.1.104
    enter image description here



  • Step5:
    demo a terminal application, like compiling the Java code

    Fzz login: tsungjung411

    Password:

    # shows the current working directory (?????????)
    $ pwd
    /var/services/homes/tsungjung411


    # edit a Java file (via vi), then compile and run it 
    # (?? vi ?? Java ??,???????)
    $ vi Main.java

    # show the file content (??????)
    $ cat Main.java
    public class Main {
        public static void main(String [] args) {
            System.out.println("hello, World!");
        }
    }

    # compiles the Java file (?? Java ??)
    javac Main.java

    # executes the Java file (?? Java ??)
    $ java Main
    hello, World!

    # shows the file list (??????)
    $ ls
    CloudStation  Main.class  Main.java  www

enter image description here


    # shows the JRE version on this Synology Disk Station
    $ java -version
    openjdk version "1.8.0_151"
    OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12)
    OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)




  • Step6:
    demo another terminal application, like running the Python code

    $ python
    Python 2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    >>> import sys
    >>>
    >>> # shows the the python version
    >>> print(sys.version)
    2.7.12 (default, Nov 10 2017, 20:30:30)
    [GCC 4.9.3 20150311 (prerelease)]
    >>>
    >>> import os
    >>>
    >>> # shows the current working directory
    >>> print(os.getcwd())
    /volume1/homes/tsungjung411

enter image description here


    $ # launch Python 3
    $ python3
    Python 3.5.1 (default, Dec  9 2016, 00:20:03)
    [GCC 4.9.3 20150311 (prerelease)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>




Send response to all clients except sender

I am using namespaces and rooms - I found

socket.broadcast.to('room1').emit('event', 'hi');

to work where

namespace.broadcast.to('room1').emit('event', 'hi');

did not

(should anyone else face that problem)