Programs & Examples On #Observers

When should we use Observer and Observable?

You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.

Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.

The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.

Python Pandas merge only certain columns

If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:

df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
                left_on = 'key2', right_on = 'key1').drop('key1')

The .drop('key1') part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

iFrame src change event detection?

Since version 3.0 of Jquery you might get an error

TypeError: url.indexOf is not a function

Which can be easily fix by doing

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');
});

Shortcut to create properties in Visual Studio?

I think Alt+R+F is the correct one for creating property from a variable declaration

Query to list number of records in each table in a database

Fastest way to find row count of all tables in SQL Refreence (http://www.codeproject.com/Tips/811017/Fastest-way-to-find-row-count-of-all-tables-in-SQL)

SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT] 
    FROM   sys.tables AS T 
       INNER JOIN sys.sysindexes AS I ON T.object_id = I.id 
       AND I.indid < 2 
ORDER  BY I.rows DESC

Spring REST Service: how to configure to remove null objects in json response

If you are using Jackson 2, the message-converters tag is:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="prefixJson" value="true"/>
            <property name="supportedMediaTypes" value="application/json"/>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

CSS opacity only to background color, not the text on it?

This will work with every browser

div {
    -khtml-opacity: .50;
    -moz-opacity: .50;
    -ms-filter: ”alpha(opacity=50)”;
    filter: alpha(opacity=50);
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0.5);
    opacity: .50;
}

If you don't want transparency to affect the entire container and its children, check this workaround. You must have an absolutely positioned child with a relatively positioned parent to achieve this. CSS Opacity That Doesn’t Affect Child Elements

Check a working demo at CSS Opacity That Doesn't Affect "Children"

How to extract text from a PDF?

Since today I know it: the best thing for text extraction from PDFs is TET, the text extraction toolkit. TET is part of the PDFlib.com family of products.

PDFlib.com is Thomas Merz's company. In case you don't recognize his name: Thomas Merz is the author of the "PostScript and PDF Bible".

TET's first incarnation is a library. That one can probably do everything Budda006 wanted, including positional information about every element on the page. Oh, and it can also extract images. It recombines images which are fragmented into pieces.

pdflib.com also offers another incarnation of this technology, the TET plugin for Acrobat. And the third incarnation is the PDFlib TET iFilter. This is a standalone tool for user desktops. Both these are free (as in beer) to use for private, non-commercial purposes.

And it's really powerful. Way better than Adobe's own text extraction. It extracted text for me where other tools (including Adobe's) do spit out garbage only.

I just tested the desktop standalone tool, and what they say on their webpage is true. It has a very good commandline. Some of my "problematic" PDF test files the tool handled to my full satisfaction.

This thing will from now on be my recommendation for every sophisticated and challenging PDF text extraction requirements.

TET is simply awesome. It detects tables. Inside tables, it identifies cells spanning multiple columns. It identifies table rows and contents of each table cell separately. It deals very well with hyphenations: it removes hyphens and restores complete words. It supports non-ASCII languages (including CJK, Arabic and Hebrew). When encountering ligatures, it restores the original characters...

Give it a try.

How to use vertical align in bootstrap

Prinsen's answer is the best choice. But, to fix the issue where the columns don't collapse his code needs to be surrounded by a media check statement. This way these styles are only applied when the larger columns are active. Here is the updated complete answer.

HTML:

<div class="row display-table">
    <div class="col-xs-12 col-sm-4 display-cell">
        img
    </div>
    <div class="col-xs-12 col-sm-8 display-cell">
        text
    </div>
</div>

CSS:

@media (min-width: 768px){
   .display-table{
       display: table;
       table-layout: fixed;
   }

   .display-cell{
       display: table-cell;
       vertical-align: middle;
       float: none;
   }
}

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

Use of for_each on map elements

How about a plain C++? (example fixed according to the note by @Noah Roberts)

for(std::map<int, MyClass>::iterator itr = Map.begin(), itr_end = Map.end(); itr != itr_end; ++itr) {
  itr->second.Method();
}

Extending from two classes

The creators of java decided that the problems of multiple inheritance outweigh the benefits, so they did not include multiple inheritance. You can read about one of the largest issues of multiple inheritance (the double diamond problem) here.

The two most similar concepts are interface implementation and including objects of other classes as members of the current class. Using default methods in interfaces is almost exactly the same as multiple inheritance, however it is considered bad practice to use an interface with only default methods.

Oracle database: How to read a BLOB?

SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.

WCF, Service attribute value in the ServiceHost directive could not be found

Double check that you're referencing the correct type from the ServiceHost directive in the .svc file. Here's how...

  1. In the VS project containing your web service, open the .svc file in the XML editor (right-click the file, Open With..., choose XML (Text) Editor, OK).
  2. Note the "Service" attribute value.
  3. Make sure it matches the fully qualified type name of your service. This includes the namespace + type name. For example, if the namespace is "MyCompany.Department.Services" and the class is called "MyService", then the Service attribute value should be "MyCompany.Department.Services.MyService".

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

For outlook use following setting that is not giving error to me

SMTP server name smtp-mail.outlook.com

SMTP port 587

How to convert a number to string and vice versa in C++

Update for C++11

As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

string to numeric

float              stof(const string& str, size_t *idx = 0);
double             stod(const string& str, size_t *idx = 0);
long double        stold(const string& str, size_t *idx = 0);
int                stoi(const string& str, size_t *idx = 0, int base = 10);
long               stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long      stoul(const string& str, size_t *idx = 0, int base = 10);
long long          stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);

Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an exception is thrown (std::invalid_argument or std::out_of_range).

If conversion succeeded and idx is not 0, idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10 until z=35). You can find more information about the exact formatting that can parsed here for floating-point numbers, signed integers and unsigned integers.

Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

numeric to string

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

As noted in the comments these functions fall back to a default mantissa precision that is likely not the maximum precision. If more precision is required for your application it's also best to go back to other string formatting procedures.

There are also similar functions defined that are named to_wstring, these will return a std::wstring.

What is (functional) reactive programming?

After reading many pages about FRP I finally came across this enlightening writing about FRP, it finally made me understand what FRP really is all about.

I quote below Heinrich Apfelmus (author of reactive banana).

What is the essence of functional reactive programming?

A common answer would be that “FRP is all about describing a system in terms of time-varying functions instead of mutable state”, and that would certainly not be wrong. This is the semantic viewpoint. But in my opinion, the deeper, more satisfying answer is given by the following purely syntactic criterion:

The essence of functional reactive programming is to specify the dynamic behavior of a value completely at the time of declaration.

For instance, take the example of a counter: you have two buttons labelled “Up” and “Down” which can be used to increment or decrement the counter. Imperatively, you would first specify an initial value and then change it whenever a button is pressed; something like this:

counter := 0                               -- initial value
on buttonUp   = (counter := counter + 1)   -- change it later
on buttonDown = (counter := counter - 1)

The point is that at the time of declaration, only the initial value for the counter is specified; the dynamic behavior of counter is implicit in the rest of the program text. In contrast, functional reactive programming specifies the whole dynamic behavior at the time of declaration, like this:

counter :: Behavior Int
counter = accumulate ($) 0
            (fmap (+1) eventUp
             `union` fmap (subtract 1) eventDown)

Whenever you want to understand the dynamics of counter, you only have to look at its definition. Everything that can happen to it will appear on the right-hand side. This is very much in contrast to the imperative approach where subsequent declarations can change the dynamic behavior of previously declared values.

So, in my understanding an FRP program is a set of equations: enter image description here

j is discrete: 1,2,3,4...

f depends on t so this incorporates the possiblilty to model external stimuli

all state of the program is encapsulated in variables x_i

The FRP library takes care of progressing time, in other words, taking j to j+1.

I explain these equations in much more detail in this video.

EDIT:

About 2 years after the original answer, recently I came to the conclusion that FRP implementations have another important aspect. They need to (and usually do) solve an important practical problem: cache invalidation.

The equations for x_i-s describe a dependency graph. When some of the x_i changes at time j then not all the other x_i' values at j+1 need to be updated, so not all the dependencies need to be recalculated because some x_i' might be independent from x_i.

Furthermore, x_i-s that do change can be incrementally updated. For example let's consider a map operation f=g.map(_+1) in Scala, where f and g are List of Ints. Here f corresponds to x_i(t_j) and g is x_j(t_j). Now if I prepend an element to g then it would be wasteful to carry out the map operation for all the elements in g. Some FRP implementations (for example reflex-frp) aim to solve this problem. This problem is also known as incremental computing.

In other words, behaviours (the x_i-s ) in FRP can be thought as cache-ed computations. It is the task of the FRP engine to efficiently invalidate and recompute these cache-s (the x_i-s) if some of the f_i-s do change.

Passing parameters in rails redirect_to

You can pass arbitrary objects to the template with the flash parameter.

 redirect_to :back, flash: {new_solution_errors: solution.errors}

And then access them in the template via the hash.

<% flash[:new_solution_errors].each do |err| %>

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

How to do logging in React Native?

Just console.log('debug');

And run it you can see the log in the terminal/cd prompt .

How to get the filename without the extension from a path in Python?

import os
list = []
def getFileName( path ):
for file in os.listdir(path):
    #print file
    try:
        base=os.path.basename(file)
        splitbase=os.path.splitext(base)
        ext = os.path.splitext(base)[1]
        if(ext):
            list.append(base)
        else:
            newpath = path+"/"+file
            #print path
            getFileName(newpath)
    except:
        pass
return list

getFileName("/home/weexcel-java3/Desktop/backup")
print list

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

They have set the header to SAMEORIGIN in this case, which means that they have disallowed loading of the resource in an iframe outside of their domain. So this iframe is not able to display cross domain

enter image description here

For this purpose you need to match the location in your apache or any other service you are using

If you are using apache then in httpd.conf file.

  <LocationMatch "/your_relative_path">
      ProxyPass absolute_path_of_your_application/your_relative_path
      ProxyPassReverse absolute_path_of_your_application/your_relative_path
   </LocationMatch>

Example on ToggleButton

Just remove the line toggle.toggle(); from your click listener toggle() method will always reset your toggle button value.

And as you are trying to take the value of EditText in string variable which always remains same as you are getting value in onCreate() so better directly use the EditText to get the value of it in your onClick listener.

Just change your code as below its working fine now.

  btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                       //toggle.toggle();
            if ( ed.getText().toString().equalsIgnoreCase("1")) {

                toggle.setTextOff("TOGGLE ON");
                toggle.setChecked(true);
            } else if ( ed.getText().toString().equalsIgnoreCase("0")) {

                toggle.setTextOn("TOGGLE OFF");
                toggle.setChecked(false);

            }
        }
    });

How to use MySQL dump from a remote machine

Try it with Mysqldump

#mysqldump --host=the.remotedatabase.com -u yourusername -p yourdatabasename > /User/backups/adump.sql

compare differences between two tables in mysql

Problem below, is to compare table before and after i do big update!.

If you use Linux, you can use commands as follow:

In terminal,

mysqldump -hlocalhost -uroot -p schema_name_here table_name_here > /home/ubuntu/database_dumps/dump_table_before_running_update.sql

mysqldump -hlocalhost -uroot -p schema_name_here table_name_here > /home/ubuntu/database_dumps/dump_table_after_running_update.sql

diff -uP /home/ubuntu/database_dumps/dump_some_table_after_running_update.sql /home/ubuntu/database_dumps/dump_table_before_running_update.sql > /home/ubuntu/database_dumps/diff.txt

You will need online tools for

  • Formatting SQL exported from the dumps,

e.g http://www.dpriver.com/pp/sqlformat.htm [Not the best I've seen]

  • We have diff.txt, you have to take manually the + - showing inside, which is 1 line of insert statements, that has the values.

  • Do diff online for the 2 lines - & + in diff.txt, past them in online diff tool

e.g https://www.diffchecker.com [you can save and share it, and has no limit on file size!]

Note: be extra careful if its sensitive/production data!

diff preview

How diff.txt will look like

Can I add and remove elements of enumeration at runtime in Java

I faced this problem on the formative project of my young career.

The approach I took was to save the values and the names of the enumeration externally, and the end goal was to be able to write code that looked as close to a language enum as possible.

I wanted my solution to look like this:

enum HatType
{
    BASEBALL,
    BRIMLESS,
    INDIANA_JONES
}

HatType mine = HatType.BASEBALL;

// prints "BASEBALL"
System.out.println(mine.toString());

// prints true
System.out.println(mine.equals(HatType.BASEBALL));

And I ended up with something like this:

// in a file somewhere:
// 1 --> BASEBALL
// 2 --> BRIMLESS
// 3 --> INDIANA_JONES

HatDynamicEnum hats = HatEnumRepository.retrieve();

HatEnumValue mine = hats.valueOf("BASEBALL");

// prints "BASEBALL"
System.out.println(mine.toString());

// prints true
System.out.println(mine.equals(hats.valueOf("BASEBALL"));

Since my requirements were that it had to be possible to add members to the enum at run-time, I also implemented that functionality:

hats.addEnum("BATTING_PRACTICE");

HatEnumRepository.storeEnum(hats);

hats = HatEnumRepository.retrieve();

HatEnumValue justArrived = hats.valueOf("BATTING_PRACTICE");
// file now reads:
// 1 --> BASEBALL
// 2 --> BRIMLESS
// 3 --> INDIANA_JONES
// 4 --> BATTING_PRACTICE

I dubbed it the Dynamic Enumeration "pattern", and you read about the original design and its revised edition.

The difference between the two is that the revised edition was designed after I really started to grok OO and DDD. The first one I designed when I was still writing nominally procedural DDD, under time pressure no less.

Rotate image with javascript

You can always apply CCS class with rotate property - http://css-tricks.com/snippets/css/text-rotation/

To keep rotated image within your div dimensions you need to adjust CSS as well, there is no needs to use JavaScript except of adding class.

How to break out from a ruby block?

Use the keyword next. If you do not want to continue to the next item, use break.

When next is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:

f.each do |line|              # Iterate over the lines in file f
  next if line[0,1] == "#"    # If this line is a comment, go to the next
  puts eval(line)
end

When used in a block, break transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:

f.each do |line|             # Iterate over the lines in file f
  break if line == "quit\n"  # If this break statement is executed...
  puts eval(line)
end
puts "Good bye"              # ...then control is transferred here

And finally, the usage of return in a block:

return always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):

def find(array, target)
  array.each_with_index do |element,index|
    return index if (element == target)  # return from find
  end
  nil  # If we didn't find the element, return nil
end

Using Thymeleaf when the value is null

The shortest way is using '?' operator. If you have User entity with embedded Address entity in order to access fields of Address entity and print them if address is not null, otherwise here will be an empty column:

<td th:text="${user?.address?.city}"></td>

Presenting modal in iOS 13 fullscreen

an alternative approach is to have your own base viewcontroller component in your app, and just implementing the designated and required initialisers with a basic setup, something like the following:

class MyBaseViewController: UIViewController {

//MARK: Initialisers

/// Alternative initializer which allows you to set the modal presentation syle
/// - Parameter modalStyle: the presentation style to be used
init(with modalStyle:UIModalPresentationStyle) {
    super.init(nibName: nil, bundle: nil)
    self.setup(modalStyle: modalStyle)
}

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    // default modal presentation style as fullscreen
    self.setup(modalStyle: .fullScreen)
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    // default modal presentation style as fullscreen
    self.setup(modalStyle: .fullScreen)
}

//MARK: Private

/// Setup the view
///
/// - Parameter modalStyle: indicates which modal presentation style to be used
/// - Parameter modalPresentation: default true, it prevent modally presented view to be dismissible with the default swipe gesture
private func setup(modalStyle:UIModalPresentationStyle, modalPresentation:Bool = true){
    if #available(iOS 13, *) {
        self.modalPresentationStyle = modalStyle
        self.isModalInPresentation = modalPresentation
    }
}

NOTE: If your view controller is contained in a navigation controller which is actually presented modally, then the navigation controller should approach the problem in the same way (meaning, having your custom navigation controller component customised in the same way

Tested on Xcode 11.1 on iOS 13.1 and iOS 12.4

Hope it helps

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

How do I retrieve my MySQL username and password?

An improvement to the most useful answer here:

1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network

There is no need to restart the MySQL server.

use FLUSH PRIVILEGES; after the update mysql.user statement for password change.

The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

The --skip-grant-options enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to

use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.

from: reference: resetting-permissions-generic

Repeating a function every few seconds

There are lot of different Timers in the .NET BCL:

When to use which?

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer, a timer that's integrated into the Dispatcher queue. This timer is processed with a specified priority at a specified time interval.

Source


Some of them needs explicit Start call to begin ticking (for example System.Timers, System.Windows.Forms). And an explicit Stop to finish ticking.

using TimersTimer = System.Timers.Timer;

static void Main(string[] args)
{
    var timer = new TimersTimer(1000);
    timer.Elapsed += (s, e) => Console.WriteLine("Beep");
    Thread.Sleep(1000); //1 second delay
    timer.Start();
    Console.ReadLine();
    timer.Stop();

}

While on the other hand there are some Timers (like: System.Threading) where you don't need explicit Start and Stop calls. (The provided delegate will run a background thread.) Your timer will tick until you or the runtime dispose it.

So, the following two versions will work in the same way:

using ThreadingTimer = System.Threading.Timer;

static void Main(string[] args)
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
    Console.ReadLine();
}
using ThreadingTimer = System.Threading.Timer;
static void Main(string[] args)
{
    StartTimer();
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

But if your timer disposed then it will stop ticking obviously.

using ThreadingTimer = System.Threading.Timer; 

static void Main(string[] args)
{
    StartTimer();
    GC.Collect(0);
    Console.ReadLine();
}

static void StartTimer()
{
    var timer = new ThreadingTimer(_ => Console.WriteLine("Beep"), null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
}

In Java, what does NaN mean?

Not a Java guy, but in JS and other languages I use it's "Not a Number", meaning some operation caused it to become not a valid number.

Is it possible to have a multi-line comments in R?

You can, if you want, use standalone strings for multi-line comments — I've always thought that prettier than if (FALSE) { } blocks. The string will get evaluated and then discarded, so as long as it's not the last line in a function nothing will happen.

"This function takes a value x, and does things and returns things that
 take several lines to explain"
doEverythingOften <- function(x) {
     # Non! Comment it out! We'll just do it once for now.
     "if (x %in% 1:9) {
          doTenEverythings()
     }"
     doEverythingOnce()
     ...
     return(list(
         everythingDone = TRUE, 
         howOftenDone = 1
     ))
}

The main limitation is that when you're commenting stuff out, you've got to watch your quotation marks: if you've got one kind inside, you'll have to use the other kind for the comment; and if you've got something like "strings with 'postrophes" inside that block, then there's no way this method is a good idea. But then there's still the if (FALSE) block.

The other limitation, one that both methods have, is that you can only use such blocks in places where an expression would be syntactically valid - no commenting out parts of lists, say.

Regarding what do in which IDE: I'm a Vim user, and I find NERD Commenter an utterly excellent tool for quickly commenting or uncommenting multiple lines. Very user-friendly, very well-documented.

Lastly, at the R prompt (at least under Linux), there's the lovely Alt-Shift-# to comment the current line. Very nice to put a line 'on hold', if you're working on a one-liner and then realise you need a prep step first.

Java 8 Streams FlatMap method example

Am I the only one who finds unwinding lists boring? ;-)

Let's try with objects. Real world example by the way.

Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start and repeat every repeatPeriod repeatUnit(e.g. 5 HOURS) and there will be repeatCount reminders in total(including starting one).

Goal: achieve a list of task copies, one for each task reminder invocation.

List<Task> tasks =
            Arrays.asList(
                    new Task(
                            false,//completed sign
                            "My important task",//task name (text)
                            LocalDateTime.now().plus(2, ChronoUnit.DAYS),//first reminder(start)
                            true,//is task repetitive?
                            1,//reminder interval
                            ChronoUnit.DAYS,//interval unit
                            5//total number of reminders
                    )
            );

tasks.stream().flatMap(
        x -> LongStream.iterate(
                x.getStart().toEpochSecond(ZoneOffset.UTC),
                p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
        ).limit(x.getRepeatCount()).boxed()
        .map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))
).forEach(System.out::println);

Output:

Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}

P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.

UPDATE: @RBz asked for detailed explanation so here it is. Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate... creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount() instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC) and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds(). boxed() returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!

Get the key corresponding to the minimum value within a dictionary

I compared how the following three options perform:

    import random, datetime

myDict = {}
for i in range( 10000000 ):
    myDict[ i ] = random.randint( 0, 10000000 )



# OPTION 1

start = datetime.datetime.now()

sorted = []
for i in myDict:
    sorted.append( ( i, myDict[ i ] ) )
sorted.sort( key = lambda x: x[1] )
print( sorted[0][0] )

end = datetime.datetime.now()
print( end - start )



# OPTION 2

start = datetime.datetime.now()

myDict_values = list( myDict.values() )
myDict_keys = list( myDict.keys() )
min_value = min( myDict_values )
print( myDict_keys[ myDict_values.index( min_value ) ] )

end = datetime.datetime.now()
print( end - start )



# OPTION 3

start = datetime.datetime.now()

print( min( myDict, key=myDict.get ) )

end = datetime.datetime.now()
print( end - start )

Sample output:

#option 1
236230
0:00:14.136808

#option 2
236230
0:00:00.458026

#option 3
236230
0:00:00.824048

Forgot Oracle username and password, how to retrieve?

Go to SQL command line:- type:

sql>connect / as sysdba;

then type:

sql>desc dba_users;

then type:

sql>select username,password from dba_users;

If sysdba doesn't work then try connecting with username:scott and password: Tiger

You will be able to see all users with passwords. Probably you might find your's. Hope this helps

Bootstrap - How to add a logo to navbar class?

Enter the image and give height:100%;width:auto then just change the height of navbar itself to resize image. There is a really good example in codepen. https://codepen.io/bootstrapped/pen/KwYGwq

builder for HashMap

You can use:

HashMap<String,Integer> m = Maps.newHashMap(
    ImmutableMap.of("a",1,"b",2)
);

It's not as classy and readable, but does the work.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Bootstrap: change background color

You can target that div from your stylesheet in a number of ways.

Simply use

.col-md-6:first-child {
  background-color: blue;
}

Another way is to assign a class to one div and then apply the style to that class.

<div class="col-md-6 blue"></div>

.blue {
  background-color: blue;
}

There are also inline styles.

<div class="col-md-6" style="background-color: blue"></div>

Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary class from the section and add you custom class to the div.

_x000D_
_x000D_
.blue {_x000D_
  background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
  <div class="container">_x000D_
    <div class="row">_x000D_
    <!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
      <div class="col-xs-6">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
      <div class="col-xs-6 blue">_x000D_
        <h2 class="section-heading text-center">Title</h2>_x000D_
        <p class="text-faded text-center">.col-md-6</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Regular Expressions: Search in list

You can create an iterator in Python 3.x or a list in Python 2.x by using:

filter(r.match, list)

To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).

How do I use dataReceived event of the SerialPort Port Object in C#?

I think your issue is the line:**

sp.DataReceived += port_OnReceiveDatazz;

Shouldn't it be:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

I've also seen suggestions that you should turn the following options on for your serial port:

sp.DtrEnable = true;    // Data-terminal-ready
sp.RtsEnable = true;    // Request-to-send

You may also have to set the handshake to RequestToSend (via the handshake enumeration).


UPDATE:

Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

So instead of this:

sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();

Do this:

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

Let me know how that goes.

Excel: VLOOKUP that returns true or false?

You can use:

=IF(ISERROR(VLOOKUP(lookup value,table array,column no,FALSE)),"FALSE","TRUE")

Understanding the difference between Object.create() and new SomeFunction()

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

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

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

ImportError: No module named BeautifulSoup

Try this from bs4 import BeautifulSoup

This might be a problem with Beautiful Soup, version 4, and the beta days. I just read this from the homepage.

How to convert milliseconds into human readable form?

You should use the datetime functions of whatever language you're using, but, just for fun here's the code:

int milliseconds = someNumber;

int seconds = milliseconds / 1000;

int minutes = seconds / 60;

seconds %= 60;

int hours = minutes / 60;

minutes %= 60;

int days = hours / 24;

hours %= 24;

Better way to revert to a previous SVN revision of a file?

Reverse merge is exactly what you want (see luapyad's answer). Just apply the merge to the erroneously-commited file instead of the entire directory.

PHP JSON String, escape Double Quotes for JS output

I succefully just did this :

$json = str_replace("\u0022","\\\\\"",json_encode( $phpArray,JSON_HEX_QUOT)); 

json_encode() by default will escape " to \" . But it's still wrong JSON for json.PARSE(). So by adding option JSON_HEX_QUOT, json_encode() will replace " with \u0022. json.PARSE() still will not like \u0022. So then we need to replace \u0022 with \\". The \\\\\" is escaped \\".

NOTE : you can add option JSON_HEX_APOS to replace single quote with unicode HEX value if you have javascript single quote issue.

ex: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));

Fast Bitmap Blur For Android SDK

On the i/o 2019 the following solution was presented:

/**
 * Blurs the given Bitmap image
 * @param bitmap Image to blur
 * @param applicationContext Application context
 * @return Blurred bitmap image
 */
@WorkerThread
fun blurBitmap(bitmap: Bitmap, applicationContext: Context): Bitmap {
    lateinit var rsContext: RenderScript
    try {

        // Create the output bitmap
        val output = Bitmap.createBitmap(
                bitmap.width, bitmap.height, bitmap.config)

        // Blur the image
        rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG)
        val inAlloc = Allocation.createFromBitmap(rsContext, bitmap)
        val outAlloc = Allocation.createTyped(rsContext, inAlloc.type)
        val theIntrinsic = ScriptIntrinsicBlur.create(rsContext, Element.U8_4(rsContext))
        theIntrinsic.apply {
            setRadius(10f)
            theIntrinsic.setInput(inAlloc)
            theIntrinsic.forEach(outAlloc)
        }
        outAlloc.copyTo(output)

        return output
    } finally {
        rsContext.finish()
    }
}

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

MessageBox with YesNoCancel - No & Cancel triggers same event

Closing conformation alert:

Private Sub cmd_exit_click()

    ' By clicking on the button the MsgBox will appear
    If MsgBox("Are you sure want to exit now?", MsgBoxStyle.YesNo, "closing warning") = MsgBoxResult.Yes Then ' If you select yes in the MsgBox then it will close the window
               Me.Close() ' Close the window
    Else
        ' Will not close the application
    End If
End Sub

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

You can use this small library: https://github.com/ledfusion/php-rest-curl

Making a call is as simple as:

// GET
$result = RestCurl::get($URL, array('id' => 12345678));

// POST
$result = RestCurl::post($URL, array('name' => 'John'));

// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));

// DELETE
$result = RestCurl::delete($URL); 

And for the $result variable:

  • $result['status'] is the HTTP response code
  • $result['data'] an array with the JSON response parsed
  • $result['header'] a string with the response headers

Hope it helps

JPA & Criteria API - Select only specific columns

cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION")));  // HERE IS NO ERROR

https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria#Constructors

What can I use for good quality code coverage for C#/.NET?

JetBrains (of ReSharper fame) has been working on a coverage tool for a little while called dotCover. It's showing a great deal of promise.

jQuery won't parse my JSON from AJAX query

If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.

Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?

What backend are you returning this from?

On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.

Angular 2 Sibling Component Communication

Behaviour subjects. I wrote a blog about that.

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
private noId = new BehaviorSubject<number>(0); 
  defaultId = this.noId.asObservable();

newId(urlId) {
 this.noId.next(urlId); 
 }

In this example i am declaring a noid behavior subject of type number. Also it is an observable. And if "something happend" this will change with the new(){} function.

So, in the sibling's components, one will call the function, to make the change, and the other one will be affected by that change, or vice-versa.

For example, I get the id from the URL and update the noid from the behavior subject.

public getId () {
  const id = +this.route.snapshot.paramMap.get('id'); 
  return id; 
}

ngOnInit(): void { 
 const id = +this.getId ();
 this.taskService.newId(id) 
}

And from the other side, I can ask if that ID is "what ever i want" and make a choice after that, in my case if i want to delte a task, and that task is the current url, it have to redirect me to the home:

delete(task: Task): void { 
  //we save the id , cuz after the delete function, we  gonna lose it 
  const oldId = task.id; 
  this.taskService.deleteTask(task) 
      .subscribe(task => { //we call the defaultId function from task.service.
        this.taskService.defaultId //here we are subscribed to the urlId, which give us the id from the view task 
                 .subscribe(urlId => {
            this.urlId = urlId ;
                  if (oldId == urlId ) { 
                // Location.call('/home'); 
                this.router.navigate(['/home']); 
              } 
          }) 
    }) 
}

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

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

This situation happens when the IDE looks for src folder, and it cannot find it in the path. Select the project root (F4 in windows) > Go to Modules on Side Tab > Select Sources > Select appropriate folder with source files in it> Click on the blue sources folder icon (for adding sources) > Click on Green Test Sources folder ( to add Unit test folders).

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

LPCSTR, LPCTSTR and LPTSTR

To answer the first part of your question:

LPCSTR is a pointer to a const string (LP means Long Pointer)

LPCTSTR is a pointer to a const TCHAR string, (TCHAR being either a wide char or char depending on whether UNICODE is defined in your project)

LPTSTR is a pointer to a (non-const) TCHAR string

In practice when talking about these in the past, we've left out the "pointer to a" phrase for simplicity, but as mentioned by lightness-races-in-orbit they are all pointers.

This is a great codeproject article describing C++ strings (see 2/3 the way down for a chart comparing the different types)

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Running a CMD or BAT in silent mode

I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)

That should answer your question.

Here it is:


From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

See the question for the full invis.vbs script:

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
                                                         ^
                             means "invisible window" ---| 

Update after Tammen's feedback:

If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.

How to style a JSON block in Github Wiki?

2019 Github Solution

```yaml
{
   "this-json": "looks awesome..."
}

Result

enter image description here

If you want to have keys a different colour to the parameters, set your language as yaml

@Ankanna's answer gave me the idea of going through github's supported language list and yaml was my best find.

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

Are complex expressions possible in ng-hide / ng-show?

This will work if you do not have too many expressions.

Example: ng-show="form.type === 'Limited Company' || form.type === 'Limited Partnership'"

For any more expressions than this use a controller.

Reading a file character by character in C

the file is being opened and not closed for each call to the function also

How can I remove file extension from a website address?

You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

Old page: http://something.com/profile.php?id=a&abc=1

New page: http://something.com/profile/?id=a&abc=1

If you are not satisfied leave a comment for complicated methods.

AttributeError: 'module' object has no attribute 'model'

In class poll, you inherited your class from models.model but there's no module in models called that name.

Because Python is case sensitive, you need to use the capital Model instead of model.

class poll(models.Model):
...

Disable Chrome strict MIME type checking

Another solution when a file pretends another extension

I use php inside of var.js file with this .htaccess.

<Files var.js>
    AddType application/x-httpd-php .js
</Files>

Then I write php code in the .js file

<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";

When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type header line in the .js(but php) file.

<?php
header('Content-Type: application/javascript');        // <- Add this line
// This is a `.js` file but works with php
...

A browser won't execute .js file because apache sends the Content-Type header of the file as application/x-httpd-php that is defined in .htaccess. That's a security reason. But apache won't execute php as far as htaccess commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type header with the php function header(). I guess that apache stops sending its own header when php sends it instead of apache before.

What is the difference between bottom-up and top-down?

Dynamic Programming is often called Memoization!

1.Memoization is the top-down technique(start solving the given problem by breaking it down) and dynamic programming is a bottom-up technique(start solving from the trivial sub-problem, up towards the given problem)

2.DP finds the solution by starting from the base case(s) and works its way upwards. DP solves all the sub-problems, because it does it bottom-up

Unlike Memoization, which solves only the needed sub-problems

  1. DP has the potential to transform exponential-time brute-force solutions into polynomial-time algorithms.

  2. DP may be much more efficient because its iterative

On the contrary, Memoization must pay for the (often significant) overhead due to recursion.

To be more simple, Memoization uses the top-down approach to solve the problem i.e. it begin with core(main) problem then breaks it into sub-problems and solve these sub-problems similarly. In this approach same sub-problem can occur multiple times and consume more CPU cycle, hence increase the time complexity. Whereas in Dynamic programming same sub-problem will not be solved multiple times but the prior result will be used to optimize the solution.

How to check if a string array contains one string in JavaScript?

var stringArray = ["String1", "String2", "String3"];

return (stringArray.indexOf(searchStr) > -1)

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

If you are just testing your PL/SQL in SQL Plus you can direct it to a file like this:

spool output.txt
set serveroutput on

begin
  SELECT systimestamp FROM dual INTO time_db;
  DBMS_OUTPUT.PUT_LINE('time before procedure ' || time_db);
end;
/

spool off

IDEs like Toad and SQL Developer can capture the output in other ways, but I'm not familiar with how.

WPF Check box: Check changed handling

Im putting this in an answer because it's too long for a comment:

If you need the VM to be aware when the CheckBox is changed, you should really bind the CheckBox to the VM, and not a static value:

public class ViewModel
{
    private bool _caseSensitive;
    public bool CaseSensitive
    {
        get { return _caseSensitive; }
        set
        {
            _caseSensitive = value;
            NotifyPropertyChange(() => CaseSensitive);

            Settings.Default.bSearchCaseSensitive = value;
        }
    }
}

XAML:

<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>

Handle Button click inside a row in RecyclerView

You can check if you have any similar entries first, if you get a collection with size 0, start a new query to save.

OR

more professional and faster way. create a cloud trigger (before save)

check out this answer https://stackoverflow.com/a/35194514/1388852

PadLeft function in T-SQL

I believe this may be what your looking for:

SELECT padded_id = REPLACE(STR(id, 4), SPACE(1), '0') 

FROM tableA

or

SELECT REPLACE(STR(id, 4), SPACE(1), '0') AS [padded_id]

FROM tableA

I haven't tested the syntax on the 2nd example. I'm not sure if that works 100% - it may require some tweaking - but it conveys the general idea of how to obtain your desired output.

EDIT

To address concerns listed in the comments...

@pkr298 - Yes STR does only work on numbers... The OP's field is an ID... hence number only.

@Desolator - Of course that won't work... the First parameter is 6 characters long. You can do something like:

SELECT REPLACE(STR(id,
(SELECT LEN(MAX(id)) + 4 FROM tableA)), SPACE(1), '0') AS [padded_id] FROM tableA

this should theoretically move the goal posts... as the number gets bigger it should ALWAYS work.... regardless if its 1 or 123456789...

So if your max value is 123456... you would see 0000123456 and if your min value is 1 you would see 0000000001

How to match a substring in a string, ignoring case

You can use in operator in conjunction with lower method of strings.

if "mandy" in line.lower():

How can I change the image displayed in a UIImageView programmatically?

Following Jordan's advice (which should work actually), try to set the UIImageView to be visible:

 [imageView setHidden: NO];

and also - don't forget to attach it to the main UIView:

[mainView addSubview: imageView];

and to bring to the front:

[mainView bringSubviewToFront: imageView];

Hope combining all these steps will help you solve the mystery.

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

Show "Open File" Dialog

Addition to what Albert has already said:

This code (a mashup of various samples) provides the ability to have a SaveAs dialog box

Function getFileName() As String
    Dim fDialog    As Object
    Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
    Dim varFile As Variant

    With fDialog
       .AllowMultiSelect = False
       .Title = "Select File Location to Export XLSx :"
       .InitialFileName = "jeffatwood.xlsx"

    If .Show = True Then
       For Each varFile In .SelectedItems
         getFileName = varFile
       Next
    End If
End With
End Function

SQL Server: How to check if CLR is enabled?

The accepted answer needs a little clarification. The row will be there if CLR is enabled or disabled. Value will be 1 if enabled, or 0 if disabled.

I use this script to enable on a server, if the option is disabled:

if not exists(
    SELECT value
    FROM sys.configurations
    WHERE name = 'clr enabled'
     and value = 1
)
begin
    exec sp_configure @configname=clr_enabled, @configvalue=1
    reconfigure
end

Replace HTML page with contents retrieved via AJAX

try this with jQuery:

$('body').load( url,[data],[callback] );

Read more at docs.jquery.com / Ajax / load

How can I check if a MySQL table exists with PHP?

$res = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = '$databasename' AND table_name = '$tablename';");

If no records are returned then it doesn't exist.

Space between border and content? / Border distance from content?

Just wrap another div around it, which has the border and the padding you want.

Where is Xcode's build folder?

With a project previously created in Xcode3, I see an intermediate directory under build/ called Foo.build where Foo is my project's name, and then in that are the directories you'd expect (Debug-iphonesimulator, Release-iphoneos, etc, assuming you've done a build of that type) containing the object files and products.

Now, I suspect that if you start a new project in Xcode4, the default location is under DerivedData, but if you open an Xcode3 project in Xcode4, then Xcode4 uses the build/ directory (as described above). So, there are several correct answers. :-) Under the File menu, Project Settings, you can see you can customize how XCode works in this regard as much or as little as you like.

How can I check MySQL engine type for a specific table?

Yet another way, perhaps the shortest to get status of a single or matched set of tables:

SHOW TABLE STATUS LIKE 'table';

You can then use LIKE operators for example:

SHOW TABLE STATUS LIKE 'field_data_%';

Recover unsaved SQL query scripts

SSMSBoost add-in (currently free)

  • keeps track on all executed statements (saves them do disk)
  • regulary saves snapshot of SQL Editor contents. You keep history of the modifications of your script. Sometimes "the best" version is not the last and you want to restore the intermediate state.
  • keeps track of opened tabs and allows to restore them after restart. Unsaved tabs are also restored.

+tons of other features. (I am the developer of the add-in)

CodeIgniter Select Query

function news_get_by_id ( $news_id )
{

    $this->db->select('*');
    $this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human",  FALSE );
    $this->db->select("DATE_FORMAT( date, '%H:%i') as time_human",      FALSE );


    $this->db->from('news');

    $this->db->where('news_id', $news_id );


    $query = $this->db->get();

    if ( $query->num_rows() > 0 )
    {
        $row = $query->row_array();
        return $row;
    }

}   
This 

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

Error message Strict standards: Non-static method should not be called statically in php

return false is usually meant to terminate the object creation with a failure. It is as simple as that.

How to print a certain line of a file with PowerShell?

Here's a function that uses .NET's System.IO classes directly:

function GetLineAt([String] $path, [Int32] $index)
{
    [System.IO.FileMode] $mode = [System.IO.FileMode]::Open;
    [System.IO.FileAccess] $access = [System.IO.FileAccess]::Read;
    [System.IO.FileShare] $share = [System.IO.FileShare]::Read;
    [Int32] $bufferSize = 16 * 1024;
    [System.IO.FileOptions] $options = [System.IO.FileOptions]::SequentialScan;
    [System.Text.Encoding] $defaultEncoding = [System.Text.Encoding]::UTF8;
    # FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) constructor
    # http://msdn.microsoft.com/library/d0y914c5.aspx
    [System.IO.FileStream] $input = New-Object `
        -TypeName 'System.IO.FileStream' `
        -ArgumentList ($path, $mode, $access, $share, $bufferSize, $options);
    # StreamReader(Stream, Encoding, Boolean, Int32) constructor
    # http://msdn.microsoft.com/library/ms143458.aspx
    [System.IO.StreamReader] $reader = New-Object `
        -TypeName 'System.IO.StreamReader' `
        -ArgumentList ($input, $defaultEncoding, $true, $bufferSize);
    [String] $line = $null;
    [Int32] $currentIndex = 0;

    try
    {
        while (($line = $reader.ReadLine()) -ne $null)
        {
            if ($currentIndex++ -eq $index)
            {
                return $line;
            }
        }
    }
    finally
    {
        # Close $reader and $input
        $reader.Close();
    }

    # There are less than ($index + 1) lines in the file
    return $null;
}

GetLineAt 'file.txt' 9;

Tweaking the $bufferSize variable might affect performance. A more concise version that uses default buffer sizes and doesn't provide optimization hints could look like this:

function GetLineAt([String] $path, [Int32] $index)
{
    # StreamReader(String, Boolean) constructor
    # http://msdn.microsoft.com/library/9y86s1a9.aspx
    [System.IO.StreamReader] $reader = New-Object `
        -TypeName 'System.IO.StreamReader' `
        -ArgumentList ($path, $true);
    [String] $line = $null;
    [Int32] $currentIndex = 0;

    try
    {
        while (($line = $reader.ReadLine()) -ne $null)
        {
            if ($currentIndex++ -eq $index)
            {
                return $line;
            }
        }
    }
    finally
    {
        $reader.Close();
    }

    # There are less than ($index + 1) lines in the file
    return $null;
}

GetLineAt 'file.txt' 9;

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

how to loop through json array in jquery?

You are iterating through an undefined value, ie, com property of the Array's object, you should iterate through the array itself:

$.each(obj, function(key,value) {
   // here `value` refers to the objects 
});

Also note that jQuery intelligently tries to parse the sent JSON, probably you don't need to parse the response. If you are using $.ajax(), you can set the dataType to json which tells jQuery parse the JSON for you.

If it still doesn't work, check the browser's console for troubleshooting.

iOS - Dismiss keyboard when touching outside of UITextField

If I got you right you want to resign keyboard wile tapping on outSide of textfield but you don't have reference of your textfield.

Try this;

  • Take global textField, lets call it reftextField
  • Now in textFieldDidBeginEditing set referenced text field to

    - (void) textFieldDidBeginEditing:(UITextField *)textField{
        reftextField = textField;
    }
    
  • Now you can happily use on any button clock, (adding a transparent button on begin editing recomended)

    - (void)dismissKeyboard {
          [reftextField resignFirstResponder];
    }
    
  • Or for resigning done button try this.

    //for resigning on done button    
    - (BOOL) textFieldShouldReturn:(UITextField *)textField{
        [textField resignFirstResponder];
        return YES;
    }
    

General error: 1364 Field 'user_id' doesn't have a default value

In my case, the error was because I had not declared the field in my $fillable array in the model. Well, it seems to be something basic, but for us who started with laravel it could work.

int to unsigned int conversion

with a little help of math

#include <math.h>
int main(){
  int a = -1;
  unsigned int b;
  b = abs(a);
}

Remove warning messages in PHP

in Core Php to hide warning message set error_reporting(0) at top of common include file or individual file.

In Wordpress hide Warnings and Notices add following code in wp-config.php file

ini_set('log_errors','On');
ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

How to copy and paste code without rich text formatting?

I usually work with Notepad2, all the text I copy from the web are pasted there and then reused, that allows me to clean it (from format and make modifications).

You can download Notepad2 here

BarCode Image Generator in Java

ZXing is a free open source Java library to read and generate barcode images. You need to get the source code and build the jars yourself. Here's a simple tutorial that I wrote for building with ZXing jars and writing your first program with ZXing.

[http://www.vineetmanohar.com/2010/09/java-barcode-api/]

How to find a hash key containing a matching value

Heres an easy way to do find the keys of a given value:

    clients = {
      "yellow"=>{"client_id"=>"2178"}, 
      "orange"=>{"client_id"=>"2180"}, 
      "red"=>{"client_id"=>"2179"}, 
      "blue"=>{"client_id"=>"2181"}
    }

    p clients.rassoc("client_id"=>"2180")

...and to find the value of a given key:

    p clients.assoc("orange") 

it will give you the key-value pair.

Javadoc link to method in other class

For the Javadoc tag @see, you don't need to use @link; Javadoc will create a link for you. Try

@see com.my.package.Class#method()

Here's more info about @see.

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

PHP - add 1 day to date format mm-dd-yyyy

Actually I wanted same alike thing, To get one year backward date, for a given date! :-)

With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!

Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!

$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');

Hopes this answer will help somebody too! :-)

Good luck guys!

Make function wait until element exists

This will only work with modern browsers but I find it easier to just use a then so please test first but:

Code

function rafAsync() {
    return new Promise(resolve => {
        requestAnimationFrame(resolve); //faster than set time out
    });
}

function checkElement(selector) {
    if (document.querySelector(selector) === null) {
        return rafAsync().then(() => checkElement(selector));
    } else {
        return Promise.resolve(true);
    }
}

Or using generator functions

async function checkElement(selector) {
    const querySelector = null;
    while (querySelector === null) {
        await rafAsync();
        querySelector = document.querySelector(selector);
    }
    return querySelector;
}  

Usage

checkElement('body') //use whichever selector you want
.then((element) => {
     console.info(element);
     //Do whatever you want now the element is there
});

Google Chrome redirecting localhost to https

I believe this is caused by HSTS - see http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security

If you have (developed) any other localhost sites which send a HSTS header...

eg. Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

...then depending on the value of max-age, future requests to localhost will be required to be served over HTTPS.

To get around this, I did the following.

  • In the Chrome address bar type "chrome://net-internals/#hsts"
  • At the very bottom of a page is QUERY domain textbox - verify that localhost is known to the browser. If it says "Not found" then this is not the answer you are looking for.
  • If it is, DELETE the localhost domain using the textbox above
  • Your site should now work using plain old HTTP

This is not a permanent solution, but will at least get it working between projects. If anyone knows how to permanently exclude localhost from the HSTS list please let me know :)

UPDATE - November 2017

Chrome has recently moved this setting to sit under Delete domain security policies

enter image description here

UPDATE - December 2017 If you are using .dev domain see other answers below as Chrome (and others) force HTTPS via preloaded HSTS.

How to Run Terminal as Administrator on Mac Pro

search for terminal after opening the termincal type

su <admin-user-name>   //su - switch user

enter and then give the admin password then run your sudo commands e.g:

sudo open MySQLWorkbench.app

How to enable scrolling on website that disabled scrolling?

In a browser like Chrome etc.:

  1. Inspect the code (for e.g. in Chrome press ctrl + shift + c);
  2. Set overflow: visible on body element (for e.g., <body style="overflow: visible">)
  3. Find/Remove any JavaScripts that may routinely be checking for removal of the overflow property:
    • To find such JavaScript code, you could for example, go through the code, or click on different JavaScript code in the code debugger console and hit backspace on your keyboard to remove it.
    • If you're having trouble finding it, you can simply try removing a couple of JavaScripts (you can of course simply press ctrl + z to undo whatever code you delete, or hit refresh to start over).

Good luck!

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

How to calculate distance from Wifi router using Signal Strength?

To calculate the distance you need signal strength and frequency of the signal. Here is the java code:

public double calculateDistance(double signalLevelInDb, double freqInMHz) {
    double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(signalLevelInDb)) / 20.0;
    return Math.pow(10.0, exp);
}

The formula used is:

distance = 10 ^ ((27.55 - (20 * log10(frequency)) + signalLevel)/20)

Example: frequency = 2412MHz, signalLevel = -57dbm, result = 7.000397427391188m

This formula is transformed form of Free Space Path Loss(FSPL) formula. Here the distance is measured in meters and the frequency - in megahertz. For other measures you have to use different constant (27.55). Read for the constants here.

For more information read here.

Make code in LaTeX look *nice*

It turns out that lstlisting is able to format code nicely, but requires a lot of tweaking.

Wikibooks has a good example for the parameters you can tweak.

Nested classes' scope?

In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.

class OuterClass:
    def __init__(self):
        self.outer_var = 1
        self.inner_class = OuterClass.InnerClass(self)
        print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)

    class InnerClass:
        def __init__(self, outer_class):
            self.outer_class = outer_class
            self.inner_var = 2
            print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)

Doctrine and LIKE query

This is not possible with the magic find methods. Try using the query builder:

$result = $em->getRepository("Orders")->createQueryBuilder('o')
   ->where('o.OrderEmail = :email')
   ->andWhere('o.Product LIKE :product')
   ->setParameter('email', '[email protected]')
   ->setParameter('product', 'My Products%')
   ->getQuery()
   ->getResult();

Break string into list of characters in Python

You can do this using list:

new_list = list(fL)

Be aware that any spaces in the line will be included in this list, to the best of my knowledge.

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

ValueError: setting an array element with a sequence

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

How do you use https / SSL on localhost?

This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:

install webpack-dev-server

npm i -g webpack-dev-server

start webpack-dev-server with https

webpack-dev-server --https

How to find a value in an array of objects in JavaScript?

If you have an array such as

var people = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

You can use the filter method of an Array object:

people.filter(function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

In newer JavaScript implementations you can use a function expression:

people.filter(p => p.dinner == "sushi")
  // => [{ "name": "john", "dinner": "sushi" }]

You can search for people who have "dinner": "sushi" using a map

people.map(function (person) {
  if (person.dinner == "sushi") {
    return person
  } else {
    return null
  }
}); // => [null, { "name": "john", "dinner": "sushi" }, null]

or a reduce

people.reduce(function (sushiPeople, person) {
  if (person.dinner == "sushi") {
    return sushiPeople.concat(person);
  } else {
    return sushiPeople
  }
}, []); // => [{ "name": "john", "dinner": "sushi" }]

I'm sure you are able to generalize this to arbitrary keys and values!

Should I use 'border: none' or 'border: 0'?

You may simply use both as per the specification kindly provided by Oli.

I always use border:0 none;.

Though there is no harm in specifying them seperately and some browsers will parse the CSS faster if you do use the legacy CSS1 property calls.

Though border:0; will normally default the border style to none, I have however noticed some browsers enforcing their default border style which can strangely overwrite border:0;.

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

C# catch a stack overflow exception

The right way is to fix the overflow, but....

You can give yourself a bigger stack:-

using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();

You can use System.Diagnostics.StackTrace FrameCount property to count the frames you've used and throw your own exception when a frame limit is reached.

Or, you can calculate the size of the stack remaining and throw your own exception when it falls below a threshold:-

class Program
{
    static int n;
    static int topOfStack;
    const int stackSize = 1000000; // Default?

    // The func is 76 bytes, but we need space to unwind the exception.
    const int spaceRequired = 18*1024; 

    unsafe static void Main(string[] args)
    {
        int var;
        topOfStack = (int)&var;

        n=0;
        recurse();
    }

    unsafe static void recurse()
    {
        int remaining;
        remaining = stackSize - (topOfStack - (int)&remaining);
        if (remaining < spaceRequired)
            throw new Exception("Cheese");
        n++;
        recurse();
    }
}

Just catch the Cheese. ;)

How do I load an org.w3c.dom.Document from XML in a string?

This works for me in Java 1.5 - I stripped out specific exceptions for readability.

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;

public Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}

How to call a function from a string stored in a variable?

Solution: Use PHP7

Note: For a summarized version, see TL;DR at the end of the answer.

Old Methods

Update: One of the old methods explained here has been removed. Refer to other answers for explanation on other methods, it is not covered here. By the way, if this answer doesn't help you, you should return upgrading your stuff. PHP 5.6 support has ended in January 2019 (now even PHP 7.1 and 7.2 are not being supported). See supported versions for more information.

As others mentioned, in PHP5 (and also in newer versions like PHP7) we could use variables as function names, use call_user_func() and call_user_func_array() (which, personally, I hate those functions), etc.

New Methods

As of PHP7, there are new ways introduced:

Note: Everything inside <something> brackets means one or more expressions to form something, e.g. <function_name> means expressions forming a function name.

Dynamic Function Call: Function Name On-the-fly

We can use one or more expressions inside parentheses as the function name in just one go, in the form of:

(<function_name>)(arguments);

For example:

function something(): string
{
    return "something";
}

$bar = "some_thing";

(str_replace("_", "", $bar))(); // something

// Possible, too; but generally, not recommended, because makes your code more complicated
(str_replace("_", "", $bar))()(); 

Note: Although removing the parentheses around str_replace() is not an error, putting parentheses makes code more readable. However, you cannot do that sometimes, e.g. while using . operator. To be consistent, I recommend you to put the parentheses always.

Dynamic Method Call: Method Name On-the-fly

Just like dynamic function calls, we can do the same way with method calls, surrounded by curly braces instead of parentheses (for extra forms, navigate to TL;DR section):

$object->{<method_name>}(arguments);
$object::{<method_name>}(arguments);

See it in an example:

class Foo
{
    public function another(): string
    {
        return "something";
    }
}

$bar = "another thing";

(new Something())->{explode(" ", $bar)[0]}(); // something

Dynamic Method Call: The Array Syntax

A more elegant way added in PHP7 is the following:

[<object>, <method_name>](arguments);
[<class_name>, <method_name>](arguments); // Static calls only

As an example:

class Foo
{
    public function nonStaticCall()
    {
        echo "Non-static call";
    }
    public static function staticCall()
    {
        echo "Static call";
    }
}

$x = new X();

[$x, "non" . "StaticCall"](); // Non-static call
[$x, "static" . "Call"](); // Static call

Note: The benefit of using this method over the previous one is that, you don't care about the call type (i.e. whether it's static or not).

Note: If you care about performance (and micro-optimizations), don't use this method. As I tested, this method is really slower than other methods (more than 10 times).

Extra Example: Using Anonymous Classes

Making things a bit complicated, you could use a combination of anonymous classes and the features above:

$bar = "SomeThing";

echo (new class {
    public function something()
    {
        return 512;
    }
})->{strtolower($bar)}(); // 512

TL;DR (Conclusion)

Generally, in PHP7, using the following forms are all possible:

// Everything inside `<something>` brackets means one or more expressions
// to form something

// Dynamic function call
(<function_name>)(arguments)

// Dynamic method call on an object
$object->{<method_name>}(arguments)
$object::{<method_name>}(arguments)

// Dynamic method call on a dynamically-generated object
(<object>)->{<method_name>}(arguments)
(<object>)::{<method_name>}(arguments)

// Dynamic method call, statically
ClassName::{<method_name>}(arguments)
(<class_name>)::{<method_name>}(arguments)

// Dynamic method call, array-like (no different between static and non-static calls
[<object>, <method_name>](arguments)

// Dynamic method call, array-like, statically
[<class_name>, <method_name>](arguments)

Special thanks to this PHP talk.

How to pass arguments to a Dockerfile?

You are looking for --build-arg and the ARG instruction. These are new as of Docker 1.9. Check out https://docs.docker.com/engine/reference/builder/#arg. This will allow you to add ARG arg to the Dockerfile and then build with docker build --build-arg arg=2.3 ..

CSS scale height to match width - possibly with a formfactor

.video {
    width: 100%;
    position: relative;
    padding-bottom: 56.25%; /* ratio 16/9 */
}

.video iframe {
    border: none;
    position: absolute;
    width: 100%;
    height: 100%;
}

16:9

padding-bottom = 9/16 * 100 = 56.25

Validate phone number with JavaScript

I would suggest using something clearer (especially thinking to who will have to maintain the code)... what about:

var formats = "(999)999-9999|999-999-9999|9999999999";
var r = RegExp("^(" +
               formats
                 .replace(/([\(\)])/g, "\\$1")
                 .replace(/9/g,"\\d") +
               ")$");

where the regexp is built from a clear template ? Adding a new one would then be a no-brainer and may be even the customer itself could be able to do that in a "options" page.

How to tell if tensorflow is using gpu acceleration from inside python shell?

You have some options to test whether GPU acceleration is being used by your TensorFlow installation.

You can type in the following commands in three different platforms.

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
  1. Jupyter Notebook - Check the console which is running the Jupyter Notebook. You will be able to see the GPU being used.
  2. Python Shell - You will be able to directly see the output. (Note- do not assign the output of the second command to the variable 'sess'; if that helps).
  3. Spyder - Type in the following command in the console.

    import tensorflow as tf tf.test.is_gpu_available()

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use http://www.jacklmoore.com/autosize/ to make the text area act more like a div.

<style>
.hidden{
display:none
}
</style>

<textarea class="hidden" rows="4" cols="50">

</textarea>


$("#hiddentextarea").change(function() {

alert('Textarea changed');

})

Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

How to switch between frames in Selenium WebDriver using Java

This code is in groovy, so most likely you will need to do some rework. The first param is a url, the second is a counter to limit the tries.

public boolean selectWindow(window, maxTries) {
    def handles
    int tries = 0
    while (true) {
        try {
            handles = driver.getWindowHandles().toArray()
            for (int a = handles.size() - 1; a >= 0 ; a--) { // Backwards is faster with FF since it requires two windows
                try {
                    Log.logger.info("Attempting to select window: " + window)
                    driver.switchTo().window(handles[a]);
                    if (driver.getCurrentUrl().equals(window))
                        return true;
                    else {
                        Thread.sleep(2000)
                        tries++
                    }
                    if (tries > maxTries) {
                        Log.logger.warn("Cannot select page")
                        return false
                    }
                } catch (Exception ex) {
                    Thread.sleep(2000)
                    tries++
                }
            }
        } catch (Exception ex2) {
            Thread.sleep(2000)
            tries++
        }
    }
    return false;
}

Converting Go struct to JSON

Related issue:

I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

Wasted a lot of time, so posting solution here.

In Go:

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

In JavaScript:

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

Where's my invalid character (ORA-00911)

Of the top of my head, can you try to use the 'q' operator for the string literal

something like

insert all
  into domo_queries values (q'[select 
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;

Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.

Python float to int conversion

>>> x = 2.51
>>> x*100
250.99999999999997

the floating point numbers are inaccurate. in this case, it is 250.99999999999999, which is really close to 251, but int() truncates the decimal part, in this case 250.

you should take a look at the Decimal module or maybe if you have to do a lot of calculation at the mpmath library http://code.google.com/p/mpmath/ :),

Returning JSON object as response in Spring Boot

use ResponseEntity<ResponseBean>

Here you can use ResponseBean or Any java bean as you like to return your api response and it is the best practice. I have used Enum for response. it will return status code and status message of API.

@GetMapping(path = "/login")
public ResponseEntity<ServiceStatus> restApiExample(HttpServletRequest request,
            HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        loginService.login(username, password, request);
        return new ResponseEntity<ServiceStatus>(ServiceStatus.LOGIN_SUCCESS,
                HttpStatus.ACCEPTED);
    }

for response ServiceStatus or(ResponseBody)

    public enum ServiceStatus {

    LOGIN_SUCCESS(0, "Login success"),

    private final int id;
    private final String message;

    //Enum constructor
    ServiceStatus(int id, String message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public String getMessage() {
        return message;
    }
}

Spring REST API should have below key in response

  1. Status Code
  2. Message

you will get final response below

{

   "StatusCode" : "0",

   "Message":"Login success"

}

you can use ResponseBody(java POJO, ENUM,etc..) as per your requirement.

Setting maxlength of textbox with JavaScript or jQuery

without jQuery you can use

document.getElementById('text_input').setAttribute('maxlength',200);

Convert Little Endian to Big Endian

Below program produce the result as needed:

#include <stdio.h>
 
unsigned int Little_To_Big_Endian(unsigned int num);
 
int main( )
{
    int num = 0x11223344 ;
    
    printf("\n Little_Endian = 0x%X\n",num);
    
    printf("\n Big_Endian    = 0x%X\n",Little_To_Big_Endian(num));
 
}
 
unsigned int Little_To_Big_Endian(unsigned int num)
{
    return (((num >> 24) & 0x000000ff) | ((num >> 8) & 0x0000ff00) | ((num << 8) & 0x00ff0000) | ((num << 24) & 0xff000000));
}

And also below function can be used:

    unsigned int Little_To_Big_Endian(unsigned int num)
    {
        return (((num & 0x000000ff) << 24) | ((num & 0x0000ff00) << 8 ) | ((num & 0x00ff0000) >> 8) | ((num & 0xff000000) >> 24 ));
    }

Play sound file in a web-page in the background

<audio controls autoplay loop>
  <source src="path/your_song.mp3" type="audio/ogg">
  <embed src="path/your_song.mp3" autostart="true" loop="true" hidden="true"> 
</audio>

[ps. replace the "path/your_song.mp3" with the folder and the song title eg. "music/samplemusic.mp3" or "media/bgmusic.mp3" etc.

What is the use of the %n format specifier in C?

Those who want to use %n Format Specifier may want to look at this:

Do Not Use the "%n" Format String Specifier

Abstract

Careless use of "%n" format strings can introduce a vulnerability.

Description

There are many kinds of vulnerability that can be caused by misusing format strings. Most of these are covered elsewhere, but this document covers one specific kind of format string vulnerability that is entirely unique for format strings. Documents in the public are inconsistent in coverage of these vulnerabilities.

In C, use of the "%n" format specification in printf() and sprintf() type functions can change memory values. Inappropriate design/implementation of these formats can lead to a vulnerability generated by changes in memory content. Many format vulnerabilities, particularly those with specifiers other than "%n", lead to traditional failures such as segmentation fault. The "%n" specifier has generated more damaging vulnerabilities. The "%n" vulnerabilities may have secondary impacts, since they can also be a significant consumer of computing and networking resources because large guantities of data may have to be transferred to generate the desired pointer value for the exploit.

Avoid using the "%n" format specifier. Use other means to accomplish your purpose.

Source: link

npm install vs. update - what's the difference?

In most cases, this will install the latest version of the module published on npm.

npm install express --save

or better to upgrade module to latest version use:

npm install express@latest --save --force

--save: Package will appear in your dependencies.

More info: npm-install

Which port we can use to run IIS other than 80?

You can run IIS on any port you like, as long as it does not conflict with other applications. I am using 88, 8888 and other easy to remember ports.

You can find the common used port here: PORT NUMBERS, and it is safer to choose an unassigned TCP port.

Quote:

The Dynamic and/or Private Ports are those from 49152 through 65535

If IIS is working and you have troubles with an ASP.NET applications, those links might be helpful:

If you are still having troubles, it would be helpful to provide more information about your environment, the steps taken so far to solve the problem, and retagging the question (append asp.net for example)

Use async await with Array.map

I had a task on BE side to find all entities from a repo, and to add a new property url and to return to controller layer. This is how I achieved it (thanks to Ajedi32's response):

async findAll(): Promise<ImageResponse[]> {
    const images = await this.imageRepository.find(); // This is an array of type Image (DB entity)
    const host = this.request.get('host');
    const mappedImages = await Promise.all(images.map(image => ({...image, url: `http://${host}/images/${image.id}`}))); // This is an array of type Object
    return plainToClass(ImageResponse, mappedImages); // Result is an array of type ImageResponse
  }

Note: Image (entity) doesn't have property url, but ImageResponse - has

How do I find numeric columns in Pandas?

Simple one-liner:

df.select_dtypes('number').columns

How to kill a process in MacOS?

in the spotlight, search for Activity Monitor. You can force fully remove any application from here.

enter image description here

How to Use -confirm in PowerShell

For when you want a 1-liner

while( -not ( ($choice= (Read-Host "May I continue?")) -match "y|n")){ "Y or N ?"}

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

How can I find matching values in two arrays?

Loop through the second array each time you iterate over an element in the first array, then check for matches.

var array1 = ["cat", "sum", "fun", "run"],
    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];

function getMatch(a, b) {
    var matches = [];

    for ( var i = 0; i < a.length; i++ ) {
        for ( var e = 0; e < b.length; e++ ) {
            if ( a[i] === b[e] ) matches.push( a[i] );
        }
    }
    return matches;
}

getMatch(array1, array2); // ["cat"]

ASP.NET MVC: Custom Validation by DataAnnotation

Background:

Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

public class EmployeeModel 
{
    [Required]
    [UniqueEmailAddress]
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}
}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
{
    private IEmployeeRepository _employeeRepository;
    [Inject]
    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository; }
        set
        {
            _employeeRepository = value;
        }
    }
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
    {
        var model = (EmployeeModel)validationContext.ObjectInstance;
        if(model.Field1 == null){
            return new ValidationResult("Field1 is null");
        }
        if(model.Field2 == null){
            return new ValidationResult("Field2 is null");
        }
        if(model.Field3 == null){
            return new ValidationResult("Field3 is null");
        }
        return ValidationResult.Success;
    }
}

Hope this helps. Cheers !

References

How to retrieve checkboxes values in jQuery

You can also return all selected checkboxes value in comma separated string. This will also make it easier for you when you send it as a parameter to SQL

Here is a sample that return all selected checkboxes values that have the name "chkboxName" in comma separate string

And here is the javascript

function showSelectedValues()
{
  alert($("input[name=chkboxName]:checked").map(function () {
    return this.value;
  }).get().join(","));
}

Here is the HTML sample

<html>
  <head>
 </head>
 <body>
  <div>
   <input name="chkboxName" type="checkbox" value="one_name" checked>
   <input name="chkboxName" type="checkbox" value="one_name1">
   <input name="chkboxName" type="checkbox" value="one_name2">
  </div>  
 </body>
 </html>

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

I am writing application to API level 21, I tried all the above but didn't worked, Finally i deleted Values-v23 from appcompat_v7.It worked.

Android: keeping a background service alive (preventing process death)

Keep your service footprint small, this reduces the probability of Android closing your application. You can't prevent it from being killed because if you could then people could easily create persistent spyware

How do I correct the character encoding of a file?

If you see question marks in the file or if the accents are already lost, going back to utf8 will not help your cause. e.g. if café became cafe - changing encoding alone will not help (and you'll need original data).

Can you paste some text here, that'll help us answer for sure.

Change a column type from Date to DateTime during ROR migration

AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).

open link of google play store in mobile version android

You'll want to use the specified market protocol:

final String appPackageName = "com.example"; // Can also use getPackageName(), as below
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));

Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:

final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}

While using getPackageName() from Context or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.

Unicode (UTF-8) reading and writing to files in Python

You can also improve the original open() function to work with Unicode files by replacing it in place, using the partial function. The beauty of this solution is you don't need to change any old code. It's transparent.

import codecs
import functools
open = functools.partial(codecs.open, encoding='utf-8')

Calling a Javascript Function from Console

If it's inside a closure, i'm pretty sure you can't.

Otherwise you just do functionName(); and hit return.

Difference between .keystore file and .jks file

You are confused on this.

A keystore is a container of certificates, private keys etc.

There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

JKS is Java's keystore implementation. There is also BKS etc.

These are all keystore types.

So to answer your question:

difference between .keystore files and .jks files

There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

How to use Monitor (DDMS) tool to debug application

I think things (location) have changed little bit. For: Android Studio 1.2.1.1 Build @AI-141.1903250 - built on May 5, 2015

Franco Rondinis answer should be

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. Select your device from the dropdown list.
  4. Select your app by its package name from the list of running apps.
  5. On the Android DDMS tool window, select Memory tab.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking (same icon)

how to start allocation tracking in android studio 1.2.1.1

Duplicate keys in .NET dictionaries?

If you're using .NET 3.5, use the Lookup class.

EDIT: You generally create a Lookup using Enumerable.ToLookup. This does assume that you don't need to change it afterwards - but I typically find that's good enough.

If that doesn't work for you, I don't think there's anything in the framework which will help - and using the dictionary is as good as it gets :(

PDO Prepared Inserts multiple rows in single query

For what it is worth, I have seen a lot of users recommend iterating through INSERT statements instead of building out as a single string query as the selected answer did. I decided to run a simple test with just two fields and a very basic insert statement:

<?php
require('conn.php');

$fname = 'J';
$lname = 'M';

$time_start = microtime(true);
$stmt = $db->prepare('INSERT INTO table (FirstName, LastName) VALUES (:fname, :lname)');

for($i = 1; $i <= 10; $i++ )  {
    $stmt->bindParam(':fname', $fname);
    $stmt->bindParam(':lname', $lname);
    $stmt->execute();

    $fname .= 'O';
    $lname .= 'A';
}


$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Completed in ". $time ." seconds <hr>";

$fname2 = 'J';
$lname2 = 'M';

$time_start2 = microtime(true);
$qry = 'INSERT INTO table (FirstName, LastName) VALUES ';
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?), ";
$qry .= "(?,?)";

$stmt2 = $db->prepare($qry);
$values = array();

for($j = 1; $j<=10; $j++) {
    $values2 = array($fname2, $lname2);
    $values = array_merge($values,$values2);

    $fname2 .= 'O';
    $lname2 .= 'A';
}

$stmt2->execute($values);

$time_end2 = microtime(true);
$time2 = $time_end2 - $time_start2;

echo "Completed in ". $time2 ." seconds <hr>";
?>

While the overall query itself took milliseconds or less, the latter (single string) query was consistently 8 times faster or more. If this was built out to say reflect an import of thousands of rows on many more columns, the difference could be enormous.

How do I get column names to print in this C# program?

Code for Find the Column Name same as using the Like in sql.

foreach (DataGridViewColumn column in GrdMarkBook.Columns)  
                      //GrdMarkBook is Data Grid name
{                      
    string HeaderName = column.HeaderText.ToString();

    //  This line Used for find any Column Have Name With Exam

    if (column.HeaderText.ToString().ToUpper().Contains("EXAM"))
    {
        int CoumnNo = column.Index;
    }
}

Simulating Slow Internet Connection

For Linux, the following list of papers might be useful:

Personally, whilst Dummynet is good, I find NetEm to be the most versatile for my use-cases; I'm usually interested in the effect of delays, rather than bandwidth (i.e. WiFi connection issues), and it's super-easy to emulate random packet loss/corruption, etc. It's also very accessible, and free (unlike the hardware-based Linktropy).

On a side-note, for Windows, Clumsy is awesome. I would also like to add that (regarding websites) browser throttling is not an accurate method for emulating real-life network issues (I think "TKK" commented on a few of the reasons why above).

Hope this helps someone!

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

Adding the default_url in routes not the right solution although, it works for some cases.

You've to set the default_url in each environment(development, test, production).

You need make these changes.

    config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

 config/environments/test.rb
      config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

  config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

Has an event handler already been added?

I recently came to a similar situation where I needed to register a handler for an event only once. I found that you can safely unregister first, and then register again, even if the handler is not registered at all:

myClass.MyEvent -= MyHandler;
myClass.MyEvent += MyHandler;

Note that doing this every time you register your handler will ensure that your handler is registered only once. Sounds like a pretty good practice to me :)

How to deploy a war file in Tomcat 7

1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file. There you go!

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

Your vm does not find the class org/apache/juli/logging/LogFactory check if this class is present in the tomcat-juli.jar that you use (unzip it and search the file), if it's not present download the library from apache web site else if it's present put the tomcat-juli.jar in a path (the lib directory) that Tomcat use to load classes. If your Tomcat does not find it you can copy the jar in the lib directory of the JRE that you are using.

How to read from standard input in the console?

you can as well try:

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

if scanner.Err() != nil {
    // handle error.
}

What is *.o file?

You've gotten some answers, and most of them are correct, but miss what (I think) is probably the point here.

My guess is that you have a makefile you're trying to use to create an executable. In case you're not familiar with them, makefiles list dependencies between files. For a really simple case, it might have something like:

myprogram.exe: myprogram.o
    $(CC) -o myprogram.exe myprogram.o

myprogram.o: myprogram.cpp
    $(CC) -c myprogram.cpp

The first line says that myprogram.exe depends on myprogram.o. The second line tells how to create myprogram.exe from myprogram.o. The third and fourth lines say myprogram.o depends on myprogram.cpp, and how to create myprogram.o from myprogram.cpp` respectively.

My guess is that in your case, you have a makefile like the one above that was created for gcc. The problem you're running into is that you're using it with MS VC instead of gcc. As it happens, MS VC uses ".obj" as the extension for its object files instead of ".o".

That means when make (or its equivalent built into the IDE in your case) tries to build the program, it looks at those lines to try to figure out how to build myprogram.exe. To do that, it sees that it needs to build myprogram.o, so it looks for the rule that tells it how to build myprogram.o. That says it should compile the .cpp file, so it does that.

Then things break down -- the VC++ compiler produces myprogram.obj instead of myprogram.o as the object file, so when it tries to go to the next step to produce myprogram.exe from myprogram.o, it finds that its attempt at creating myprogram.o simply failed. It did what the rule said to do, but that didn't produce myprogram.o as promised. It doesn't know what to do, so it quits and give you an error message.

The cure for that specific problem is probably pretty simple: edit the make file so all the object files have an extension of .obj instead of .o. There's room for a lot of question whether that will fix everything though -- that may be all you need, or it may simply lead to other (probably more difficult) problems.

SQL WHERE ID IN (id1, id2, ..., idn)

What Ed Guiness suggested is really a performance booster , I had a query like this

select * from table where id in (id1,id2.........long list)

what i did :

DECLARE @temp table(
            ID  int
            )
insert into @temp 
select * from dbo.fnSplitter('#idlist#')

Then inner joined the temp with main table :

select * from table inner join temp on temp.id = table.id

And performance improved drastically.

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

If you don't need the entire string, you can take advantage of the delayed execution:

public static class StringExtensions
{
    public static IEnumerable<char> RemoveChar(this IEnumerable<char> originalString, char removingChar)
    {
        return originalString.Where(@char => @char != removingChar);
    }
}

You can even combine multiple characters...

string veryLongText = "abcdefghijk...";

IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
            .RemoveChar('c')
            .RemoveChar('d')
            .Take(5);

... and only the first 7 characters will be evaluated :)

EDIT: or, even better:

public static class StringExtensions
{
    public static IEnumerable<char> RemoveChars(this IEnumerable<char> originalString,
        params char[] removingChars)
    {
        return originalString.Except(removingChars);
    }
}

and its usage:

        var veryLongText = "abcdefghijk...";
        IEnumerable<char> firstFiveCharsWithoutCsAndDs = veryLongText
            .RemoveChars('c', 'd')
            .Take(5)
            .ToArray(); //to prevent multiple execution of "RemoveChars"

case statement in SQL, how to return multiple variables?

You could use a subselect combined with a UNION. Whenever you can return the same fields for more than one condition use OR with the parenthesis as in this example:

SELECT * FROM
  (SELECT val1, val2 FROM table1 WHERE (condition1 is true) 
                                    OR (condition2 is true))
UNION
SELECT * FROM
  (SELECT val5, val6 FROM table7 WHERE (condition9 is true) 
                                    OR (condition4 is true))

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

I would recommend using INSERT...ON DUPLICATE KEY UPDATE.

If you use INSERT IGNORE, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an error. It generates a warning instead. These cases include:

  • Inserting a duplicate key in columns with PRIMARY KEY or UNIQUE constraints.
  • Inserting a NULL into a column with a NOT NULL constraint.
  • Inserting a row to a partitioned table, but the values you insert don't map to a partition.

If you use REPLACE, MySQL actually does a DELETE followed by an INSERT internally, which has some unexpected side effects:

  • A new auto-increment ID is allocated.
  • Dependent rows with foreign keys may be deleted (if you use cascading foreign keys) or else prevent the REPLACE.
  • Triggers that fire on DELETE are executed unnecessarily.
  • Side effects are propagated to replicas too.

correction: both REPLACE and INSERT...ON DUPLICATE KEY UPDATE are non-standard, proprietary inventions specific to MySQL. ANSI SQL 2003 defines a MERGE statement that can solve the same need (and more), but MySQL does not support the MERGE statement.


A user tried to edit this post (the edit was rejected by moderators). The edit tried to add a claim that INSERT...ON DUPLICATE KEY UPDATE causes a new auto-increment id to be allocated. It's true that the new id is generated, but it is not used in the changed row.

See demonstration below, tested with Percona Server 5.5.28. The configuration variable innodb_autoinc_lock_mode=1 (the default):

mysql> create table foo (id serial primary key, u int, unique key (u));
mysql> insert into foo (u) values (10);
mysql> select * from foo;
+----+------+
| id | u    |
+----+------+
|  1 |   10 |
+----+------+

mysql> show create table foo\G
CREATE TABLE `foo` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `u` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `u` (`u`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1

mysql> insert into foo (u) values (10) on duplicate key update u = 20;
mysql> select * from foo;
+----+------+
| id | u    |
+----+------+
|  1 |   20 |
+----+------+

mysql> show create table foo\G
CREATE TABLE `foo` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `u` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `u` (`u`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

The above demonstrates that the IODKU statement detects the duplicate, and invokes the update to change the value of u. Note the AUTO_INCREMENT=3 indicates an id was generated, but not used in the row.

Whereas REPLACE does delete the original row and inserts a new row, generating and storing a new auto-increment id:

mysql> select * from foo;
+----+------+
| id | u    |
+----+------+
|  1 |   20 |
+----+------+
mysql> replace into foo (u) values (20);
mysql> select * from foo;
+----+------+
| id | u    |
+----+------+
|  3 |   20 |
+----+------+

OnClickListener in Android Studio

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         int id = item.getItemId();
         if (id == R.id.standingsButton) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

I just encountered this exception and in my case it was cause by a white space between asp:content elements

So, this failed:

<asp:content runat="server" ContentPlaceHolderID="Header">
    Header
</asp:content>

<asp:Content runat="server" ContentPlaceHolderID="Content">
    Content
</asp:Content>

But removing the white spaces between the elements worked:

<asp:content runat="server" ContentPlaceHolderID="Header">
    Header
</asp:content><asp:Content runat="server" ContentPlaceHolderID="Content">
    Content
</asp:Content>

Pad a number with leading zeros in JavaScript

This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0.

function ZeroPadNumber ( nValue )
{
    if ( nValue < 10 )
    {
        return ( '000' + nValue.toString () );
    }
    else if ( nValue < 100 )
    {
        return ( '00' + nValue.toString () );
    }
    else if ( nValue < 1000 )
    {
        return ( '0' + nValue.toString () );
    }
    else
    {
        return ( nValue );
    }
}

This function is also hardcoded to your particular need (4 digit padding), so it's not generic.

Delete files older than 10 days using shell script in Unix

find is the common tool for this kind of task :

find ./my_dir -mtime +10 -type f -delete

EXPLANATIONS

  • ./my_dir your directory (replace with your own)
  • -mtime +10 older than 10 days
  • -type f only files
  • -delete no surprise. Remove it to test your find filter before executing the whole command

And take care that ./my_dir exists to avoid bad surprises !

Passing a string array as a parameter to a function java

Feel free to use this how ever you like.

/*
 * The extendStrArray() method will takes a number "n" and
 * a String Array "strArray" and will return a new array
 * containing 'n' new positions. This new returned array
 * can then be assigned to a new array, or the existing
 * one to "extend" it, it contain the old value in the 
 * new array with the addition n empty positions.
 */
private String[] extendStrArray(int n, String[] strArray){
    String[] old_str_array = strArray;
    String[] new_str_array = new String[(old_str_array.length + n)];
    for(int i = 0; i < old_str_array.length; i++ ){
        new_str_array[i] = old_str_array[i];
    }//end for loop

    return new_str_array;

}//end extendStrArray()

Basically I would use it like this:

String[] students = {"Tom", "Jeff", "Ashley", "Mary"};
// 4 new students enter the class so we need to extend the string array
students = extendStrArray(4, students); //this will effectively add 4 new empty positions to the "students" array.

UTL_FILE.FOPEN() procedure not accepting path for directory?

For utl_file.open(location,filename,mode) , we need to give directory name for location but not path. For Example:DATA_FILE_DIR , this is the directory name and check out the directory path for that particular directory name.

Is it possible to GROUP BY multiple columns using MySQL?

To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.

SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

jQuery Get Selected Option From Dropdown

you should use this syntax:

var value = $('#Id :selected').val();

So try this Code:

var values = $('#aioConceptName :selected').val();

you can test in Fiddle: http://jsfiddle.net/PJT6r/9/

see about this answer in this post

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Count length of array and return 1 if it only contains one element

Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

$cars.count should give you what you seem to be looking for.

JavaScript: undefined !== undefined?

That's a bad practice to use the == equality operator instead of ===.

undefined === undefined // true
null == undefined // true
null === undefined // false

The object.x === undefined should return true if x is unknown property.

In chapter Bad Parts of JavaScript: The Good Parts, Crockford writes the following:

If you attempt to extract a value from an object, and if the object does not have a member with that name, it returns the undefined value instead.

In addition to undefined, JavaScript has a similar value called null. They are so similar that == thinks they are equal. That confuses some programmers into thinking that they are interchangeable, leading to code like

value = myObject[name];
if (value == null) {
    alert(name + ' not found.');
}

It is comparing the wrong value with the wrong operator. This code works because it contains two errors that cancel each other out. That is a crazy way to program. It is better written like this:

value = myObject[name];
if (value === undefined) {
    alert(name + ' not found.');
}

Closing Twitter Bootstrap Modal From Angular Controller

You can do it like this:

angular.element('#modal').modal('hide');

Get size of folder or file

Here's the best way to get a general File's size (works for directory and non-directory):

public static long getSize(File file) {
    long size;
    if (file.isDirectory()) {
        size = 0;
        for (File child : file.listFiles()) {
            size += getSize(child);
        }
    } else {
        size = file.length();
    }
    return size;
}

Edit: Note that this is probably going to be a time-consuming operation. Don't run it on the UI thread.

Also, here (taken from https://stackoverflow.com/a/5599842/1696171) is a nice way to get a user-readable String from the long returned:

public static String getReadableSize(long size) {
    if(size <= 0) return "0";
    final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
    int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
    return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups))
            + " " + units[digitGroups];
}

How do I get the current date in Cocoa

There is no difference in the location of the asterisk (at in C, which Obj-C is based on, it doesn't matter). It is purely preference (style).

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

I'm all for good names, and I often write about the importance of taking great care when choosing names for things. For this very same reason, I am wary of metaphors when naming things. In the original question, "factory" and "synchronizer" look like good names for what they seem to mean. However, "shepherd" and "nanny" are not, because they are based on metaphors. A class in your code can't be literally a nanny; you call it a nanny because it looks after some other things very much like a real-life nanny looks after babies or kids. That's OK in informal speech, but not OK (in my opinion) for naming classes in code that will have to be maintained by who knows whom who knows when.

Why? Because metaphors are culture dependent and often individual dependent as well. To you, naming a class "nanny" can be very clear, but maybe it's not that clear to somebody else. We shouldn't rely on that, unless you're writing code that is only for personal use.

In any case, convention can make or break a metaphor. The use of "factory" itself is based on a metaphor, but one that has been around for quite a while and is currently fairly well known in the programming world, so I would say it's safe to use. However, "nanny" and "shepherd" are unacceptable.

Best way to do multi-row insert in Oracle?

If you have the values that you want to insert in another table already, then you can Insert from a select statement.

INSERT INTO a_table (column_a, column_b) SELECT column_a, column_b FROM b_table;

Otherwise, you can list a bunch of single row insert statements and submit several queries in bulk to save the time for something that works in both Oracle and MySQL.

@Espo's solution is also a good one that will work in both Oracle and MySQL if your data isn't already in a table.

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

How to make bootstrap 3 fluid layout without horizontal scrollbar

Bootstrap 3.0 version is tricky they will add fix for this issue and probably return container-fluid in Bootstrap 3.1. But until then here is a fix that I'm using:

First of, you would need custom container and set it to 100% width, and then you will need to fix row margin disposition, and navbar too if you have it:

/* Custom container */
.container-full {
  margin: 0 auto;
  width: 100%;
}

/*fix row -15px margin*/
.container-fluid {
    padding: 0 15px;
}

/*fix navbar margin*/
.navbar{
  margin: 0 -15px;
}

/*fix navbar-right margin*/
.navbar-nav.navbar-right:last-child {
  margin-right: 0px;
}

You can stack container-full and container-fluid classes on root div, and you can use container-fluid later on.

Hope it helps, if you need more info let me know.

Using Linq to get the last N elements of a collection?

collection.Skip(Math.Max(0, collection.Count() - N));

This approach preserves item order without a dependency on any sorting, and has broad compatibility across several LINQ providers.

It is important to take care not to call Skip with a negative number. Some providers, such as the Entity Framework, will produce an ArgumentException when presented with a negative argument. The call to Math.Max avoids this neatly.

The class below has all of the essentials for extension methods, which are: a static class, a static method, and use of the this keyword.

public static class MiscExtensions
{
    // Ex: collection.TakeLast(5);
    public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int N)
    {
        return source.Skip(Math.Max(0, source.Count() - N));
    }
}

A brief note on performance:

Because the call to Count() can cause enumeration of certain data structures, this approach has the risk of causing two passes over the data. This isn't really a problem with most enumerables; in fact, optimizations exist already for Lists, Arrays, and even EF queries to evaluate the Count() operation in O(1) time.

If, however, you must use a forward-only enumerable and would like to avoid making two passes, consider a one-pass algorithm like Lasse V. Karlsen or Mark Byers describe. Both of these approaches use a temporary buffer to hold items while enumerating, which are yielded once the end of the collection is found.

How do I URl encode something in Node.js?

The built-in module querystring is what you're looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'

Resource leak: 'in' is never closed

You should close your Scanner when you're done with it:

in.close();