Programs & Examples On #Dotnetzip

Questions dealing with the DotNetZip open-source zip library for .NET

Fatal error: Cannot use object of type stdClass as array in

CodeIgniter returns result rows as objects, not arrays. From the user guide:

result()


This function returns the query result as an array of objects, or an empty array on failure.

You'll have to access the fields using the following notation:

foreach ($getvidids->result() as $row) {
    $vidid = $row->videoid;
}

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

(of course you can choose the color, line width, line style, etc.)

From your example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

new chart

How do you know a variable type in java?

I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name...)

Actually for me it's totally impossible that any a.xxx().yyy() method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method...

As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true...

One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field and create your own Field class, and then declare all your local variables as this custom Field implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?

In jQuery, how do I select an element by its name attribute?

<input type="radio" name="ans3" value="help"> 
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">

<input type="radio" name="ans2" value="test"> 
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">

<script type="text/javascript">
  var ans3 = jq("input[name='ans3']:checked").val()
  var ans2 = jq("input[name='ans2']:checked").val()
</script>

How to format string to money

Parse to your string to a decimal first.

Combine multiple Collections into a single logical Collection?

You could create a new List and addAll() of your other Lists to it. Then return an unmodifiable list with Collections.unmodifiableList().

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
        }
      res.end(err);
      }
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      }
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
  }
}).listen(8888);

What is an idiomatic way of representing enums in Go?

Here is an example that will prove useful when there are many enumerations. It uses structures in Golang, and draws upon Object Oriented Principles to tie them all together in a neat little bundle. None of the underlying code will change when a new enumeration is added or deleted. The process is:

  • Define an enumeration structure for enumeration items: EnumItem. It has an integer and string type.
  • Define the enumeration as a list of enumeration items: Enum
  • Build methods for the enumeration. A few have been included:
    • enum.Name(index int): returns the name for the given index.
    • enum.Index(name string): returns the name for the given index.
    • enum.Last(): returns the index and name of the last enumeration
  • Add your enumeration definitions.

Here is some code:

type EnumItem struct {
    index int
    name  string
}

type Enum struct {
    items []EnumItem
}

func (enum Enum) Name(findIndex int) string {
    for _, item := range enum.items {
        if item.index == findIndex {
            return item.name
        }
    }
    return "ID not found"
}

func (enum Enum) Index(findName string) int {
    for idx, item := range enum.items {
        if findName == item.name {
            return idx
        }
    }
    return -1
}

func (enum Enum) Last() (int, string) {
    n := len(enum.items)
    return n - 1, enum.items[n-1].name
}

var AgentTypes = Enum{[]EnumItem{{0, "StaffMember"}, {1, "Organization"}, {1, "Automated"}}}
var AccountTypes = Enum{[]EnumItem{{0, "Basic"}, {1, "Advanced"}}}
var FlagTypes = Enum{[]EnumItem{{0, "Custom"}, {1, "System"}}}

jQuery vs. javascript?

  • Does jQuery heavily rely on browser sniffing? Could be that potential problem in future? Why?

No - there is the $.browser method, but it's deprecated and isn't used in the core.

  • I found plenty JS-selector engines, are there any AJAX and FX libraries?

Loads. jQuery is often chosen because it does AJAX and animations well, and is easily extensible. jQuery doesn't use it's own selector engine, it uses Sizzle, an incredibly fast selector engine.

  • Is there any reason (besides browser sniffing and personal "hate" against John Resig) why jQuery is wrong?

No - it's quick, relatively small and easy to extend.

For me personally it's nice to know that as browsers include more stuff (classlist API for example) that jQuery will update to include it, meaning that my code runs as fast as possible all the time.

Read through the source if you are interested, http://code.jquery.com/jquery-1.4.3.js - you'll see that features are added based on the best case first, and gradually backported to legacy browsers - for example, a section of the parseJSON method from 1.4.3:

return window.JSON && window.JSON.parse ?
    window.JSON.parse( data ) :
    (new Function("return " + data))();

As you can see, if window.JSON exists, the browser uses the native JSON parser, if not, then it avoids using eval (because otherwise minfiers won't minify this bit) and sets up a function that returns the data. This idea of assuming modern techniques first, then degrading to older methods is used throughout meaning that new browsers get to use all the whizz bang features without sacrificing legacy compatibility.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

I needed to do a count of a very complex query with many joins. I was using the joins as filters, so I only wanted to know the count of the actual objects. count() was insufficient, but I found the answer in the docs here:

http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

The code would look something like this (to count user objects):

from sqlalchemy import func

session.query(func.count(User.id)).scalar() 

What datatype to use when storing latitude and longitude data in SQL databases?

We use float, but any flavor of numeric with 6 decimal places should also work.

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

Using phpMyAdmin (or whatever you prefer), I just created a database called "forge" and re-ran the php artisan migrate command and it all worked.

Count the number of occurrences of a character in a string in Javascript

I believe you will find the below solution to be very short, very fast, able to work with very long strings, able to support multiple character searches, error proof, and able to handle empty string searches.

function substring_count(source_str, search_str, index) {
    source_str += "", search_str += "";
    var count = -1, index_inc = Math.max(search_str.length, 1);
    index = (+index || 0) - index_inc;
    do {
        ++count;
        index = source_str.indexOf(search_str, index + index_inc);
    } while (~index);
    return count;
}

Example usage:

_x000D_
_x000D_
console.log(substring_count("Lorem ipsum dolar un sit amet.", "m "))_x000D_
_x000D_
function substring_count(source_str, search_str, index) {_x000D_
    source_str += "", search_str += "";_x000D_
    var count = -1, index_inc = Math.max(search_str.length, 1);_x000D_
    index = (+index || 0) - index_inc;_x000D_
    do {_x000D_
        ++count;_x000D_
        index = source_str.indexOf(search_str, index + index_inc);_x000D_
    } while (~index);_x000D_
    return count;_x000D_
}
_x000D_
_x000D_
_x000D_

The above code fixes the major performance bug in Jakub Wawszczyk's that the code keeps on looks for a match even after indexOf says there is none and his version itself is not working because he forgot to give the function input parameters.

Read from file or stdin

You're thinking it wrong.

What you are trying to do:

If stdin exists use it, else check whether the user supplied a filename.

What you should be doing instead:

If the user supplies a filename, then use the filename. Else use stdin.

You cannot know the total length of an incoming stream unless you read it all and keep it buffered. You just cannot seek backwards into pipes. This is a limitation of how pipes work. Pipes are not suitable for all tasks and sometimes intermediate files are required.

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

I had the same problem when trying to load Hadoop project in eclipse. I tried the solutions above, and I believe it might have worked in Eclipse Kepler... not even sure anymore (tried too many things).

With all the problems I was having, I decided to move on to Eclipse Luna, and the solutions above did not work for me.

There was another post that recommended changing the ... tag to package. I started doing that, and it would "clear" the errors... However, I start to think that the changes would bite me later - I am not an expert on Maven.

Fortunately, I found out how to remove all the errors. Go to Window->Preferences->Maven-> Error/Warnings and change "Plugin execution not covered by lifecycle..." option to "Ignore". Hope it helps.

Display a tooltip over a button using Windows Forms

Using the form designer:

  • Drag the ToolTip control from the Toolbox, onto the form.
  • Select the properties of the control you want the tool tip to appear on.
  • Find the property 'ToolTip on toolTip1' (the name may not be toolTip1 if you changed it's default name).
  • Set the text of the property to the tool tip text you would like to display.

You can set also the tool tip programatically using the following call:

this.toolTip1.SetToolTip(this.targetControl, "My Tool Tip");

jQuery - checkbox enable/disable

Change your markup slightly:

_x000D_
_x000D_
$(function() {_x000D_
  enable_cb();_x000D_
  $("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    $("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    $("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.

When do you use POST and when do you use GET?

i dont see a problem using get though, i use it for simple things where it makes sense to keep things on the query string.

Using it to update state - like a GET of delete.php?id=5 to delete a page - is very risky. People found that out when Google's web accelerator started prefetching URLs on pages - it hit all the 'delete' links and wiped out peoples' data. Same thing can happen with search engine spiders.

Can't find SDK folder inside Android studio path, and SDK manager not opening

Tools > Android > SDK Manager > there you'll see the path to SDK

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

Modify XML existing content in C#

Forming a XML file

XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();            
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();  
xmlw.Close();           

To edit the Xml nodes use the below code

XmlDocument doc = new XmlDocument(); 
doc.Load(@"C:\WINDOWS\Temp\exm.xml"); 
XmlNode root = doc.DocumentElement["Starttime"]; 
root.FirstChild.InnerText = "First"; 
XmlNode root1 = doc.DocumentElement["Changetime"]; 
root1.FirstChild.InnerText = "Second"; 
doc.Save(@"C:\WINDOWS\Temp\exm.xml"); 

Try this. It's C# code.

How to force DNS refresh for a website?

There's no guaranteed way to force the user to clear the DNS cache, and it is often done by their ISP on top of their OS. It shouldn't take more than 24 hours for the updated DNS to propagate. Your best option is to make the transition seamless to the user by using something like mod_proxy with Apache to create a reverse proxy to your new server. That would cause all queries to the old server to still return the proper results and after a few days you would be free to remove the reverse proxy.

String format currency

You need to provide an IFormatProvider:

@String.Format(new CultureInfo("en-US"), "{0:C}", @price)

Best practice for instantiating a new Android Fragment

use this code 100% fix your problem

enter this code in firstFragment

public static yourNameParentFragment newInstance() {

    Bundle args = new Bundle();
    args.putBoolean("yourKey",yourValue);
    YourFragment fragment = new YourFragment();
    fragment.setArguments(args);
    return fragment;
}

this sample send boolean data

and in SecendFragment

yourNameParentFragment name =yourNameParentFragment.newInstance();
   Bundle bundle;
   bundle=sellDiamondFragments2.getArguments();
  boolean a= bundle.getBoolean("yourKey");

must value in first fragment is static

happy code

Oracle client ORA-12541: TNS:no listener

I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.

Truncate number to two decimal places without rounding

Here is another one variant to save .toFixed([digits]) functional without rounding float variable:

Number.prototype.toRealFixed = function(digits) {
    return Math.floor(this.valueOf() * Math.pow(10, digits)) / Math.pow(10, digits);
};

And calling:

var float_var = 0.02209062;
float_var.toRealFixed();

Redirect stdout to a file in Python?

You need a terminal multiplexer like either tmux or GNU screen

I'm surprised that a small comment by Ryan Amos' to the original question is the only mention of a solution far preferable to all the others on offer, no matter how clever the python trickery may be and how many upvotes they've received. Further to Ryan's comment, tmux is a nice alternative to GNU screen.

But the principle is the same: if you ever find yourself wanting to leave a terminal job running while you log-out, head to the cafe for a sandwich, pop to the bathroom, go home (etc) and then later, reconnect to your terminal session from anywhere or any computer as though you'd never been away, terminal multiplexers are the answer. Think of them as VNC or remote desktop for terminal sessions. Anything else is a workaround. As a bonus, when the boss and/or partner comes in and you inadvertently ctrl-w / cmd-w your terminal window instead of your browser window with its dodgy content, you won't have lost the last 18 hours-worth of processing!

Expand/collapse section in UITableView in iOS

I found another relatively simple way to solve that problem. By using this method we will not required to alter our cell which is almost always related to data array index, potentially causing mess in our view controller.

First, we add this following properties to our controller class:

@property (strong, nonatomic) NSMutableArray* collapsedSections;
@property (strong, nonatomic) NSMutableArray* sectionViews;

collapsedSections will save collapsed section numbers. sectionViews will store our custom section view.

Synthesize it:

@synthesize collapsedSections;
@synthesize sectionViews;

Initialize it:

- (void) viewDidLoad
{
    [super viewDidLoad];

    self.collapsedSections = [NSMutableArray array];
    self.sectionViews      = [NSMutableArray array];
}

After that, we must connect our UITableView so it can be accessed from within our view controller class:

@property (strong, nonatomic) IBOutlet UITableView *tblMain;

Connect it from XIB to view controller using ctrl + drag like usually.

Then we create view as custom section header for our table view by implementing this UITableView delegate:

- (UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    // Create View
    CGRect frame = CGRectZero;

    frame.origin = CGPointZero;

    frame.size.height = 30.f;
    frame.size.width  = tableView.bounds.size.width;

    UIView* view = [[UIView alloc] initWithFrame:frame];

    [view setBackgroundColor:[UIColor blueColor]];

    // Add label for title
    NSArray* titles = @[@"Title 1", @"Title 2", @"Title 3"];

    NSString* selectedTitle = [titles objectAtIndex:section];

    CGRect labelFrame = frame;

    labelFrame.size.height = 30.f;
    labelFrame.size.width -= 20.f;
    labelFrame.origin.x += 10.f;

    UILabel* titleLabel = [[UILabel alloc] initWithFrame:labelFrame];

    [titleLabel setText:selectedTitle];
    [titleLabel setTextColor:[UIColor whiteColor]];

    [view addSubview:titleLabel];

    // Add touch gesture
    [self attachTapGestureToView:view];

    // Save created view to our class property array
    [self saveSectionView:view inSection:section];

    return view;
}

Next, we implement method to save our previously created custom section header in class property:

- (void) saveSectionView:(UIView*) view inSection:(NSInteger) section
{
    NSInteger sectionCount = [self numberOfSectionsInTableView:[self tblMain]];

    if(section < sectionCount)
    {
        if([[self sectionViews] indexOfObject:view] == NSNotFound)
        {
            [[self sectionViews] addObject:view];
        }
    }
}

Add UIGestureRecognizerDelegate to our view controller .h file:

@interface MyViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>

Then we create method attachTapGestureToView:

- (void) attachTapGestureToView:(UIView*) view
{
    UITapGestureRecognizer* tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];

    [tapAction setDelegate:self];

    [view addGestureRecognizer:tapAction];
}

Above method will add tap gesture recognizer to all of section view we created before. Next we should implement onTap: selector

- (void) onTap:(UITapGestureRecognizer*) gestureRecognizer
{
    // Take view who attach current recognizer
    UIView* sectionView = [gestureRecognizer view]; 

    // [self sectionViews] is Array containing our custom section views
    NSInteger section = [self sectionNumberOfView:sectionView];

    // [self tblMain] is our connected IBOutlet table view
    NSInteger sectionCount = [self numberOfSectionsInTableView:[self tblMain]];

    // If section more than section count minus one set at last
    section = section > (sectionCount - 1) ? 2 : section;

    [self toggleCollapseSection:section];
}

Above method will invoked when user tap any of our table view section. This method search correct section number based on our sectionViews array we created before.

Also, we implement method to get wihch section of header view belongs to.

- (NSInteger) sectionNumberOfView:(UIView*) view
{
    UILabel* label = [[view subviews] objectAtIndex:0];

    NSInteger sectionNum = 0;

    for(UIView* sectionView in [self sectionViews])
    {
        UILabel* sectionLabel = [[sectionView subviews] objectAtIndex:0];

        //NSLog(@"Section: %d -> %@ vs %@", sectionNum, [label text], [sectionLabel text]);

        if([[label text] isEqualToString:[sectionLabel text]])
        {
            return sectionNum;
        }

        sectionNum++;
    }

    return NSNotFound;
}

Next, we must implement method toggleCollapseSection:

- (void) toggleCollapseSection:(NSInteger) section
{
    if([self isCollapsedSection:section])
    {
        [self removeCollapsedSection:section];
    }
    else
    {
        [self addCollapsedSection:section];
    }

    [[self tblMain] reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}

This method will insert/remove section number to our collapsedSections array we created before. When a section number inserted to that array, it means that the section should be collapsed and expanded if otherwise.

Next we implement removeCollapsedSection:, addCollapsedSection:section and isCollapsedSection:section

- (BOOL)isCollapsedSection:(NSInteger) section
{
    for(NSNumber* existing in [self collapsedSections])
    {
        NSInteger current = [existing integerValue];

        if(current == section)
        {
            return YES;
        }
    }

    return NO;
}

- (void)removeCollapsedSection:(NSInteger) section
{
    [[self collapsedSections] removeObjectIdenticalTo:[NSNumber numberWithInteger:section]];
}

- (void)addCollapsedSection:(NSInteger) section
{
    [[self collapsedSections] addObject:[NSNumber numberWithInteger:section]];
}

This three method is just helpers to make us easier in accessing collapsedSections array.

Finally, implement this table view delegate so our custom section views looks nice.

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.f; // Same as each custom section view height
}

Hope it helps.

failed to open stream: HTTP wrapper does not support writeable connections

May this code help you. It works in my case.

$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
    $fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
    if(!file_exists($filename)):
        $handle = fopen( $filename, 'a' ) or die( 'Cannot open file:  ' . $fileUrl ); //implicitly creates file
        fwrite( $handle, json_encode(array()));
        fclose( $handle );
    endif;
    $response = file_get_contents($filename);
    $tempArray = json_decode($response);
    if(!empty($tempArray)):
        $count = count($tempArray) + 1;
    else:
        $count = 1;
    endif;
    $tempArray[] = array_merge(array("sn." => $count), $data);
    $jsonData = json_encode($tempArray);
    file_put_contents($filename, $jsonData);

How to convert a List<String> into a comma separated string without iterating List explicitly

You can use below code if object has attibutes under it.

String getCommonSeperatedString(List<ActionObject> actionObjects) {
    StringBuffer sb = new StringBuffer();
    for (ActionObject actionObject : actionObjects){
        sb.append(actionObject.Id).append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}

Place a button right aligned

It is not always so simple and sometimes the alignment must be defined in the container and not in the Button element itself !

For your case, the solution would be

<div style="text-align:right; width:100%; padding:0;">
    <input type="button" value="Click Me"/>
</div>

I have taken care to specify width=100% to be sure that <div> take full width of his container.

I have also added padding:0 to avoid before and after space as with <p> element.

I can say that if <div> is defined in a FSF/Primefaces table's footer, the float:right don't work correctly because the Button height will become higher than the footer height !

In this Primefaces situation, the only acceptable solution is to use text-align:right in container.

With this solution, if you have 6 Buttons to align at right, you must only specify this alignment in container :-)

<div style="text-align:right; width:100%; padding:0;">
    <input type="button" value="Click Me 1"/>
    <input type="button" value="Click Me 2"/>
    <input type="button" value="Click Me 3"/>
    <input type="button" value="Click Me 4"/>
    <input type="button" value="Click Me 5"/>
    <input type="button" value="Click Me 6"/>
</div>

Instance member cannot be used on type

Another example is, you have class like :

@obc class Album: NSObject {
    let name:String
    let singer:Singer
    let artwork:URL
    let playingSong:Song


    // ...

    class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
        // ...
       return playingSong.lyric
    }
}

you will also get the same type of error like :

instance member x cannot be used on type x. 

It's because you assign your method with "class" keyword (which makes your method a type method) and using like :

Album.getCurrentlyPlayingSongLyric(duration: 5)

but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :

 // ...

 func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
        // ...
       return playingSong.lyric
 }

 // ...

Now you're free to go.

Choose File Dialog

You just need to override onCreateDialog in an Activity.

//In an Activity
private String[] mFileList;
private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
private String mChosenFile;
private static final String FTYPE = ".txt";    
private static final int DIALOG_LOAD_FILE = 1000;

private void loadFileList() {
    try {
        mPath.mkdirs();
    }
    catch(SecurityException e) {
        Log.e(TAG, "unable to write on the sd card " + e.toString());
    }
    if(mPath.exists()) {
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                return filename.contains(FTYPE) || sel.isDirectory();
            }

        };
        mFileList = mPath.list(filter);
    }
    else {
        mFileList= new String[0];
    }
}

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    switch(id) {
        case DIALOG_LOAD_FILE:
            builder.setTitle("Choose your file");
            if(mFileList == null) {
                Log.e(TAG, "Showing file picker before loading the file list");
                dialog = builder.create();
                return dialog;
            }
            builder.setItems(mFileList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    mChosenFile = mFileList[which];
                    //you can do stuff with the file here too
                }
            });
            break;
    }
    dialog = builder.show();
    return dialog;
}

How to show all of columns name on pandas dataframe?

To get all column name you can iterate over the data_all2.columns.

columns = data_all2.columns
for col in columns:
    print col

You will get all column names. Or you can store all column names to another list variable and then print list.

Owl Carousel Won't Autoplay

You should set both autoplay and autoplayTimeout properties. I used this code, and it works for me:

$('.owl-carousel').owlCarousel({
                autoplay: true,
                autoplayTimeout: 5000,
                navigation: false,
                margin: 10,
                responsive: {
                    0: {
                        items: 1
                    },
                    600: {
                        items: 2
                    },
                    1000: {
                        items: 2
                    }
                }
            })

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

Timer Interval 1000 != 1 second?

Instead of Tick event, use Elapsed event.

timer.Elapsed += new EventHandler(TimerEventProcessor);

and change the signiture of TimerEventProcessor method;

private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
  label1.Text = _counter.ToString();
  _counter += 1;
}

ExpressionChangedAfterItHasBeenCheckedError Explained

In my case, I had an async property in LoadingService with a BehavioralSubject isLoading

Using the [hidden] model works, but *ngIf fails

    <h1 [hidden]="!(loaderService.isLoading | async)">
        THIS WORKS FINE
        (Loading Data)
    </h1>

    <h1 *ngIf="!(loaderService.isLoading | async)">
        THIS THROWS ERROR
        (Loading Data)
    </h1>

Check if TextBox is empty and return MessageBox?

Adding on to what @tjg184 said, you could do something like...

if (String.IsNullOrEmpty(MaterialTextBox.Text.Trim())) 

...

How to show multiline text in a table cell

For my case, I can use like this.

td { white-space:pre-line , word-break: break-all}

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

In my case, I created a folder audio in res directory. That caused the problem! Deleting the folder fixed it. Hope it might help someone.

DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled

Try setting the definer for the function!

So instead of

CREATE FUNCTION get_pet_owner

you will write something akin to

CREATE DEFINER=procadmin@% FUNCTION get_pet_owner

which ought to work if the user prodacmin has rights to create functions/procedures.

In my case the function worked when generated through MySQL Workbench but did not work when run directly as an SQL script. Making the changes above fixed the problem.

sh: 0: getcwd() failed: No such file or directory on cited drive

Try the following command, it worked for me.

cd; cd -

How can I disable all views inside the layout?

tutu's answer is on the right track, but his recursion is a little awkward. I think this is cleaner:

private static void setViewAndChildrenEnabled(View view, boolean enabled) {
    view.setEnabled(enabled);
    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            View child = viewGroup.getChildAt(i);
            setViewAndChildrenEnabled(child, enabled);
        }
    }
}

How to pause for specific amount of time? (Excel/VBA)

instead of using:

Application.Wait(Now + #0:00:01#)

i prefer:

Application.Wait(Now + TimeValue("00:00:01"))

because it is a lot easier to read afterwards.

Syntax for if/else condition in SCSS mixin

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Failed Apache2 start, no error log

in the apache virtualhost you have to define the path to the error log file. when apache2 start for the first time it will create it automatically.

for example ErrorLog "/var/www/www.localhost.com/log-apache2/error.log" in the apache virtualhost..

String delimiter in string.split method

Use the Pattern#quote() method for escaping ||. Try:

final String[] tokens = myString.split(Pattern.quote("||"));

This is required because | is an alternation character and hence gains a special meaning when passed to split call (basically the argument to split is a regular expression in string form).

How to add "active" class to Html.ActionLink in ASP.NET MVC

This solution is simple for Asp.net MCV 5.

  1. Create a static class, for example Utilitarios.cs.

  2. Inside the Class create a static method:

    public static string IsLinkActive(this UrlHelper url, string action, string controller)
    {
        if (url.RequestContext.RouteData.Values["controller"].ToString() == controller &&
            url.RequestContext.RouteData.Values["action"].ToString() == action)
        {
            return "active";
        }
    
        return "";
    }
    
  3. call like this

    <ul class="sidebar-menu" data-widget="tree">
        <li class="header">HEADER</li>
        <li class="@Url.IsLinkActive("Index", "Home")">
            <a href="@Url.Action("Index", "Home")"><i class="fa fa-link"></i> <span>Home</span></a>
        </li>
        <li class="@Url.IsLinkActive("About", "Home")">
            <a href="@Url.Action("About", "Home")"><i class="fa fa-link"></i><span>About</span></a>
        </li>
    </ul>
    

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Cannot use a leading ../ to exit above the top directory

I know these answers are enough, but I'll show the place that's throwing an error.

If you have the structure like the below:

  • ./Src/Master.cs - (Master Form Page)
  • ./Invoice/SubFolder/InvoiceEdit.aspx - (Sub Form Page)

If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png").

Now ResolveClientUrl is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png. This is the wrong way.

Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../.

Mailto: Body formatting

Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).

You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)

By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.

Good tool for testing socket connections?

Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Perhaps the below method could be the cause if you've set it to

func webView(_ webView: WebView!,decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) 

ends with

decisionHandler(.cancel)

for the default navigationAction.request.url

Hope it works!

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.

Kolorobot’s example application includes the following:

  • No-xml Spring MVC 3.2 web application for Servlet 3.0 environment
  • Apache Tiles with configuration in place,
  • Bootstrap
  • JPA 2.0 (Hibernate/HSQLDB)
  • JUnit/Mockito
  • Spring Security 3.1

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

How to show full column content in a Spark Dataframe?

Below code would help to view all rows without truncation in each column

df.show(df.count(), False)

"date(): It is not safe to rely on the system's timezone settings..."

If you are using CodeIgniter and can't change php.ini, I added the following to the beginning of index.php:

date_default_timezone_set('GMT');

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

Why is System.Web.Mvc not listed in Add References?

The desired assembly has appeared in the list now.

I can only speculate what caused it to appear, but I suspect it is the fact that I went File ? New ? Project ? ASP.NET Web Application, which I had never done before. It is possible that this caused some sort of late initialisation to happen and the list to be populated with additional assemblies for Web development.

Server returned HTTP response code: 401 for URL: https

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.

How to display binary data as image - extjs 4

In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:

<img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">

my-image is a binary image file. This will load just fine.

Xcode 5 and iOS 7: Architecture and Valid architectures

None of the answers worked and then I was forgetting to set minimum deployment target which can be found in Project -> General -> Deployment Info -> Deployment Target -> 8.0

Example

Crontab Day of the Week syntax

0 and 7 both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON, THU, etc:

0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday

Graphically:

 +---------- minute (0 - 59)
 ¦ +-------- hour (0 - 23)
 ¦ ¦ +------ day of month (1 - 31)
 ¦ ¦ ¦ +---- month (1 - 12)
 ¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
 ¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
 ? ? ? ? ?
 * * * * * command to be executed

Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

Set a div width, align div center and text align left

Try:

#your_div_id {
  width: 855px;
  margin:0 auto;
  text-align: center;
}

What are the ascii values of up down left right?

You can check it by compiling,and running this small C++ program.

#include <iostream>
#include <conio.h>
#include <cstdlib>

int show;
int main()
{    
while(true)
    {
    int show = getch();
    std::cout << show;
    }
getch(); // Just to keep the console open after program execution  
}

There are No resources that can be added or removed from the server

I didn't find the Dynamic Web Module option when I clicked on the link, then I have installed Maven(Java EE) Integration for Eclipse WTP from the Eclipse Marketplace.Then, the above steps worked.

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

This worked for me:

[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }    

[Serializable]
public class BankPayment : Payment {} 

[Serializable]
public class Payments : List<Payment>{}

XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});

Session only cookies with Javascript

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return false;
  }
  
  
  if(getCookie("KoiMilGaya")) {
    //alert('found'); 
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    //alert('nothing');
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 
    setCookie('KoiMilGaya','1');
  }

What does "publicPath" in Webpack do?

filename specifies the name of file into which all your bundled code is going to get accumulated after going through build step.

path specifies the output directory where the app.js(filename) is going to get saved in the disk. If there is no output directory, webpack is going to create that directory for you. for example:

module.exports = {
  output: {
    path: path.resolve("./examples/dist"),
    filename: "app.js"
  } 
}

This will create a directory myproject/examples/dist and under that directory it creates app.js, /myproject/examples/dist/app.js. After building, you can browse to myproject/examples/dist/app.js to see the bundled code

publicPath: "What should I put here?"

publicPath specifies the virtual directory in web server from where bundled file, app.js is going to get served up from. Keep in mind, the word server when using publicPath can be either webpack-dev-server or express server or other server that you can use with webpack.

for example

module.exports = {
  output: {
    path: path.resolve("./examples/dist"),
    filename: "app.js",
    publicPath: path.resolve("/public/assets/js")   
  } 
}

this configuration tells webpack to bundle all your js files into examples/dist/app.js and write into that file.

publicPath tells webpack-dev-server or express server to serve this bundled file ie examples/dist/app.js from specified virtual location in server ie /public/assets/js. So in your html file, you have to reference this file as

<script src="public/assets/js/app.js"></script>

So in summary, publicPath is like mapping between virtual directory in your server and output directory specified by output.path configuration, Whenever request for file public/assets/js/app.js comes, /examples/dist/app.js file will be served

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Maven Run Project

No need to add new plugin in pom.xml. Just run this command

mvn org.codehaus.mojo:exec-maven-plugin:1.5.0:java -Dexec.mainClass="com.example.Main" | grep -Ev '(^\[|Download\w+:)' 

See the maven exec plugin for more usage.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

<option value="" selected disabled hidden>Default Text</option>

Leaving the disabled flag in prevents them from not selecting an option and the hidden flag will remove it from the list. In my case I was using it with an enum list as well and the concept holds the same

<select asp-for="Property" asp-items="Html.GetEnumSelectList<PropertyEnum>()">
                        <option value="" selected disabled hidden>Select Property Enum</option>
                        <option value=""></option>
                    </select>

How do I make flex box work in safari?

Maybe this would be useful

-webkit-justify-content: space-around;

Immutable array in Java

There is one way to make an immutable array in Java:

final String[] IMMUTABLE = new String[0];

Arrays with 0 elements (obviously) cannot be mutated.

This can actually come in handy if you are using the List.toArray method to convert a List to an array. Since even an empty array takes up some memory, you can save that memory allocation by creating a constant empty array, and always passing it to the toArray method. That method will allocate a new array if the array you pass doesn't have enough space, but if it does (the list is empty), it will return the array you passed, allowing you to reuse that array any time you call toArray on an empty List.

final static String[] EMPTY_STRING_ARRAY = new String[0];

List<String> emptyList = new ArrayList<String>();
return emptyList.toArray(EMPTY_STRING_ARRAY); // returns EMPTY_STRING_ARRAY

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

No newline after div?

This works like magic, use it in the CSS file on the div you want to have on the new line:

.div_class {
    clear: left;
}

Or declare it in the html:

<div style="clear: left">
     <!-- Content... -->
</div>

What special characters must be escaped in regular expressions?

Unfortunately, the meaning of things like ( and \( are swapped between Emacs style regular expressions and most other styles. So if you try to escape these you may be doing the opposite of what you want.

So you really have to know what style you are trying to quote.

How can I avoid getting this MySQL error Incorrect column specifier for column COLUMN NAME?

You cannot auto increment the char values. It should be int or long(integers or floating points). Try with this,

CREATE TABLE discussion_topics (
    topic_id int(5) NOT NULL AUTO_INCREMENT,
    project_id char(36) NOT NULL,
    topic_subject VARCHAR(255) NOT NULL,
    topic_content TEXT default NULL,
    date_created DATETIME NOT NULL,
    date_last_post DATETIME NOT NULL,
    created_by_user_id char(36) NOT NULL,
    last_post_user_id char(36) NOT NULL,
    posts_count char(36) default NULL,
    PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

Hope this helps

Pass a JavaScript function as parameter

Here it's another approach :

function a(first,second)    
{        
return (second)(first);           
}     

a('Hello',function(e){alert(e+ ' world!');}); //=> Hello world     

JavaScript code to stop form submission

Use prevent default

Dojo Toolkit

dojo.connect(form, "onsubmit", function(evt) {
    evt.preventDefault();
    window.history.back();
});

jQuery

$('#form').submit(function (evt) {
    evt.preventDefault();
    window.history.back();
});

Vanilla JavaScript

if (element.addEventListener) {
    element.addEventListener("submit", function(evt) {
        evt.preventDefault();
        window.history.back();
    }, true);
}
else {
    element.attachEvent('onsubmit', function(evt){
        evt.preventDefault();
        window.history.back();
    });
}

Create a Bitmap/Drawable from file path

It works for me:

File imgFile = new  File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    //Drawable d = new BitmapDrawable(getResources(), myBitmap);
    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    myImage.setImageBitmap(myBitmap);

}

Edit:

If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:

String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new  File(sdcardPath);

How to dynamically create CSS class in JavaScript and apply?

As of IE 9. You can now load a text file and set a style.innerHTML property. So essentially you can now load a css file through ajax (and get the callback) and then just set the text inside of a style tag like this.

This works in other browsers, not sure how far back. But as long as you don't need to support IE8 then it would work.

// RESULT: doesn't work in IE8 and below. Works in IE9 and other browsers.
$(document).ready(function() {
    // we want to load the css as a text file and append it with a style.
    $.ajax({
        url:'myCss.css',
        success: function(result) {
            var s = document.createElement('style');
            s.setAttribute('type', 'text/css');
            s.innerHTML = result;
            document.getElementsByTagName("head")[0].appendChild(s);
        },
        fail: function() {
            alert('fail');
        }
    })
});

and then you can have it pull an external file like the myCss.css

.myClass { background:#F00; }

Django CharField vs TextField

CharField has max_length of 255 characters while TextField can hold more than 255 characters. Use TextField when you have a large string as input. It is good to know that when the max_length parameter is passed into a TextField it passes the length validation to the TextArea widget.

How to Read from a Text File, Character by Character in C++

@cnicutar and @Pete Becker have already pointed out the possibility of using noskipws/unsetting skipws to read a character at a time without skipping over white space characters in the input.

Another possibility would be to use an istreambuf_iterator to read the data. Along with this, I'd generally use a standard algorithm like std::transform to do the reading and processing.

Just for example, let's assume we wanted to do a Caesar-like cipher, copying from standard input to standard output, but adding 3 to every upper-case character, so A would become D, B could become E, etc. (and at the end, it would wrap around so XYZ converted to ABC.

If we were going to do that in C, we'd typically use a loop something like this:

int ch;
while (EOF != (ch = getchar())) {
    if (isupper(ch)) 
        ch = ((ch - 'A') +3) % 26 + 'A';
    putchar(ch);
}

To do the same thing in C++, I'd probably write the code more like this:

std::transform(std::istreambuf_iterator<char>(std::cin),
               std::istreambuf_iterator<char>(),
               std::ostreambuf_iterator<char>(std::cout),
               [](int ch) { return isupper(ch) ? ((ch - 'A') + 3) % 26 + 'A' : ch;});

Doing the job this way, you receive the consecutive characters as the values of the parameter passed to (in this case) the lambda function (though you could use an explicit functor instead of a lambda if you preferred).

Working copy locked error in tortoise svn while committing

No problem... try this:

  • Go to top level SVN folder.
  • Right click on folder (that has your svn files) > TortoiseSVN > CleanUp

This will surely solve your problem. I did this lots of time... :)

Note. Make sure "Break locks" option is selected in the Cleanup dialog.

Show "Open File" Dialog

Addition to what Albert has already said:

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

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

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

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

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I also got the same issue and not able to create a jar, and I found that in Windows-->Prefernces-->Java-->installed JREs By default JRE was added to the build path of newly created java project so just changed it to your prefered JDK.

JavaScript property access: dot notation vs. brackets?

Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like

var x = elem["foo[]"]; // can't do elem.foo[];

This can be extended to any property containing special characters.

java - path to trustStore - set property doesn't work?

Both

-Djavax.net.ssl.trustStore=path/to/trustStore.jks

and

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore in javax.net.ssl.trustStore.

Implement paging (skip / take) functionality with this query

In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

Example:

select * from table order by [some_column] 
offset 10 rows
FETCH NEXT 10 rows only

And you can't use the "TOP" keyword when doing this.

You can learn more here: https://technet.microsoft.com/pt-br/library/gg699618%28v=sql.110%29.aspx

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

for Python 3 users. you can do

with open(csv_name_here, 'r', encoding="utf-8") as f:
    #some codes

it works with flask too :)

mySQL :: insert into table, data from another table?

Answered by zerkms is the correct method. But, if someone looking to insert more extra column in the table then you can get it from the following:

INSERT INTO action_2_members (`campaign_id`, `mobile`, `email`, `vote`, `vote_date`, `current_time`)
SELECT `campaign_id`, `from_number`, '[email protected]', `received_msg`, `date_received`, 1502309889 FROM `received_txts` WHERE `campaign_id` = '8'

In the above query, there are 2 extra columns named email & current_time.

Remove Android App Title Bar

Use this Remove title and image from top.

Before:

setContentView(R.layout.actii);

Write this code:

requestWindowFeature(Window.FEATURE_NO_TITLE);

AngularJS/javascript converting a date String to date object

_x000D_
_x000D_
//JS_x000D_
//First Solution_x000D_
moment(myDate)_x000D_
_x000D_
//Second Solution_x000D_
moment(myDate).format('YYYY-MM-DD HH:mm:ss')_x000D_
//or_x000D_
moment(myDate).format('YYYY-MM-DD')_x000D_
_x000D_
//Third Solution_x000D_
myDate = $filter('date')(myDate, "dd/MM/yyyy");
_x000D_
<!--HTML-->_x000D_
<!-- First Solution -->_x000D_
{{myDate  | date:'M/d/yyyy HH:mm:ss'}}_x000D_
<!-- or -->_x000D_
{{myDate  | date:'medium'}}_x000D_
_x000D_
<!-- Second Solution -->_x000D_
{{myDate}}_x000D_
_x000D_
<!-- Third Solution -->_x000D_
{{myDate}}
_x000D_
_x000D_
_x000D_

overlay a smaller image on a larger image python OpenCv

When attempting to write to the destination image using any of these answers above and you get the following error:

ValueError: assignment destination is read-only

A quick potential fix is to set the WRITEABLE flag to true.

img.setflags(write=1)

Is a URL allowed to contain a space?

Yes, the space is usually encoded to "%20" though. Any parameters that pass to a URL should be encoded, simply for safety reasons.

How to convert a string to lower or upper case in Ruby

Won't work for every, but this just saved me a bunch of time. I just had the problem with a CSV returning "TRUE or "FALSE" so I just added VALUE.to_s.downcase == "true" which will return the boolean true if the value is "TRUE" and false if the value is "FALSE", but will still work for the boolean true and false.

Overloading and overriding

I want to share an example which made a lot sense to me when I was learning:

This is just an example which does not include the virtual method or the base class. Just to give a hint regarding the main idea.

Let's say there is a Vehicle washing machine and it has a function called as "Wash" and accepts Car as a type.

Gets the Car input and washes the Car.

public void Wash(Car anyCar){
       //wash the car
}

Let's overload Wash() function

Overloading:

public void Wash(Truck anyTruck){
   //wash the Truck  
}

Wash function was only washing a Car before, but now its overloaded to wash a Truck as well.

  • If the provided input object is a Car, it will execute Wash(Car anyCar)
  • If the provided input object is a Truck, then it will execute Wash(Truck anyTruck)

Let's override Wash() function

Overriding:

public override void Wash(Car anyCar){
   //check if the car has already cleaned
   if(anyCar.Clean){ 
       //wax the car
   }
   else{
       //wash the car
       //dry the car
       //wax the car
   }     
}

Wash function now has a condition to check if the Car is already clean and not need to be washed again.

  • If the Car is clean, then just wax it.

  • If not clean, then first wash the car, then dry it and then wax it

.

So the functionality has been overridden by adding a new functionality or do something totally different.

Binding Button click to a method

Some more explanations to the solution Rachel already gave:

"WPF Apps With The Model-View-ViewModel Design Pattern"

by Josh Smith

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Difference between java HH:mm and hh:mm on SimpleDateFormat

Please take a look here

HH is hour in a day (starting from 0 to 23)

hh are hours in am/pm format

kk is hour in day (starting from 1 to 24)

mm is minute in hour

ss are the seconds in a minute

Pass correct "this" context to setTimeout callback?

There are ready-made shortcuts (syntactic sugar) to the function wrapper @CMS answered with. (Below assuming that the context you want is this.tip.)


ECMAScript 2015 (all common browsers and smartphones, Node.js 5.0.0+)

For virtually all javascript development (in 2020) you can use fat arrow functions, which are part of the ECMAScript 2015 (Harmony/ES6/ES2015) specification.

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value [...].

(param1, param2, ...rest) => { statements }

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(() => { this.tip.destroy(); }, 1000);
}

ECMAScript 5 (older browsers and smartphones, Node.js) and Prototype.js

If you target browser compatible with ECMA-262, 5th edition (ECMAScript 5) or Node.js, which (in 2020) means all common browsers as well as older browsers, you could use Function.prototype.bind. You can optionally pass any function arguments to create partial functions.

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Again, in your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(this.tip.destroy.bind(this.tip), 1000);
}

The same functionality has also been implemented in Prototype (any other libraries?).

Function.prototype.bind can be implemented like this if you want custom backwards compatibility (but please observe the notes).


jQuery

If you are already using jQuery 1.4+, there's a ready-made function for explicitly setting the this context of a function.

jQuery.proxy(): Takes a function and returns a new one that will always have a particular context.

$.proxy(function, context[, additionalArguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout($.proxy(this.tip.destroy, this.tip), 1000);
}

Underscore.js, lodash

It's available in Underscore.js, as well as lodash, as _.bind(...)1,2

bind Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, bind arguments to the function to pre-fill them, also known as partial application.

_.bind(function, object, [*arguments])

In your case, try this:

if (this.options.destroyOnHide) {
    setTimeout(_.bind(this.tip.destroy, this.tip), 1000);
}

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

Is there a difference between /\s/g and /\s+/g?

In the first regex, each space character is being replaced, character by character, with the empty string.

In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +.

However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.

If you change the replacement string to '#', the difference becomes much clearer:

var str = '  A B  C   D EF ';
console.log(str.replace(/\s/g, '#'));  // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#

$rootScope.$broadcast vs. $scope.$emit

I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Scope, rootScope, emit, broadcast

As you can see, $rootScope.$broadcast hits a lot more listeners than $scope.$emit.

Also, $scope.$emit's bubbling effect can be cancelled, whereas $rootScope.$broadcast cannot.

Get current language in CultureInfo

Current system language is retrieved using :

  CultureInfo.InstalledUICulture

"Gets the CultureInfo that represents the culture installed with the operating system."

InstalledUICulture

To set it as default language for thread use :

   System.Globalization.CultureInfo.DefaultThreadCurrentCulture=CultureInfo.InstalledUICulture;

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

RecyclerView onClick

Step 1 ) Write the click interface

Create an interface named RecyclerViewClickListener.java and add below code. Here we declare two methods onClick and onLongClick to identify item click and long click respectively.

package com.androidtutorialshub.recyclerviewtutorial.Helper;

import android.view.View;

public interface RecyclerViewClickListener {
    void onClick(View view, int position);

    void onLongClick(View view, int position);
}

Step 2 ) Write the Item Touch Class

Create a class named RecyclerViewTouchListener.java and add below code . Here we write the logic to detect click and long press on recycler view item .

package com.androidtutorialshub.recyclerviewtutorial.Helper;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;


public class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener{

    private GestureDetector gestureDetector;
    private RecyclerViewClickListener clickListener;

    public RecyclerViewTouchListener(Context context, final RecyclerView recyclerView, final RecyclerViewClickListener clickListener) {
        this.clickListener = clickListener;
        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                if (child != null && clickListener != null) {
                    clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {

        View child = rv.findChildViewUnder(e.getX(), e.getY());
        if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
            clickListener.onClick(child, rv.getChildPosition(child));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

Step 3 ) Defining click listener

Open MainActivity.java and update the below changes. Here onClick() method will detect click on item and onLongClick will detect long click on item.

recyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(getApplicationContext(), recyclerView, new RecyclerViewClickListener() {
            @Override
            public void onClick(View view, int position) {
                Toast.makeText(getApplicationContext(), bookList.get(position).getTitle() + " is clicked!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(View view, int position) {
                Toast.makeText(getApplicationContext(), bookList.get(position).getTitle() + " is long pressed!", Toast.LENGTH_SHORT).show();

            }
        }));

For more info or Download source code :- http://www.androidtutorialshub.com/android-recyclerview-click-listener-tutorial/

Calling ASP.NET MVC Action Methods from JavaScript

If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.

<div class="cart">
      @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>

That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Using the GET parameter of a URL in JavaScript

Here is a version that JSLint likes:

/*jslint browser: true */
var GET = {};
(function (input) {
    'use strict';
    if (input.length > 1) {
        var param = input.slice(1).replace(/\+/g, ' ').split('&'),
            plength = param.length,
            tmp,
            p;

        for (p = 0; p < plength; p += 1) {
            tmp = param[p].split('=');
            GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp[1]);
        }
    }
}(window.location.search));

window.alert(JSON.stringify(GET));

Or if you need support for several values for one key like eg. ?key=value1&key=value2 you can use this:

/*jslint browser: true */
var GET = {};
(function (input) {
    'use strict';
    if (input.length > 1) {
        var params = input.slice(1).replace(/\+/g, ' ').split('&'),
            plength = params.length,
            tmp,
            key,
            val,
            obj,
            p;

        for (p = 0; p < plength; p += 1) {
            tmp = params[p].split('=');
            key = decodeURIComponent(tmp[0]);
            val = decodeURIComponent(tmp[1]);
            if (GET.hasOwnProperty(key)) {
                obj = GET[key];
                if (obj.constructor === Array) {
                    obj.push(val);
                } else {
                    GET[key] = [obj, val];
                }
            } else {
                GET[key] = val;
            }
        }
    }
}(window.location.search));

window.alert(JSON.stringify(GET));

How make background image on newsletter in outlook?

The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.

The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.

<td bgcolor="#your_color" background="your_image.jpg">

<!--[if gte mso 9]>

<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>

<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>

<![endif]-->

<p>Text over background image.</p>

<!--[if gte mso 9]>

</v:shape>

<![endif]-->

</td>

source

Comparing the contents of two files in Sublime Text

The Diff Option only appears if the files are in a folder that is part of a Project.

Than you can actually compare files natively right in Sublime Text.

Navigate to the folder containing them through Open Folder... or in a project Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar Right click and select the Diff files... option.

Add list to set?

You'll want to use tuples, which are hashable (you can't hash a mutable object like a list).

>>> a = set("abcde")
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> t = ('f', 'g')
>>> a.add(t)
>>> a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])

Inserting NOW() into Database with CodeIgniter's Active Record

According to the source code of codeigniter, the function set is defined as:

public function set($key, $value = '', $escape = TRUE)
{
    $key = $this->_object_to_array($key);

    if ( ! is_array($key))
    {
        $key = array($key => $value);
    }

    foreach ($key as $k => $v)
    {
        if ($escape === FALSE)
        {
            $this->ar_set[$this->_protect_identifiers($k)] = $v;
        }
        else
        {
            $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
        }
    }

    return $this;
}

Apparently, if $key is an array, codeigniter will simply ignore the second parameter $value, but the third parameter $escape will still work throughout the iteration of $key, so in this situation, the following codes work (using the chain method):

$this->db->set(array(
    'name' => $name ,
    'email' => $email,
    'time' => 'NOW()'), '', FALSE)->insert('mytable');

However, this will unescape all the data, so you can break your data into two parts:

$this->db->set(array(
    'name' => $name ,
    'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');

How to kill zombie process

You can clean up a zombie process by killing its parent process with the following command:

kill -HUP $(ps -A -ostat,ppid | awk '{/[zZ]/{ print $2 }')

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

ImageView rounded corners

You should use RoundedCornersTransformation from this library and create a circular ImageView.

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import com.squareup.picasso.Transformation;

public class RoundedCornersTransformation implements Transformation {

    public enum CornerType {
        ALL,
        TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT,
        TOP, BOTTOM, LEFT, RIGHT,
        OTHER_TOP_LEFT, OTHER_TOP_RIGHT, OTHER_BOTTOM_LEFT, OTHER_BOTTOM_RIGHT,
        DIAGONAL_FROM_TOP_LEFT, DIAGONAL_FROM_TOP_RIGHT
    }

    private int mRadius;
    private int mDiameter;
    private int mMargin;
    private CornerType mCornerType;

    public RoundedCornersTransformation(int radius, int margin) {
        this(radius, margin, CornerType.ALL);
    }

    public RoundedCornersTransformation(int radius, int margin, CornerType cornerType) {
        mRadius = radius;
        mDiameter = radius * 2;
        mMargin = margin;
        mCornerType = cornerType;
    }

    @Override public Bitmap transform(Bitmap source) {
        int width = source.getWidth();
        int height = source.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
        drawRoundRect(canvas, paint, width, height);
        source.recycle();
        return bitmap;
    }

    private void drawRoundRect(Canvas canvas, Paint paint, float width, float height) {
        float right = width - mMargin;
        float bottom = height - mMargin;
        switch (mCornerType) {
            case ALL:
                canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
            break;
            case TOP_LEFT:
                drawTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case TOP_RIGHT:
                drawTopRightRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM_LEFT:
                drawBottomLeftRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM_RIGHT:
                drawBottomRightRoundRect(canvas, paint, right, bottom);
            break;
            case TOP:
                drawTopRoundRect(canvas, paint, right, bottom);
            break;
            case BOTTOM:
                drawBottomRoundRect(canvas, paint, right, bottom);
            break;
            case LEFT:
                drawLeftRoundRect(canvas, paint, right, bottom);
            break;
            case RIGHT:
                drawRightRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_TOP_LEFT:
                drawOtherTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_TOP_RIGHT:
                drawOtherTopRightRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_BOTTOM_LEFT:
                drawOtherBottomLeftRoundRect(canvas, paint, right, bottom);
            break;
            case OTHER_BOTTOM_RIGHT:
                drawOtherBottomRightRoundRect(canvas, paint, right, bottom);
            break;
            case DIAGONAL_FROM_TOP_LEFT:
                drawDiagonalFromTopLeftRoundRect(canvas, paint, right, bottom);
            break;
            case DIAGONAL_FROM_TOP_RIGHT:
                drawDiagonalFromTopRightRoundRect(canvas, paint, right, bottom);
            break;
            default:
                canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
            break;
        }
    }

    private void drawTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, mMargin + mRadius, bottom), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
        canvas.drawRect(new RectF(right - mRadius, mMargin + mRadius, right, bottom), paint);
    }

    private void drawBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom - mRadius), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
        canvas.drawRect(new RectF(right - mRadius, mMargin, right, bottom - mRadius), paint);
    }

    private void drawTopRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right, bottom), paint);
    }

    private void drawBottomRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right, bottom - mRadius), paint);
    }

    private void drawLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
    }

    private void drawRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
    }

    private void drawOtherTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
    }

    private void drawOtherTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom - mRadius), paint);
    }

    private void drawOtherBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mRadius, bottom), paint);
    }

    private void drawOtherBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
    }

    private void drawDiagonalFromTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mDiameter, bottom), paint);
        canvas.drawRect(new RectF(mMargin + mDiameter, mMargin, right, bottom - mRadius), paint);
    }

    private void drawDiagonalFromTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
        canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius, mRadius, paint);
        canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom), mRadius, mRadius, paint);
        canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
        canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
    }

    @Override public String key() {
        return "RoundedTransformation(radius=" + mRadius + ", margin=" + mMargin + ", diameter=" + mDiameter + ", cornerType=" + mCornerType.name() + ")";
    }
}

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

Visual Studio Code pylint: Unable to import 'protorpc'

First I will check the python3 path where it lives

enter image description here

And then in the VS Code settings just add that path, for example:

"python.pythonPath": "/usr/local/bin/python3"

How to trim whitespace from a Bash variable?

In order to remove all the spaces from the beginning and the end of a string (including end of line characters):

echo $variable | xargs echo -n

This will remove duplicate spaces also:

echo "  this string has a lot       of spaces " | xargs echo -n

Produces: 'this string has a lot of spaces'

Running javascript in Selenium using Python

If you move from iframes, you may get lost in your page, best way to execute some jquery without issue (with selenimum/python/gecko):

# 1) Get back to the main body page
driver.switch_to.default_content()

# 2) Download jquery lib file to your current folder manually & set path here
with open('./_lib/jquery-3.3.1.min.js', 'r') as jquery_js: 
    # 3) Read the jquery from a file
    jquery = jquery_js.read() 
    # 4) Load jquery lib
    driver.execute_script(jquery)
    # 5) Execute your command 
    driver.execute_script('$("#myId").click()')

Select N random elements from a List<T> in C#

I would use an extension method.

    public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> elements, int countToTake)
    {
        var random = new Random();

        var internalList = elements.ToList();

        var selected = new List<T>();
        for (var i = 0; i < countToTake; ++i)
        {
            var next = random.Next(0, internalList.Count - selected.Count);
            selected.Add(internalList[next]);
            internalList[next] = internalList[internalList.Count - selected.Count];
        }
        return selected;
    }

How to check if a string starts with a specified string?

You can check if your string starts with http or https using the small function below.

function has_prefix($string, $prefix) {
   return substr($string, 0, strlen($prefix)) == $prefix;
}

$url   = 'http://www.google.com';
echo 'the url ' . (has_prefix($url, 'http://')  ? 'does' : 'does not') . ' start with http://';
echo 'the url ' . (has_prefix($url, 'https://') ? 'does' : 'does not') . ' start with https://';

How can I make the Android emulator show the soft keyboard?

To be more precise, with Lollipop these are the steps I followed to show soft keyboard:

  1. Settings > Language & Input;
  2. under "Keyboard & input methods" label, select "Current Keyboard";
  3. A Dialog named "Change Keyboard" appears, switch ON "Hardware", then select "Choose keyboards";
  4. another Dialog appears, switch ON the "Sample Soft Keyboard". Here you get an alert about the possibility that keyboard will store everything you write, also passwords. Give OK;
  5. Repeat above steps in order to show "Change Keyboard" Dialog again, here the new option "Sample Soft Keyboard" is available and you can select it.

NOTE: after that, you might experience problems in running you app (as I had). Simply restart the emulator.

[Vue warn]: Property or method is not defined on the instance but referenced during render

If you use two times vue instance. Then it will give you this error. For example in app.js and your own script tag in view file. Just use one time

 const app = new Vue({
    el: '#app',
});

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

Gooye if it's possible to use Joda Time in your project then this code works for me:

String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);

String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);

Changing the space between each item in Bootstrap navbar

As of Bootstrap 4, you can use the spacing utilities.

Add for instance px-2 in the classes of the nav-item to increase the padding.

module.exports vs. export default in Node.js and ES6

Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs

module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export

// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()

Defining constant string in Java?

simply use

final String WELCOME_MESSAGE = "Hello, welcome to the server";

the main part of this instruction is the 'final' keyword.

rsync error: failed to set times on "/foo/bar": Operation not permitted

I had the same problem. For me the solution is to delete the remote file and let rsync create again.

How can I get a list of Git branches, ordered by most recent commit?

Use the --sort=-committerdate option of git for-each-ref;

Also available since Git 2.7.0 for git branch:

Basic Usage:

git for-each-ref --sort=-committerdate refs/heads/

# Or using git branch (since version 2.7.0)
git branch --sort=-committerdate  # DESC
git branch --sort=committerdate  # ASC

Result:

Result

Advanced Usage:

git for-each-ref --sort=committerdate refs/heads/ --format='%(HEAD) %(color:yellow)%(refname:short)%(color:reset) - %(color:red)%(objectname:short)%(color:reset) - %(contents:subject) - %(authorname) (%(color:green)%(committerdate:relative)%(color:reset))'

Result:

Result

How to pass all arguments passed to my bash script to a function of mine?

I needed a variation on this, which I expect will be useful to others:

function diffs() {
        diff "${@:3}" <(sort "$1") <(sort "$2")
}

The "${@:3}" part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff:

diffs file1 file2 [other diff args, e.g. -y]

How can I get selector from jQuery object

Are you trying to get the name of the current tag that was clicked?

If so, do this..

$("*").click(function(){
    alert($(this)[0].nodeName);
});

You can't really get the "selector", the "selector" in your case is *.

Renaming branches remotely in Git

First checkout to the branch which you want to rename:

git branch -m old_branch new_branch
git push -u origin new_branch

To remove an old branch from remote:

git push origin :old_branch

Array slices in C#

In C# 7.2, you can use Span<T>. The benefit of the new System.Memory system is that it doesn't need copying around data.

The method you need is Slice:

Span<byte> slice = foo.Slice(0, 40);

A lot of methods now support Span and IReadOnlySpan, so it will be very straightforward to use this new type.

Note that at the time of writing the Span<T> type is not defined in the the most recent version of .NET yet (4.7.1) so to use it you need to install the System.Memory package from NuGet.

How to use If Statement in Where Clause in SQL?

You have to use CASE Statement/Expression

Select * from Customer
WHERE  (I.IsClose=@ISClose OR @ISClose is NULL)  
AND    
    (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )    
AND 
     CASE @Value
         WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL) 
         WHEN 3 THEN (CASE WHEN I.RecurringCharge like 
                               '%'+cast(@Total as varchar(50))+'%' 
                     or @Total is NULL )
     END

Node.js Error: connect ECONNREFUSED

If you are on MEAN (Mongo-Express-AngularJS-Node) stack, run mongod first, and this error message will go away.

Avoid trailing zeroes in printf()

Your code rounds to three decimal places due to the ".3" before the f

printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);

Thus if you the second line rounded to two decimal places, you should change it to this:

printf("%1.3f", 359.01335);
printf("%1.2f", 359.00999);

That code will output your desired results:

359.013
359.01

*Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:

printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);

The Following program source code was my test for this answer

#include <cstdio>

int main()
{

    printf("%1.3f\n", 359.01335);
    printf("%1.2f\n", 359.00999);

    while (true){}

    return 0;

}

How to trigger a build only if changes happen on particular set of files

While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:

/*
 * Check a folder if changed in the latest commit.
 * Returns true if changed, or false if no changes.
 */
def checkFolderForDiffs(path) {
    try {
        // git diff will return 1 for changes (failure) which is caught in catch, or
        // 0 meaning no changes 
        sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
        return false
    } catch (err) {
        return true
    }
}

if ( checkFolderForDiffs('api/') ) {
    //API folder changed, run steps here
}

Unable to resolve host "<URL here>" No address associated with host name

Check permission for INTERNET in mainfest file and check network connectivity.

Set the maximum character length of a UITextField in Swift

update for this Fattie answer

thanks

extension UITextField {

    /// Runtime key
    private struct AssociatedKeys {
        /// max lenght key
        static var maxlength: UInt8 = 0
        /// temp string key
        static var tempString: UInt8 = 0
    }

    /// Limit the maximum input length of the textfiled
    @IBInspectable var maxLength: Int {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.maxlength) as? Int ?? 0
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.maxlength, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            addTarget(self, action: #selector(handleEditingChanged(textField:)), for: .editingChanged)
        }
    }

    /// temp string
    private var tempString: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.tempString) as? String
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.tempString, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    /// When the text changes, process the amount of text in the input box so that its length is within the controllable range.
    @objc private func handleEditingChanged(textField: UITextField) {

        /// Special Processing for Chinese Input Method
        guard markedTextRange == nil else { return }

        if textField.text?.count == maxLength {

            /// SET lastQualifiedString where text length == max lenght
            tempString = textField.text
        } else if textField.text?.count ?? 0 < maxLength {

            /// clear lastQualifiedString when text lengeht > maxlength
            tempString = nil
        }

        /// keep current text range in arcgives
        let archivesEditRange: UITextRange?

        if textField.text?.count ?? 0 > maxLength {

            /// if text length > maxlength,remove last range,to move to -1 postion.
            let position = textField.position(from: safeTextPosition(selectedTextRange?.start), offset: -1) ?? textField.endOfDocument
            archivesEditRange = textField.textRange(from: safeTextPosition(position), to: safeTextPosition(position))
        } else {

            /// just set current select text range
            archivesEditRange = selectedTextRange
        }

        /// main handle string max length
        textField.text = tempString ?? String((textField.text ?? "").prefix(maxLength))

        /// last config edit text range
        textField.selectedTextRange = archivesEditRange
    }

    /// get safe textPosition
    private func safeTextPosition(_ optionlTextPosition: UITextPosition?) -> UITextPosition {

        /* beginningOfDocument -> The end of the the text document. */
        return optionlTextPosition ?? endOfDocument
    }
}

Best way to Bulk Insert from a C# DataTable

Here's how I do it using a DataTable. This is a working piece of TEST code.

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();

    // Create a table with some rows. 
    DataTable table = MakeTable();

    // Get a reference to a single row in the table. 
    DataRow[] rowArray = table.Select();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
    {
        bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";

        try
        {
            // Write the array of rows to the destination.
            bulkCopy.WriteToServer(rowArray);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

}//using

What's default HTML/CSS link color?

As of HTML5, the foreground colors of hyperlinks, among other things, are on track for standardization in the form of guidelines for expected default rendering behavior. In particular, taken from the section Phrasing content, the recommended default colors for unvisited and visited hyperlinks are the following:

:link { color: #0000EE; }
:visited { color: #551A8B; }

Notice that there is no recommended default for active hyperlinks (:link:active, :visited:active), however.

You can use these default colors and reasonably expect them to work. But keep in mind that a browser is free to ignore any or all of these guidelines, as it is never required to follow them. It is, however, recommended for a consistent user experience across browsers (which is how "expected" is defined in this context), so chances are that these colors will correspond to the defaults for most browsers. At worst, they still serve as reasonable approximations of the actual values.

In particular, the default unvisited and visited link colors in the latest versions of Firefox and Chrome are consistent with the above guidelines, but recent versions of IE report different values: unvisited links are rgb(0, 102, 204), or #0066CC, and visited links are rgb(128, 0, 128), or #800080. Older versions of Firefox (and possibly Safari/Chrome) had different defaults as well. Those are older versions, however; the main outlier today that I am aware of is IE. No word yet on whether this will change in Project Spartan — currently it still reflects the same values as the latest version of IE.

If you are looking for a standardized color scheme that is used by all browsers rather than suggested by HTML5, then there isn't one. Neither is there a way to revert to a browser's default value for a particular property on a particular element using pure CSS. You will have to either use the colors suggested by HTML5, or devise your own color scheme and use that instead. Either of these options will take precedence over a browser's defaults, regardless of browser.

If in doubt, you can always use the about:blank technique I described before to sniff out the default colors, as it remains applicable today. You can use this to sniff the active link color in all browsers, for example; in the latest version of Firefox (29 as of this update), it's rgb(238, 0, 0), or #EE0000.

How do I use Comparator to define a custom sort order?

Using just simple loops:

public static void compareSortOrder (List<String> sortOrder, List<String> listToCompare){
        int currentSortingLevel = 0;
        for (int i=0; i<listToCompare.size(); i++){
            System.out.println("Item from list: " + listToCompare.get(i));
            System.out.println("Sorting level: " + sortOrder.get(currentSortingLevel));
            if (listToCompare.get(i).equals(sortOrder.get(currentSortingLevel))){

            } else {
                try{
                    while (!listToCompare.get(i).equals(sortOrder.get(currentSortingLevel)))
                        currentSortingLevel++;
                    System.out.println("Changing sorting level to next value: " + sortOrder.get(currentSortingLevel));
                } catch (ArrayIndexOutOfBoundsException e){

                }

            }
        }
    }

And sort order in List

public static List<String> ALARMS_LIST = Arrays.asList(
            "CRITICAL",
            "MAJOR",
            "MINOR",
            "WARNING",
            "GOOD",
            "N/A");

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

Loop backwards using indices in Python?

Try range(100,-1,-1), the 3rd argument being the increment to use (documented here).

("range" options, start, stop, step are documented here)

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the equivalent to getch() & getche() in Linux?

#include <unistd.h>
#include <termios.h>

char getch(void)
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if(tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if(tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if(read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    printf("%c\n", buf);
    return buf;
 }

Remove the last printf if you don't want the character to be displayed.

.mp4 file not playing in chrome

After running into the same issue - here're some of my thoughts:

  • due to Chrome removing support for h264, on some machines, mp4 videos encoded with it will either not work (throwing an Parser error when viewing under Firebug/Network tab - consistent with issue submitted here), or crash the browser, depending upon the encoding settings
  • it isn't consistent - it entirely depends upon the codecs installed on the computer - while I didn't encounter this issue on my machine, we did have one in the office where the issue occurred (and thus we used this one for testing)
  • it might to do with Quicktime / divX settings (the machine in question had an older version of Quicktime than my native one - we didn't want to loose our testing pc though, so we didn't update it).

As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:

for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:

if (window.chrome)
    $("[type=video\\\/mp4]").each(function()
    {
        $(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
    });

Unfortunately it's a bad Chrome hack, but hey, at least it works.

Source: user: eithedog

This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec

Also check your version of crome here: html5test

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

Renaming a branch in GitHub

Rename branches in Git local and remote

1. Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

If you are on a different branch:

git branch -m old-name new-name

2. Delete the old-name remote branch and push the new-name local branch.

git push origin :old-name new-name

3. Reset the upstream branch for the new-name local branch.

Switch to the branch and then:

git push origin -u new-name

So the conclusion is:

git branch -m new-name
git push origin :old-name new-name
git push origin -u new-name

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

ExecuteReader: Connection property has not been initialized

You can also write this:

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);

How to parse JSON Array (Not Json Object) in Android

Old post I know, but unless I've misunderstood the question, this should do the trick:

s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
    alert(array[i][index]);
}

}

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

You will need to add external Repository to your pom, since this is using Mulsoft-Release repository not Maven Central

<project>
   ...
    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>
  ...
</project>

Dependency

Apache Maven - Setting up Multiple Repositories

Bootstrap css hides portion of container below navbar navbar-fixed-top

I too have had this problem but solved it without script and only using CSS. I start by following the recommended padding-top for a fixed menu by setting of 60px described on the Bootstrap website. Then I added three media tags that resize the padding at the cutoff points where my menu also resizes.

<style>      
    body{
        padding-top:60px;
    }
    /* fix padding under menu after resize */
    @media screen and (max-width: 767px) {
        body { padding-top: 60px; }
    }
    @media screen and (min-width:768px) and (max-width: 991px) {
        body { padding-top: 110px; }
    }
    @media screen and (min-width: 992px) {
        body { padding-top: 60px; }
    }
</style>

One note, when my menu width is between 768 and 991, the menu logo in my layout plus the <li> options cause the menu to wrap to two lines. Therefore, I had to adjust the padding-top to prevent the menu from covering the content, hence 110px.

Hope this helps...

Change remote repository credentials (authentication) on Intellij IDEA 14

You can change your password from settings screen (Ctrl + Alt + S by default) as attached screenshot. After clearing, on the firts remote operation (like pull/push, etc.) it'll ask you your credentials)

IMPORTANT: Take a copy of the file before this operation.

Settings Screen

PHP Fatal error: Cannot access empty property

Interesting:

  1. You declared an array var $my_value = array();
  2. Pushed value into it $a->my_value[] = 'b';
  3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
  4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

And your foreach wont work anymore.

How can I use grep to show just filenames on Linux?

From the grep(1) man page:

  -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)

Detect element content changes with jQuery

I wrote a snippet that will check for the change of an element on an event.

So if you are using third party javascript code or something and you need to know when something appears or changes when you have clicked then you can.

For the below snippet, lets say you need to know when a table content changes after you clicked a button.

$('.button').live('click', function() {

            var tableHtml = $('#table > tbody').html();
            var timeout = window.setInterval(function(){

                if (tableHtml != $('#table > tbody').
                    console.log('no change');
                } else {
                    console.log('table changed!');
                    clearInterval(timeout);
                }

            }, 10);
        });

Pseudo Code:

  • Once you click a button
  • the html of the element you are expecting to change is captured
  • we then continually check the html of the element
  • when we find the html to be different we stop the checking

Form submit with AJAX passing form data to PHP without page refresh

$(document).ready(function(){
$('#userForm').on('submit', function(e){
        e.preventDefault();
//I had an issue that the forms were submitted in geometrical progression after the next submit. 
// This solved the problem.
        e.stopImmediatePropagation();
    // show that something is loading
    $('#response').html("<b>Loading data...</b>");

    // Call ajax for pass data to other place
    $.ajax({
    type: 'POST',
    url: 'somephpfile.php',
    data: $(this).serialize() // getting filed value in serialize form
    })
    .done(function(data){ // if getting done then call.

    // show the response
    $('#response').html(data);

    })
    .fail(function() { // if fail then getting message

    // just in case posting your form failed
    alert( "Posting failed." );

    });

    // to prevent refreshing the whole page page
    return false;

    });

Get Hard disk serial Number

The best way I found is, download a dll from here

Then, add the dll to your project.

Then, add code:

[DllImportAttribute("HardwareIDExtractorC.dll")]
public static extern String GetIDESerialNumber(byte DriveNumber);

Then, call the hard disk ID from where you need it

GetIDESerialNumber(0).Replace(" ", string.Empty);

Note: go to properties of the dll in explorer and set "Build action" to "Embedded Resource"

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

How to build PDF file from binary string returned from a web-service using javascript

The answer of @alexandre with base64 does the trick.

The explanation why that works for IE is here

https://en.m.wikipedia.org/wiki/Data_URI_scheme

Under header 'format' where it says

Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset's specification must precede the base64 token.

Laravel Eloquent - distinct() and count() not working properly together

Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.

public function scopeShowProductCount($query)
{
    $query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
          ->groupBy('pid')
          ->orderBy('count_pid', 'desc');
}

This facade worked to get the same result in the controller:

$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();

The resulting dump for both queries was as follows:

#attributes: array:2 [
  "pid" => "1271"
  "count_pid" => 19
],
#attributes: array:2 [
  "pid" => "1273"
  "count_pid" => 12
],
#attributes: array:2 [
  "pid" => "1275"
  "count_pid" => 7
]

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

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

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

Casting int to bool in C/C++

The following cites the C11 standard (final draft).

6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

bool (mapped by stdbool.h to the internal name _Bool for C) itself is an unsigned integer type:

... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

According to 6.2.5p2:

An object declared as type _Bool is large enough to store the values 0 and 1.

AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool for C++ and _Bool for C.

Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool behaves as in C++.

Validate email with a regex in jQuery

function mailValidation(val) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!expr.test(val)) {
        $('#errEmail').text('Please enter valid email.');
    }
    else {
        $('#errEmail').hide();
    }
}

Android 'Unable to add window -- token null is not for an application' exception

I got this exception, when I tried to open Progress Dialog under Cordova Plugin by using below two cases,

  1. new ProgressDialog(this.cordova.getActivity().getParent());

  2. new ProgressDialog(this.cordova.getActivity().getApplicationContext());

Later changed like this,

new ProgressDialog(this.cordova.getActivity());

Its working fine for me.

"PKIX path building failed" and "unable to find valid certification path to requested target"

This is a solution but in form of my story with this problem:

I was almost dead trying all the solution given above(for 3 days ) and nothing worked for me.

I lost all hope.

I contacted my security team regarding this because i was behind a proxy and they told that they had recently updated their security policy.

I scolded them badly for not informing the Developers.

Later they issued a new "cacerts" file which contains all the certificates.

I removed the cacerts file which is present inside %JAVA_HOME%/jre/lib/security and it solved my problem.

So if you are facing this issue it might be from your network team also like this.

How to trigger a phone call when clicking a link in a web page on mobile phone

Essentially, use an <a> element with an href attr pointing to the phone number prefixed by tel:. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.

MDN Web Docs

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link

The HTML <a> element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

[…]

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

<a href="tel:+491570156">+49 157 0156</a>

IETF Documents

https://tools.ietf.org/html/rfc3966

The tel URI for Telephone Numbers

The "tel" URI has the following syntax:

telephone-uri = "tel:" telephone-subscriber

[…]

Examples

tel:+1-201-555-0123: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.

tel:7042;phone-context=example.com: The URI describes a local phone number valid within the context "example.com".

tel:863-1234;phone-context=+1-914-555: The URI describes a local phone number that is valid within a particular phone prefix.

Count number of days between two dates

To have the number of whole days between two dates (DateTime objects):

((end_at - start_at).to_f / 1.day).floor

Having both a Created and Last Updated timestamp columns in MySQL 4.0

My web host is stuck on version 5.1 of mysql so anyone like me that doesn't have the option of upgrading can follow these directions:

http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

Show space, tab, CRLF characters in editor of Visual Studio

Display white space characters

Menu: You can toggle the visibility of the white space characters from the menu: Edit > Advanced > View White Space.

Button: If you want to add the button to a toolbar, it is called Toggle Visual Space in the command category "Edit".
The actual command name is: Edit.ViewWhiteSpace.

Keyboard Shortcut: In Visual Studio 2015, 2017 and 2019 the default keyboard shortcut still is CTRL+R, CTRL+W
Type one after the other.
All default shortcuts

End-of-line characters

Extension: There is a minimal extension adding the displaying of end-of-line characters (LF and CR) to the visual white space mode, as you would expect. Additionally it supplies buttons and short-cuts to modify all line-endings in a document, or a selection.
VisualStudio gallery: End of the Line

Note: Since Visual Studio 2017 there is no option in the File-menu called Advanced Save Options. Changing the encoding and line-endings for a file can be done using Save File As ... and clicking the down-arrow on the right side of the save-button. This shows the option Save with Encoding. You'll be asked permission to overwrite the current file.

angular 4: *ngIf with multiple conditions

Besides the redundant ) this expression will always be true because currentStatus will always match one of these two conditions:

currentStatus !== 'open' || currentStatus !== 'reopen'

perhaps you mean one of

!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')

ViewPager and fragments — what's the right way to store fragment's state?

My solution is very rude but works: being my fragments dynamically created from retained data, I simply remove all fragment from the PageAdapter before calling super.onSaveInstanceState() and then recreate them on activity creation:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("viewpagerpos", mViewPager.getCurrentItem() );
    mSectionsPagerAdapter.removeAllfragments();
    super.onSaveInstanceState(outState);
}

You can't remove them in onDestroy(), otherwise you get this exception:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Here the code in the page adapter:

public void removeAllfragments()
{
    if ( mFragmentList != null ) {
        for ( Fragment fragment : mFragmentList ) {
            mFm.beginTransaction().remove(fragment).commit();
        }
        mFragmentList.clear();
        notifyDataSetChanged();
    }
}

I only save the current page and restore it in onCreate(), after the fragments have been created.

if (savedInstanceState != null)
    mViewPager.setCurrentItem( savedInstanceState.getInt("viewpagerpos", 0 ) );  

How to set corner radius of imageView?

import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer

Sorting HTML table with JavaScript

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
var collection = [{_x000D_
  "Country": "France",_x000D_
  "Date": "2001-01-01",_x000D_
  "Size": "25",_x000D_
}, {_x000D_
  "Country": "spain",_x000D_
  "Date": "2005-05-05",_x000D_
  "Size": "",_x000D_
}, {_x000D_
  "Country": "Lebanon",_x000D_
  "Date": "2002-02-02",_x000D_
  "Size": "-17",_x000D_
}, {_x000D_
  "Country": "Argentina",_x000D_
  "Date": "2005-04-04",_x000D_
  "Size": "100",_x000D_
}, {_x000D_
  "Country": "USA",_x000D_
  "Date": "",_x000D_
  "Size": "-6",_x000D_
}]_x000D_
_x000D_
for (var j = 0; j < 3; j++) {_x000D_
  $("#myTable th:eq(" + j + ")").addClass("control-label clickable");_x000D_
  $("#myTable th:eq(" + j + ")").attr('onClick', "w3.sortHTML('#myTable', '.item', 'td:nth-child(" + (j + 1) + ")')");_x000D_
}_x000D_
_x000D_
$tbody = $("#myTable").append('<tbody></tbody>');_x000D_
_x000D_
for (var i = 0; i < collection.length; i++) {_x000D_
  $tbody = $tbody.append('<tr class="item"><td>' + collection[i]["Country"] + '</td><td>' + collection[i]["Date"] + '</td><td>' + collection[i]["Size"] + '</td></tr>');_x000D_
}
_x000D_
.control-label:after {_x000D_
  content: "*";_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.clickable {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="myTable" class="w3-table-all">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Country</th>_x000D_
      <th>Date</th>_x000D_
      <th>Size</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
</table>
_x000D_
_x000D_
_x000D_

UTF-8 byte[] to String

Here's a simplified function that will read in bytes and create a string. It assumes you probably already know what encoding the file is in (and otherwise defaults).

static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";

public static String readFileToString(String filePath, String encoding) throws IOException {

    if (encoding == null || encoding.length() == 0)
        encoding = DEFAULT_ENCODING;

    StringBuffer content = new StringBuffer();

    FileInputStream fis = new FileInputStream(new File(filePath));
    byte[] buffer = new byte[BUFF_SIZE];

    int bytesRead = 0;
    while ((bytesRead = fis.read(buffer)) != -1)
        content.append(new String(buffer, 0, bytesRead, encoding));

    fis.close();        
    return content.toString();
}

Margin on child element moves parent element

This is normal behaviour (among browser implementations at least). Margin does not affect the child's position in relation to its parent, unless the parent has padding, in which case most browsers will then add the child's margin to the parent's padding.

To get the behaviour you want, you need:

.child {
    margin-top: 0;
}

.parent {
    padding-top: 10px;
}

XAMPP - Apache could not start - Attempting to start Apache service

In my case, with the same problem and Xampp window, I had copied \apache\conf\extra\httpd-vhosts.conf entries from an old Xampp version to a newly installed one so I could continue to open local projects in browsers. One of the vhosts paths was wrong. After deleting that entry Apache started without problem.

The reference by @Karthik to "in the Event viewer (Control panel -> View Event Logs" saved me time. It's all too easy to presume Xampp logs will point to the problem. It doesn't.

SOAP or REST for Web Services?

SOAP is useful from a tooling perspective because the WSDL is so easily consumed by tools. So, you can get Web Service clients generated for you in your favorite language.

REST plays well with AJAX'y web pages. If you keep your requests simple, you can make service calls directly from your JavaScript, and that comes in very handy. Try to stay away from having any namespaces in your response XML, I've seen browsers choke on those. So, xsi:type is probably not going to work for you, no overly complex XML Schemas.

REST tends to have better performance as well. CPU requirements of the code generating REST responses tend to be lower than what SOAP frameworks exhibit. And, if you have your XML generation ducks lined up on the server side, you can effectively stream XML out to the client. So, imagine you're reading rows of database cursor. As you read a row, you format it as an XML element, and you write that directly out to the service consumer. This way, you don't have to collect all of the database rows in memory before starting to write your XML output - you read and write at the same time. Look into novel templating engines or XSLT to get the streaming to work for REST.

SOAP on the other hand tends to get generated by tool-generated services as a big blob and only then written. This is not an absolute truth, mind you, there are ways to get streaming characteristics out of SOAP, like by using attachments.

My decision making process is as follows: if I want my service to be easily tooled by consumers, and the messages I write will be medium-to-small-ish (10MB or less), and I don't mind burning some extra CPU cycles on the server, I go with SOAP. If I need to serve to AJAX on web browsers, or I need the thing to stream, or my responses are gigantic, I go REST.

Finally, there are lots of great standards built up around SOAP, like WS-Security and getting stateful Web Services, that you can plug in to if you're using the right tools. That kind of stuff really makes a difference, and can help you satisfy some hairy requirements.

How to fix curl: (60) SSL certificate: Invalid certificate chain

NOTE: This answer obviously defeats the purpose of SSL and should be used sparingly as a last resort.

For those having issues with scripts that download scripts that download scripts and want a quick fix, create a file called ~/.curlrc

With the contents

--insecure

This will cause curl to ignore SSL certificate problems by default.

Make sure you delete the file when done.

UPDATE

12 days later I got notified of an upvote on this answer, which made me go "Hmmm, did I follow my own advice remember to delete that .curlrc?", and discovered I hadn't. So that really underscores how easy it is to leave your curl insecure by following this method.

System has not been booted with systemd as init system (PID 1). Can't operate

I had this problem running WSL 2

the solution was the command

 $ sudo dockerd

if after that you still have a problem with permission, run the command:

 $ sudo usermod -aG docker your-user

How can I get the active screen dimensions?

Adding a solution that doesn't use WinForms but NativeMethods instead. First you need to define the native methods needed.

public static class NativeMethods
{
    public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
    public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;


    [DllImport( "user32.dll" )]
    public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );


    [DllImport( "user32.dll" )]
    public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );


    [Serializable, StructLayout( LayoutKind.Sequential )]
    public struct NativeRectangle
    {
        public Int32 Left;
        public Int32 Top;
        public Int32 Right;
        public Int32 Bottom;


        public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
        {
            this.Left = left;
            this.Top = top;
            this.Right = right;
            this.Bottom = bottom;
        }
    }


    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
    public sealed class NativeMonitorInfo
    {
        public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
        public NativeRectangle Monitor;
        public NativeRectangle Work;
        public Int32 Flags;
    }
}

And then get the monitor handle and the monitor info like this.

        var hwnd = new WindowInteropHelper( this ).EnsureHandle();
        var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );

        if ( monitor != IntPtr.Zero )
        {
            var monitorInfo = new NativeMonitorInfo();
            NativeMethods.GetMonitorInfo( monitor, monitorInfo );

            var left = monitorInfo.Monitor.Left;
            var top = monitorInfo.Monitor.Top;
            var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
            var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
        }

Best practices to test protected methods with PHPUnit

You can indeed use __call() in a generic fashion to access protected methods. To be able to test this class

class Example {
    protected function getMessage() {
        return 'hello';
    }
}

you create a subclass in ExampleTest.php:

class ExampleExposed extends Example {
    public function __call($method, array $args = array()) {
        if (!method_exists($this, $method))
            throw new BadMethodCallException("method '$method' does not exist");
        return call_user_func_array(array($this, $method), $args);
    }
}

Note that the __call() method does not reference the class in any way so you can copy the above for each class with protected methods you want to test and just change the class declaration. You may be able to place this function in a common base class, but I haven't tried it.

Now the test case itself only differs in where you construct the object to be tested, swapping in ExampleExposed for Example.

class ExampleTest extends PHPUnit_Framework_TestCase {
    function testGetMessage() {
        $fixture = new ExampleExposed();
        self::assertEquals('hello', $fixture->getMessage());
    }
}

I believe PHP 5.3 allows you to use reflection to change the accessibility of methods directly, but I assume you'd have to do so for each method individually.

Run Stored Procedure in SQL Developer?

With simple parameter types (i.e. not refcursors etc.) you can do something like this:

SET serveroutput on;
DECLARE
    InParam1 number;
    InParam2 number;
    OutParam1 varchar2(100);
    OutParam2 varchar2(100);
    OutParam3 varchar2(100);
    OutParam4 number;
BEGIN
    /* Assign values to IN parameters */
    InParam1 := 33;
    InParam2 := 89;

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(InParam1, InParam2,
        OutParam1, OutParam2, OutParam3, OutParam4);

    /* Display OUT parameters */
    dbms_output.put_line('OutParam1: ' || OutParam1);
    dbms_output.put_line('OutParam2: ' || OutParam2);
    dbms_output.put_line('OutParam3: ' || OutParam3);
    dbms_output.put_line('OutParam4: ' || OutParam4);
END;
/


Edited to use the OP's spec, and with an alternative approach to utilise :var bind variables:

var InParam1 number;
var InParam2 number;
var OutParam1 varchar2(100);
var OutParam2 varchar2(100);
var OutParam3 varchar2(100);
var OutParam4 number;

BEGIN
    /* Assign values to IN parameters */
    :InParam1 := 33;
    :InParam2 := 89;

    /* Call procedure within package, identifying schema if necessary */
    schema.package.procedure(:InParam1, :InParam2,
        :OutParam1, :OutParam2, :OutParam3, :OutParam4);
END;
/

-- Display OUT parameters
print :OutParam1;
print :OutParam2;
print :OutParam3;
print :OutParam4;

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

A workaround for CONTAINS: If you don't want to create a full text Index on the column, and performance is not one of your priorities you could use the LIKE statement which doesn't need any prior configuration:

Example: find all Products that contains the letter Q:

SELECT ID, ProductName
FROM [ProductsDB].[dbo].[Products]
WHERE [ProductsDB].[dbo].[Products].ProductName LIKE '%Q%'

Check string for palindrome

public boolean isPalindrome(String abc){
    if(abc != null && abc.length() > 0){
        char[] arr = abc.toCharArray();
        for (int i = 0; i < arr.length/2; i++) {
            if(arr[i] != arr[arr.length - 1 - i]){
                return false;
            }
        }
        return true;
    }
    return false;
}

How to use router.navigateByUrl and router.navigate in Angular

router.navigate vs router.navigateByUrl

router.navigate is just a convenience method that wraps router.navigateByUrl, it boils down to:

navigate(commands: any[], extras) {
    return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}

As mentioned in other answers router.navigateByUrl will only accept absolute URLs:

// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})

All the relative calculations are done by router.createUrlTree and router.navigate. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".." - go up, "path" - go down, {expand: true} - add query param, etc.. You can use it like this:

// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});

That {relativeTo: route} parameter is important as that's what router will use as the root for relative operations.

Get it through your component's constructor:

  // In my-awesome.component.ts:

  constructor(private route: ActivatedRoute, private router: Router) {}
  
  // Example call
  onNavigateClick() {
    // Navigates to a parent component
    this.router.navigate([..], { relativeTo: this.route })
  }

routerLink directive

Nicest thing about this directive is that it will retrieve the ActivatedRoute for you. Under the hood it's using already familiar:

router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });

Following variants will produce identical result:

[routerLink]="['../..']"

// if the string parameter is passed it will be wrapped into an array
routerLink="../.."

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

Collection was modified; enumeration operation may not execute

So a different way to solve this problem would be instead of removing the elements create a new dictionary and only add the elements you didnt want to remove then replace the original dictionary with the new one. I don't think this is too much of an efficiency problem because it does not increase the number of times you iterate over the structure.

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.