Programs & Examples On #Vote up buttons

What's the purpose of META-INF?

I've noticed that some Java libraries have started using META-INF as a directory in which to include configuration files that should be packaged and included in the CLASSPATH along with JARs. For example, Spring allows you to import XML Files that are on the classpath using:

<import resource="classpath:/META-INF/cxf/cxf.xml" />
<import resource="classpath:/META-INF/cxf/cxf-extensions-*.xml" />

In this example, I'm quoting straight out of the Apache CXF User Guide. On a project I worked on in which we had to allow multiple levels of configuration via Spring, we followed this convention and put our configuration files in META-INF.

When I reflect on this decision, I don't know what exactly would be wrong with simply including the configuration files in a specific Java package, rather than in META-INF. But it seems to be an emerging de facto standard; either that, or an emerging anti-pattern :-)

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

I need to test against a string of any character (including white space, marks, numbers, unicode characters...). Because white space, numbers, marks... will be the same in both upper case and lower case, and I want to find real upper case letters, I do this:

let countUpperCase = 0;
let i = 0;
while (i <= string.length) {
  const character = string.charAt(i);
  if (character === character.toUpperCase() && character !== character.toLowerCase()) {
    countUpperCase++;
  }
  i++;
}

How to change UIButton image in Swift

From your Obc-C code I think you want to set an Image for button so try this way:

let playButton  = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
    playButton.setImage(image, forState: .Normal)
}

In Short:

playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)

For Swift 3:

let playButton  = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)

Grep characters before and after match?

With gawk , you can use match function:

    x="hey there how are you"
    echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
    ere   are

If you are ok with perl, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.

echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how

This can also be applied to words instead of just characters.Following will print one word before the actual matching string.

echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey

Following will print one word after the pattern:

echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how

Following will print one word before the pattern , then the actual word and then one word after the pattern:

echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how

Default interface methods are only supported starting with Android N

As CommonsWare mentioned, for reference add this inside the android {...} closure in the build.gradle for your app module to resolve issue:

android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

How to reset the bootstrap modal when it gets closed and open it fresh again?

Just reset any content manually when modal is hidden:

$(".modal").on("hidden.bs.modal", function(){
    $(".modal-body1").html("");
});

There is more events. More about them here

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".modal").on("hidden.bs.modal", function() {_x000D_
    $(".modal-body1").html("Where did he go?!?!?!");_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch modal_x000D_
</button>_x000D_
_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>_x000D_
        </button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <div class='modal-body1'>_x000D_
          <h3>Close and open, I will be gone!</h3>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to know function return type and argument types?

Docstrings (and documentation in general). Python 3 introduces (optional) function annotations, as described in PEP 3107 (but don't leave out docstrings)

Toad for Oracle..How to execute multiple statements?

  1. Just finsih all of your queries with ;
  2. Select all queries you need (inserts, selects, ...).
  3. Push or F5 or F9 both Works.

Not necessary to execute as script

How to vertically align text in input type="text"?

I found this question while looking for a solution to my own problem. The previous answers rely on padding to make the text appear at the top or bottom of the input or use a combination of height and line-height to align the text to the vertical middle.

Here is an alternative solution to making the text appear in the middle using a div and positioning. Check out the jsfiddle.

<style type="text/css">
    div {
        display: inline-block;
        height: 300px;
        position: relative;
        width: 500px;
    }

    input {
        height: 100%;
        position: absolute;
        text-align: center; /* Optional */
        width: 100%;
    }
</style>

<div>
    <input type="text" value="Hello world!" />
</div>

Convert Mat to Array/Vector in OpenCV

You can use iterators:

Mat matrix = ...;

std::vector<float> vec(matrix.begin<float>(), matrix.end<float>());

How to get a string after a specific substring?

If you want to do this using regex, you could simply use a non-capturing group, to get the word "world" and then grab everything after, like so

(?:world).*

The example string is tested here

Unresolved external symbol in object files

Yet another possibility to check, it was my problem this time.

I had added the function to the library, and included the library's output folder in the search path.

But I also had a folder with an older version of the library listed before, so VS was using the old library, and of course not finding the new function.

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

Rolling or sliding window iterator?

Optimized Function for sliding window data in Deep learning

def SlidingWindow(X, window_length, stride):
    indexer = np.arange(window_length)[None, :] + stride*np.arange(int(len(X)/stride)-window_length+4)[:, None]
    return X.take(indexer)

to apply on multidimensional array

import numpy as np
def SlidingWindow(X, window_length, stride1):
    stride=  X.shape[1]*stride1
    window_length = window_length*X.shape[1]
    indexer = np.arange(window_length)[None, :] + stride1*np.arange(int(len(X)/stride1)-window_length-1)[:, None]
    return X.take(indexer)

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When I encountered this exception, I solved this by using Run Configurations... panel as picture shows below.Especially, at JRE tab, the VM Arguments are the critical
( "-Xmx1024m -Xms512m -XX:MaxPermSize=1024m -XX:PermSize=512m" ).

enter image description here

jquery click event not firing?

Might be useful to some : check for

pointer-events: none;

In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.

How to check if a file exists before creating a new file

Assuming it is OK that the operation is not atomic, you can do:

if (std::ifstream(name))
{
     std::cout << "File already exists" << std::endl;
     return false;
}
std::ofstream file(name);
if (!file)
{
     std::cout << "File could not be created" << std::endl;
     return false;
}
... 

Note that this doesn't work if you run multiple threads trying to create the same file, and certainly will not prevent a second process from "interfering" with the file creation because you have TOCTUI problems. [We first check if the file exists, and then create it - but someone else could have created it in between the check and the creation - if that's critical, you will need to do something else, which isn't portable].

A further problem is if you have permissions such as the file is not readable (so we can't open it for read) but is writeable, it will overwrite the file.

In MOST cases, neither of these things matter, because all you care about is telling someone that "you already have a file like that" (or something like that) in a "best effort" approach.

Execute PowerShell Script from C# with Commandline Arguments

Mine is a bit more smaller and simpler:

/// <summary>
/// Runs a PowerShell script taking it's path and parameters.
/// </summary>
/// <param name="scriptFullPath">The full file path for the .ps1 file.</param>
/// <param name="parameters">The parameters for the script, can be null.</param>
/// <returns>The output from the PowerShell execution.</returns>
public static ICollection<PSObject> RunScript(string scriptFullPath, ICollection<CommandParameter> parameters = null)
{
    var runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    var pipeline = runspace.CreatePipeline();
    var cmd = new Command(scriptFullPath);
    if (parameters != null)
    {
        foreach (var p in parameters)
        {
            cmd.Parameters.Add(p);
        }
    }
    pipeline.Commands.Add(cmd);
    var results = pipeline.Invoke();
    pipeline.Dispose();
    runspace.Dispose();
    return results;
}

How to pass parameter to a promise function

You can use .bind() to pass the param(this) to the function.

var someFunction =function(resolve, reject) {
  /* get username, password*/
  var username=this.username;
  var password=this.password;
  if ( /* everything turned out fine */ ) {
    resolve("Stuff worked!");
  } else {
    reject(Error("It broke"));
  }
}
var promise=new Promise(someFunction.bind({username:"your username",password:"your password"}));

CSS - make div's inherit a height

The Problem

When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.

Take a look at the following article to get a better idea of how the CSS Float property works:

The Mystery Of The CSS Float Property


A Potential Solution

Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.

Equal Height Columns with Cross-Browser CSS

I hope this helps.

Memory address of variables in Java

What you are getting is the result of the toString() method of the Object class or, more precisely, the identityHashCode() as uzay95 has pointed out.

"When we create an object in java with new keyword, we are getting a memory address from the OS."

It is important to realize that everything you do in Java is handled by the Java Virtual Machine. It is the JVM that is giving this information. What actually happens in the RAM of the host operating system depends entirely on the implementation of the JRE.

How to upload image in CodeIgniter?

Below code for an uploading a single file at a time. This is correct and perfect to upload a single file. Read all commented instructions and follow the code. Definitely, it is worked.

public function upload_file() {
    ***// Upload folder location***
    $config['upload_path'] = './public/upload/';

    ***// Allowed file type***
    $config['allowed_types'] = 'jpg|jpeg|png|pdf';

    ***// Max size, i will set 2MB***
    $config['max_size'] = '2024';

    $config['max_width'] = '1024';
    $config['max_height'] = '768';

    ***// load upload library***            
    $this->load->library('upload', $config);

    ***// do_upload is the method, to send the particular image and file on that 
       // particular 
       // location that is detail in $config['upload_path']. 
       // In bracks will set name upload, here you need to set input name attribute 
       // value.***

    if($this->upload->do_upload('upload')) {
       $data = $this->upload->data();
       $post['upload'] = $data['file_name'];
    } else {
      $error = array('error' => $this->upload->display_errors());
    }
 }

Batch files: List all files in a directory with relative paths

Of course, you may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
set mypath=
call :treeProcess
goto :eof

:treeProcess
setlocal
for %%f in (*.txt) do echo %mypath%%%f
for /D %%d in (*) do (
    set mypath=%mypath%%%d\
    cd %%d
    call :treeProcess
    cd ..
)
endlocal
exit /b

how to overwrite css style

Just add

.flex-control-thumbs li {
width: auto; 
}

What does O(log n) mean exactly?

Every time we write an algorithm or code we try to analyze its asymptotic complexity. It is different from its time complexity.

Asymptotic complexity is the behavior of execution time of an algorithm while the time complexity is the actual execution time. But some people use these terms interchangeably.

Because time complexity depends on various parameters viz.
1. Physical System
2. Programming Language
3. coding Style
4. And much more ......

The actual execution time is not a good measure for analysis.


Instead we take input size as the parameter because whatever the code is, the input is same. So the execution time is a function of input size.

Following is an example of Linear Time Algorithm


Linear Search
Given n input elements, to search an element in the array you need at most 'n' comparisons. In other words, no matter what programming language you use, what coding style you prefer, on what system you execute it. In the worst case scenario it requires only n comparisons.The execution time is linearly proportional to the input size.

And its not just search, whatever may be the work (increment, compare or any operation) its a function of input size.

So when you say any algorithm is O(log n) it means the execution time is log times the input size n.

As the input size increases the work done(here the execution time) increases.(Hence proportionality)

      n      Work
      2     1 units of work
      4     2 units of work
      8     3 units of work

See as the input size increased the work done is increased and it is independent of any machine. And if you try to find out the value of units of work It's actually dependent onto those above specified parameters.It will change according to the systems and all.

Undefined index error PHP

Hey this is happening because u r trying to display value before assignnig it U just fill in the values and submit form it will display correct output Or u can write ur php code below form tags It ll run without any errors

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

Markdown and including multiple files

You can actually use the Markdown Preprocessor (MarkdownPP). Running with the hypothetical book example from the other answers, you would create .mdpp files representing your chapters. The .mdpp files can then use the !INCLUDE "path/to/file.mdpp" directive, which operates recursively replacing the directive with the contents of the referenced file in the final output.

chapters/preface.mdpp
chapters/introduction.mdpp
chapters/why_markdown_is_useful.mdpp
chapters/limitations_of_markdown.mdpp
chapters/conclusions.mdpp

You would then need an index.mdpp that contained the following:

!INCLUDE "chapters/preface.mdpp"
!INCLUDE "chapters/introduction.mdpp"
!INCLUDE "chapters/why_markdown_is_useful.mdpp"
!INCLUDE "chapters/limitations_of_markdown.mdpp"
!INCLUDE "chapters/conclusions.mdpp"

To render your book you simply run the preprocessor on index.mdpp:

$ markdown-pp.py index.mdpp mybook.md

Don't forget to look at the readme.mdpp in the MarkdownPP repository for an exposition of preprocessor features suited for larger documentation projects.

Can inner classes access private variables?

An inner class has access to all members of the outer class, but it does not have an implicit reference to a parent class instance (unlike some weirdness with Java). So if you pass a reference to the outer class to the inner class, it can reference anything in the outer class instance.

Run .php file in Windows Command Prompt (cmd)

If running Windows 10:

  1. Open the start menu
  2. Type path
  3. Click Edit the system environment variables (usually, it's the top search result) and continue on step 6 below.

If on older Windows:

  1. Show Desktop.

  2. Right Click My Computer shortcut in the desktop.

  3. Click Properties.

  4. You should see a section of control Panel - Control Panel\System and Security\System.

  5. Click Advanced System Settings on the Left menu.

  6. Click Enviornment Variables towards the bottom of the System Properties window.

  7. Select PATH in the user variables list.

  8. Append your PHP Path (C:\myfolder\php) to your PATH variable, separated from the already existing string by a semi colon.

  9. Click OK

  10. Open your "cmd"

  11. Type PATH, press enter

  12. Make sure that you see your PHP folder among the list.

That should work.

Note: Make sure that your PHP folder has the php.exe. It should have the file type CLI. If you do not have the php.exe, go ahead and check the installation guidelines at - http://www.php.net/manual/en/install.windows.manual.php - and download the installation file from there.

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

How can we print line numbers to the log in java

I use this little method that outputs the trace and line number of the method that called it.

 Log.d(TAG, "Where did i put this debug code again?   " + Utils.lineOut());

Double click the output to go to that source code line!

You might need to adjust the level value depending on where you put your code.

public static String lineOut() {
    int level = 3;
    StackTraceElement[] traces;
    traces = Thread.currentThread().getStackTrace();
    return (" at "  + traces[level] + " " );
}

Android App Not Install. An existing package by the same name with a conflicting signature is already installed

I had the same error message, but these answers did not help. On a 4.3 nexus 7, I was using a user who was NOT the owner. I had uninstalled the older version but I kept getting the same message.

Solution: I had to login as the owner and go to Settings -> Apps, then swipe to the All tab. Scroll down to the very end of the list where the old versions are listed with a mark 'not installed'. Select it and press the 'settings' button in the top right corner and finally 'uninstall for all users'

Check if Internet Connection Exists with jQuery?

i have a solution who work here to check if internet connection exist :

$.ajax({
    url: "http://www.google.com",
    context: document.body,
    error: function(jqXHR, exception) {
        alert('Offline')
    },
    success: function() {
        alert('Online')
    }
})

Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

After some research I understand - I have very similar, but different root project locations and its cached in /bootstrap/cache. After cache clearing project started.

How can I put an icon inside a TextInput in React Native?

You can use combination of View, Icon and TextInput like so:

<View style={styles.searchSection}>
    <Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/>
    <TextInput
        style={styles.input}
        placeholder="User Nickname"
        onChangeText={(searchString) => {this.setState({searchString})}}
        underlineColorAndroid="transparent"
    />
</View>

and use flex-direction for styling

searchSection: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
},
searchIcon: {
    padding: 10,
},
input: {
    flex: 1,
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    paddingLeft: 0,
    backgroundColor: '#fff',
    color: '#424242',
},

Icons were taken from "react-native-vector-icons"

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.

However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:

  1. Make sure your system is in its normal/idle state. Stop all running processes (applications) that you started or that use CPU intensively (or poll over the network).
  2. Your datasize must be greater in size.
  3. Your test must run for something more than 5-10 seconds.
  4. Do not rely on just one sample. Perform your test N times. Collect results and calculate the mean or median of the result.

No mapping found for HTTP request with URI.... in DispatcherServlet with name

I had the same issue and after lots of reserach I found the classes were not getting published in my target folder. So I had run the below two commands from cmd

  1. mvn clean install
  2. mvn package

Surprisingly I was able to access the page and error was gone. Same can be verified from target folder where you will be able to find the complied classes which were missing earlier.

How can I refresh or reload the JFrame?

You should use this code

this.setVisible(false); //this will close frame i.e. NewJFrame

new NewJFrame().setVisible(true); // Now this will open NewJFrame for you again and will also get refreshed 

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

You need to add JAX-B dependencies when using JDK 9+. For Android Studio user, you'll need to add this to your build.gradle's dependencies {} block:

// Add missing dependencies for JDK 9+
if (JavaVersion.current().ordinal() >= JavaVersion.VERSION_1_9.ordinal()) {
    // If you're using @AutoValue or any libs that requires javax.annotation (like Dagger)
    compileOnly 'com.github.pengrad:jdk9-deps:1.0'
    compileOnly 'javax.annotation:javax.annotation-api:1.3.2'

    // If you're using Kotlin
    kapt "com.sun.xml.bind:jaxb-core:2.3.0.1"
    kapt "javax.xml.bind:jaxb-api:2.3.1"
    kapt "com.sun.xml.bind:jaxb-impl:2.3.2"

    // If you're using Java
    annotationProcessor "com.sun.xml.bind:jaxb-core:2.3.0.1"
    annotationProcessor "javax.xml.bind:jaxb-api:2.3.1"

    testAnnotationProcessor "com.sun.xml.bind:jaxb-core:2.3.0.1"
    testAnnotationProcessor "javax.xml.bind:jaxb-api:2.3.1"
}

Assert that a method was called in a Python unit test

I use Mock (which is now unittest.mock on py3.3+) for this:

from mock import patch
from PyQt4 import Qt


@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

For your case, it could look like this:

import mock
from mock import patch


def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock supports quite a few useful features, including ways to patch an object or module, as well as checking that the right thing was called, etc etc.

Caveat emptor! (Buyer beware!)

If you mistype assert_called_with (to assert_called_once or assert_called_wiht) your test may still run, as Mock will think this is a mocked function and happily go along, unless you use autospec=true. For more info read assert_called_once: Threat or Menace.

Group by & count function in sqlalchemy

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

React Native absolute positioning horizontal centre

<View style={{...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center'}}>
  <Text>CENTERD TEXT</Text>
</View>

And add this

import {StyleSheet} from 'react-native';

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

Why SpringMVC Request method 'GET' not supported?

I also had the same issue. I changed it to the following and it worked.

Java :

@RequestMapping(value = "/test", method = RequestMethod.GET)

HTML code:

  <form action="<%=request.getContextPath() %>/test" method="GET">
    <input type="submit" value="submit"> 
    </form>

By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.

Hope this helps.

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

FXCop typically prefers OrdinalIgnoreCase. But your requirements may vary.

For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.

OrdinalIgnoreCase

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx

InvariantCultureIgnoreCase

The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx

The invariant culture is the CultureInfo object returned by the InvariantCulture property.

The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.

What is a 'NoneType' object?

In the error message, instead of telling you that you can't concatenate two objects by showing their values (a string and None in this example), the Python interpreter tells you this by showing the types of the objects that you tried to concatenate. The type of every string is str while the type of the single None instance is called NoneType.

You normally do not need to concern yourself with NoneType, but in this example it is necessary to know that type(None) == NoneType.

unable to remove file that really exists - fatal: pathspec ... did not match any files

Your file .idea/workspace.xml is not under git version control. You have either not added it yet (check git status/Untracked files) or ignored it (using .gitignore or .git/info/exclude files)

You can verify it using following git command, that lists all ignored files:

git ls-files --others -i --exclude-standard

How to implement class constants?

TypeScript 2.0 has the readonly modifier:

class MyClass {
    readonly myReadOnlyProperty = 1;

    myMethod() {
        console.log(this.myReadOnlyProperty);
        this.myReadOnlyProperty = 5; // error, readonly
    }
}

new MyClass().myReadOnlyProperty = 5; // error, readonly

It's not exactly a constant because it allows assignment in the constructor, but that's most likely not a big deal.

Alternative Solution

An alternative is to use the static keyword with readonly:

class MyClass {
    static readonly myReadOnlyProperty = 1;

    constructor() {
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }

    myMethod() {
        console.log(MyClass.myReadOnlyProperty);
        MyClass.myReadOnlyProperty = 5; // error, readonly
    }
}

MyClass.myReadOnlyProperty = 5; // error, readonly

This has the benefit of not being assignable in the constructor and only existing in one place.

env: node: No such file or directory in mac

I re-installed node through this link and it fixed it.

I think the issue was that I somehow got node to be in my /usr/bin instead of /usr/local/bin.

make div's height expand with its content

You need to force a clear:both before the #main_content div is closed. I would probably move the <br class="clear" />; into the #main_content div and set the CSS to be:

.clear { clear: both; }

Update: This question still gets a fair amount of traffic, so I wanted to update the answer with a modern alternative using a new layout mode in CSS3 called Flexible boxes or Flexbox:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.flex-container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  min-height: 100vh;_x000D_
}_x000D_
_x000D_
header {_x000D_
  background-color: #3F51B5;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
section.content {_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  background-color: #FFC107;_x000D_
  color: #333;_x000D_
}
_x000D_
<div class="flex-container">_x000D_
  <header>_x000D_
    <h1>_x000D_
     Header   _x000D_
    </h1>_x000D_
  </header>_x000D_
_x000D_
  <section class="content">_x000D_
    Content_x000D_
  </section>_x000D_
_x000D_
  <footer>_x000D_
    <h4>_x000D_
      Footer_x000D_
    </h4>_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Most modern browsers currently support Flexbox and viewport units, but if you have to maintain support for older browsers, make sure to check compatibility for the specific browser version.

How do I mock an open used in a with statement (using the Mock framework in Python)?

The top answer is useful but I expanded on it a bit.

If you want to set the value of your file object (the f in as f) based on the arguments passed to open() here's one way to do it:

def save_arg_return_data(*args, **kwargs):
    mm = MagicMock(spec=file)
    mm.__enter__.return_value = do_something_with_data(*args, **kwargs)
    return mm
m = MagicMock()
m.side_effect = save_arg_return_array_of_data

# if your open() call is in the file mymodule.animals 
# use mymodule.animals as name_of_called_file
open_name = '%s.open' % name_of_called_file

with patch(open_name, m, create=True):
    #do testing here

Basically, open() will return an object and with will call __enter__() on that object.

To mock properly, we must mock open() to return a mock object. That mock object should then mock the __enter__() call on it (MagicMock will do this for us) to return the mock data/file object we want (hence mm.__enter__.return_value). Doing this with 2 mocks the way above allows us to capture the arguments passed to open() and pass them to our do_something_with_data method.

I passed an entire mock file as a string to open() and my do_something_with_data looked like this:

def do_something_with_data(*args, **kwargs):
    return args[0].split("\n")

This transforms the string into a list so you can do the following as you would with a normal file:

for line in file:
    #do action

Custom height Bootstrap's navbar

I believe you are using Bootstrap 3. If so, please try this code, here is the bootply

<header>
    <div class="navbar navbar-static-top navbar-default">
        <div class="navbar-header">
            <a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="glyphicon glyphicon-th-list"></span>
            </a>
        </div>
        <div class="container" style="background:yellow;">
            <a href="/">
                <img src="img/logo.png" class="logo img-responsive">
            </a>

            <nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
                <ul class="nav navbar-nav" style="display:inline-block;">
                    <li><a href="">Portfolio</a></li>
                    <li><a href="">Blog</a></li>
                    <li><a href="">Contact</a></li>
                </ul>
            </nav>
        </div>
    </div>
</header>

How to Count Duplicates in List with LINQ

The other solutions use GroupBy. GroupBy is slow (it holds all the elements in memory) so I wrote my own method CountBy:

public static Dictionary<TKey,int> CountBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
    var countsByKey = new Dictionary<TKey,int>();
    foreach(var x in source)
    {
        var key = keySelector(x);
        if (!countsByKey.ContainsKey(key))
            countsByKey[key] = 0;
        countsByKey[key] += 1;
    }
    return countsByKey;
}

Fastest way to convert string to integer in PHP

I personally feel casting is the prettiest.

$iSomeVar = (int) $sSomeOtherVar;

Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.

If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Hide all elements with class using plain Javascript

Late answer, but I found out that this is the simplest solution (if you don't use jQuery):

var myClasses = document.querySelectorAll('.my-class'),
    i = 0,
    l = myClasses.length;

for (i; i < l; i++) {
    myClasses[i].style.display = 'none';
}

Demo

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

How to use class from other files in C# with visual studio?

According to your explanation you haven't included your Class2.cs in your project. You have just created the required Class file but haven't included that in the project.

The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.

Do the following to overcome this,

Simply Right click on your project then -> [Add] - > [Existing Item...] : Select Class2.cs and press OK

Problem should be solved now.

Furthermore, when adding new classes use this procedure,

Right click on project -> [Add] -> Select Required Item (ex - A class, Form etc.)

How do I plot in real-time in a while loop using matplotlib?

Another option is to go with bokeh. IMO, it is a good alternative at least for real-time plots. Here is a bokeh version of the code in the question:

from bokeh.plotting import curdoc, figure
import random
import time

def update():
    global i
    temp_y = random.random()
    r.data_source.stream({'x': [i], 'y': [temp_y]})
    i += 1

i = 0
p = figure()
r = p.circle([], [])
curdoc().add_root(p)
curdoc().add_periodic_callback(update, 100)

and for running it:

pip3 install bokeh
bokeh serve --show test.py

bokeh shows the result in a web browser via websocket communications. It is especially useful when data is generated by remote headless server processes.

bokeh sample plot

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

Here are shortcuts for the IPython Notebook.

Ctrl-m i interrupts the kernel. (that is, the sole letter i after Ctrl-m)

According to this answer, I twice works as well.

How can I set the default timezone in node.js?

Set server timezone and use NTP sync. Here is one better solution to change server time.

To list timezones

timedatectl list-timezones

To set timezone

sudo timedatectl set-timezone America/New_York

Verify time zone

timedatectl

I prefer using UTC timezone for my servers and databases. Any conversions must be handled on client. We can make used of moment.js on client side.

It will be easy to maintain many instances as well,

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

Try smallR for writing quick R scripts in the command line:

http://code.google.com/p/simple-r/

(r command in the directory)

Plotting from the command line using smallR would look like this:

r -p file.txt

git: fatal: Could not read from remote repository

Go to MINGW32 terminal put this Command : git branch --set-upstream-to=origin/(branch Name)

How do I consume the JSON POST data in an Express application

For those getting an empty object in req.body

I had forgotten to set headers: {"Content-Type": "application/json"} in the request. Changing it solved the problem.

Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

Add data to JSONObject

In order to have this result:

{"aoColumnDefs":[{"aTargets":[0],"aDataSort":[0,1]},{"aTargets":[1],"aDataSort":[1,0]},{"aTargets":[2],"aDataSort":[2,3,4]}]}

that holds the same data as:

  {
    "aoColumnDefs": [
     { "aDataSort": [ 0, 1 ], "aTargets": [ 0 ] },
     { "aDataSort": [ 1, 0 ], "aTargets": [ 1 ] },
     { "aDataSort": [ 2, 3, 4 ], "aTargets": [ 2 ] }
   ]
  }

you could use this code:

    JSONObject jo = new JSONObject();
    Collection<JSONObject> items = new ArrayList<JSONObject>();

    JSONObject item1 = new JSONObject();
    item1.put("aDataSort", new JSONArray(0, 1));
    item1.put("aTargets", new JSONArray(0));
    items.add(item1);
    JSONObject item2 = new JSONObject();
    item2.put("aDataSort", new JSONArray(1, 0));
    item2.put("aTargets", new JSONArray(1));
    items.add(item2);
    JSONObject item3 = new JSONObject();
    item3.put("aDataSort", new JSONArray(2, 3, 4));
    item3.put("aTargets", new JSONArray(2));
    items.add(item3);

    jo.put("aoColumnDefs", new JSONArray(items));

    System.out.println(jo.toString());

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

How to clear cache in Yarn?

Ok I found out the answer myself. Much like npm cache clean, Yarn also has its own

yarn cache clean

Calling Python in PHP

The backquote operator will also allow you to run python scripts using similar syntax to above

In a python file called python.py:

hello = "hello"
world = "world"
print hello + " " + world

In a php file called python.php:

$python = `python python.py`;
echo $python;

How can I undo a `git commit` locally and on a remote after `git push`

You can do an interactive rebase:

git rebase -i <commit>

This will bring up your default editor. Just delete the line containing the commit you want to remove to delete that commit.

You will, of course, need access to the remote repository to apply this change there too.

See this question: Git: removing selected commits from repository

Android Studio drawable folders

This tool creates the folders with the images in them automatically for you. All you have to do is supply your image then drag the generated folders to your res folder. http://romannurik.github.io/AndroidAssetStudio/

All the best.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

What is the difference between HTML tags and elements?

lets put this in a simple term. An element is a set of opening and closing tags in use.

Element

<h1>...</h1>

Tag H1 opening tag

<h1>

H1 closing tag

</h1>

Rails - Could not find a JavaScript runtime?

I ran into this issue using Phusion Passenger (running as an nginx module) on a Redhat server. We already had a Javascript runtime installed. Other Rails apps in the same parent directory worked fine.

It turned out that we had a permissions issue. Run "ls -l" and see if the folder has the same owner and group as other working apps on the system. I had to run chown and chgrp on the folder (with the recursive switch) to fix it.

How do I pass an object from one activity to another on Android?

Your object can also implement the Parcelable interface. Then you can use the Bundle.putParcelable() method and pass your object between activities within intent.

The Photostream application uses this approach and may be used as a reference.

How do I use brew installed Python as the default Python?

Use pyenv instead to install and switch between versions of Python. I've been using rbenv for years which does the same thing, but for Ruby. Before that it was hell managing versions.

Consult pyenv's github page for installation instructions. Basically it goes like this: - Install pyenv using homebrew. brew install pyenv - Add a function to the end of your shell startup script so pyenv can do it's magic. echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

  • Use pyenv to install however many different versions of Python you need. pyenv install 3.7.7.
  • Set the default (global) version to a modern version you just installed. pyenv global 3.7.7.
  • If you work on a project that needs to use a different version of python, look into pyevn local. This creates a file in your project's folder that specifies the python version. Pyenv will look override the global python version with the version in that file.

Overloading operators in typedef structs (c++)

  1. bool operator==(pos a) const{ - this method doesn't change object's elements.
  2. bool operator==(pos a) { - it may change object's elements.

How can I set the background color of <option> in a <select> element?

_x000D_
_x000D_
select.list1 option.option2
{
    background-color: #007700;
}
_x000D_
<select class="list1">
  <option value="1">Option 1</option>
  <option value="2" class="option2">Option 2</option>
</select>
_x000D_
_x000D_
_x000D_

X-Frame-Options Allow-From multiple domains

From RFC 7034:

Wildcards or lists to declare multiple domains in one ALLOW-FROM statement are not permitted

So,

How do I set the X-Frame-Options: ALLOW-FROM to support more than a single domain?

You can't. As a workaround you can use different URLs for different partners. For each URL you can use it's own X-Frame-Options value. For example:

partner   iframe URL       ALLOW-FROM
---------------------------------------
Facebook  fb.yoursite.com  facebook.com
VK.COM    vk.yoursite.com  vk.com

For yousite.com you can just use X-Frame-Options: deny.

BTW, for now Chrome (and all webkit-based browsers) does not support ALLOW-FROM statements at all.

How to change Vagrant 'default' machine name?

If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:

Change the basebox name, when using "vagrant status"

 config.vm.define "tendo" do |tendo|
  end

Where "tendo" will be the name that will appear instead of default

MSVCP120d.dll missing

From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).

  • vc8 = Visual Studio 2005
  • vc9 = Visual Studio 2008
  • vc10 = Visual Studio 2010
  • vc11 = Visual Studio 2012
  • vc12 = Visual Studio 2013
  • vc14 = Visual Studio 2015
  • vc15 = Visual Studio 2017
  • vc16 = Visual Studio 2019

The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.

  • MSVCP80.DLL is from Visual Studio 2005
  • MSVCP90.DLL is from Visual Studio 2008
  • MSVCP100.DLL is from Visual Studio 2010
  • MSVCP110.DLL is from Visual Studio 2012
  • MSVCP120.DLL is from Visual Studio 2013
  • MSVCP140.DLL is from Visual Studio 2015, 2017 and 2019

There is binary compatibility between Visual Studio 2015, 2017 and 2019.

How can I recursively find all files in current and subfolders based on wildcard matching?

fd

In case, find is too slow, try fd utility - a simple and fast alternative to find written in Rust.

Syntax:

fd PATTERN

Demo:

Homepage: https://github.com/sharkdp/fd

Browse files and subfolders in Python

Use newDirName = os.path.abspath(dir) to create a full directory path name for the subdirectory and then list its contents as you have done with the parent (i.e. newDirList = os.listDir(newDirName))

You can create a separate method of your code snippet and call it recursively through the subdirectory structure. The first parameter is the directory pathname. This will change for each subdirectory.

This answer is based on the 3.1.1 version documentation of the Python Library. There is a good model example of this in action on page 228 of the Python 3.1.1 Library Reference (Chapter 10 - File and Directory Access). Good Luck!

Asp.net - Add blank item at top of dropdownlist

After your databind:

drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;

What character represents a new line in a text area

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

If you use anything else you will cause issues with cut and paste on Windows platforms.

The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.

Interestingly, in spite of the Unix line end convention being \n, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n. Yes, it may not make a lot of sense, but that's history and evolving standards for you!

Delete directories recursively in Java

i coded this routine that has 3 safety criteria for safer use.

package ch.ethz.idsc.queuey.util;

import java.io.File;
import java.io.IOException;

/** recursive file/directory deletion
 * 
 * safety from erroneous use is enhanced by three criteria
 * 1) checking the depth of the directory tree T to be deleted
 * against a permitted upper bound "max_depth"
 * 2) checking the number of files to be deleted #F
 * against a permitted upper bound "max_count"
 * 3) if deletion of a file or directory fails, the process aborts */
public final class FileDelete {
    /** Example: The command
     * FileDelete.of(new File("/user/name/myapp/recordings/log20171024"), 2, 1000);
     * deletes given directory with sub directories of depth of at most 2,
     * and max number of total files less than 1000. No files are deleted
     * if directory tree exceeds 2, or total of files exceed 1000.
     * 
     * abort criteria are described at top of class
     * 
     * @param file
     * @param max_depth
     * @param max_count
     * @return
     * @throws Exception if criteria are not met */
    public static FileDelete of(File file, int max_depth, int max_count) throws IOException {
        return new FileDelete(file, max_depth, max_count);
    }

    // ---
    private final File root;
    private final int max_depth;
    private int removed = 0;

    /** @param root file or a directory. If root is a file, the file will be deleted.
     *            If root is a directory, the directory tree will be deleted.
     * @param max_depth of directory visitor
     * @param max_count of files to delete
     * @throws IOException */
    private FileDelete(final File root, final int max_depth, final int max_count) throws IOException {
        this.root = root;
        this.max_depth = max_depth;
        // ---
        final int count = visitRecursively(root, 0, false);
        if (count <= max_count) // abort criteria 2)
            visitRecursively(root, 0, true);
        else
            throw new IOException("more files to be deleted than allowed (" + max_count + "<=" + count + ") in " + root);
    }

    private int visitRecursively(final File file, final int depth, final boolean delete) throws IOException {
        if (max_depth < depth) // enforce depth limit, abort criteria 1)
            throw new IOException("directory tree exceeds permitted depth");
        // ---
        int count = 0;
        if (file.isDirectory()) // if file is a directory, recur
            for (File entry : file.listFiles())
                count += visitRecursively(entry, depth + 1, delete);
        ++count; // count file as visited
        if (delete) {
            final boolean deleted = file.delete();
            if (!deleted) // abort criteria 3)
                throw new IOException("cannot delete " + file.getAbsolutePath());
            ++removed;
        }
        return count;
    }

    public int deletedCount() {
        return removed;
    }

    public void printNotification() {
        int count = deletedCount();
        if (0 < count)
            System.out.println("deleted " + count + " file(s) in " + root);
    }
}

Close pre-existing figures in matplotlib when running from eclipse

It will kill not only all plot windows, but all processes that are called python3, except the current script you run. It works for python3. So, if you are running any other python3 script it will be terminated. As I only run one script at once, it does the job for me.

import os
import subprocess
subprocess.call(["bash","-c",'pyIDs=($(pgrep python3));for x in "${pyIDs[@]}"; do if [ "$x" -ne '+str(os.getpid())+' ];then  kill -9 "$x"; fi done'])

PowerShell equivalent to grep -f

This question already has an answer, but I just want to add that in Windows there is Windows Subsystem for Linux WSL.

So for example if you want to check if you have service named Elasicsearch that is in status running you can do something like the snippet below in powershell

net start | grep Elasticsearch

Java Inheritance - calling superclass method

Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

If you write super() at that time parents's default constructor is called. same if you write super.

this keyword refers the current object same as super key word facilty for accessing parents.

C#: calling a button event handler method without actually clicking the button

You can call the btnTest_Click just like any other function.

The most basic form would be this:

btnTest_Click(this, null);

Merge two array of objects based on a key

This is a version when you have an object and an array and you want to merge them and give the array a key value so it fits into the object nicely.

_x000D_
_x000D_
var fileData = [_x000D_
    { "id" : "1", "filename" : "myfile1", "score" : 33.1 }, _x000D_
    { "id" : "2", "filename" : "myfile2", "score" : 31.4 }, _x000D_
    { "id" : "3", "filename" : "myfile3", "score" : 36.3 }, _x000D_
    { "id" : "4", "filename" : "myfile4", "score" : 23.9 }_x000D_
];_x000D_
_x000D_
var fileQuality = [0.23456543,0.13413131,0.1941344,0.7854522];_x000D_
_x000D_
var newOjbect = fileData.map((item, i) => Object.assign({}, item, {fileQuality:fileQuality[i]}));_x000D_
_x000D_
console.log(newOjbect);
_x000D_
_x000D_
_x000D_

Check if a specific tab page is selected (active)

in .Net 4 can use

if (tabControl1.Controls[5] == tabControl1.SelectedTab)
                MessageBox.Show("Tab 5 Is Selected");

OR

if ( tabpage5 == tabControl1.SelectedTab)
         MessageBox.Show("Tab 5 Is Selected");

How do I parse a URL into hostname and path in javascript?

a simple hack with the first answer

var getLocation = function(href=window.location.href) {
    var l = document.createElement("a");
    l.href = href;
    return l;
};

this can used even without argument to figure out the current hostname getLocation().hostname will give current hostname

SQL query: Delete all records from the table except latest N?

If you need to delete the records based on some other column as well, then here is a solution:

DELETE
FROM articles
WHERE id IN
    (SELECT id
     FROM
       (SELECT id
        FROM articles
        WHERE user_id = :userId
        ORDER BY created_at DESC LIMIT 500, 10000000) abc)
  AND user_id = :userId

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

How to check if Receiver is registered in Android?

i put this code in my parent activity

List registeredReceivers = new ArrayList<>();

@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    registeredReceivers.add(System.identityHashCode(receiver));
    return super.registerReceiver(receiver, filter);
}

@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
    if(registeredReceivers.contains(System.identityHashCode(receiver)))
    super.unregisterReceiver(receiver);
}

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

How do I exit from the text window in Git?

First type

 i

to enter the commit message then press ESC then type

 :wq

to save the commit message and to quit. Or type

 :q!

to quit without saving the message.

How do I set the size of an HTML text box?

Try:

input[type="text"]{
padding:10px 0;}

This is way it remains independent of what textsize has been set for the textbox. You are increasing the height using padding instead

Remove background drawable programmatically in Android

In addition to the excellent answers, if you want to achieve this via xml then you can add:

android:background="@android:color/transparent

to your view.

OnItemClickListener using ArrayAdapter for ListView

Ok, after the information that your Activity extends ListActivity here's a way to implement OnItemClickListener:

public class newListView extends ListView {

    public newListView(Context context) {
        super(context);
    }

    @Override
    public void setOnItemClickListener(
            android.widget.AdapterView.OnItemClickListener listener) {
        super.setOnItemClickListener(listener);
        //do something when item is clicked

    }

}

How to use npm with node.exe?

I am running node.js on Windows with npm. The trick is simply use cygwin. I followed the howto under https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-(Windows) . But make sure that you use version 0.4.11 of nodejs or npm will fail!

WPF ListView turn off selection

The easiest way I found:

<Setter Property="Focusable" Value="false"/>

Is there a shortcut to make a block comment in Xcode?

I modified the code of Nikola Milicevic a little bit so it also remove comment block if code is already commented:

on run {input, parameters}
    repeat with anInput in input
        if "/*" is in anInput then
            set input to replaceText("/*", "", input as string)
            set input to replaceText("*/", "", input as string)

            return input
            exit repeat
        end if
    end repeat
    return "/*" & (input as string) & "*/"
end run

on replaceText(find, replace, textString)
    set prevTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to find
    set textString to text items of textString
    set AppleScript's text item delimiters to replace
    set textString to "" & textString
    set AppleScript's text item delimiters to prevTIDs
    return textString
end replaceText

Hope this will help someone.enter image description here

Adding a directory to the PATH environment variable in Windows

A better alternative to Control Panel is to use this freeware program from SourceForge called Pathenator.

However, it only works for a system that has .NET 4.0 or greater such as Windows 7, Windows 8, or Windows 10.

javascript functions to show and hide divs

You need the link inside to be clickable, meaning it needs a href with some content, and also, close() is a built-in function of window, so you need to change the name of the function to avoid a conflict.

<div id="upbutton"><a href="#" onclick="close2()">click to close</a></div>

Also if you want a real "button" instead of a link, you should use <input type="button"/> or <button/>.

Can I use Objective-C blocks as properties?

Disclamer

This is not intended to be "the good answer", as this question ask explicitly for ObjectiveC. As Apple introduced Swift at the WWDC14, I'd like to share the different ways to use block (or closures) in Swift.

Hello, Swift

You have many ways offered to pass a block equivalent to function in Swift.

I found three.

To understand this I suggest you to test in playground this little piece of code.

func test(function:String -> String) -> String
{
    return function("test")
}

func funcStyle(s:String) -> String
{
    return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle)

let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle)

let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" })


println(resultFunc)
println(resultBlock)
println(resultAnon)

Swift, optimized for closures

As Swift is optimized for asynchronous development, Apple worked more on closures. The first is that function signature can be inferred so you don't have to rewrite it.

Access params by numbers

let resultShortAnon = test({return "ANON_" + $0 + "__ANON" })

Params inference with naming

let resultShortAnon2 = test({myParam in return "ANON_" + myParam + "__ANON" })

Trailing Closure

This special case works only if the block is the last argument, it's called trailing closure

Here is an example (merged with inferred signature to show Swift power)

let resultTrailingClosure = test { return "TRAILCLOS_" + $0 + "__TRAILCLOS" }

Finally:

Using all this power what I'd do is mixing trailing closure and type inference (with naming for readability)

PFFacebookUtils.logInWithPermissions(permissions) {
    user, error in
    if (!user) {
        println("Uh oh. The user cancelled the Facebook login.")
    } else if (user.isNew) {
        println("User signed up and logged in through Facebook!")
    } else {
        println("User logged in through Facebook!")
    }
}

What is the difference between char s[] and char *s?

In the light of comments here it should be obvious that : char * s = "hello" ; Is a bad idea, and should be used in very narrow scope.

This might be a good opportunity to point out that "const correctness" is a "good thing". Whenever and wherever You can, use the "const" keyword to protect your code, from "relaxed" callers or programmers, which are usually most "relaxed" when pointers come into play.

Enough melodrama, here is what one can achieve when adorning pointers with "const". (Note: One has to read pointer declarations right-to-left.) Here are the 3 different ways to protect yourself when playing with pointers :

const DBJ* p means "p points to a DBJ that is const" 

— that is, the DBJ object can't be changed via p.

DBJ* const p means "p is a const pointer to a DBJ" 

— that is, you can change the DBJ object via p, but you can't change the pointer p itself.

const DBJ* const p means "p is a const pointer to a const DBJ" 

— that is, you can't change the pointer p itself, nor can you change the DBJ object via p.

The errors related to attempted const-ant mutations are caught at compile time. There is no runtime space or speed penalty for const.

(Assumption is you are using C++ compiler, of course ?)

--DBJ

Convert Numeric value to Varchar

i think it should be

select convert(varchar(10),StandardCost) +'S' from DimProduct where ProductKey = 212

or

select cast(StandardCost as varchar(10)) + 'S' from DimProduct where ProductKey = 212

How to remove empty lines with or without whitespace in Python

I also tried regexp and list solutions, and list one is faster.

Here is my solution (by previous answers):

text = "\n".join([ll.rstrip() for ll in original_text.splitlines() if ll.strip()])

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

Should work for any collection except Map, but it's easy to support, too. Modify code to pass these 3 chars as arguments if needed.

static <T> String seqToString(Iterable<T> items) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    boolean needSeparator = false;
    for (T x : items) {
        if (needSeparator)
            sb.append(' ');
        sb.append(x.toString());
        needSeparator = true;
    }
    sb.append(']');
    return sb.toString();
}

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

Why powershell does not run Angular commands?

open windows powershell, run as administrater and SetExecution policy as Unrestricted then it will work.

How do I count unique visitors to my site?

Here is a nice tutorial, it is what you need. (Source: coursesweb.net/php-mysql)

Register and show online users and visitors

Count Online users and visitors using a MySQL table

In this tutorial you can learn how to register, to count, and display in your webpage the number of online users and visitors. The principle is this: each user / visitor is registered in a text file or database. Every time a page of the website is accessed, the php script deletes all records older than a certain time (eg 2 minutes), adds the current user / visitor and takes the number of records left to display.

You can store the online users and visitors in a file on the server, or in a MySQL table. In this case, I think that using a text file to add and read the records is faster than storing them into a MySQL table, which requires more requests.

First it's presented the method with recording in a text file on the server, than the method with MySQL table.

To download the files with the scripts presented in this tutorial, click -> Count Online Users and Visitors.

• Both scripts can be included in ".php" files (with include()), or in ".html" files (with <script>), as you can see in the examples presented at the bottom of this page; but the server must run PHP.

Storing online users and visitors in a text file

To add records in a file on the server with PHP you must set CHMOD 0766 (or CHMOD 0777) permissions to that file, so the PHP can write data in it.

  1. Create a text file on your server (for example, named userson.txt) and give it CHMOD 0777 permissions (in your FTP application, right click on that file, choose Properties, then select Read, Write, and Execute options).
  2. Create a PHP file (named usersontxt.php) having the code below, then copy this php file in the same directory as userson.txt.

The code for usersontxt.php;

<?php
// Script Online Users and Visitors - http://coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();        // start Session, if not already started

$filetxt = 'userson.txt';  // the file in which the online users /visitors are stored
$timeon = 120;             // number of secconds to keep a user online
$sep = '^^';               // characters used to separate the user name and date-time
$vst_id = '-vst-';        // an identifier to know that it is a visitor, not logged user

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)

    $uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the line with visitors
$nrvst = 0;                                       // to store the number of visitors

// sets the row with the current user /visitor that must be added in $filetxt (and current timestamp)

    $addrow[] = $uvon. $sep. time();

// check if the file from $filetxt exists and is writable

    if(is_writable($filetxt)) {
      // get into an array the lines added in $filetxt
      $ar_rows = file($filetxt, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
      $nrrows = count($ar_rows);

            // number of rows

  // if there is at least one line, parse the $ar_rows array

      if($nrrows>0) {
        for($i=0; $i<$nrrows; $i++) {
          // get each line and separate the user /visitor and the timestamp
          $ar_line = explode($sep, $ar_rows[$i]);
      // add in $addrow array the records in last $timeon seconds
          if($ar_line[0]!=$uvon && (intval($ar_line[1])+$timeon)>=time()) {
            $addrow[] = $ar_rows[$i];
          }
        }
      }
    }

$nruvon = count($addrow);                   // total online
$usron = '';                                    // to store the name of logged users
// traverse $addrow to get the number of visitors and users
for($i=0; $i<$nruvon; $i++) {
 if(preg_match($rgxvst, $addrow[$i])) $nrvst++;       // increment the visitors
 else {
   // gets and stores the user's name
   $ar_usron = explode($sep, $addrow[$i]);
   $usron .= '<br/> - <i>'. $ar_usron[0]. '</i>';
 }
}
$nrusr = $nruvon - $nrvst;              // gets the users (total - visitors)

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. $nruvon. '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// write data in $filetxt
if(!file_put_contents($filetxt, implode("\n", $addrow))) $reout = 'Error: Recording file not exists, or is not writable';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. If you want to include the script above in a ".php" file, add the following code in the place you want to show the number of online users and visitors:

4.To show the number of online visitors /users in a ".html" file, use this code:

<script type="text/javascript" src="usersontxt.php?uvon=showon"></script>

This script (and the other presented below) works with $_SESSION. At the beginning of the PHP file in which you use it, you must add: session_start();. Count Online users and visitors using a MySQL table

To register, count and show the number of online visitors and users in a MySQL table, require to perform three SQL queries: Delete the records older than a certain time. Insert a row with the new user /visitor, or, if it is already inserted, Update the timestamp in its column. Select the remaining rows. Here's the code for a script that uses a MySQL table (named "userson") to store and display the Online Users and Visitors.

  1. First we create the "userson" table, with 2 columns (uvon, dt). In the "uvon" column is stored the name of the user (if logged in) or the visitor's IP. In the "dt" column is stored a number with the timestamp (Unix time) when the page is accessed.
  • Add the following code in a php file (for example, named "create_userson.php"):

The code for create_userson.php:

<?php
header('Content-type: text/html; charset=utf-8');

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// check connection
if (mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

// sql query for CREATE "userson" TABLE
$sql = "CREATE TABLE `userson` (
 `uvon` VARCHAR(32) PRIMARY KEY,
 `dt` INT(10) UNSIGNED NOT NULL
 ) CHARACTER SET utf8 COLLATE utf8_general_ci"; 

// Performs the $sql query on the server to create the table
if ($conn->query($sql) === TRUE) echo 'Table "userson" successfully created';
else echo 'Error: '. $conn->error;

$conn->close();
?>
  1. Now we create the script that Inserts, Deletes, and Selects data in the userson table (For explanations about the code, see the comments in script).
  • Add the code below in another php file (named usersmysql.php): In both file you must add your personal data for connecting to MySQL database, in the variables: $host, $user, $pass, and $dbname .

The code for usersmysql.php:

<?php
// Script Online Users and Visitors - coursesweb.net/php-mysql/
if(!isset($_SESSION)) session_start();         // start Session, if not already started

// HERE add your data for connecting to MySQ database
$host = 'localhost';           // MySQL server address
$user = 'root';                // User name
$pass = 'password';            // User`s password
$dbname = 'database';          // Database name

/*
 If you have an user registration script,
 replace $_SESSION['nume'] with the variable in which the user name is stored.
 You can get a free registration script from:  http://coursesweb.net/php-mysql/register-login-script-users-online_s2
*/

// get the user name if it is logged, or the visitors IP (and add the identifier)
$vst_id = '-vst-';         // an identifier to know that it is a visitor, not logged user
$uvon = isset($_SESSION['nume']) ? $_SESSION['nume'] : $_SERVER['SERVER_ADDR']. $vst_id;

$rgxvst = '/^([0-9\.]*)'. $vst_id. '/i';         // regexp to recognize the rows with visitors
$dt = time();                                    // current timestamp
$timeon = 120;             // number of secconds to keep a user online
$nrvst = 0;                                     // to store the number of visitors
$nrusr = 0;                                     // to store the number of usersrs
$usron = '';                                    // to store the name of logged users

// connect to the MySQL server
$conn = new mysqli($host, $user, $pass, $dbname);

// Define and execute the Delete, Insert/Update, and Select queries
$sqldel = "DELETE FROM `userson` WHERE `dt`<". ($dt - $timeon);
$sqliu = "INSERT INTO `userson` (`uvon`, `dt`) VALUES ('$uvon', $dt) ON DUPLICATE KEY UPDATE `dt`=$dt";
$sqlsel = "SELECT * FROM `userson`";

// Execute each query
if(!$conn->query($sqldel)) echo 'Error: '. $conn->error;
if(!$conn->query($sqliu)) echo 'Error: '. $conn->error;
$result = $conn->query($sqlsel);

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // traverse the sets of results and set the number of online visitors and users ($nrvst, $nrusr)
  while($row = $result->fetch_assoc()) {
    if(preg_match($rgxvst, $row['uvon'])) $nrvst++;       // increment the visitors
    else {
      $nrusr++;                   // increment the users
      $usron .= '<br/> - <i>'.$row['uvon']. '</i>';          // stores the user's name
    }
  }
}

$conn->close();                  // close the MySQL connection

// the HTML code with data to be displayed
$reout = '<div id="uvon"><h4>Online: '. ($nrusr+$nrvst). '</h4>Visitors: '. $nrvst. '<br/>Users: '. $nrusr. $usron. '</div>';

// if access from <script>, with GET 'uvon=showon', adds the string to return into a JS statement
// in this way the script can also be included in .html files
if(isset($_GET['uvon']) && $_GET['uvon']=='showon') $reout = "document.write('$reout');";

echo $reout;             // output /display the result
?>
  1. After you have created these two php files on your server, run the "create_userson.php" on your browser to create the "userson" table.

  2. Include the usersmysql.php file in the php file in which you want to display the number of online users and visitors.

  3. Or, if you want to insert it in a ".html" file, add this code:

Examples using these scripts

• Including the "usersontxt.php` in a php file:

<!doctype html>

Counter Online Users and Visitors

• Including the "usersmysql.php" in a html file:

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <title>Counter Online Users and Visitors</title>
 <meta name="description" content="PHP script to count and show the number of online users and visitors" />
 <meta name="keywords" content="online users, online visitors" />
</head>
<body>

<!-- Includes the script ("usersontxt.php", or "usersmysql.php") -->
<script type="text/javascript" src="usersmysql.php?uvon=showon"></script>

</body>
</html>

Both scripts (with storing data in a text file on the server, or into a MySQL table) will display a result like this: Online: 5

Visitors: 3 Users: 2

  • MarPlo
  • Marius

XAMPP installation on Win 8.1 with UAC Warning

To disable UAC (as an administrator), from Control Panel:

Type UAC in the search button in your windows the upper right corner. Click the (Change User Account Control settings) in the search results. Drag the slider down and select Never notify and click OK.it will work.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

    NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
    [dateformat setDateFormat:@"Your Date Format"];

set the format to return is....

yyyy-MM-dd return 2015-12-17 date

yyyy-MMM-dd return 2015-Dec-17 date

yy-MM-dd return 15-12-17 date

dd-MM-yy return 17-12-15 date

dd-MM-yyyy return 17-12-2015 date

yyyy-MMM-dd HH:mm:ss return 2015-Dec-17 08:07:13 date and time

yyyy-MMM-dd HH:mm return 2015-Dec-17 08:07 date and time

For more Details Data and Time Format for Click Now.

Thank you.....

Getting attributes of Enum's value

This piece of code should give you a nice little extension method on any enum that lets you retrieve a generic attribute. I believe it's different to the lambda function above because it's simpler to use and slightly - you only need to pass in the generic type.

public static class EnumHelper
{
    /// <summary>
    /// Gets an attribute on an enum field value
    /// </summary>
    /// <typeparam name="T">The type of the attribute you want to retrieve</typeparam>
    /// <param name="enumVal">The enum value</param>
    /// <returns>The attribute of type T that exists on the enum value</returns>
    /// <example><![CDATA[string desc = myEnumVariable.GetAttributeOfType<DescriptionAttribute>().Description;]]></example>
    public static T GetAttributeOfType<T>(this Enum enumVal) where T:System.Attribute
    {
        var type = enumVal.GetType();
        var memInfo = type.GetMember(enumVal.ToString());
        var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
        return (attributes.Length > 0) ? (T)attributes[0] : null;
    }
}

How to expire a cookie in 30 minutes using jQuery?

I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);

This was from the FAQs for Cookie.js

Difference between String replace() and replaceAll()

From Java 9 there is some optimizations in replace method.

In Java 8 it uses a regex.

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

From Java 9 and on.

enter image description here

And Stringlatin implementation.

enter image description here

Which perform way better.

https://medium.com/madhash/composite-pattern-in-a-nutshell-ad1bf78479cc?source=post_internal_links---------2------------------

How can I use a JavaScript variable as a PHP variable?

You can take all values like this:

$abc = "<script>document.getElementByID('yourid').value</script>";

Position: absolute and parent height?

Here is my workaround,
In your example you can add a third element with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:

HTML

<article>
   <div class="one"></div>
   <div class="two"></div>
   <div class="three"></div>
</article>

CSS

.three{
    height: 30px;
    z-index: -1;
    visibility: hidden;
}

How to stop PHP code execution?

or try

trigger_error('Die', E_ERROR);

How to upgrade PowerShell version from 2.0 to 3.0

do use the links above. If you run into error "This update is not applicable to your computer. " then make sure you are in fact using the right file for your os. for example i tried running windows 2012 server from that link on windows 7 service pack 1 and I got the above error so be sure to use the right zip. If you don't know which os you have then go to start and system and it should pop right up This should be self explanatory but

Java "lambda expressions not supported at this language level"

Just add compileOptions in build.gradle yours app:

android {


...

  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

How to get the body's content of an iframe in Javascript?

AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.

Here's how to get its body content using plane old javascript. This works with both IE and Firefox.

function getFrameContents(){
   var iFrame =  document.getElementById('id_description_iframe');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   }
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
   }
    alert(iFrameBody.innerHTML);
 }

Error - replacement has [x] rows, data has [y]

The answer by @akrun certainly does the trick. For future googlers who want to understand why, here is an explanation...

The new variable needs to be created first.

The variable "valueBin" needs to be already in the df in order for the conditional assignment to work. Essentially, the syntax of the code is correct. Just add one line in front of the code chuck to create this name --

df$newVariableName <- NA

Then you continue with whatever conditional assignment rules you have, like

df$newVariableName[which(df$oldVariableName<=250)] <- "<=250"

I blame whoever wrote that package's error message... The debugging was made especially confusing by that error message. It is irrelevant information that you have two arrays in the df with different lengths. No. Simply create the new column first. For more details, consult this post https://www.r-bloggers.com/translating-weird-r-errors/

Can I add extension methods to an existing static class?

It's not possible.

And yes, I think MS made a mistake here.

Their decision does not make sense and forces programmers to write (as described above) a pointless wrapper class.

Here is a good example: Trying to extend static MS Unit testing class Assert: I want 1 more Assert method AreEqual(x1,x2).

The only way to do this is to point to different classes or write a wrapper around 100s of different Assert methods. Why!?

If the decision was being made to allow extensions of instances, I see no logical reason to not allow static extensions. The arguments about sectioning libraries does not stand up once instances can be extended.

REST API Token-based Authentication

Let me seperate up everything and solve approach each problem in isolation:

Authentication

For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.

Auth server load

If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.

Transmission Security

If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.

url = username:[email protected]/api/call/nonce

If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:

nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call

It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).

Secure secret storage

It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.

If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.

(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.

How to get a responsive button in bootstrap 3

In Bootstrap, the .btn class has a white-space: nowrap; property, making it so that the button text won't wrap. So, after setting that to normal, and giving the button a width, the text should wrap to the next line if the text would exceed the set width.

#new-board-btn {
    white-space: normal;
}

http://jsfiddle.net/ADewB/

Only variables should be passed by reference

Since it raise a flag for over 10 years, but works just fine and return the expected value, a little stfu operator is the goodiest bad practice you are all looking for:

$file_extension = @end(explode('.', $file_name));

But warning, don't use in loops due to a performance hit. Newest version of php 7.3+ offer the method array_key_last() and array_key_first().

https://www.php.net/manual/en/function.array-key-last.php

How to draw rounded rectangle in Android UI?

Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

Why .NET String is immutable?

Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.

If you don't believe me look at the String.Concat definition using reflector. The last lines are...

int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;

As you can see the FastAllocateString returns an empty but allocated string and then it is modified by FillStringChecked

Actually the FastAllocateString is an extern method and the FillStringChecked is unsafe so it uses pointers to copy the bytes.

Maybe there are better examples but this is the one I have found so far.

What version of Python is on my Mac?

Use the which command. It will show you the path

which python

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

I added a "long" version to Leo Dabus's asnwer in case you want to have a string that says something like "2 weeks ago" instead of just "2w"...

extension Date {
    /// Returns the amount of years from another date
    func years(from date: Date) -> Int {
        return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0
    }
    /// Returns the amount of months from another date
    func months(from date: Date) -> Int {
        return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0
    }
    /// Returns the amount of weeks from another date
    func weeks(from date: Date) -> Int {
        return Calendar.current.dateComponents([.weekOfYear], from: date, to: self).weekOfYear ?? 0
    }
    /// Returns the amount of days from another date
    func days(from date: Date) -> Int {
        return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0
    }
    /// Returns the amount of hours from another date
    func hours(from date: Date) -> Int {
        return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
    }
    /// Returns the amount of minutes from another date
    func minutes(from date: Date) -> Int {
        return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0
    }
    /// Returns the amount of seconds from another date
    func seconds(from date: Date) -> Int {
        return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0
    }
    /// Returns the a custom time interval description from another date
    func offset(from date: Date) -> String {
        if years(from: date)   > 0 { return "\(years(from: date))y"   }
        if months(from: date)  > 0 { return "\(months(from: date))M"  }
        if weeks(from: date)   > 0 { return "\(weeks(from: date))w"   }
        if days(from: date)    > 0 { return "\(days(from: date))d"    }
        if hours(from: date)   > 0 { return "\(hours(from: date))h"   }
        if minutes(from: date) > 0 { return "\(minutes(from: date))m" }
        if seconds(from: date) > 0 { return "\(seconds(from: date))s" }
        return ""
    }

    func offsetLong(from date: Date) -> String {
        if years(from: date)   > 0 { return years(from: date) > 1 ? "\(years(from: date)) years ago" : "\(years(from: date)) year ago" }
        if months(from: date)  > 0 { return months(from: date) > 1 ? "\(months(from: date)) months ago" : "\(months(from: date)) month ago" }
        if weeks(from: date)   > 0 { return weeks(from: date) > 1 ? "\(weeks(from: date)) weeks ago" : "\(weeks(from: date)) week ago"   }
        if days(from: date)    > 0 { return days(from: date) > 1 ? "\(days(from: date)) days ago" : "\(days(from: date)) day ago" }
        if hours(from: date)   > 0 { return hours(from: date) > 1 ? "\(hours(from: date)) hours ago" : "\(hours(from: date)) hour ago"   }
        if minutes(from: date) > 0 { return minutes(from: date) > 1 ? "\(minutes(from: date)) minutes ago" : "\(minutes(from: date)) minute ago" }
        if seconds(from: date) > 0 { return seconds(from: date) > 1 ? "\(seconds(from: date)) seconds ago" : "\(seconds(from: date)) second ago" }
        return ""
    }

}

Android textview outline text

I've just been trying to figure out how to do this and couldn't find a good guide online but eventually figured it out. As Steve Pomeroy suggested, you do have to do something more involved. In order to get the outlined text effect, you draw the text twice: once with a thick outline and then the second time we draw the main text over the outline. But, the task is made easier because you can very easily adapt one of the code samples provided with the SDK, namely the one under this name in your SDK directory: "/samples/android-/ApiDemos/src/com/example/android/apis/view/LabelView.java". Which can also found on the Android developer website here.

Depending on what you're doing, it's very easy to see you will only need to make minor modifications to that code, such as changing it to extend from TextView, etc. Before I discovered this sample I forgot to override onMeasure() (which you must do in addition to overriding onDraw() as is mentioned in the "Building Custom Components" guide on the Android Developer website), which is part of why I was having trouble.

Once you've done that, you can do what I did:

public class TextViewOutline extends TextView {

private Paint mTextPaint;
private Paint mTextPaintOutline; //add another paint attribute for your outline
...
//modify initTextViewOutline to setup the outline style
   private void initTextViewOutline() {
       mTextPaint = new Paint();
       mTextPaint.setAntiAlias(true);
       mTextPaint.setTextSize(16);
       mTextPaint.setColor(0xFF000000);
       mTextPaint.setStyle(Paint.Style.FILL);

       mTextPaintOutline = new Paint();
       mTextPaintOutline.setAntiAlias(true);
       mTextPaintOutline.setTextSize(16);
       mTextPaintOutline.setColor(0xFF000000);
       mTextPaintOutline.setStyle(Paint.Style.STROKE);
       mTextPaintOutline.setStrokeWidth(4);

       setPadding(3, 3, 3, 3);
}
...
//make sure to update other methods you've overridden to handle your new paint object
...
//and finally draw the text, mAscent refers to a member attribute which had
//a value assigned to it in the measureHeight and Width methods
   @Override
   protected void onDraw(Canvas canvas) {
       super.onDraw(canvas);
       canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, 
           mTextPaintOutline);
       canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
   }

So, in order to get the outlined text effect, you draw the text twice: once with a thick outline and then the second time we draw the main text over the outline.

Open a URL in a new tab (and not a new window)

You can use a trick with form:

$(function () {
    $('#btn').click(function () {
        openNewTab("http://stackoverflow.com")
        return false;
    });
});

function openNewTab(link) {
    var frm = $('<form   method="get" action="' + link + '" target="_blank"></form>')
    $("body").append(frm);
    frm.submit().remove();
}

jsFiddle demo

How to parse JSON in Kotlin?

A bit late, but whatever.

If you prefer parsing JSON to JavaScript-like constructs making use of Kotlin syntax, I recommend JSONKraken, of which I am the author.

Suggestions and opinions on the matter are much apreciated!

Change private static final field using Java reflection

The whole point of a final field is that it cannot be reassigned once set. The JVM uses this guarentee to maintain consistency in various places (eg inner classes referencing outer variables). So no. Being able to do so would break the JVM!

The solution is not to declare it final in the first place.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

compression and decompression of string data in java

The above Answer solves our problem but in addition to that. if we are trying to decompress a uncompressed("not a zip format") byte[] . we will get "Not in GZIP format" exception message.

For solving that we can add addition code in our Class.

public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}

My Complete Compression Class with compress/decompress would look like:

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompression {
  public static byte[] compress(final String str) throws IOException {
    if ((str == null) || (str.length() == 0)) {
      return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();
    return obj.toByteArray();
  }

  public static String decompress(final byte[] compressed) throws IOException {
    final StringBuilder outStr = new StringBuilder();
    if ((compressed == null) || (compressed.length == 0)) {
      return "";
    }
    if (isCompressed(compressed)) {
      final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
      final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        outStr.append(line);
      }
    } else {
      outStr.append(compressed);
    }
    return outStr.toString();
  }

  public static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
  }
}

Read input stream twice

Convert inputstream into bytes and then pass it to savefile function where you assemble the same into inputstream. Also in original function use bytes to use for other tasks

Check if a varchar is a number (TSQL)

Do not forget to exclude carriage returns from your data !!!

as in:

SELECT 
  Myotherval
  , CASE WHEN TRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '%[^0-9]%' and RTRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '.' and isnumeric(REPLACE([MyVal], char(13) + char(10), '')) = 1 THEN 'my number: ' +  [MyVal]
             ELSE ISNULL(Cast([MyVal] AS VARCHAR(8000)), '')
        END AS 'MyVal'
FROM MyTable

apt-get for Cygwin?

you can always make a bash alias to setup*.exe files in $home/.bashrc

cygwin 32bit

alias cyg-get="/cygdrive/c/cygwin/setup-x86.exe -q -P"

cygwin 64bit

alias cyg-get="/cygdrive/c/cygwin64/setup-x86_64.exe -q -P"

now you can install packages with

cyg-get <package>

What should be the values of GOPATH and GOROOT?

If you are using the distro go, you should point to where the include files are, for example:

$ rpm -ql golang | grep include
/usr/lib/golang/include

(This is for Fedora 20)

What's wrong with using == to compare floats in Java?

This is a problem not specific to java. Using == to compare two floats/doubles/any decimal type number can potentially cause problems because of the way they are stored. A single-precision float (as per IEEE standard 754) has 32 bits, distributed as follows:

1 bit - Sign (0 = positive, 1 = negative)
8 bits - Exponent (a special (bias-127) representation of the x in 2^x)
23 bits - Mantisa. The actuall number that is stored.

The mantisa is what causes the problem. It's kinda like scientific notation, only the number in base 2 (binary) looks like 1.110011 x 2^5 or something similar. But in binary, the first 1 is always a 1 (except for the representation of 0)

Therefore, to save a bit of memory space (pun intended), IEEE deccided that the 1 should be assumed. For example, a mantisa of 1011 really is 1.1011.

This can cause some issues with comparison, esspecially with 0 since 0 cannot possibly be represented exactly in a float. This is the main reason the == is discouraged, in addition to the floating point math issues described by other answers.

Java has a unique problem in that the language is universal across many different platforms, each of which could have it's own unique float format. That makes it even more important to avoid ==.

The proper way to compare two floats (not-language specific mind you) for equality is as follows:

if(ABS(float1 - float2) < ACCEPTABLE_ERROR)
    //they are approximately equal

where ACCEPTABLE_ERROR is #defined or some other constant equal to 0.000000001 or whatever precision is required, as Victor mentioned already.

Some languages have this functionality or this constant built in, but generally this is a good habit to be in.

Xcode build failure "Undefined symbols for architecture x86_64"

Could also be an #include <windows.h> in the .c file that you're trying to compile.

How to bind an enum to a combobox control in WPF?

I used another solution using MarkupExtension.

  1. I made class which provides items source:

    public class EnumToItemsSource : MarkupExtension
    {
        private readonly Type _type;
    
        public EnumToItemsSource(Type type)
        {
            _type = type;
        }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Enum.GetValues(_type)
                .Cast<object>()
                .Select(e => new { Value = (int)e, DisplayName = e.ToString() });
        }
    }
    
  2. That's almost all... Now use it in XAML:

        <ComboBox DisplayMemberPath="DisplayName"
              ItemsSource="{persons:EnumToItemsSource {x:Type enums:States}}"
              SelectedValue="{Binding Path=WhereEverYouWant}"
              SelectedValuePath="Value" />
    
  3. Change 'enums:States' to your enum

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

In php 7 you can do:

$_POST['value'] ?? null;

If value is equal to '' as said in other answers it will also send you null.

Animate the transition between fragments

Try using this simple and fasted solution. Android provides some default animations.

fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.replace(R.id.frame, firstFragment, "h");
fragmentTransaction.addToBackStack("h");
fragmentTransaction.commit();

Output:

enter image description here

Saving a select count(*) value to an integer (SQL Server)

Declare @MyInt int
Set @MyInt = ( Select Count(*) From MyTable )

If @MyInt > 0
Begin
    Print 'There''s something in the table'
End

I'm not sure if this is your issue, but you have to esacpe the single quote in the print statement with a second single quote. While you can use SELECT to populate the variable, using SET as you have done here is just fine and clearer IMO. In addition, you can be guaranteed that Count(*) will never return a negative value so you need only check whether it is greater than zero.

google-services.json for different productFlavors

    ...
    gradle.taskGraph.beforeTask { Task task ->
        if (task.name ==~ /process.*GoogleServices/) {
            android.applicationVariants.all { variant ->
                if (task.name ==~ /(?i)process${variant.flavorName}(Debug|Release)GoogleServices/) {
                    copy {
                        from "src/tenants/${variant.flavorName}"
                        include 'google-services.json'
                        into '.'
                    }
                }
            }
        }
    }

    gradle.taskGraph.afterTask { Task task ->
        if (task.name ==~ /process.*GoogleServices/) {
            android.applicationVariants.all { variant ->
                if (task.name ==~ /(?i)process${variant.flavorName}(Debug|Release)GoogleServices/) {
                    delete fileTree(".").matching {
                        include 'google-services.json'
                    }
                }
            }
        }
    }

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

Open links in new window using AngularJS

It works for me. Inject $window service in to your controller.

$window.open("somepath/", "_blank")

How can I use ":" as an AWK field separator?

If you want to do it programatically, you can use the FS variable:

echo "1: " | awk 'BEGIN { FS=":" } /1/ { print $1 }'

Note that if you change it in the main loop rather than the BEGIN loop, it takes affect for the next line read in, since the current line has already been split.

Best way to save a trained model in PyTorch?

I've found this page on their github repo, I'll just paste the content here.


Recommended approach for saving a model

There are two main approaches for serializing and restoring a model.

The first (recommended) saves and loads only the model parameters:

torch.save(the_model.state_dict(), PATH)

Then later:

the_model = TheModelClass(*args, **kwargs)
the_model.load_state_dict(torch.load(PATH))

The second saves and loads the entire model:

torch.save(the_model, PATH)

Then later:

the_model = torch.load(PATH)

However in this case, the serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors.

Good Hash Function for Strings

You should probably use String.hashCode().

If you really want to implement hashCode yourself:

Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance -- Joshua Bloch, Effective Java

Using only the first five characters is a bad idea. Think about hierarchical names, such as URLs: they will all have the same hash code (because they all start with "http://", which means that they are stored under the same bucket in a hash map, exhibiting terrible performance.

Here's a war story paraphrased on the String hashCode from "Effective Java":

The String hash function implemented in all releases prior to 1.2 examined at most sixteen characters, evenly spaced throughout the string, starting with the first character. For large collections of hierarchical names, such as URLs, this hash function displayed terrible behavior.

Call to a member function on a non-object

It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?

As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:

function page_properties(PageAtrributes $objPortal) {    
    ...
    $objPage->set_page_title($myrow['title']);
}

This function will only accept PageAtrributes for the first parameter.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

I have solved this problem with the following code.

public WebElement waitForElement(final By findBy, final int waitTime) {
    Wait<AppiumDriver> wait = new FluentWait<>((AppiumDriver) driver)
            .withTimeout(waitTime, TimeUnit.SECONDS)
            .pollingEvery(POLL_TIME, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class,StaleElementReferenceException.class);

    WebElement webElement = wait.until(new Function<AppiumDriver, WebElement>() {
        @Override
        public WebElement apply(AppiumDriver driver) {
            System.out.println("Trying to find element " + findBy.toString());                
            WebElement element = driver.findElement(findBy);
            return element;
        }
    });
    return webElement;
}

HTML input - name vs. id

IDs must be unique

...within page DOM element tree so each control is individually accessible by its id on the client side (within browser page) by

  • Javascript scripts loaded in the page
  • CSS styles defined on the page

Having non-unique IDs on your page will still render your page, but it certainly won't be valid. Browsers are quite forgiving when parsing invalid HTML. but don't do that just because it seems that it works.

Names are quite often unique but can be shared

...within page DOM between several controls of the same type (think of radio buttons) so when data gets POSTed to server only a particular value gets sent. So when you have several radio buttons on your page, only the selected one's value gets posted back to server even though there are several related radio button controls with the same name.

Addendum to sending data to server: When data gets sent to server (usually by means of HTTP POST request) all data gets sent as name-value pairs where name is the name of the input HTML control and value is its value as entered/selected by the user. This is always true for non-Ajax requests. In Ajax requests name-value pairs can be independent of HTML input controls on the page, because developers can send whatever they want to the server. Quite often values are also read from input controls, but I'm just trying to say that this is not necessarily the case.

When names can be duplicated

It may sometimes be beneficial that names are shared between controls of any form input type. But when? You didn't state what your server platform may be, but if you used something like Asp.net MVC you get the benefit of automatic data validation (client and server) and also binding sent data to strong types. That means that those names have to match type property names.

Now suppose you have this scenario:

  • you have a view with a list of items of the same type
  • user usually works with one item at a time, so they will only enter data with one item alone and send it to server

So your view's model (since it displays a list) is of type IEnumerable<SomeType> but your server side only accepts one single item of type SomeType.

How about name sharing then?

Each item is wrapped within its own FORM element and input elements within it have the same names so when data gets to the server (from any element) it gets correctly bound to the string type expected by the controller action.

This particular scenario can be seen on my Creative stories mini-site. You won't understand the language, but you can check out those multiple forms and shared names. Never mind that IDs are also duplicated (which is a rule violation) but that could be solved. It just doesn't matter in this case.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I want to add another pitfall. Even if you did everything right, you may get trapped by this error if you support more than one target in your build process.

The image asset catalog is part of a target and even if you selected it in Xcode5 to be used for your target, it does not mean it is automatically added.

As a result, the build works like a charm, but the asset catalog is not added to the IPA and the AppStore validation fails with the Error, that the icons are missing.

To fix or check that the assets are part of the target, select the assets-entry in the Xcode project and make sure your target is checked in the inspector.

Where do I find some good examples for DDD?

The difficulty with DDD samples is that they're often very domain specific and the technical implementation of the resulting system doesn't always show the design decisions and transitions that were made in modelling the domain, which is really at the core of DDD. DDD is much more about the process than it is the code. (as some say, the best DDD sample is the book itself!)

That said, a well commented sample app should at least reveal some of these decisions and give you some direction in terms of matching up your domain model with the technical patterns used to implement it.

You haven't specified which language you're using, but I'll give you a few in a few different languages:

DDDSample - a Java sample that reflects the examples Eric Evans talks about in his book. This is well commented and shows a number of different methods of solving various problems with separate bounded contexts (ie, the presentation layer). It's being actively worked on, so check it regularly for updates.

dddps - Tim McCarthy's sample C# app for his book, .NET Domain-Driven Design with C#

S#arp Architecture - a pragmatic C# example, not as "pure" a DDD approach perhaps due to its lack of a real domain problem, but still a nice clean approach.

With all of these sample apps, it's probably best to check out the latest trunk versions from SVN/whatever to really get an idea of the thinking and technology patterns as they should be updated regularly.

How can I get the browser's scrollbar sizes?

function getScrollBarWidth() {
    return window.innerWidth - document.documentElement.clientWidth;
}

Most of the browser use 15px for the scrollbar width

PIG how to count a number of rows in alias

What you want is to count all the lines in a relation (dataset in Pig Latin)

This is very easy following the next steps:

logs = LOAD 'log'; --relation called logs, using PigStorage with tab as field delimiter
logs_grouped = GROUP logs ALL;--gives a relation with one row with logs as a bag
number = FOREACH LOGS_GROUP GENERATE COUNT_STAR(logs);--show me the number

I have to say it is important Kevin's point as using COUNT instead of COUNT_STAR we would have only the number of lines which first field is not null.

Also I like Jerome's one line syntax it is more concise but in order to be didactic I prefer to divide it in two and add some comment.

In general I prefer:

numerito = FOREACH (GROUP CARGADOS3 ALL) GENERATE COUNT_STAR(CARGADOS3);

over

name = GROUP CARGADOS3 ALL
number = FOREACH name GENERATE COUNT_STAR(CARGADOS3);

access key and value of object using *ngFor

Have Object.keys accessible in the template and use it in *ngFor.

@Component({
  selector: 'app-myview',
  template: `<div *ngFor="let key of objectKeys(items)">{{key + ' : ' + items[key]}}</div>`
})

export class MyComponent {
  objectKeys = Object.keys;
  items = { keyOne: 'value 1', keyTwo: 'value 2', keyThree: 'value 3' };
  constructor(){}
}

How to "properly" create a custom object in JavaScript?

When one uses the trick of closing on "this" during a constructor invocation, it's in order to write a function that can be used as a callback by some other object that doesn't want to invoke a method on an object. It's not related to "making the scope correct".

Here's a vanilla JavaScript object:

function MyThing(aParam) {
    var myPrivateVariable = "squizzitch";

    this.someProperty = aParam;
    this.useMeAsACallback = function() {
        console.log("Look, I have access to " + myPrivateVariable + "!");
    }
}

// Every MyThing will get this method for free:
MyThing.prototype.someMethod = function() {
    console.log(this.someProperty);
};

You might get a lot out of reading what Douglas Crockford has to say about JavaScript. John Resig is also brilliant. Good luck!

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:

1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok

I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use

Vue.js - How to properly watch for nested data

You can use a deep watcher for that:

watch: {
  item: {
     handler(val){
       // do stuff
     },
     deep: true
  }
}

This will now detect any changes to the objects in the item array and additions to the array itself (when used with Vue.set). Here's a JSFiddle: http://jsfiddle.net/je2rw3rs/

EDIT

If you don't want to watch for every change on the top level object, and just want a less awkward syntax for watching nested objects directly, you can simply watch a computed instead:

var vm = new Vue({
  el: '#app',
  computed: {
    foo() {
      return this.item.foo;
    }
  },
  watch: {
    foo() {
      console.log('Foo Changed!');
    }
  },
  data: {
    item: {
      foo: 'foo'
    }
  }
})

Here's the JSFiddle: http://jsfiddle.net/oa07r5fw/

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Im new to java hibernate but i could solve this problem, this is how i did it : I was working with hibernate and maven project. First you have to put persistence.xml under project directory, then add jdbc manually. Maven couldn't download my dependency so i added it manually. In the persistence.xml in design jdbc connection add it manually ps: i work with netbeans good luck

In Javascript, how to conditionally add a member to an object?

more simplified,

const a = {
    ...(condition && {b: 1}) // if condition is true 'b' will be added.
}

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

Redirect website after certain amount of time

The simplest way is using HTML META tag like this:

<meta http-equiv="refresh" content="3;url=http://example.com/" />

Wikipedia

"unmappable character for encoding" warning in Java

Gradle Steps

If you are using Gradle then you can find the line that applies the java plugin:

apply plugin: 'java'

Then set the encoding for the compile task to be UTF-8:

compileJava {options.encoding = "UTF-8"}   

If you have unit tests, then you probably want to compile those with UTF-8 too:

compileTestJava {options.encoding = "UTF-8"}

Overall Gradle Example

This means that the overall gradle code would look something like this:

apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
compileTestJava {options.encoding = "UTF-8"}

Java: how do I check if a Date is within a certain range?

tl;dr

ZoneId z = ZoneId.of( "America/Montreal" );  // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone.
LocalDate ld = 
    givenJavaUtilDate.toInstant()  // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes.
                     .atZone( z )  // Adjust into the time zone in order to determine date.
                     .toLocalDate();  // Extract date-only value.

LocalDate today = LocalDate.now( z );  // Get today’s date for specific time zone.
LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 );  // Kwanzaa starts on Boxing Day, day after Christmas.
LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 );  // Kwanzaa lasts one week.
Boolean isDateInKwanzaaThisYear = (
    ( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after".
    &&
    today.isBefore( kwanzaaStop )  // Half-Open span of time, beginning inclusive, ending is *exclusive*.
)

Half-Open

Date-time work commonly employs the "Half-Open" approach to defining a span of time. The beginning is inclusive while the ending is exclusive. So a week starting on a Monday runs up to, but does not include, the following Monday.

java.time

Java 8 and later comes with the java.time framework built-in. Supplants the old troublesome classes including java.util.Date/.Calendar and SimpleDateFormat. Inspired by the successful Joda-Time library. Defined by JSR 310. Extended by the ThreeTen-Extra project.

An Instant is a moment on the timeline in UTC with nanosecond resolution.

Instant

Convert your java.util.Date objects to Instant objects.

Instant start = myJUDateStart.toInstant();
Instant stop = …

If getting java.sql.Timestamp objects through JDBC from a database, convert to java.time.Instant in a similar way. A java.sql.Timestamp is already in UTC so no need to worry about time zones.

Instant start = mySqlTimestamp.toInstant() ;
Instant stop = …

Get the current moment for comparison.

Instant now = Instant.now();

Compare using the methods isBefore, isAfter, and equals.

Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ;

LocalDate

Perhaps you want to work with only the date, not the time-of-day.

The LocalDate class represents a date-only value, without time-of-day and without time zone.

LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;

To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

We can use the isEqual, isBefore, and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.

Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ;

Interval

If you chose to add the ThreeTen-Extra library to your project, you could use the Interval class to define a span of time. That class offers methods to test if the interval contains, abuts, encloses, or overlaps other date-times/intervals.

The Interval class works on Instant objects. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

We can adjust the LocalDate into a specific moment, the first moment of the day, by specifying a time zone to get a ZonedDateTime. From there we can get back to UTC by extracting a Instant.

ZoneId z = ZoneId.of( "America/Montreal" );
Interval interval = 
    Interval.of( 
        start.atStartOfDay( z ).toInstant() , 
        stop.atStartOfDay( z ).toInstant() );
Instant now = Instant.now();
Boolean containsNow = interval.contains( now );

About java.time

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

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

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

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
  • Built-in.
  • Part of the standard Java API with a bundled implementation.
  • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
  • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
  • See How to use….

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

adb connection over tcp not working now

I couldn't do it on a Galaxy S3 (non rooted).

For me it would hang saying...

restaring in tcp mode

So i found this series of commands quite useful.

First disconnect your device, start from scratch (cmd in admin mode and all the stuff).

connect your device and write in CMD/Terminal:

adb kill-server

control should return as normal. Now type and enter

adb tcpip 5555

you will see..

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully * restarting in TCP mode port: 5555

and then connect device with

adb connect <IP>

That's how it worked for me after a lot of hassle!

UPDATE FOR ANDROID STUDIO

I noticed this doesn't work sometimes, even after correctly repeating steps a number of times. Catch was; sometimes ADB is yet not initialized by Studio unless, Android Tab at the bottom is opened and you see "Initializing Android Studio".

You will large Initializing text.

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

just right click on your project, hover maven then click update project.. done!!

How can I change text color via keyboard shortcut in MS word 2010

You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.

if arguments is equal to this string, define a variable like this string

Don't forget about spaces:

source=""
samples=("")
if [ $1 = "country" ]; then
   source="country"
   samples="US Canada Mexico..."
else
  echo "try again"
fi

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Best C++ IDE or Editor for Windows

vi or gvim if you don't like terminals.

Does overflow:hidden applied to <body> work on iPhone Safari?

After many days trying, I found this solution that worked for me:

touch-action: none;
-ms-touch-action: none;

Parsing JSON array with PHP foreach

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

I had the same issue when I changed the home directory of one use. In my case it was because of selinux. I used the below to fix the issue:

selinuxenabled 0
setenforce 0

Uploading Laravel Project onto Web Server

If you are trying to host your Laravel app on a shared hosting, this may help you.

Hosting Laravel on shared hosting #1

Hosting Laravel on shared hosting #2

If you want PHP 5.4 add this line to your .htaccess file or call your hosting provider.

AddType application/x-httpd-php54 .php

What is the purpose of backbone.js?

Backbone.js is basically an uber-light framework that allows you to structure your Javascript code in an MVC (Model, View, Controller) fashion where...

Model is part of your code that retrieves and populates the data,

View is the HTML representation of this model (views change as models change, etc.)

and optional Controller that in this case allows you to save the state of your Javascript application via a hashbang URL, for example: http://twitter.com/#search?q=backbone.js

Some pros that I discovered with Backbone:

  • No more Javascript Spaghetti: code is organized and broken down into semantically meaningful .js files which are later combined using JAMMIT

  • No more jQuery.data(bla, bla): no need to store data in DOM, store data in models instead

  • event binding just works

  • extremely useful Underscore utility library

  • backbone.js code is well documented and a great read. Opened my eyes to a number of JS code techniques.

Cons:

  • Took me a while to wrap my head around it and figure out how to apply it to my code, but I'm a Javascript newbie.

Here is a set of great tutorials on using Backbone with Rails as the back-end:

CloudEdit: A Backbone.js Tutorial with Rails:

http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/

http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/

p.s. There is also this wonderful Collection class that lets you deal with collections of models and mimic nested models, but I don't want to confuse you from the start.

How to update npm

don't forget to close and start the terminal window again ;)

(at least if you want to check "npm --version" in the terminal)

sudo npm install npm -g

that did the trick for me, too

What are the proper permissions for an upload folder with PHP/Apache?

You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them.

Windows 10 SSH keys

  1. Open the windows command line (type "cmd" on the search box and hit enter).
  2. It'll default to your home folder, so you don't need to cd to a different one.
  3. Type ssh-keygen
  4. Follow the instructions and you are good to go
  5. Your ssh keys should be stored at chosed directory, the default is: /c/Users/YourUserName/.ssh/id_rsa.pub

p.s.: If you installed git with bash integration (like me) open "Git Bash" instead of "cmd" on first step

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

I think the question here is how to find .bashrc file on Windows.

Since you are using Windows, you can simply use commands like

start .

OR

explorer .

to open the window with the root directory of your Git Bash installation where you'll find the .bashrc file. You may need to create one if it doesn't exist.

You can use Windows tools like Notepad++ to edit the file instead of using Vim in your Bash window.

What is the Swift equivalent of respondsToSelector?

I guess you want to make a default implementation for delegate. You can do this:

let defaultHandler = {}
(delegate?.method ?? defaultHandler)()

Converting string to Date and DateTime

If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:

/**
 * Quietly convert European format to American format
 *
 * Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
 * as well as all other built-in formats
 * 
 */
class CustomDateTime extends DateTime 
{
  public function __construct(string $time="now", DateTimeZone $timezone = null) 
  {
    // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
    $time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );

    parent::__construct($time, $timezone);
  }
}

// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');

// => '2019-07-24'

Or, you can make a function to accept m-d-Y and output Y-m-d:

/**
 * Accept dates in various m, d, y formats and return as Y-m-d
 * 
 * Changes PHP's default behaviour for dates with dashes or dots.
 * Accepts:
 *   m-d-y, m-d-Y, Y-m-d,
 *   m.d.y, m.d.Y, Y.m.d,
 *   m/d/y, m/d/Y, Y/m/d,
 *   ... and all other formats natively supported 
 * 
 * Unsupported formats or invalid dates will generate an Exception
 * 
 * @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
 * @param  string $d various representations of date
 * @return string    Y-m-d or '----' for null or blank
 */
function asYmd($d) {
  if(is_null($d) || $d=='') { return '----'; }

  // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
  $d = str_replace(['-','.'], '/', $d);

  return (new DateTime($d))->format('Y-m-d');
}

// usage:

<?= asYmd('7-24-2019') ?>

// or

<?php echo asYmd('7-24-2019'); ?>