Programs & Examples On #Customvalidator

ASP.NET Custom Validator Client side & Server Side validation not firing

Your CustomValidator will only fire when the TextBox isn't empty.

If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.

Note: If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to require the user to enter data in the input control.

EDIT:

If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.

If you don't specify ControlToValidate then your validation functions will be called every time.

This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:

Client Side code (Javascript):

function TextBoxDCountyClient(sender, args) {
    var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
    if (v == '') {
        args.IsValid = false;  // field is empty
    }
    else {
        // do your other validation tests here...
    }
}

Server side code (C#):

protected void TextBoxDTownCity_Validate(
    object source, ServerValidateEventArgs args)
{
    string v = TextBoxDTownCity.Text;
    if (v == string.Empty)
    {
        args.IsValid = false;  // field is empty
    }
    else
    {
        // do your other validation tests here...
    }
}

How to find the nearest parent of a Git branch?

Anyone wanting to do this these days - Atlassian's SourceTree application shows you a great visual representation of how your branches relate to one another, i.e. Where they began and where they currently sit in the commit order (e.g. HEAD or 4 commits behind, etc.).

What's the best way to join on the same table twice?

You could use UNION to combine two joins:

SELECT Table1.PhoneNumber1 as PhoneNumber, Table2.SomeOtherField as OtherField
  FROM Table1
  JOIN Table2
    ON Table1.PhoneNumber1 = Table2.PhoneNumber
 UNION
SELECT Table1.PhoneNumber2 as PhoneNumber, Table2.SomeOtherField as OtherField
  FROM Table1
  JOIN Table2
    ON Table1.PhoneNumber2 = Table2.PhoneNumber

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

Subset a dataframe by multiple factor levels

Here's another:

data[data$Code == "A" | data$Code == "B", ]

It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,

data[Code == "A" | Code == "B", ]

also works, which is one of the really useful things about R.

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>

What is JSONP, and why was it created?

Because you can ask the server to prepend a prefix to the returned JSON object. E.g

function_prefix(json_object);

in order for the browser to eval "inline" the JSON string as an expression. This trick makes it possible for the server to "inject" javascript code directly in the Client browser and this with bypassing the "same origin" restrictions.

In other words, you can achieve cross-domain data exchange.


Normally, XMLHttpRequest doesn't permit cross-domain data-exchange directly (one needs to go through a server in the same domain) whereas:

<script src="some_other_domain/some_data.js&prefix=function_prefix>` one can access data from a domain different than from the origin.


Also worth noting: even though the server should be considered as "trusted" before attempting that sort of "trick", the side-effects of possible change in object format etc. can be contained. If a function_prefix (i.e. a proper js function) is used to receive the JSON object, the said function can perform checks before accepting/further processing the returned data.

HttpClient not supporting PostAsJsonAsync method C#

PostAsJsonAsync is no longer in the System.Net.Http.dll (.NET 4.5.2). You can add a reference to System.Net.Http.Formatting.dll, but this actually belongs to an older version. I ran into problems with this on our TeamCity build server, these two wouldn't cooperate together.

Alternatively, you can replace PostAsJsonAsyncwith a PostAsync call, which is just part of new dll. Replace

var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;

With:

var response = client.PostAsync("api/AgentCollection", new StringContent(
   new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;

Note that JavaScriptSerializer is in the namespace: System.Web.Script.Serialization.

You will have to add an assembly reference in your csproj: System.Web.Extensions.dll

See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836

Superscript in markdown (Github flavored)?

Comments about previous answers

The universal solution is using the HTML tag <sup>, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.

Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.

Finally, I would like to remember the simplest solution for some documents: the character ^.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.

Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.

Laravel Fluent Query Builder Join with subquery

I think what you looking for is "joinSub". It's supported from laravel ^5.6. If you using laravel version below 5.6 you can also register it as macro in your app service provider file. like this https://github.com/teamtnt/laravel-scout-tntsearch-driver/issues/171#issuecomment-413062522

$subquery = DB::table('catch-text')
            ->select(DB::raw("user_id,MAX(created_at) as MaxDate"))
            ->groupBy('user_id');

$query = User::joinSub($subquery,'MaxDates',function($join){
          $join->on('users.id','=','MaxDates.user_id');
})->select(['users.*','MaxDates.*']);

Java associative-array

Java equivalent of Perl's hash

HashMap<Integer, HashMap<String, String>> hash;

How to add leading zeros?

Here is another alternative for adding leading to 0s to strings such as CUSIPs which can sometimes look like a number and which many applications such as Excel will corrupt and remove the leading 0s or convert them to scientific notation.

When I tried the answer provided by @metasequoia the vector returned had leading spaces and not 0s. This was the same problem mentioned by @user1816679 -- and removing the quotes around the 0 or changing from %d to %s did not make a difference either. FYI, I am using RStudio Server running on an Ubuntu Server. This little two-step solution worked for me:

gsub(pattern = " ", replacement = "0", x = sprintf(fmt = "%09s", ids[,CUSIP]))

using the %>% pipe function from the magrittr package it could look like this:

sprintf(fmt = "%09s", ids[,CUSIP]) %>% gsub(pattern = " ", replacement = "0", x = .)

I'd prefer a one-function solution, but it works.

PHP call Class method / function

You need to create Object for the class.

$obj = new Functions();
$var = $obj->filter($_GET['params']);

Parsing JSON from URL

GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).

This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.

Only three lines of relevant code.

import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import com.google.gson.Gson;

public class GsonFetchNetworkJson {

    public static void main(String[] ignored) throws Exception {

        URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyDto dto = new Gson().fromJson(reader, MyDto.class);

        // using the deserialized object
        System.out.println(dto.headers);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
    }

    private class MyDto {
        Map<String, String> headers;
        Map<String, String> args;
        String origin;
        String url;
    }
}

If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

XAMPP permissions on Mac OS X?

Tried the above but the option to amend the permission was not available for the htdocs folder,

My solution was:

  1. Open applications folder
  2. Locate XAMPP folder
  3. Right click, get info (as described above)
  4. In pop-up window locate the 'sharing & permission' section
  5. Click the 'locked' padlock symbol
  6. Enter admin password
  7. Change 'Everyone' permissions to read & write
  8. In the get info window still, select the 'cog' icon' drop down option at the very bottom and select 'Apply to enclosed items' this will adjust the permission across all sub-folders as well.
  9. Re-lock the padlock symbol
  10. Close the 'Get Info' window.

Task complete, this will now allow you to populate sub-folders within the htdocs folder as needed to populate your website(s).

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

CSS background-size: cover replacement for Mobile Safari

I found a working solution, the following CSS code example is targeting the iPad:

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {

    html {  
        height: 100%;
        overflow: hidden;
        background: url('http://url.com/image.jpg') no-repeat top center fixed;
        background-size: cover; 
    }

    body {  
        height:100%;
        overflow: scroll;
        -webkit-overflow-scrolling: touch;
    }

}

Reference link: https://www.jotform.com/answers/565598-Page-background-image-scales-massively-when-form-viewed-on-iPad

How to float a div over Google Maps?

#floating-panel {
  position: absolute;
  top: 10px;
  left: 25%;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
  text-align: center;
  font-family: 'Roboto','sans-serif';
  line-height: 30px;
  padding-left: 10px;
}

Just need to move the map below this box. Work to me.

From Google

Read all worksheets in an Excel workbook into an R list with data.frames

Note that most of XLConnect's functions are already vectorized. This means that you can read in all worksheets with one function call without having to do explicit vectorization:

require(XLConnect)
wb <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", package = "XLConnect"))
lst = readWorksheet(wb, sheet = getSheets(wb))

With XLConnect 0.2-0 lst will already be a named list.

How to see tomcat is running or not

open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

Goto Project Properties -> Build -> Advanced...

In the "Output" section select "full" in Debug Info dropdown

How to write a caption under an image?

<div style="margin: 0 auto; text-align: center; overflow: hidden;">
  <div style="float: left;">
    <a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px"></a>
    caption 1
  </div>
 <div style="float: left;">
   <a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px"></a>
   caption 2                      
 </div>
</div>

Load Image from javascript

You can try this:

<img id="id1" src="url/to/file.png" onload="showImage()">

function showImage() {
 $('#id1').attr('src', 'new/file/link.png');
}

Also, try to remove the ~, that is just the operator, that is needed for Server-Side (for example ASP.NET) you don't need it in JS.

This way, you can change the attribute for the image.

Here is the fiddle: http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

Load properties file in JAR?

The problem is that you are using getSystemResourceAsStream. Use simply getResourceAsStream. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.

It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.

EDIT: Normally, you would call getClass().getResourceAsStream() to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer, e.g.

[public] class MyClass {
  static
  {
    ...
    props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
  }
}

How to open mail app from Swift

@IBAction func launchEmail(sender: AnyObject) {
 if if MFMailComposeViewController.canSendMail() {
   var emailTitle = "Feedback"
   var messageBody = "Feature request or bug report?"
   var toRecipents = ["[email protected]"]
   var mc: MFMailComposeViewController = MFMailComposeViewController()
   mc.mailComposeDelegate = self
   mc.setSubject(emailTitle)
   mc.setMessageBody(messageBody, isHTML: false)
   mc.setToRecipients(toRecipents)

   self.present(mc, animated: true, completion: nil)
 } else {
   // show failure alert
 }
}

func mailComposeController(controller:MFMailComposeViewController, didFinishWithResult result:MFMailComposeResult, error:NSError) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(error?.localizedDescription)")
    default:
        break
    }
    self.dismiss(animated: true, completion: nil)
}

Note that not all users have their device configure to send emails, which is why we need to check the result of canSendMail() before trying to send. Note also that you need to catch the didFinishWith callback in order to dismiss the mail window.

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

Standardize data columns in R

'Caret' package provides methods for preprocessing data (e.g. centering and scaling). You could also use the following code:

library(caret)
# Assuming goal class is column 10
preObj <- preProcess(data[, -10], method=c("center", "scale"))
newData <- predict(preObj, data[, -10])

More details: http://www.inside-r.org/node/86978

How to get current timestamp in milliseconds since 1970 just the way Java gets

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

How to select first parent DIV using jQuery?

two of the best options are

$(this).parent("div:first")

$(this).parent().closest('div')

and of course you can find the class attr by

$(this).parent("div:first").attr("class")

$(this).parent().closest('div').attr("class")

Export table data from one SQL Server to another

If you don't have permission to link servers, here are the steps to import a table from one server to another using Sql Server Import/Export Wizard:

  • Right click on the source database you want to copy from.
  • Select Tasks - Export Data.
  • Select Sql Server Native Client in the data source.
  • Select your authentication type (Sql Server or Windows authentication).
  • Select the source database.
  • Next, choose the Destination: Sql Server Native Client
  • Type in your Server Name (the server you want to copy the table to).
  • Select your authentication type (Sql Server or Windows authentication).
  • Select the destination database.
  • Select Copy data.
  • Select your table from the list.
  • Hit Next, Select Run immediately, or optionally, you can also save the package to a file or Sql Server if you want to run it later.
  • Finish

Changing datagridview cell color based on condition

foreach (DataGridViewRow row in dgvWebData.Rows)
{
    if (Convert.ToString(row.Cells["IssuerName"].Value) != Convert.ToString(row.Cells["SearchTermUsed"].Value))
    {
        row.DefaultCellStyle.BackColor = Color.Yellow;
    }
    else
    {
        row.DefaultCellStyle.BackColor = Color.White;
    }
}

This Perfectly worked for me . even if a row is changed, same event takes care.

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

If you are still looking for an answer, try checking this question thread. It helped me resolve a similar problem.

edit: The solution that helped me was to run Update-Package Microsoft.AspNet.WebApi -reinstall from the NugGet package manager, as suggested by Pathoschild. I then had to delete my .suo file and restart VS, as suggested by Sergey Osypchuk in this thread.

window.onload vs <body onload=""/>

'so many subjective answers to an objective question. "Unobtrusive" JavaScript is superstition like the old rule to never use gotos. Write code in a way that helps you reliably accomplish your goal, not according to someone's trendy religious beliefs.

Anyone who finds:

 <body onload="body_onload();">

to be overly distracting is overly pretentious and doesn't have their priorities straight.

I normally put my JavaScript code in a separate .js file, but I find nothing cumbersome about hooking event handlers in HTML, which is valid HTML by the way.

Can (domain name) subdomains have an underscore "_" in it?

Here my 2 cents from Java world:

From a Spark Scala console, with Java 8:

scala> new java.net.URI("spark://spark_master").getHost
res10: String = null

scala> new java.net.URI("spark://spark-master").getHost
res11: String = spark-master

scala> new java.net.URI("spark://spark_master.google.fr").getHost
res12: String = null

scala> new java.net.URI("spark://spark.master.google.fr").getHost
res13: String = spark.master.google.fr

scala> new java.net.URI("spark://spark-master.google.fr:3434").getHost
res14: String = spark-master.google.fr

scala> new java.net.URI("spark://spark-master.goo_gle.fr:3434").getHost
res15: String = null

It's definitely a bad idea ^^

`getchar()` gives the same output as the input string

In the simple setup you are likely using, getchar works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF; in fact, EOF is not really a character, but a magic value that indicates the end of the file. But EOF is not part of the string read. It's what getchar returns when there is nothing left to read.

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

Naming Conventions: What to name a boolean variable?

isBeforeTheLastItem

isInFrontOfTheLastItem

isTowardsTheFrontOfTheList

Maybe too wordy but they may help give you ideas.

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

Passing a method parameter using Task.Factory.StartNew

Try this,

        var arg = new { i = 123, j = 456 };
        var task = new TaskFactory().StartNew(new Func<dynamic, int>((argument) =>
        {
            dynamic x = argument.i * argument.j;
            return x;
        }), arg, CancellationToken.None, TaskCreationOptions.AttachedToParent, TaskScheduler.Default);
        task.Wait();
        var result = task.Result;

How can I change the version of npm using nvm?

Slight variation on the above instructions, worked for me. (MacOS Sierra 10.12.6)

npm install -g [email protected]
rm /usr/local/bin/npm
ln -s ~/.npm-packages/bin/npm /usr/local/bin/npm
npm --version

How to set my default shell on Mac?

edit .zshrc and change it to

exec /bin/bash

or to whatever shell you might prefer. Bonus: this doesn't require root access and will work on every version of osx.

The only problem is that it doesn't read .bash_profile this way; it is only read if bash is run as an interactive login shell, you would have to include it from .bashrc with something like this:

if [[ "$OSTYPE" == "darwin"* ]]; then
    #local hack on osx.
    if [[ -f $HOME/.bash_profile ]]; then
      . $HOME/.bash_profile
    fi
fi

Is it possible to insert multiple rows at a time in an SQLite database?

As of version 3.7.11 SQLite does support multi-row-insert. Richard Hipp comments:

I'm using 3.6.13

I command like this:

insert into xtable(f1,f2,f3) select v1 as f1, v2 as f2, v3 as f3 
union select nextV1+, nextV2+, nextV3+

With 50 records inserted at a time, it takes only a second or less.

It's true using sqlite to insert multiple rows at a time is very possible. By @Andy wrote.

thanks Andy +1

How do you set the Content-Type header for an HttpClient request?

You can use this it will be work!

HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Get,"URL");
msg.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpResponseMessage response = await _httpClient.SendAsync(msg);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();

Submit form using AJAX and jQuery

There is a nice form plugin that allows you to send an HTML form asynchroniously.

$(document).ready(function() { 
    $('#myForm1').ajaxForm(); 
});

or

$("select").change(function(){
    $('#myForm1').ajaxSubmit();
});

to submit the form immediately

Using Node.js require vs. ES6 import/export

Are there any performance benefits to using one over the other?

Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts import and export declaration to CommonJS (require/module.exports) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.

There are technical differences between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.

Since ES6 modules are part of the standard, I would use them.


Update 2020

Since Node v12, support for ES modules is enabled by default, but it's still experimental at the time of writing this. Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module". The Node documentation has a ton more information, also about interop between CommonJS and ES modules.

Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end you have to run benchmarks to get a definite answer anyway.

ES modules can be loaded dynamically via the import() function. Unlike require, this returns a promise.

How to extract closed caption transcript from YouTube video?

You can download the streaming subtitles from YouTube with KeepSubs DownSub and SaveSubs.

You can choose from the Automatic Transcript or author supplied close captions. It also offers the possibility to automatically translate the English subtitles into other languages using Google Translate.

scroll up and down a div on button click using jquery

Where did it come from scrollBottom this is not a valid property it should be scrollTop and this can be positive(+) or negative(-) values to scroll down(+) and up(-), so you can change:

scrollBottom 

to this scrollTop:

$("#upClick").on("click", function () {
    scrolled = scrolled - 300;

    $(".cover").animate({
        scrollTop: scrolled
    });//^^^^^^^^------------------------------this one
});

javascript regex for special characters

How about this:-

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;

It will allow a minimum of 6 characters including numbers, alphabets, and special characters

python-dev installation error: ImportError: No module named apt_pkg

  1. Check your default Python 3 version:
python --version
Python 3.7.5
  1. cd into /usr/lib/python3/dist-packages and check the apt_pkg.* files. You will find that there is none for your default Python version:
ll apt_pkg.*
apt_pkg.cpython-36m-x86_64-linux-gnu.so
  1. Create the symlink:
sudo ln -s apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.cpython-37m-x86_64- linux-gnu.so 

Difference between Python's Generators and Iterators

Generator Function, Generator Object, Generator:

A Generator function is just like a regular function in Python but it contains one or more yield statements. Generator functions is a great tool to create Iterator objects as easy as possible. The Iterator object returend by generator function is also called Generator object or Generator.

In this example I have created a Generator function which returns a Generator object <generator object fib at 0x01342480>. Just like other iterators, Generator objects can be used in a for loop or with the built-in function next() which returns the next value from generator.

def fib(max):
    a, b = 0, 1
    for i in range(max):
        yield a
        a, b = b, a + b
print(fib(10))             #<generator object fib at 0x01342480>

for i in fib(10):
    print(i)               # 0 1 1 2 3 5 8 13 21 34


print(next(myfib))         #0
print(next(myfib))         #1
print(next(myfib))         #1
print(next(myfib))         #2

So a generator function is the easiest way to create an Iterator object.

Iterator:

Every generator object is an iterator but not vice versa. A custom iterator object can be created if its class implements __iter__ and __next__ method (also called iterator protocol).

However, it is much easier to use generators function to create iterators because they simplify their creation, but a custom Iterator gives you more freedom and you can also implement other methods according to your requirements as shown in the below example.

class Fib:
    def __init__(self,max):
        self.current=0
        self.next=1
        self.max=max
        self.count=0

    def __iter__(self):
        return self

    def __next__(self):
        if self.count>self.max:
            raise StopIteration
        else:
            self.current,self.next=self.next,(self.current+self.next)
            self.count+=1
            return self.next-self.current

    def __str__(self):
        return "Generator object"

itobj=Fib(4)
print(itobj)               #Generator object

for i in Fib(4):  
    print(i)               #0 1 1 2

print(next(itobj))         #0
print(next(itobj))         #1
print(next(itobj))         #1

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

This will validate against special characters and leading and trailing spaces:

var strString = "Your String";

strString.match(/^[A-Za-z0-9][A-Za-z0-9 ]\*[A-Za-z0-9]\*$/)

..The underlying connection was closed: An unexpected error occurred on a receive

To expand on Bartho Bernsmann's answer, I should like to add that one can have a universal, future-proof implementation at the expense of a little reflection:

static void AllowAllSecurityPrototols()
{   int                  i, n;
    Array                types;
    SecurityProtocolType combined;

    types = Enum.GetValues( typeof( SecurityProtocolType ) ); 
    combined = ( SecurityProtocolType )types.GetValue( 0 );

    n = types.Length;
    for( i = 1; i < n; i += 1 )
    {   combined |= ( SecurityProtocolType )types.GetValue( i );  }

    ServicePointManager.SecurityProtocol = combined;
}

I invoke this method in the static constructor of the class that accesses the internet.

Invoking a jQuery function after .each() has completed

Ok, this might be a little after the fact, but .promise() should also achieve what you're after.

Promise documentation

An example from a project i'm working on:

$( '.panel' )
    .fadeOut( 'slow')
    .promise()
    .done( function() {
        $( '#' + target_panel ).fadeIn( 'slow', function() {});
    });

:)

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Simply i have import in appmodule.ts

import { HttpClientModule } from '@angular/common/http';
  imports: [
     BrowserModule,
     FormsModule,
     HttpClientModule  <<<this 
  ],

My problem resolved

python mpl_toolkits installation issue

It is not on PyPI and you should not be installing it via pip. If you have matplotlib installed, you should be able to import mpl_toolkits directly:

$ pip install --upgrade matplotlib
...

$ python
>>> import mpl_toolkits
>>> 

Command to find information about CPUs on a UNIX machine

My favorite is to look at the boot messages. If it's been recently booted try running /etc/dmesg. Otherwise find the boot messages, logged in /var/adm or some place in /var.

How can I find my php.ini on wordpress?

Use the php_ini_loaded_file function to get the location of your php.ini file.

<?php
$inipath = php_ini_loaded_file();

if ($inipath) {
    echo 'Loaded php.ini: ' . $inipath;
} else {
    echo 'A php.ini file is not loaded';
}

C# string replace

You need to escape the double-quotes inside the search string, like this:

string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");

Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res will have the replacements.

How to run Python script on terminal?

You need python installed on your system. Then you can run this in the terminal in the correct directory:

python gameover.py

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

Convert ASCII TO UTF-8 Encoding

If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.

But if you still want to convert, just to be sure that its UTF-8, then you can use iconv

$string = iconv('ASCII', 'UTF-8//IGNORE', $string);

The IGNORE will discard any invalid characters just in case some were not valid ASCII.

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

I read all the comments and thought that GitHub made it too difficult for normal user to create GitHub pages until I visited GitHub theme Page where its clearly mentioned that there is a section of "GitHub Pages" under settings Page of the concerned repo where you can choose the option "use the master branch for GitHub Pages." and voilà!!...checkout that particular repo on https://username.github.io/reponame

screenshot to support my answer

Turn off warnings and errors on PHP and MySQL

Prepend functions with the '@' symbol to suppress certain errors, as opposed to turning off all error reporting.

More information: http://php.net/manual/en/language.operators.errorcontrol.php

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

@fsockopen();

Check if list is empty in C#

Why not...

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

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

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

<emptydatatemplate>

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

    No Data Found!  

</emptydatatemplate> 

Read and write a String from text file

Latest swift3 code
You can read data from text file just use bellow code This my text file

     {
"NumberOfSlices": "8",
"NrScenes": "5",
"Scenes": [{
           "dataType": "label1",
           "image":"http://is3.mzstatic.com/image/thumb/Purple19/v4/6e/81/31/6e8131cf-2092-3cd3-534c-28e129897ca9/mzl.syvaewyp.png/53x53bb-85.png",

           "value": "Hello",
           "color": "(UIColor.red)"
           }, {
           "dataType": "label2",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "Hi There",
           "color": "(UIColor.blue)"
           }, {
           "dataType": "label3",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",

           "value": "hi how r u ",
           "color": "(UIColor.green)"
           }, {
           "dataType": "label4",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "what are u doing  ",
           "color": "(UIColor.purple)"
           }, {
           "dataType": "label5",
          "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/6c/4c/c1/6c4cc1bc-8f94-7b13-f3aa-84c41443caf3/mzl.hcqvmrix.png/53x53bb-85.png",
           "value": "how many times ",
           "color": "(UIColor.white)"
           }, {
           "dataType": "label6",
           "image":"http://is1.mzstatic.com/image/thumb/Purple71/v4/5a/f3/06/5af306b0-7cac-1808-f440-bab7a0d18ec0/mzl.towjvmpm.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.blue)"
           }, {
           "dataType": "label7",
           "image":"http://is5.mzstatic.com/image/thumb/Purple71/v4/a8/dc/eb/a8dceb29-6daf-ca0f-d037-df9f34cdc476/mzl.ukhhsxik.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.gry)"
           }, {
           "dataType": "label8",
           "image":"http://is2.mzstatic.com/image/thumb/Purple71/v4/15/23/e0/1523e03c-fff2-291e-80a7-73f35d45c7e5/mzl.zejcvahm.png/53x53bb-85.png",
           "value": "hi how r u ",
           "color": "(UIColor.brown)"
           }]

}

You can use this code you get data from text json file in swift3

     let filePath = Bundle.main.path(forResource: "nameoftheyourjsonTextfile", ofType: "json")


    let contentData = FileManager.default.contents(atPath: filePath!)
    let content = NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String

    print(content)
    let json = try! JSONSerialization.jsonObject(with: contentData!) as! NSDictionary
    print(json)
    let app = json.object(forKey: "Scenes") as! NSArray!
    let _ : NSDictionary
    for dict in app! {
        let colorNam = (dict as AnyObject).object(forKey: "color") as! String
        print("colors are \(colorNam)")

       // let colour = UIColor(hexString: colorNam) {
       // colorsArray.append(colour.cgColor)
       // colorsArray.append(colorNam  as! UIColor)

        let value = (dict as AnyObject).object(forKey: "value") as! String
        print("the values are \(value)")
        valuesArray.append(value)

        let images = (dict as AnyObject).object(forKey: "image") as! String
        let url = URL(string: images as String)
        let data = try? Data(contentsOf: url!)
        print(data)
        let image1 = UIImage(data: data!)! as UIImage
        imagesArray.append(image1)
         print(image1)
            }

How do I set an absolute include path in PHP?

The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.

So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.

ini_set("include_path", "/your_include_path:".ini_get("include_path"));

This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.

Using getopts to process long and short command line options

A simple DIY to get only long named args:

Use:

$ ./test-args.sh --a1 a1 --a2 "a 2" --a3 --a4= --a5=a5 --a6="a 6"
a1 = "a1"
a2 = "a 2"
a3 = "TRUE"
a4 = ""
a5 = "a5"
a6 = "a 6"
a7 = ""

Script:

#!/bin/bash

function main() {
    ARGS=`getArgs "$@"`

    a1=`echo "$ARGS" | getNamedArg a1`
    a2=`echo "$ARGS" | getNamedArg a2`
    a3=`echo "$ARGS" | getNamedArg a3`
    a4=`echo "$ARGS" | getNamedArg a4`
    a5=`echo "$ARGS" | getNamedArg a5`
    a6=`echo "$ARGS" | getNamedArg a6`
    a7=`echo "$ARGS" | getNamedArg a7`

    echo "a1 = \"$a1\""
    echo "a2 = \"$a2\""
    echo "a3 = \"$a3\""
    echo "a4 = \"$a4\""
    echo "a5 = \"$a5\""
    echo "a6 = \"$a6\""
    echo "a7 = \"$a7\""

    exit 0
}


function getArgs() {
    for arg in "$@"; do
        echo "$arg"
    done
}


function getNamedArg() {
    ARG_NAME=$1

    sed --regexp-extended --quiet --expression="
        s/^--$ARG_NAME=(.*)\$/\1/p  # Get arguments in format '--arg=value': [s]ubstitute '--arg=value' by 'value', and [p]rint
        /^--$ARG_NAME\$/ {          # Get arguments in format '--arg value' ou '--arg'
            n                       # - [n]ext, because in this format, if value exists, it will be the next argument
            /^--/! p                # - If next doesn't starts with '--', it is the value of the actual argument
            /^--/ {                 # - If next do starts with '--', it is the next argument and the actual argument is a boolean one
                # Then just repla[c]ed by TRUE
                c TRUE
            }
        }
    "
}


main "$@"

C# testing to see if a string is an integer?

If you only want to check whether it's a string or not, you can place the "out int" keywords directly inside a method call. According to dotnetperls.com website, older versions of C# do not allow this syntax. By doing this, you can reduce the line count of the program.

string x = "text or int";
if (int.TryParse(x, out int output))
{
  // Console.WriteLine(x);
  // x is an int
  // Do something
}
else
{
  // x is not an int
}

If you also want to get the int values, you can write like this.

Method 1

string x = "text or int";
int value = 0;
if(int.TryParse(x, out value))
{
  // x is an int
  // Do something
}
  else
{
  // x is not an int
}

Method 2

string x = "text or int";
int num = Convert.ToInt32(x);
Console.WriteLine(num);

Referece: https://www.dotnetperls.com/parse

How to write a large buffer into a binary file in C++, fast?

I see no difference between std::stream/FILE/device. Between buffering and non buffering.

Also note:

  • SSD drives "tend" to slow down (lower transfer rates) as they fill up.
  • SSD drives "tend" to slow down (lower transfer rates) as they get older (because of non working bits).

I am seeing the code run in 63 secondds.
Thus a transfer rate of: 260M/s (my SSD look slightly faster than yours).

64 * 1024 * 1024 * 8 /*sizeof(unsigned long long) */ * 32 /*Chunks*/

= 16G
= 16G/63 = 260M/s

I get a no increase by moving to FILE* from std::fstream.

#include <stdio.h>

using namespace std;

int main()
{
    
    FILE* stream = fopen("binary", "w");

    for(int loop=0;loop < 32;++loop)
    {
         fwrite(a, sizeof(unsigned long long), size, stream);
    }
    fclose(stream);

}

So the C++ stream are working as fast as the underlying library will allow.

But I think it is unfair comparing the OS to an application that is built on-top of the OS. The application can make no assumptions (it does not know the drives are SSD) and thus uses the file mechanisms of the OS for transfer.

While the OS does not need to make any assumptions. It can tell the types of the drives involved and use the optimal technique for transferring the data. In this case a direct memory to memory transfer. Try writing a program that copies 80G from 1 location in memory to another and see how fast that is.

Edit

I changed my code to use the lower level calls:
ie no buffering.

#include <fcntl.h>
#include <unistd.h>


const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    int data = open("test", O_WRONLY | O_CREAT, 0777);
    for(int loop = 0; loop < 32; ++loop)
    {   
        write(data, a, size * sizeof(unsigned long long));
    }   
    close(data);
}

This made no diffference.

NOTE: My drive is an SSD drive if you have a normal drive you may see a difference between the two techniques above. But as I expected non buffering and buffering (when writting large chunks greater than buffer size) make no difference.

Edit 2:

Have you tried the fastest method of copying files in C++

int main()
{
    std::ifstream  input("input");
    std::ofstream  output("ouptut");

    output << input.rdbuf();
}

Can I call a base class's virtual function if I'm overriding it?

Just in case you do this for a lot of functions in your class:

class Foo {
public:
  virtual void f1() {
    // ...
  }
  virtual void f2() {
    // ...
  }
  //...
};

class Bar : public Foo {
private:
  typedef Foo super;
public:
  void f1() {
    super::f1();
  }
};

This might save a bit of writing if you want to rename Foo.

Why call super() in a constructor?

We can access super class elements by using super keyword

Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.

    class parent {
    String str="I am parent";
    //method of parent Class
    public void foo() {
        System.out.println("Hello World " + str);
    }
}

class child extends parent {
    String str="I am child";
    // different foo implementation in child Class
    public void foo() {
        System.out.println("Hello World "+str);
    }

    // calling the foo method of parent class
    public void parentClassFoo(){
        super.foo();
    }

    // changing the value of str in parent class and calling the foo method of parent class
    public void parentClassFooStr(){
        super.str="parent string changed";
        super.foo();
    }
}


public class Main{
        public static void main(String args[]) {
            child obj = new child();
            obj.foo();
            obj.parentClassFoo();
            obj.parentClassFooStr();
        }
    }

How do I restart my C# WinForm Application?

Unfortunately you can't use Process.Start() to start an instance of the currently running process. According to the Process.Start() docs: "If the process is already running, no additional process resource is started..."

This technique will work fine under the VS debugger (because VS does some kind of magic that causes Process.Start to think the process is not already running), but will fail when not run under the debugger. (Note that this may be OS-specific - I seem to remember that in some of my testing, it worked on either XP or Vista, but I may just be remembering running it under the debugger.)

This technique is exactly the one used by the last programmer on the project on which I'm currently working, and I've been trying to find a workaround for this for quite some time. So far, I've only found one solution, and it just feels dirty and kludgy to me: start a 2nd application, that waits in the background for the first application to terminate, then re-launches the 1st application. I'm sure it would work, but, yuck.

Edit: Using a 2nd application works. All I did in the second app was:

    static void RestartApp(int pid, string applicationName )
    {
        // Wait for the process to terminate
        Process process = null;
        try
        {
            process = Process.GetProcessById(pid);
            process.WaitForExit(1000);
        }
        catch (ArgumentException ex)
        {
            // ArgumentException to indicate that the 
            // process doesn't exist?   LAME!!
        }
        Process.Start(applicationName, "");
    }

(This is a very simplified example. The real code has lots of sanity checking, error handling, etc)

Inversion of Control vs Dependency Injection

Rather than contrast DI and IoC directly, it may be helpful to start from the beginning: every non-trivial application depends on other pieces of code.

So I am writing a class, MyClass, and I need to call a method of YourService... somehow I need to acquire an instance of YourService. The simplest, most straightforward way is to instantiate it myself.

YourService service = new YourServiceImpl();

Direct instantiation is the traditional (procedural) way to acquire a dependency. But it has a number of drawbacks, including tight coupling of MyClass to YourServiceImpl, making my code difficult to change and difficult to test. MyClass doesn't care what the implementation of YourService looks like, so MyClass doesn't want to be responsible for instantiating it.

I'd prefer to invert that responsibility from MyClass to something outside MyClass. The simplest way to do that is just to move the instantiation call (new YourServiceImpl();) into some other class. I might name this other class a Locator, or a Factory, or any other name; but the point is that MyClass is no longer responsible for YourServiceImpl. I've inverted that dependency. Great.

Problem is, MyClass is still responsible for making the call to the Locator/Factory/Whatever. Since all I've done to invert the dependency is insert a middleman, now I'm coupled to the middleman (even if I'm not coupled to the concrete objects the middleman gives me).

I don't really care where my dependencies come from, so I'd prefer not to be responsible for making the call(s) to retrieve them. Inverting the dependency itself wasn't quite enough. I want to invert control of the whole process.

What I need is a totally separate piece of code that MyClass plugs into (call it a framework). Then the only responsibility I'm left with is to declare my dependency on YourService. The framework can take care of figuring out where and when and how to get an instance, and just give MyClass what it needs. And the best part is that MyClass doesn't need to know about the framework. The framework can be in control of this dependency wiring process. Now I've inverted control (on top of inverting dependencies).

There are different ways of connecting MyClass into a framework. Injection is one such mechanism whereby I simply declare a field or parameter that I expect a framework to provide, typically when it instantiates MyClass.

I think the hierarchy of relationships among all these concepts is slightly more complex than what other diagrams in this thread are showing; but the basic idea is that it is a hierarchical relationship. I think this syncs up with DIP in the wild.

Hierarchy of Dependency Acquisition

Setting a spinner onClickListener() in Android

Here is a working solution:

Instead of setting the spinner's OnClickListener, we are setting OnTouchListener and OnKeyListener.

spinner.setOnTouchListener(Spinner_OnTouch);
spinner.setOnKeyListener(Spinner_OnKey);

and the listeners:

private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            doWhatYouWantHere();
        }
        return true;
    }
};
private static View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            doWhatYouWantHere();
            return true;
        } else {
            return false;
        }
    }
};

How do I run a program with commandline arguments using GDB within a Bash script?

You could create a file with context:

run arg1 arg2 arg3 etc

program input

And call gdb like

gdb prog < file

What are the best practices for SQLite on Android?

The Database is very flexible with multi-threading. My apps hit their DBs from many different threads simultaneously and it does just fine. In some cases I have multiple processes hitting the DB simultaneously and that works fine too.

Your async tasks - use the same connection when you can, but if you have to, its OK to access the DB from different tasks.

How to find the size of an int[]?

You have to use sizeof() function.

Code Snippet:

#include<bits/stdc++.h>
using namespace std;

int main()
{
      ios::sync_with_stdio(false);

      int arr[] ={5, 3, 6, 7};

      int size = sizeof(arr) / sizeof(arr[0]);
      cout<<size<<endl;

      return 0;
}

How to find integer array size in java

Array's has

array.length

whereas List has

list.size()

Replace array.size() to array.length

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

Spring Boot War deployed to Tomcat

I had same problem and i find out solution by following this guide . I run with goal in maven.

clean package

Its worked for me Thanq

How to check if an object is a list or tuple (but not string)?

The str object doesn't have an __iter__ attribute

>>> hasattr('', '__iter__')
False 

so you can do a check

assert hasattr(x, '__iter__')

and this will also raise a nice AssertionError for any other non-iterable object too.

Edit: As Tim mentions in the comments, this will only work in python 2.x, not 3.x

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Git fast forward VS no fast forward merge

It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.

I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.

As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i and forced on the server as long as nobody else is working on that same branch.

What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".


Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

C# How to change font of a label

I noticed there was not an actual full code answer, so as i come across this, i have created a function, that does change the font, which can be easily modified. I have tested this in

- XP SP3 and Win 10 Pro 64

private void SetFont(Form f, string name, int size, FontStyle style)
{
    Font replacementFont = new Font(name, size, style);
    f.Font = replacementFont;
}

Hint: replace Form to either Label, RichTextBox, TextBox, or any other relative control that uses fonts to change the font on them. By using the above function thus making it completely dynamic.

    /// To call the function do this.
    /// e.g in the form load event etc.

public Form1()
{
      InitializeComponent();
      SetFont(this, "Arial", 8, FontStyle.Bold);  
      // This sets the whole form and 
      // everything below it.
      // Shaun Cassidy.
}

You can also, if you want a full libary so you dont have to code all the back end bits, you can download my dll from Github.

Github DLL

/// and then import the namespace
using Droitech.TextFont;

/// Then call it using:
TextFontClass fClass = new TextFontClass();
fClass.SetFont(this, "Arial", 8, FontStyle.Bold);

Simple.

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

Use jquery attr method. It works in all browsers.

var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
    'id':'uniqueIdentifier',
    'type': 'hidden',
    'value': ID,
    'class': 'ListItem'
});

Or you could use folowing code:

var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');

How to import component into another root component in Angular 2

You should declare it with declarations array(meta property) of @NgModule as shown below (RC5 and later),

import {CoursesComponent} from './courses.component';

@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent,CoursesComponent],  //<----here
  providers:    [],      
  bootstrap:    [ AppComponent ]
})

How do I set adaptive multiline UILabel text?

It should work. Try this

var label:UILabel = UILabel(frame: CGRectMake(10
    ,100, 300, 40));
label.textAlignment = NSTextAlignment.Center;
label.numberOfLines = 0;
label.font = UIFont.systemFontOfSize(16.0);
label.text = "First label\nsecond line";
self.view.addSubview(label);

How to bring a window to the front?

The rules governing what happens when you .toFront() a JFrame are the same in windows and in linux :

-> if a window of the existing application is currently the focused window, then focus swaps to the requested window -> if not, the window merely flashes in the taskbar

BUT :

-> new windows automatically get focus

So let's exploit this ! You want to bring a window to the front, how to do it ? Well :

  1. Create an empty non-purpose window
  2. Show it
  3. Wait for it to show up on screen (setVisible does that)
  4. When shown, request focus for the window you actually want to bring the focus to
  5. hide the empty window, destroy it

Or, in java code :

// unminimize if necessary
this.setExtendedState(this.getExtendedState() & ~JFrame.ICONIFIED);

// don't blame me, blame my upbringing
// or better yet, blame java !
final JFrame newFrame = new JFrame();
newFrame.add(new JLabel("boembabies, is this in front ?"));

newFrame.pack();
newFrame.setVisible(true);
newFrame.toFront();

this.toFront();
this.requestFocus();

// I'm not 100% positive invokeLater is necessary, but it seems to be on
// WinXP. I'd be lying if I said I understand why
SwingUtilities.invokeLater(new Runnable() {
  @Override public void run() {
    newFrame.setVisible(false);
  }
});

Does Typescript support the ?. operator? (And, what's it called?)

_.get(obj, 'address.street.name') works great for JavaScript where you have no types. But for TypeScript we need the real Elvis operator!

JavaScript Chart.js - Custom data formatting to display on tooltip

tooltips: {
          callbacks: {
            label: (tooltipItem, data) => {
              // data for manipulation
              return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
            },
          },
        },

How do I change the formatting of numbers on an axis with ggplot?

I find Jack Aidley's suggested answer a useful one.

I wanted to throw out another option. Suppose you have a series with many small numbers, and you want to ensure the axis labels write out the full decimal point (e.g. 5e-05 -> 0.0005), then:

NotFancy <- function(l) {
 l <- format(l, scientific = FALSE)
 parse(text=l)
}

ggplot(data = data.frame(x = 1:100, 
                         y = seq(from=0.00005,to = 0.0000000000001,length.out=100) + runif(n=100,-0.0000005,0.0000005)), 
       aes(x=x, y=y)) +
     geom_point() +
     scale_y_continuous(labels=NotFancy) 

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We solved the problem by stopping the FinalizerWatchdogDaemon.

public static void fix() {
    try {
        Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

        Method method = clazz.getSuperclass().getDeclaredMethod("stop");
        method.setAccessible(true);

        Field field = clazz.getDeclaredField("INSTANCE");
        field.setAccessible(true);

        method.invoke(field.get(null));

    }
    catch (Throwable e) {
        e.printStackTrace();
    }
}

You can call the method in Application's lifecycle, like attachBaseContext(). For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.

Looping through a hash, or using an array in PowerShell

A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.

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

forEach($y in $hash.Keys){
    Write-Host "$y -> $($hash[$y])"
}

Result:

a -> 1
b -> 2
c -> 3

Sending Arguments To Background Worker?

You can use the DoWorkEventArgs.Argument property.

A full example (even using an int argument) can be found on Microsoft's site:

Automatically set appsettings.json for dev and release environments in asp.net core?

In ASP.NET Core you should rather use Environment Variables instead of build configuration for proper appsettings.json

  1. Right click on you project > Properties > Debug > Environment Variables

    environment variables

  2. ASP.NET Core will use the appropriate appsettings.json file:

    example of appsettings files in solution explorer

  3. Now you can use that Environment Variable like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
        Configuration = builder.Build();
    }
    

Note: If you use @Dmitry's answer, you can run into problems eg. when overriding appsettings.json values on Azure.

Time calculation in php (add 10 hours)?

Full code that shows now and 10 minutes added.....

$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;

How to connect to a docker container from outside the host (same network) [Windows]

I found that along with setting the -p port values, Docker for Windows uses vpnkit and inbound traffic for it was disabled by default on my host machine's firewall. After enabling the inbound TCP rules for vpnkit I was able to access my containers from other machines on the local network.

Makefile ifeq logical or

As found on the mailing list archive,

one can use the filter function.

For example

ifeq ($(GCC_MINOR),$(filter $(GCC_MINOR),4 5))

filter X, A B will return those of A,B that are equal to X. Note, while this is not relevant in the above example, this is a XOR operation. I.e. if you instead have something like:

ifeq (4, $(filter 4, $(VAR1) $(VAR2)))

And then do e.g. make VAR1=4 VAR2=4, the filter will return 4 4, which is not equal to 4.

A variation that performs an OR operation instead is:

ifneq (,$(filter $(GCC_MINOR),4 5))

where a negative comparison against an empty string is used instead (filter will return en empty string if GCC_MINOR doesn't match the arguments). Using the VAR1/VAR2 example it would look like this:

ifneq (, $(filter 4, $(VAR1) $(VAR2)))

The downside to those methods is that you have to be sure that these arguments will always be single words. For example, if VAR1 is 4 foo, the filter result is still 4, and the ifneq expression is still true. If VAR1 is 4 5, the filter result is 4 5 and the ifneq expression is true.

One easy alternative is to just put the same operation in both the ifeq and else ifeq branch, e.g. like this:

ifeq ($(GCC_MINOR),4)
    @echo Supported version
else ifeq ($(GCC_MINOR),5)
    @echo Supported version
else
    @echo Unsupported version
endif

How to use css style in php

You can also embed it in the php. E.g.

<?php
    echo "<p style='color:blue; border:2px red solid;'>CSS Styling in php</p>";
?>

hope this help for anyone in the future.

Check if page gets reloaded or refreshed in JavaScript

New standard 2018-now (PerformanceNavigationTiming)

window.performance.navigation property is deprecated in the Navigation Timing Level 2 specification. Please use the PerformanceNavigationTiming interface instead.

PerformanceNavigationTiming.type

This is an experimental technology.

Check the Browser compatibility table carefully before using this in production.

Support on 2019-07-08

The type read-only property returns a string representing the type of navigation. The value must be one of the following:

  • navigate — Navigation started by clicking a link, entering the URL in the browser's address bar, form submission, or initializing through a script operation other than reload and back_forward as listed below.

  • reload — Navigation is through the browser's reload operation or location.reload().

  • back_forward — Navigation is through the browser's history traversal operation.

  • prerender — Navigation is initiated by a prerender hint.

This property is Read only.

The following example illustrates this property's usage.

function print_nav_timing_data() {
  // Use getEntriesByType() to just get the "navigation" events
  var perfEntries = performance.getEntriesByType("navigation");

  for (var i=0; i < perfEntries.length; i++) {
    console.log("= Navigation entry[" + i + "]");
    var p = perfEntries[i];
    // dom Properties
    console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - p.domContentLoadedEventStart));
    console.log("DOM complete = " + p.domComplete);
    console.log("DOM interactive = " + p.interactive);

    // document load and unload time
    console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
    console.log("document unload = " + (p.unloadEventEnd - p.unloadEventStart));

    // other properties
    console.log("type = " + p.type);
    console.log("redirectCount = " + p.redirectCount);
  }
}

How to set default Checked in checkbox ReactJS?

I set the state as any[] type. and in the constructor set the state to null.

onServiceChange = (e) => {
    const {value} = e.target;
    const index = this.state.services.indexOf(value);
    const services = this.state.services.filter(item => item !== value);
    this.setState(prevState => ({
        services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
    }))
}

In the input element

this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/> this.onServiceChange(e)}/>

I figured it out after some time. Thought it might help y'all :)

How to compare arrays in JavaScript?

We can use every() and includes() method to compare two arrays.

function check(a1,a2){

  let result = a1.every((x)=>{
  return a2.includes(x);
 });

return result; 
} 

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

Using HTML5/JavaScript to generate and save a file

Here is a link to the data URI method Mathew suggested, it worked on safari, but not well because I couldn't set the filetype, it gets saved as "unknown" and then i have to go there again later and change it in order to view the file...

http://www.nihilogic.dk/labs/canvas2image/

store return json value in input hidden field

You can use input.value = JSON.stringify(obj) to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)

The JSON object is available on modern browsers or you can use the json2.js library from json.org

How best to read a File into List<string>

You can simple read this way .

List<string> lines = System.IO.File.ReadLines(completePath).ToList();

Is there a better way to run a command N times in bash?

If you're using the zsh shell:

repeat 10 { echo 'Hello' }

Where 10 is the number of times the command will be repeated.

What is more efficient? Using pow to square or just multiply it with itself?

I have been busy with a similar problem, and I'm quite puzzled by the results. I was calculating x?³/² for Newtonian gravitation in an n-bodies situation (acceleration undergone from another body of mass M situated at a distance vector d) : a = M G d*(d²)?³/² (where d² is the dot (scalar) product of d by itself) , and I thought calculating M*G*pow(d2, -1.5) would be simpler than M*G/d2/sqrt(d2)

The trick is that it is true for small systems, but as systems grow in size, M*G/d2/sqrt(d2) becomes more efficient and I don't understand why the size of the system impacts this result, because repeating the operation on different data does not. It is as if there were possible optimizations as the system grow, but which are not possible with pow

enter image description here

How to check a string for a special character?

Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)

super() raises "TypeError: must be type, not classobj" for new-style class

FWIW and though I'm no Python guru I got by with this

>>> class TextParser(HTMLParser):
...    def handle_starttag(self, tag, attrs):
...        if tag == "b":
...            self.all_data.append("bold")
...        else:
...            self.all_data.append("other")
...     
...         
>>> p = TextParser()
>>> p.all_data = []
>>> p.feed(text)
>>> print p.all_data
(...)

Just got me the parse results back as needed.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

Programmatically go back to the previous fragment in the backstack

Try below code:

@Override
    public void onBackPressed() {
        Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.container);
        if (myFragment != null && myFragment instanceof StepOneFragment) {
            finish();
        } else {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
            } else {
                super.onBackPressed();
            }
        }
    }

The character encoding of the plain text document was not declared - mootool script

Check your URL's protocol.

You will also see this error if you host an encrypted page (https) and open it as plain text (http) in Firefox.

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Double vs. BigDecimal?

If you write down a fractional value like 1 / 7 as decimal value you get

1/7 = 0.142857142857142857142857142857142857142857...

with an infinite sequence of 142857. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.

Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:

1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.

Decimal numbers (like BigDecimal), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.

Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

Environ Function code samples for VBA

Some time when we use Environ() function we may get the Library or property not found error. Use VBA.Environ() or VBA.Environ$() to avoid the error.

Split array into chunks

For a functional solution, using Ramda:

Where popularProducts is your input array, 5 is the chunk size

_x000D_
_x000D_
import splitEvery from 'ramda/src/splitEvery'_x000D_
_x000D_
splitEvery(5, popularProducts).map((chunk, i) => {_x000D_
// do something with chunk_x000D_
_x000D_
})
_x000D_
_x000D_
_x000D_

Difference between javacore, thread dump and heap dump in Websphere

Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.

Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.

what's data-reactid attribute in html?

Custom Data attribute in HTML5

Would like to quote Ian's comment in my answer:

It's just an attribute (a valid one) on the element that you can use to store data/info about it.

This code then retrieves it later in the event handler, and uses it to find the target output element. It effectively stores the class of the div where its text should be outputted.

reactid is just a suffix, you can have any name here eg: data-Ayman.

If you want to find the difference check the fiddles in this SO answer and comment.

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

React: Expected an assignment or function call and instead saw an expression

Expected an assignment or function call and instead saw an expression.

I had this similar error with this code:

const mapStateToProps = (state) => {
    players: state
}

To correct all I needed to do was add parenthesis around the curved brackets

const mapStateToProps = (state) => ({
    players: state
});

Node.js version on the command line? (not the REPL)

find the installed node version.

$ node --version

or

 $ node -v

And if you want more information about installed node(i.e. node version,v8 version,platform,env variables info etc.)

then just do this.

$ node
> process
  process {
  title: 'node',
  version: 'v6.6.0',
  moduleLoadList: 
   [ 'Binding contextify',
     'Binding natives',
     'NativeModule events',
     'NativeModule util',
     'Binding uv',
     'NativeModule buffer',
     'Binding buffer',
     'Binding util',
     ...

where The process object is a global that provides information about, and control over, the current Node.js process.

When to create variables (memory management)

I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

SonarQube Exclude a directory

Add comma separated folder paths sonar.exclusions=**/abc/**,**/def/**

This worked in an angular project

How to store printStackTrace into a string

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

How can I get the session object if I have the entity-manager?

See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:

Session session = entityManager.unwrap(Session.class);

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

How do I perform the SQL Join equivalent in MongoDB?

This page on the official mongodb site addresses exactly this question:

https://mongodb-documentation.readthedocs.io/en/latest/ecosystem/tutorial/model-data-for-ruby-on-rails.html

When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.

Relational purists may be feeling uneasy already, as if we were violating some universal law. But let’s bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

Thymeleaf using path variables to th:href

try this one is a very easy method if you are in list of model foreach (var item in Modal) loop

<th:href="/category/edit/@item.idCategory>View</a>"

or

<th:href="/category/edit/@item.idCategory">View</a>

Save results to csv file with Python

this will provide exact output

import csv

import collections

with open('file.csv', 'rb') as f:

  data = list(csv.reader(f))

counter = collections.defaultdict(int)

for row in data:

    counter[row[0]] += 1

writer = csv.writer(open("file1.csv", 'w'))

for row in data:

    if counter[row[0]] >= 1:

        writer.writerow(row)

How can I get log4j to delete old rotating log files?

RollingFileAppender does this. You just need to set maxBackupIndex to the highest value for the backup file.

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

SELECT * WHERE NOT EXISTS

You can do a LEFT JOIN and assert the joined column is NULL.

Example:

SELECT * FROM employees a LEFT JOIN eotm_dyn b on (a.joinfield=b.joinfield) WHERE b.name IS NULL

What should be the package name of android app?

Android follows the same naming conventions like Java,

Naming Conventions

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:

Legalizing Package Names:

       Domain Name                            Package Name Prefix

hyphenated-name.example.org             org.example.hyphenated_name
example.int                             int_.example
123name.example.com                     com.example._123name

Giving graphs a subtitle in matplotlib

What I do is use the title() function for the subtitle and the suptitle() for the main title (they can take different fontsize arguments). Hope that helps!

How to easily resize/optimize an image size with iOS?

Swift Version

func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? {

    let scale = newWidth / image.size.width
    let newHeight = CGFloat(200.0)
    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
}

What does 'foo' really mean?

foo = File or Object. It is used in place of an object variable or file name.

Items in JSON object are out of order using "json.dumps"?

in JSON, as in Javascript, order of object keys is meaningless, so it really doesn't matter what order they're displayed in, it is the same object.

What is the difference between require() and library()?

My initial theory about the difference was that library loads the packages whether it is already loaded or not, i.e. it might reload an already loaded package, while require just checks that it is loaded, or loads it if it isn't (thus the use in functions that rely on a certain package). The documentation refutes this, however, and explicitly states that neither function will reload an already loaded package.

Bash script processing limited number of commands in parallel

See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

git undo all uncommitted or unsaved changes

I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:

1) just need to reset the workspace file status

enter image description here 2) select all unstage files (command +a), right click and select remove

enter image description here

It's that simple :D

How do I revert all local changes in Git managed project to previous state?

Adding another option here.

I'm referring to the title: Revert local changes.
It can also apply to changes that weren't staged for commit.

In this case you can use:

git restore <file>

To go back to previous state.

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

How can I increment a date by one day in Java?

Take a look at Joda-Time (https://www.joda.org/joda-time/).

DateTimeFormatter parser = ISODateTimeFormat.date();

DateTime date = parser.parseDateTime(dateString);

String nextDay = parser.print(date.plusDays(1));

Converting an integer to a hexadecimal string in Ruby

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

C# Break out of foreach loop after X number of items

Just use break, like that:

int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
   if(cont==50) { //if listViewItem reach 50 break out.
      break; 
   }
   cont++;   //increment cont.
}

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

How to format DateTime in Flutter , How to get current time in flutter?

Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

import 'package:jiffy/jiffy.dart';   

var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");

You can also do the following

var a = Jiffy().yMMMMd; // October 18, 2019

And you can also pass in your DateTime object, A string and an array

var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019

var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019

var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019

How do I get a value of a <span> using jQuery?

$('#item1 span').html(); Its working with my code

VNC viewer with multiple monitors

Real VNC Viewer (5.0.3) - Free :

Options->Expert->UseAllMonitors = True

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

How do I add a tool tip to a span element?

the "title" attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

Media Queries: How to target desktop, tablet, and mobile?

@media (max-width: 767px)   {

      .container{width:100%} *{color:green;}-Mobile

    }


    @media (min-width: 768px)  {

     .container{width:100%} *{color:pink  } -Desktop

    }
    @media (min-width: 768px) and (orientation:portrait)  {

       .container{width:100%} *{color:yellow  } -Mobile

    }
    @media (min-width: 1024px)  {

       .container{width:100%} *{color:pink  } -Desktop

    }
    @media (min-width: 1200px)  {

    .container{width:1180px} *{color:pink   } -Desktop

    }

Get an OutputStream into a String

I would use a ByteArrayOutputStream. And on finish you can call:

new String( baos.toByteArray(), codepage );

or better:

baos.toString( codepage );

For the String constructor, the codepage can be a String or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.

The method toString() accepts only a String as a codepage parameter (stand Java 8).

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

There was a relevant answer from Ask Tom published in April 2016.

If you have sufficient server power, you can do

select /*+ parallel */ count(*) from sometable

If you are just after an approximation, you can do :

select 5 * count(*) from sometable sample block (10);

Also, if there is

  1. a column that contains no nulls, but is not defined as NOT NULL, and
  2. there is an index on that column

you could try:

select /*+ index_ffs(t) */ count(*) from sometable  t where indexed_col is not null

MySQL query String contains

Quite simple actually:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");

The % is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.

How to switch to new window in Selenium for Python?

for eg. you may take

driver.get('https://www.naukri.com/')

since, it is a current window ,we can name it

main_page = driver.current_window_handle

if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index

for handle in driver.window_handles:
    if handle != main_page:
        print(handle)
        login_page = handle
        break

driver.switch_to.window(login_page)

Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done

driver.switch_to.window(main_page)
sleep(10)

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

Javascript get Object property Name

If you know for sure that there's always going to be exactly one key in the object, then you can use Object.keys:

theTypeIs = Object.keys(myVar)[0];

What does [STAThread] do?

It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.

This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).

Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.

react-router go back a page how do you configure history?

What worked for me was to import withRouter at the top of my file;

import { withRouter } from 'react-router-dom'

Then use it to wrap the exported function at the bottom of my file;

export default withRouter(WebSitePageTitleComponent)

Which then allowed me to access the Router's history prop. Full sample code below!

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

import PropTypes from 'prop-types'

class TestComponent extends Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    event.preventDefault()
    this.props.history.goBack()
  }

  render() {
    return (
      <div className="page-title">
        <a className="container" href="/location" onClick={this.handleClick}>
          <h1 className="page-header">
            { this.props.title }
          </h1>
        </a>
      </div>
    )
  }
}

const { string, object } = PropTypes

TestComponent.propTypes = {
  title: string.isRequired,
  history: object
}

export default withRouter(TestComponent)

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

Late to the party, but in case this happens with a WORDPRESS installation :

#1273 - Unknown collation: 'utf8mb4_unicode_520_ci

In phpmyadmin, under export method > Format-specific options( custom export )

Set to : MYSQL40

If you will try to import now, you now might get another error message :

1064 - You have an error in your SQL syntax; .....

That is because The older TYPE option that was synonymous with ENGINE was removed in MySQL 5.5.

Open your .sql file , search and replace all instances

from TYPE= to ENGINE=

Now the import should go smoothly.

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

How to fix SSL certificate error when running Npm on Windows?

This is what you can do to avoid npm and use yarn in window machine.

yarn config set "strict-ssl" false

Converting string format to datetime in mm/dd/yyyy

You are looking for the DateTime.Parse() method (MSDN Article)

So you can do:

var dateTime = DateTime.Parse("01/01/2001");

Which will give you a DateTime typed object.

If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)

Which you would use in a situation like this (Where you are using a British style date format):

string[] formats= { "dd/MM/yyyy" }
var dateTime = DateTime.ParseExact("01/01/2001", formats, new CultureInfo("en-US"), DateTimeStyles.None);

org.hibernate.MappingException: Could not determine type for: java.util.Set

Solution:

@Entity
@Table(name = "USER")
@Access(AccessType.FIELD)
public class User implements UserDetails, Serializable {

    private static final long serialVersionUID = 2L;

    @Id
    @Column(name = "USER_ID", updatable=false, nullable=false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "USERNAME")
    private String username;

    @Column(name = "PASSWORD")
    private String password;

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

    @Column(name = "EMAIL")
    private String email;

    @Column(name = "LOCKED")
    private boolean locked;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Role.class)
    @JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
    private Set<Role> roles;

    @Override
    public GrantedAuthority[] getAuthorities() {
        List<GrantedAuthorityImpl> list = new ArrayList<GrantedAuthorityImpl>(0);
        for (Role role : roles) {
            list.add(new GrantedAuthorityImpl(role.getRole()));
        }
        return (GrantedAuthority[]) list.toArray(new GrantedAuthority[list.size()]);
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !isLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Override
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}

Role.java same as above.

Excel - Combine multiple columns into one column

Function Concat(myRange As Range, Optional myDelimiter As String) As String 
  Dim r As Range 
  Application.Volatile 
  For Each r In myRange 
    If Len(r.Text) Then 
      Concat = Concat & IIf(Concat <> "", myDelimiter, "") & r.Text 
    End If 
  Next 
End Function

How to start a Process as administrator mode in C#

 Process proc = new Process();                                                              
                   ProcessStartInfo info = 
                   new ProcessStartInfo("Your Process name".exe, "Arguments");
                   info.WindowStyle = ProcessWindowStyle.Hidden;
                   info.UseShellExecute =true;
                   info.Verb ="runas";
                   proc.StartInfo = info;
                   proc.Start();

How to declare a global variable in React?

Create a file named "config.js" in ./src folder with this content:

module.exports = global.config = {
    i18n: {
        welcome: {
            en: "Welcome",
            fa: "??? ?????"
        }
        // rest of your translation object
    }
    // other global config variables you wish
};

In your main file "index.js" put this line:

import './config';

Everywhere you need your object use this:

global.config.i18n.welcome.en

How to Query an NTP Server using C#?

This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)

public static DateTime GetNetworkTime()
{
    const string ntpServer = "pool.ntp.org";
    var ntpData = new byte[48];
    ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

    var addresses = Dns.GetHostEntry(ntpServer).AddressList;
    var ipEndPoint = new IPEndPoint(addresses[0], 123);
    var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

    socket.Connect(ipEndPoint);
    socket.Send(ntpData);
    socket.Receive(ntpData);
    socket.Close();

    ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
    ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];

    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
    var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);

    return networkDateTime;
}

How to check the input is an integer or not in Java?

If the user input is a String then you can try to parse it as an integer using parseInt method, which throws NumberFormatException when the input is not a valid number string:

try {

    int intValue = Integer.parseInt(stringUserInput));
}(NumberFormatException e) {
    System.out.println("Input is not a valid integer");
}

What is a simple C or C++ TCP server and client example?

If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio are imho quite complicated when it comes to short and simple "hello world" example.

To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm

  1. Add following includes to both files:

    #include <cstdlib>
    #include <cstring>
    #include <unistd.h>
    
  2. In client.c, change the line:

    if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

    to:

    if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

As you can see in C++ an explicit cast is needed.

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

How to use SQL LIKE condition with multiple values in PostgreSQL?

Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%']) as per this cool trick @maniek showed earlier today.

What's the best way to use R scripts on the command line (terminal)?

#!/path/to/R won't work because R is itself a script, so execve is unhappy.

I use R --slave -f script

Reordering arrays

With ES6 you can do something like this:

const swapPositions = (array, a ,b) => {
  [array[a], array[b]] = [array[b], array[a]]
}

let array = [1,2,3,4,5];
swapPositions(array,0,1);

/// => [2, 1, 3, 4, 5]

Best way to concatenate List of String objects?

If you are developing for Android, there is TextUtils.join provided by the SDK.

Oracle get previous day records

this

    SELECT field,datetime_field 
FROM database
WHERE datetime_field > (sysdate-1)

will work. The question is: is the 'datetime_field' has the same format as sysdate ? My way to handle that: use 'to_char()' function (only works in Oracle).

samples: previous day:

select your_column
from your_table
where to_char(sysdate-1, 'dd.mm.yyyy')

or

select extract(day from date_field)||'/'|| 
       extract(month from date_field)||'/'||
       extract(year from date_field)||'/'||
as mydate
from dual(or a_table)
where extract(day from date_field) = an_int_number and
      extract(month from date_field) = an_int_number and so on..

comparing date:

select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate, 'dd.mm.yyyy')

time range between yesterday and a day before yesterday:

select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-1, 'dd.mm.yyyy') and
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-2, 'dd.mm.yyyy')

other time range variation

select your_column
from your_table
where 
to_char(a_datetime_column, 'dd.mm.yyyy') is between to_char(sysdate-1, 'dd.mm.yyyy') 
and to_char(sysdate-2, 'dd.mm.yyyy')

Wrap a text within only two lines inside div

@Asiddeen bn Muhammad's solution worked for me with a little modification to the css

    .text {
 line-height: 1.5;
  height: 6em; 
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: block;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
 }

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Cannot refer to a non-final variable inside an inner class defined in a different method

If you want to change a value in a method call within an anonymous class, that "value" is actually a Future. So, if you use Guava, you can write

...
final SettableFuture<Integer> myvalue = SettableFuture<Integer>.create();
...
someclass.run(new Runnable(){

    public void run(){
        ...
        myvalue.set(value);
        ...
    }
 }

 return myvalue.get();

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

My complete code as below is working well:

package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail
{
public static void main(String [] args)
{    
    // Sender's email ID needs to be mentioned
     String from = "[email protected]";
     String pass ="test123";
    // Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

   String host = "smtp.gmail.com";

   // Get system properties
   Properties properties = System.getProperties();
   // Setup mail server
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.host", host);
   properties.put("mail.smtp.user", from);
   properties.put("mail.smtp.password", pass);
   properties.put("mail.smtp.port", "587");
   properties.put("mail.smtp.auth", "true");

   // Get the default Session object.
   Session session = Session.getDefaultInstance(properties);

   try{
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Now set the actual message
      message.setText("This is actual message");

      // Send message
      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }catch (MessagingException mex) {
      mex.printStackTrace();
   }
}
}