Programs & Examples On #Broken pipe

Broken pipe is a general term for when a process is unable to output to a socket or pipe due to no process reading from the other end of the pipe.

How to prevent SIGPIPEs (or handle them properly)

Handle SIGPIPE Locally

It's usually best to handle the error locally rather than in a global signal event handler since locally you will have more context as to what's going on and what recourse to take.

I have a communication layer in one of my apps that allows my app to communicate with an external accessory. When a write error occurs I throw and exception in the communication layer and let it bubble up to a try catch block to handle it there.

Code:

The code to ignore a SIGPIPE signal so that you can handle it locally is:

// We expect write failures to occur but we want to handle them where 
// the error occurs rather than in a SIGPIPE handler.
signal(SIGPIPE, SIG_IGN);

This code will prevent the SIGPIPE signal from being raised, but you will get a read / write error when trying to use the socket, so you will need to check for that.

How to prevent errno 32 broken pipe?

This might be because you are using two method for inserting data into database and this cause the site to slow down.

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email).save()  <==== 
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

In above function, the error is where arrow is pointing. The correct implementation is below:

def add_subscriber(request, email=None):
    if request.method == 'POST':
        email = request.POST['email_field']
        e = Subscriber.objects.create(email=email)
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/')

What causes the Broken Pipe Error?

It can take time for the network close to be observed - the total time is nominally about 2 minutes (yes, minutes!) after a close before the packets destined for the port are all assumed to be dead. The error condition is detected at some point. With a small write, you are inside the MTU of the system, so the message is queued for sending. With a big write, you are bigger than the MTU and the system spots the problem quicker. If you ignore the SIGPIPE signal, then the functions will return EPIPE error on a broken pipe - at some point when the broken-ness of the connection is detected.

What's the advantage of a Java enum versus a class with public static final fields?

Technically one could indeed view enums as a class with a bunch of typed constants, and this is in fact how enum constants are implemented internally. Using an enum however gives you useful methods (Enum javadoc) that you would otherwise have to implement yourself, such as Enum.valueOf.

dispatch_after - GCD in Swift?

In Swift 4

Use this snippet:

    let delayInSec = 1.0
    DispatchQueue.main.asyncAfter(deadline: .now() + delayInSec) {
       // code here
       print("It works")
    }

How do I pass a variable by reference?

The problem comes from a misunderstanding of what variables are in Python. If you're used to most traditional languages, you have a mental model of what happens in the following sequence:

a = 1
a = 2

You believe that a is a memory location that stores the value 1, then is updated to store the value 2. That's not how things work in Python. Rather, a starts as a reference to an object with the value 1, then gets reassigned as a reference to an object with the value 2. Those two objects may continue to coexist even though a doesn't refer to the first one anymore; in fact they may be shared by any number of other references within the program.

When you call a function with a parameter, a new reference is created that refers to the object passed in. This is separate from the reference that was used in the function call, so there's no way to update that reference and make it refer to a new object. In your example:

def __init__(self):
    self.variable = 'Original'
    self.Change(self.variable)

def Change(self, var):
    var = 'Changed'

self.variable is a reference to the string object 'Original'. When you call Change you create a second reference var to the object. Inside the function you reassign the reference var to a different string object 'Changed', but the reference self.variable is separate and does not change.

The only way around this is to pass a mutable object. Because both references refer to the same object, any changes to the object are reflected in both places.

def __init__(self):         
    self.variable = ['Original']
    self.Change(self.variable)

def Change(self, var):
    var[0] = 'Changed'

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

SwiftUI - How do I change the background color of a View?

Xcode 11.5

Simply use ZStack to add background color or images to your main view in SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.black
        }
        .edgesIgnoringSafeArea(.vertical)
    }
}

ng is not recognized as an internal or external command

execute following lines in order to solve the issue for both not found and undefined version of ng

npm uninstall -g angular-cli

npm uninstall --save-dev angular-cli

npm cache clean

npm install -g @angular/cli@latest

onclick event function in JavaScript

click() is a reserved word and already a function, change the name from click() to runclick() it works fine

CSS/Javascript to force html table row on a single line

If you hide the overflow and there is a long word, you risk loosing that word, so you could go one step further and use the "word-wrap" css attribute.

http://msdn.microsoft.com/en-us/library/ms531186(VS.85).aspx

Get values from label using jQuery

Use .attr

$("current_month").attr("month")
$("current_month").attr("year")

And change the labels id to

<label year="2010" month="6" id="current_month"> June &nbsp;2010</label>

Difference between a theta join, equijoin and natural join

Theta Join: When you make a query for join using any operator,(e.g., =, <, >, >= etc.), then that join query comes under Theta join.

Equi Join: When you make a query for join using equality operator only, then that join query comes under Equi join.

Example:

> SELECT * FROM Emp JOIN Dept ON Emp.DeptID = Dept.DeptID;
> SELECT * FROM Emp INNER JOIN Dept USING(DeptID)
This will show:
 _________________________________________________
| Emp.Name | Emp.DeptID | Dept.Name | Dept.DeptID |
|          |            |           |             |

Note: Equi join is also a theta join!

Natural Join: a type of Equi Join which occurs implicitly by comparing all the same names columns in both tables.

Note: here, the join result has only one column for each pair of same named columns.

Example

 SELECT * FROM Emp NATURAL JOIN Dept
This will show:
 _______________________________
| DeptID | Emp.Name | Dept.Name |
|        |          |           |

How to update data in one table from corresponding data in another table in SQL Server 2005

Try a query like

INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;

Adjusting and image Size to fit a div (bootstrap)

I had this same problem and stumbled upon the following simple solution. Just add a bit of padding to the image and it resizes itself to fit within the div.

<div class="col-sm-3">
  <img src="xxx.png" class="img-responsive" style="padding-top: 5px">
</div>

How do I create a file and write to it?

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

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to format code in Xcode?

Select first the text you want to format and then press Ctrl+I.

Use Cmd+A first if you wish to format all text in the selected file.

Note: this procedure only re-indents the lines, it does not do any advanced formatting.


In XCode 12 beta:

The new key binding to re-indent is control+I.

How to fix C++ error: expected unqualified-id

As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.

void setWord(const std::string& word) {
  theWord = word;
}

ImportError: No module named sklearn.cross_validation

train_test_split is now in model_selection. Just type:

from sklearn.model_selection import train_test_split

it should work

Get a substring of a char*

You can just use strstr() from <string.h>

$ man strstr

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

Maven dependencies are failing with a 501 error

This error occured to me too. I did what Muhammad umer said above. But, it only solved error for spring-boot-dependencies and spring-boot-dependencies has child dependencies. Now, there were 21 errors. Previously, it was 2 errors. Like this:

Non-resolvable import POM: Could not transfer artifact org.springframework.cloud:spring-cloud-dependencies:pom:Hoxton.SR3 from/to central

and also https required in the error message.

I updated the maven version from 3.2.2 to 3.6.3 and java version from 8 to 11. Now, all errors of https required are gone.

To update maven version

  1. Download latest maven from here: download maven
  2. Unzip and move it to /opt/maven/
  3. Set the path export PATH=$PATH:/opt/maven/bin
  4. And, also remove old maven from PATH

How to construct a WebSocket URI relative to the page URI?

In typescript:

export class WebsocketUtils {

    public static websocketUrlByPath(path) {
        return this.websocketProtocolByLocation() +
            window.location.hostname +
            this.websocketPortWithColonByLocation() +
            window.location.pathname +
            path;
    }

    private static websocketProtocolByLocation() {
        return window.location.protocol === "https:" ? "wss://" : "ws://";
    }

    private static websocketPortWithColonByLocation() {
        const defaultPort = window.location.protocol === "https:" ? "443" : "80";
        if (window.location.port !== defaultPort) {
            return ":" + window.location.port;
        } else {
            return "";
        }
    }
}

Usage:

alert(WebsocketUtils.websocketUrlByPath("/websocket"));

How to use store and use session variables across pages?

Try this:

<!-- first page -->
<?php
  session_start(); 
  session_register('myvar');
  $_SESSION['myvar'] == 'myvalue';
?>

<!-- second page -->
<?php
    session_start();
    echo("1");
    if(session_is_registered('myvar'))
    {
        echo("2");
       if($_SESSION['myvar'] == 'myvalue')
       {
           echo("3");
           exit;
       }
    }
    ?>

What does \d+ mean in regular expression terms?

\d is a digit (a character in the range 0-9), and + means 1 or more times. So, \d+ is 1 or more digits.

This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

@JoinColumn could be used on both sides of the relationship. The question was about using @JoinColumn on the @OneToMany side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE statements.

According to documentation:

Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)

@Entity
public class Troop {
    @OneToMany(mappedBy="troop")
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk")
    public Troop getTroop() {
    ...
} 

Troop has a bidirectional one to many relationship with Soldier through the troop property. You don't have to (must not) define any physical mapping in the mappedBy side.

To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy element and set the many to one @JoinColumn as insertable and updatable to false. This solution is not optimized and will produce some additional UPDATE statements.

@Entity
public class Troop {
    @OneToMany
    @JoinColumn(name="troop_fk") //we need to duplicate the physical information
    public Set<Soldier> getSoldiers() {
    ...
}

@Entity
public class Soldier {
    @ManyToOne
    @JoinColumn(name="troop_fk", insertable=false, updatable=false)
    public Troop getTroop() {
    ...
}

"The system cannot find the file specified"

I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.

Is it possible to use Java 8 for Android development?

Android uses a Java that branches off of Java 6.

As of Android SDK version 19, you can use Java 7 features by doing this. No full support for Java 8 (yet).

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

The provider is bundled with PowerShell>=6.0.

If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

I have looked at each of these solutions that also seem to work with one issue. Dark Mode and the background setting

The Background setting of the UITextField must match the background of the parent view or no line appears

So this will work on light mode To get to work in dark mode change the background color to black and it works Exclude back color and the line does not appear

let field = UITextField() 
field.backgroundColor = UIColor.white
field.bottomBorderColor = UIColor.red

This ended up being the best solution for me

extension UITextField {

    func addPadding() {
        let paddingView = UIView(frame: CGRect(x:0, y:0, width: 10, height: self.frame.height))
        self.leftView = paddingView
        self.leftViewMode = .always
      }

      @IBInspectable var placeHolderColor: UIColor? {
          get {
              return self.placeHolderColor
          }
          set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
          }
      }

      @IBInspectable var bottomBorderColor: UIColor? {
          get {
              return self.bottomBorderColor
          }
          set {
            self.borderStyle = .none
            self.layer.masksToBounds = false
            self.layer.shadowColor = newValue?.cgColor
            self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
            self.layer.shadowOpacity = 1.0
            self.layer.shadowRadius = 0.0
          }
      }
    }

IE Enable/Disable Proxy Settings via Registry

I know this is an old question, however here is a simple one-liner to switch it on or off depending on its current state:

set-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable -value (-not ([bool](get-itemproperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'  -name ProxyEnable).proxyenable))

What is "with (nolock)" in SQL Server?

Another case where it's usually okay is in a reporting database, where data is perhaps already aged and writes just don't happen. In this case, though, the option should be set at the database or table level by the administrator by changing the default isolation level.

In the general case: you can use it when you are very sure that it's okay to read old data. The important thing to remember is that its very easy to get that wrong. For example, even if it's okay at the time you write the query, are you sure something won't change in the database in the future to make these updates more important?

I'll also 2nd the notion that it's probably not a good idea in banking app. Or inventory app. Or anywhere you're thinking about transactions.

how do I get a new line, after using float:left?

Also such way

<br clear="all" />

Exception in thread "main" java.util.NoSuchElementException

simply don't close in

remove in.close() from your code.

Elegant way to report missing values in a data.frame

Just use sapply

> sapply(airquality, function(x) sum(is.na(x)))
  Ozone Solar.R    Wind    Temp   Month     Day 
     37       7       0       0       0       0

You could also use apply or colSums on the matrix created by is.na()

> apply(is.na(airquality),2,sum)
  Ozone Solar.R    Wind    Temp   Month     Day 
     37       7       0       0       0       0
> colSums(is.na(airquality))
  Ozone Solar.R    Wind    Temp   Month     Day 
     37       7       0       0       0       0 

How can I create and style a div using JavaScript?

You can create like this

board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"

document.getElementById("main").appendChild(board);

Complete Runnable Snippet:

_x000D_
_x000D_
var board;_x000D_
board= document.createElement("div");_x000D_
board.id = "mainBoard";_x000D_
board.style.cssText = "position:fixed;height:100px;width:100px;background:#ddd;"_x000D_
    _x000D_
document.getElementById("main").appendChild(board);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Attach to a processes output for viewing

You can use reptyr:

sudo apt install reptyr
reptyr pid

Is a new line = \n OR \r\n?

The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):

  • \r\n is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.
  • \n is used for all other systems, applications and the Internet.

You'll notice that I've put most Windows apps in the \n group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n because, while Windows may use \r\n, the Internet uses \n. Therefore, it is best practice for applications to use \n alone if you want your output to be Internet friendly.

PHP also defines a newline character called PHP_EOL. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n for Windows and \n for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.

If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use / for your path separator (not \).

The even longer explanation:

An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n then display a period).

Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).

That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.

Unit Tests not discovered in Visual Studio 2017

I had the same issue. My solution was OK but suddenly when I opened the solution I found out the tests are gone.

Finally I downgraded Microsoft.VisualStudio.TestPlatform.TestFramework and Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions packages to a very old version (using NuGet manager) and test methods showed up. Then I upgraded to latest version and still there were there.

So just downgrade and upgrade packages.

How to get a complete list of ticker symbols from Yahoo Finance?

NASDAQ Stock lists ftp://ftp.nasdaqtrader.com/symboldirectory

The 2 files nasdaqlisted.txt and otherlisted.txt are | pipe separated. That should give you a good list of all stocks.

Initialize class fields in constructor or at declaration?

I normally try the constructor to do nothing but getting the dependencies and initializing the related instance members with them. This will make you life easier if you want to unit test your classes.

If the value you are going to assign to an instance variable does not get influenced by any of the parameters you are going to pass to you constructor then assign it at declaration time.

Comparing two byte arrays in .NET

User gil suggested unsafe code which spawned this solution:

// Copyright (c) 2008-2013 Hafthor Stefansson
// Distributed under the MIT/X11 software license
// Ref: http://www.opensource.org/licenses/mit-license.php.
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
  if(a1==a2) return true;
  if(a1==null || a2==null || a1.Length!=a2.Length)
    return false;
  fixed (byte* p1=a1, p2=a2) {
    byte* x1=p1, x2=p2;
    int l = a1.Length;
    for (int i=0; i < l/8; i++, x1+=8, x2+=8)
      if (*((long*)x1) != *((long*)x2)) return false;
    if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
    if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
    if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
    return true;
  }
}

which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were.

It performs about seven timers faster than the simple for loop. Using the J# library performed equivalently to the original for loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse.

How can prevent a PowerShell window from closing so I can see the error?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.

  1. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
  2. Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
  3. Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:

    ? Open With ? Windows PowerShell
    When you right-click a .ps1 file and choose Open With

    Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
    

    ? Run with PowerShell
    When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).

    Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
    

You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.

It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:

try
{
    # Do your script's stuff
}
catch
{
    Write-Error $_.Exception.ToString()
    Read-Host -Prompt "The above error occurred. Press Enter to exit."
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

Android Studio update -Error:Could not run build action using Gradle distribution

I have run into a similar problem on Mac.

Looking at the log under Help -> Show logs in Finder I found the following entry.

You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)

and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Looks like you are using pandas dataframe (from the name df2).

You could also do the following:

regr = LinearRegression()
regr.fit(df2.iloc[1:1000, 5].to_frame(), df2.iloc[1:1000, 2].to_frame())

NOTE: I have removed "values" as that converts the pandas Series to numpy.ndarray and numpy.ndarray does not have attribute to_frame().

How to compare variables to undefined, if I don’t know whether they exist?

if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...

Python Finding Prime Factors

You shouldn't loop till the square root of the number! It may be right some times, but not always!

Largest prime factor of 10 is 5, which is bigger than the sqrt(10) (3.16, aprox).

Largest prime factor of 33 is 11, which is bigger than the sqrt(33) (5.5,74, aprox).

You're confusing this with the propriety which states that, if a number has a prime factor bigger than its sqrt, it has to have at least another one other prime factor smaller than its sqrt. So, with you want to test if a number is prime, you only need to test till its sqrt.

How to debug a GLSL shader?

I am sharing a fragment shader example, how i actually debug.

#version 410 core

uniform sampler2D samp;
in VS_OUT
{
    vec4 color;
    vec2 texcoord;
} fs_in;

out vec4 color;

void main(void)
{
    vec4 sampColor;
    if( texture2D(samp, fs_in.texcoord).x > 0.8f)  //Check if Color contains red
        sampColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);  //If yes, set it to white
    else
        sampColor = texture2D(samp, fs_in.texcoord); //else sample from original
    color = sampColor;

}

enter image description here

How to show text in combobox when no item selected?

Why not do it XAML?

<ComboBox x:Name="myComboBoxMenu" PlaceholderText="Hello"/>

How to $watch multiple variable change in angular


UPDATE

Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.


This should work independent of the types and values:

$scope.$watch('[age,name]', function () { ... }, true);

You have to set the third parameter to true in this case.

The string concatenation 'age + name' will fail in a case like this:

<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>

Before the user clicks the button the watched value would be 42foo (42 + foo) and after the click 42foo (4 + 2foo). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
        <script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
        <script>

angular.module('demo', []).controller('MainCtrl', function ($scope) {

    $scope.firstWatchFunctionCounter = 0;
    $scope.secondWatchFunctionCounter = 0;

    $scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
    $scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});

describe('Demo module', function () {
    beforeEach(module('demo'));
    describe('MainCtrl', function () {
        it('watch function should increment a counter', inject(function ($controller, $rootScope) {
            var scope = $rootScope.$new();
            scope.age = 42;
            scope.name = 'foo';
            var ctrl = $controller('MainCtrl', { '$scope': scope });
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(1);
            expect(scope.secondWatchFunctionCounter).toBe(1);

            scope.age = 4;
            scope.name = '2foo';
            scope.$digest();

            expect(scope.firstWatchFunctionCounter).toBe(2);
            expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
        }));
    });
});


(function () {
    var jasmineEnv = jasmine.getEnv();
    var htmlReporter = new jasmine.HtmlReporter();
    jasmineEnv.addReporter(htmlReporter);
    jasmineEnv.specFilter = function (spec) {
        return htmlReporter.specFilter(spec);
    };
    var currentWindowOnload = window.onload;
    window.onload = function() {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };
    function execJasmine() {
        jasmineEnv.execute();
    }
})();

        </script>
    </head>
    <body></body>
</html>

http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview

PS:

As stated by @reblace in a comment, it is of course possible to access the values:

$scope.$watch('[age,name]', function (newValue, oldValue) {
    var newAge  = newValue[0];
    var newName = newValue[1];
    var oldAge  = oldValue[0];
    var oldName = oldValue[1];
}, true);

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from

EDIT:

All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.

Checking if a collection is empty in Java: which is the best method?

You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size() which can't also make isEmpty() faster, whereas the reverse is not the case.

For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E> does). Then size() would become an O(N) operation, whereas isEmpty() would still be O(1).

Additionally of course, using isEmpty() states what you're actually interested in more clearly.

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

I recently (today :D) had to integrate this behavior. In order to not impact the original design fields, including combo, I opted to apply the transformation at the focus of the field:

input[type="text"]:focus, input[type="password"]:focus,
textarea:focus, select:focus {
  font-size: 16px;
}

How to add a char/int to an char array in C?

I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:

char str[1024]; // Only declares size
char tmp = '.';

for

char str[1024] = "Hello World";  //Now you have "Hello World" in str
char tmp[2] = ".";

RuntimeError on windows trying python multiprocessing

In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.

How to make the Facebook Like Box responsive?

The answer you're looking for as of June, 2013 can be found here:

https://gist.github.com/dineshcooper/2111366

It's accomplished using jQuery to rewrite the inner HTML of the parent container that holds the facebook widget.

Hope this helps!

How do I ZIP a file in C#, using no 3rd-party APIs?

    private static string CompressFile(string sourceFileName)
    {
        using (ZipArchive archive = ZipFile.Open(Path.ChangeExtension(sourceFileName, ".zip"), ZipArchiveMode.Create))
        {
            archive.CreateEntryFromFile(sourceFileName, Path.GetFileName(sourceFileName));
        }
        return Path.ChangeExtension(sourceFileName, ".zip");
    }

Shorthand for if-else statement

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N';

The ternary operator lets us write shorthand if..else statements exactly like you want.

It looks like:

(name === 'true') - our condition

? - the ternary operator itself

'Y' - the result if the condition evaluates to true

'N' - the result if the condition evaluates to false

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

Running npm command within Visual Studio Code

VSCode User Setup is a new installer which installs VSCode and its dependencies in directories which don't require system-level / administrator permissions to modify. This is because New VSCode runs with user privileges. Your Nodejs installation added npm's path as System variable which VSCode cannot read.

Adding NPM path to Path variable in the User variable, you will be able to run NPM from the integrated command line.

H2 in-memory database. Table not found

When opening the h2-console, the JDBC URL must match the one specified in the properties:

spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb

spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

spring.h2.console.enabled=true

enter image description here

Which seems obvious, but I spent hours figuring this out..

How to center a subview of UIView

Using the same center in the view and subview is the simplest way of doing it. You can do something like this,

UIView *innerView = ....;
innerView.view.center = self.view.center;
[self.view addSubView:innerView];

concatenate variables

If you need to concatenate paths with quotes, you can use = to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.

@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"

rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%

rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%

How can I clear the terminal in Visual Studio Code?

Go to

  1. File >Preferences >Keyboard shortcuts.
  2. Search for "Terminal: clear"
  3. By default no keyboard shortcut is assigned.
  4. Just click on the Plus (+)icon in the banner and give the preferred shortcut of your choice to clear the terminal.
  5. I prefer to use ctrl+k as that shortcut is not assigned with any command.

How can you print a variable name in python?

For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.

They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!

How do I create a crontab through a script

(I don't have enough reputation to comment, so I'm adding at as an answer: feel free to add it as as comment next to his answer)

Joe Casadonte's one-liner is perfect, except if you run with set -e, i.e. if your script is set to fail on error, and if there are no cronjobs yet. In that case, the one-liner will NOT create the cronjob, but will NOT stop the script. The silent failure can be very misleading.

The reason is that crontab -l returns with a 1 return code, causing the subsequent command (the echo) not to be executed... thus the cronjob is not created. But since they are executed as a subprocess (because of the parenthesis) they don't stop the script.

(Interestingly, if you run the same command again, it will work: once you have executed crontab - once, crontab -l still outputs nothing, but it doesn't return an error anymore (you don't get the no crontab for <user> message anymore). So the subsequent echo is executed and the crontab is created)

In any case, if you run with set -e, the line must be:

(crontab -l 2>/dev/null || true; echo "*/5 * * * * /path/to/job -with args") | crontab -

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

math.sqrt is the C implementation of square root and is therefore different from using the ** operator which implements Python's built-in pow function. Thus, using math.sqrt actually gives a different answer than using the ** operator and there is indeed a computational reason to prefer numpy or math module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas ** operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".

See this Stack Overflow question for more information on the difference between ** and math.sqrt.

In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like ** e.g. C++. So ** is probably more Pythonic, but whether or not it's objectively better depends on the use case.

Python integer incrementing with ++

You can do:

number += 1

Something better than .NET Reflector?

Some others not mentioned here -

  • Mono Cecil: With Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly.

  • Kaliro: This is a tool for exploring the content of applications built using the Microsoft.Net framework.

  • Dotnet IL Editor (DILE): Dotnet IL Editor (DILE) allows disassembling and debugging .NET 1.0/1.1/2.0/3.0/3.5 applications without source code or .pdb files. It can debug even itself or the assemblies of the .NET Framework on IL level.

  • Common Compiler Infrastructure: Microsoft Research Common Compiler Infrastructure (CCI) is a set of libraries and an application programming interface (API) that supports some of the functionality that is common to compilers and related programming tools. CCI is used primarily by applications that create, modify or analyze .NET portable executable (PE) and debug (PDB) files.

CSS @media print issues with background-color;

_x000D_
_x000D_
    body{
        background-color: #E5FFE5;
    }
    .bg_print{
       border-bottom: 30px solid #FFCC33;
    }
    .orange_bg_print_content{
        margin-top: -25px;
        padding: 0 10px;
    }
_x000D_
    <div class="bg_print">
    </div>
    <div class="orange_bg_print_content">
        My Content With Background!
    </div>
_x000D_
_x000D_
_x000D_

Tested and works in Chrome and Firefox and Edge...

How to run test cases in a specified file?

in intelliJ IDEA go-lang plugin (and i assume in jetbrains Gogland) you can just set the test kind to file under run > edit configurations

screenshot create go test on go file

Write applications in C or C++ for Android?

You can download c4droid and then install the GCC plugin and install to your SD. From the shell I just traverse to the directory where the GCC binary is and then call it to make an on board executable.

find / -name gcc

/mnt/sdcard/Android/data/com.n0n3m4.droidc/files/gcc/bin/arm-linux-androideabi-gcc

cat > test.c

#include<stdio.h>
int main(){ 
 printf("hello arm!\n");
return 0;
}

./arm-linux-androideabi-gcc test.c -o test

./test

hello arm!

Why do I need 'b' to encode a string with Base64?

If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"

encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))

android: how to change layout on button click?

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

How to have git log show filenames like svn log -v

A summary of answers with example output

This is using a local repository with five simple commits.

? git log --name-only
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

file5

commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:36:32 2019 -0700

    foo file1

    really important to foo before the bar

file1

commit 1b6413400b5a6a96d062a7c13109e6325e081c85
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:34:37 2019 -0700

    foobar file2, rm file3

file2
file3

commit e0dd02ce23977c782987a206236da5ab784543cc
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:33:05 2019 -0700

    Add file4

file4

commit b58e85692f711d402bae4ca606d3d2262bb76cf1
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:32:41 2019 -0700

    Added files

file1
file2
file3


? git log --name-status
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

R100    file4   file5

commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:36:32 2019 -0700

    foo file1

    really important to foo before the bar

M       file1

commit 1b6413400b5a6a96d062a7c13109e6325e081c85
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:34:37 2019 -0700

    foobar file2, rm file3

M       file2
D       file3

commit e0dd02ce23977c782987a206236da5ab784543cc
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:33:05 2019 -0700

    Add file4

A       file4

commit b58e85692f711d402bae4ca606d3d2262bb76cf1
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:32:41 2019 -0700

    Added files

A       file1
A       file2
A       file3


? git log --stat
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

 file4 => file5 | 0
 1 file changed, 0 insertions(+), 0 deletions(-)

commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:36:32 2019 -0700

    foo file1

    really important to foo before the bar

 file1 | 3 +++
 1 file changed, 3 insertions(+)

commit 1b6413400b5a6a96d062a7c13109e6325e081c85
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:34:37 2019 -0700

    foobar file2, rm file3

 file2 | 1 +
 file3 | 0
 2 files changed, 1 insertion(+)

commit e0dd02ce23977c782987a206236da5ab784543cc
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:33:05 2019 -0700

    Add file4

 file4 | 0
 1 file changed, 0 insertions(+), 0 deletions(-)

commit b58e85692f711d402bae4ca606d3d2262bb76cf1
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:32:41 2019 -0700

    Added files

 file1 | 0
 file2 | 0
 file3 | 0
 3 files changed, 0 insertions(+), 0 deletions(-)


? git log --name-only --oneline
ed080bc (HEAD -> master) mv file4 to file5
file5
5c4e8cf foo file1
file1
1b64134 foobar file2, rm file3
file2
file3
e0dd02c Add file4
file4
b58e856 Added files
file1
file2
file3


? git log --pretty=oneline --graph --name-status
* ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master) mv file4 to file5
| R100  file4   file5
* 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328 foo file1
| M     file1
* 1b6413400b5a6a96d062a7c13109e6325e081c85 foobar file2, rm file3
| M     file2
| D     file3
* e0dd02ce23977c782987a206236da5ab784543cc Add file4
| A     file4
* b58e85692f711d402bae4ca606d3d2262bb76cf1 Added files
  A     file1
  A     file2
  A     file3


? git diff-tree HEAD
ed080bc88b7bf0c5125e093a26549f3755f7ae74
:100644 000000 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0000000000000000000000000000000000000000 D  file4
:000000 100644 0000000000000000000000000000000000000000 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 A  file5


? git log --stat --pretty=short --graph
* commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
| Author: My Name <[email protected]>
| 
|     mv file4 to file5
| 
|  file4 => file5 | 0
|  1 file changed, 0 insertions(+), 0 deletions(-)
| 
* commit 5c4e8cfbe3554fe3d7d99b5ae4ba381fa1cdb328
| Author: My Name <[email protected]>
| 
|     foo file1
| 
|  file1 | 3 +++
|  1 file changed, 3 insertions(+)
| 
* commit 1b6413400b5a6a96d062a7c13109e6325e081c85
| Author: My Name <[email protected]>
| 
|     foobar file2, rm file3
| 
|  file2 | 1 +
|  file3 | 0
|  2 files changed, 1 insertion(+)
| 
* commit e0dd02ce23977c782987a206236da5ab784543cc
| Author: My Name <[email protected]>
| 
|     Add file4
| 
|  file4 | 0
|  1 file changed, 0 insertions(+), 0 deletions(-)
| 
* commit b58e85692f711d402bae4ca606d3d2262bb76cf1
  Author: My Name <[email protected]>

      Added files

   file1 | 0
   file2 | 0
   file3 | 0
   3 files changed, 0 insertions(+), 0 deletions(-)


? git log --name-only --pretty=format:
file5

file1

file2
file3

file4

file1
file2
file3


? git log --name-status --pretty=format:
R100    file4   file5

M       file1

M       file2
D       file3

A       file4

A       file1
A       file2
A       file3


? git diff --stat 'HEAD^!'
 file4 => file5 | 0
 1 file changed, 0 insertions(+), 0 deletions(-)


? git show
commit ed080bc88b7bf0c5125e093a26549f3755f7ae74 (HEAD -> master)
Author: My Name <[email protected]>
Date:   Mon Oct 21 15:46:04 2019 -0700

    mv file4 to file5

diff --git a/file4 b/file5
similarity index 100%
rename from file4
rename to file5


Credits to @CB-Bailey @Peter-Suwara @Gaurav @Omer-Dagan @xsor @Hazok @nrz @ptc

Undefined reference to pthread_create in Linux

Both answers to this question so far are incorrect.
For Linux the correct command is:

gcc -pthread -o term term.c

In general, libraries should follow sources and objects on command line, and -lpthread is not an "option", it's a library specification. On a system with only libpthread.a installed,

gcc -lpthread ...

will fail to link.

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use zIndex for placing a view on top of another. It works like the CSS z-index property - components with a larger zIndex will render on top.

You can refer: Layout Props

Snippet:

    <ScrollView>
          <StatusBar backgroundColor="black" barStyle="light-content" />
          <Image style={styles.headerImage} source={{ uri: "http://www.artwallpaperhi.com/thumbnails/detail/20140814/cityscapes%20buildings%20hong%20kong_www.artwallpaperhi.com_18.jpg" }}>
            <View style={styles.back}>
              <TouchableOpacity>
                <Icons name="arrow-back" size={25} color="#ffffff" />
              </TouchableOpacity>
            </View>
            <Image style={styles.subHeaderImage} borderRadius={55} source={{ uri: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Albert_Einstein_1947.jpg/220px-Albert_Einstein_1947.jpg" }} />
          </Image>

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "white"
    },
    headerImage: {
        height: height(150),
        width: deviceWidth
    },
    subHeaderImage: {
        height: 110,
        width: 110,
        marginTop: height(35),
        marginLeft: width(25),
        borderColor: "white",
        borderWidth: 2,
        zIndex: 5
    },

fail to change placeholder color with Bootstrap 3

There was an issue posted here about this: https://github.com/twbs/bootstrap/issues/14107

The issue was solved by this commit: https://github.com/twbs/bootstrap/commit/bd292ca3b89da982abf34473318c77ace3417fb5

The solution therefore is to override it back to #999 and not white as suggested (and also overriding all bootstraps styles, not just for webkit-styles):

.form-control::-moz-placeholder {
  color: #999;
}
.form-control:-ms-input-placeholder {
  color: #999;
}
.form-control::-webkit-input-placeholder {
  color: #999;
}

Get the first element of an array

Get first element:

array_values($arr)[0]

Get last element

array_reverse($arr)[0]

Sending the bearer token with axios

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

c# write text on bitmap

You need to use the Graphics class in order to write on the bitmap.

Specifically, one of the DrawString methods.

Bitmap a = new Bitmap(@"path\picture.bmp");

using(Graphics g = Graphics.FromImage(a))
{
  g.DrawString(....); // requires font, brush etc
}

pictuteBox1.Image = a;

Difference in make_shared and normal shared_ptr in C++

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.

Where do the heap-allocations happen?

std::shared_ptr manages two entities:

  • the control block (stores meta data such as ref-counts, type-erased deleter, etc)
  • the object being managed

std::make_shared performs a single heap-allocation accounting for the space necessary for both the control block and the data. In the other case, new Obj("foo") invokes a heap-allocation for the managed data and the std::shared_ptr constructor performs another one for the control block.

For further information, check out the implementation notes at cppreference.

Update I: Exception-Safety

NOTE (2019/08/30): This is not a problem since C++17, due to the changes in the evaluation order of function arguments. Specifically, each argument to a function is required to fully execute before evaluation of other arguments.

Since the OP seem to be wondering about the exception-safety side of things, I've updated my answer.

Consider this example,

void F(const std::shared_ptr<Lhs> &lhs, const std::shared_ptr<Rhs> &rhs) { /* ... */ }

F(std::shared_ptr<Lhs>(new Lhs("foo")),
  std::shared_ptr<Rhs>(new Rhs("bar")));

Because C++ allows arbitrary order of evaluation of subexpressions, one possible ordering is:

  1. new Lhs("foo"))
  2. new Rhs("bar"))
  3. std::shared_ptr<Lhs>
  4. std::shared_ptr<Rhs>

Now, suppose we get an exception thrown at step 2 (e.g., out of memory exception, Rhs constructor threw some exception). We then lose memory allocated at step 1, since nothing will have had a chance to clean it up. The core of the problem here is that the raw pointer didn't get passed to the std::shared_ptr constructor immediately.

One way to fix this is to do them on separate lines so that this arbitary ordering cannot occur.

auto lhs = std::shared_ptr<Lhs>(new Lhs("foo"));
auto rhs = std::shared_ptr<Rhs>(new Rhs("bar"));
F(lhs, rhs);

The preferred way to solve this of course is to use std::make_shared instead.

F(std::make_shared<Lhs>("foo"), std::make_shared<Rhs>("bar"));

Update II: Disadvantage of std::make_shared

Quoting Casey's comments:

Since there there's only one allocation, the pointee's memory cannot be deallocated until the control block is no longer in use. A weak_ptr can keep the control block alive indefinitely.

Why do instances of weak_ptrs keep the control block alive?

There must be a way for weak_ptrs to determine if the managed object is still valid (eg. for lock). They do this by checking the number of shared_ptrs that own the managed object, which is stored in the control block. The result is that the control blocks are alive until the shared_ptr count and the weak_ptr count both hit 0.

Back to std::make_shared

Since std::make_shared makes a single heap-allocation for both the control block and the managed object, there is no way to free the memory for control block and the managed object independently. We must wait until we can free both the control block and the managed object, which happens to be until there are no shared_ptrs or weak_ptrs alive.

Suppose we instead performed two heap-allocations for the control block and the managed object via new and shared_ptr constructor. Then we free the memory for the managed object (maybe earlier) when there are no shared_ptrs alive, and free the memory for the control block (maybe later) when there are no weak_ptrs alive.

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

How to print pthread_t

Just a supplement to the first post: use a user defined union type to store the pthread_t:

union tid {
    pthread_t pthread_id;
    unsigned long converted_id;
};

Whenever you want to print pthread_t, create a tid and assign tid.pthread_id = ..., then print tid.converted_id.

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

Java: String - add character n-times

 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();

Add borders to cells in POI generated Excel File

a Helper function:

private void setRegionBorderWithMedium(CellRangeAddress region, Sheet sheet) {
        Workbook wb = sheet.getWorkbook();
        RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, region, sheet, wb);
        RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, region, sheet, wb);
    }

When you want to add Border in Excel, then

String cellAddr="$A$11:$A$17";

setRegionBorderWithMedium(CellRangeAddress.valueOf(cellAddr1), sheet);

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Even though the question is answered I would like to add that, if you are getting the above mentioned error, be sure that you have downloaded the Binary file.

The source file should only be downloaded if you are an advanced user and that you know how to deal with it.

I have had quite a share of people downloading the wrong file, seniors and juniors

AngularJS - Create a directive that uses ng-model

This is a little late answer, but I found this awesome post about NgModelController, which I think is exactly what you were looking for.

TL;DR - you can use require: 'ngModel' and then add NgModelController to your linking function:

link: function(scope, iElement, iAttrs, ngModelCtrl) {
  //TODO
}

This way, no hacks needed - you are using Angular's built-in ng-model

Make .gitignore ignore everything except a few files

If you want to ignore the whole content of a directory except one file inside it, you could write a pair of rules for each directory in the file path. E.g. .gitignore to ignore the pippo folder except from pippo/pluto/paperino.xml

pippo/*
!pippo/pluto
pippo/pluto/*
!pippo/pluto/paperino.xml

Note that if you simply had written above:

pippo/*
!pippo/pluto/paperino.xml

It wouldn't work because the intermediary pluto folder would not exist to Git, so paperino.xml could not find a place in which to exist.

fatal: does not appear to be a git repository

I had a similar problem when using TFS 2017. I was not able to push or pull GIT repositories. Eventually I reinstalled TFS 2017, making sure that I installed TFS 2017 with an SSH Port different from 22 (in my case, I chose 8022). After that, push and pull became possible against TFS using SSH.

Regex for Comma delimited list

This one will reject extraneous commas at the start or end of the line, if that's important to you.

((, )?(^)?(possible|value|patterns))*

Replace possible|value|patterns with a regex that matches your allowed values.

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Compilation fails with "relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object"

I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.

I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure replaced by $ ./configure --enable-shared (first make sure to delete all the folders and files including the .so files from the previous attempt).

Apparently this works because https://stackoverflow.com/a/13812368/10593190.

Virtualenv Command Not Found

I had same problem on Mac OS X El Capitan.

When I installed virtualenv like that sudo pip3 install virtualenv I didn't have virtualenv under my command line.

I solved this problem by following those steps:

  1. Uninstall previous installations.
  2. Switch to super user account prior to virtualenv installation by calling sudo su
  3. Install virtualenv by calling pip3 install virtualenv
  4. Finally you should be able to access virtualenv from both user and super user account.

What is the difference between C and embedded C?

In the C standard, a standalone implementation doesn't have to provide all of the library functions that a hosted implementation has to provide. The C standard doesn't care about embedded, but vendors of embedded systems usually provide standalone implementations with whatever amount of libraries they're willing to provide.

C is a widely used general purpose high level programming language mainly intended for system programming.

Embedded C is an extension to C programming language that provides support for developing efficient programs for embedded devices.It is not a part of the C language

You can also refer to the articles below:

How can I strip HTML tags from a string in ASP.NET?

For those who are complining about Michael Tiptop's solution not working, here is the .Net4+ way of doing it:

public static string StripTags(this string markup)
{
    try
    {
        StringReader sr = new StringReader(markup);
        XPathDocument doc;
        using (XmlReader xr = XmlReader.Create(sr,
                           new XmlReaderSettings()
                           {
                               ConformanceLevel = ConformanceLevel.Fragment
                               // for multiple roots
                           }))
        {
            doc = new XPathDocument(xr);
        }

        return doc.CreateNavigator().Value; // .Value is similar to .InnerText of  
                                           //  XmlDocument or JavaScript's innerText
    }
    catch
    {
        return string.Empty;
    }
}

How do I create a ListView with rounded corners in Android?

This was incredibly handy to me. I would like to suggest another workaround to perfectly highlight the rounded corners if you are using your own CustomAdapter.

Defining XML Files

First of all, go inside your drawable folder and create 4 different shapes:

  • shape_top

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    

  • shape_normal

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
    

  • shape_bottom

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:bottomRightRadius="10dp"
        android:bottomRightRadius="10dp"/>
    

  • shape_rounded

    <gradient
        android:startColor="#ffffff"
        android:endColor="#ffffff"
        android:angle="270"/>
    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"
        android:bottomRightRadius="10dp"
        android:bottomRightRadius="10dp"/>
    

Now, create a different row layout for each shape, i.e. for shape_top :

  • You can also do this programatically changing the background.

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        android:fontFamily="sans-serif-light"
        android:text="TextView"
        android:textSize="22dp" />
    
    <TextView
        android:id="@+id/txtValue1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:textSize="22dp"
        android:layout_gravity="right|center"
        android:gravity="center|right"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="35dp"
        android:text="Fix"
        android:scaleType="fitEnd" />
    

And define a selector for each shaped-list, i.e. for shape_top:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Selected Item -->

    <item android:state_selected="true"
        android:drawable="@drawable/shape_top" />
    <item android:state_activated="true"
        android:drawable="@drawable/shape_top" />

    <!-- Default Item -->
    <item android:state_selected="false"
        android:drawable="@android:color/transparent" />
</selector>

Change your CustomAdapter

Finally, define the layout options inside your CustomAdapter:

if(position==0)
{
 convertView = mInflater.inflate(R.layout.list_layout_top, null);
}
else
{
 convertView = mInflater.inflate(R.layout.list_layout_normal, null);
}

if(position==getCount()-1)
{
convertView = mInflater.inflate(R.layout.list_layout_bottom, null);
}

if(getCount()==1)
{
convertView = mInflater.inflate(R.layout.list_layout_unique, null);
}

And that's done!

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

deleted the c#... here is the vb.net

<%=Html.ActionLink("Home", "Index", "Home", New With {.class = "tab"}, Nothing)%>

How to define static property in TypeScript interface

The other solutions seem to stray from the blessed path and I found that my scenario was covered in the Typescript documentation which I've paraphrased below:

interface AppPackageCheck<T> {
  new (packageExists: boolean): T
  checkIfPackageExists(): boolean;
}

class WebApp {
    public static checkIfPackageExists(): boolean {
        return false;
    }

    constructor(public packageExists: boolean) {}
}

class BackendApp {
    constructor(public packageExists: boolean) {}
}

function createApp<T>(type: AppPackageCheck<T>): T {
    const packageExists = type.checkIfPackageExists();
    return new type(packageExists)
}

let web = createApp(WebApp);

// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp); 

Make a dictionary with duplicate keys in Python

You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html

In a dict, if a key is an object, there are no duplicate problems.

For example:

class p(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name
    def __str__(self):
        return self.name
d = {p('k'): 1, p('k'): 2}

How do I join two lists in Java?

Found this question looking to concatenate arbitrary amount of lists, not minding external libraries. So, perhaps it will help someone else:

com.google.common.collect.Iterables#concat()

Useful if you want to apply the same logic to a number of different collections in one for().

onclick="javascript:history.go(-1)" not working in Chrome

Why not get rid of the inline javascript and do something like this instead?

Inline javascript is considered bad practice as it is outdated.

Notes

Why use addEventListener?

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used. It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling) It works on any DOM element, not just HTML elements.

<a id="back" href="www.mypage.com"> Link </a>

document.getElementById("back").addEventListener("click", window.history.back, false);

On jsfiddle

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

How to read an entire file to a string using C#?

if you want to pick file from Bin folder of the application then you can try following and don't forget to do exception handling.

string content = File.ReadAllText(Path.Combine(System.IO.Directory.GetCurrentDirectory(), @"FilesFolder\Sample.txt"));

how to set image from url for imageView

EDIT:

Create a class that extends AsyncTask

public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;

    public ImageLoadTask(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        try {
            URL urlConnection = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlConnection
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        imageView.setImageBitmap(result);
    }

}

And call this like new ImageLoadTask(url, imageView).execute();

Direct method:

Use this method and pass your url as string. It returns a bitmap. Set the bitmap to your ImageView.

public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src",src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap","returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception",e.getMessage());
        return null;
    }
}

And then this to ImageView like so:

imageView.setImageBitmap(getBitmapFromURL(url));

And dont forget about this permission in maifest.

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

NOTE:

Try to call this method from another thread or AsyncTask because we are performing networking operations.

Using Font Awesome icon for bullet points, with a single list item element

I'd like to build upon some of the answers above and given elsewhere and suggest using absolute positioning along with the :before pseudo class. A lot of the examples above (and in similar questions) are utilizing custom HTML markup, including Font Awesome's method of handling. This goes against the original question, and isn't strictly necessary.

DEMO HERE

ul {
  list-style-type: none;
  padding-left: 20px;
}

li {
  position: relative;
  padding-left: 20px;
  margin-bottom: 10px
}

li:before {
  position: absolute;
  top: 0;
  left: 0;
  font-family: FontAwesome;
  content: "\f058";
  color: green;
}

That's basically it. You can get the ISO value for use in CSS content on the Font Awesome cheatsheet. Simply use the last 4 alphanumerics prefixed with a backslash. So [&#xf058;] becomes \f058

How do I sort strings alphabetically while accounting for value when a string is numeric?

Just pad with zeroes to the same length:

int maxlen = sizes.Max(x => x.Length);
var result = sizes.OrderBy(x => x.PadLeft(maxlen, '0'));

Class has no member named

Try to define the functions right into the header

 #ifndef ATTACK_H
 #define ATTACK_H

 class Attack {
     public:
         Attack(){};
         void printShiz(){};
     protected:
     private: };

 #endif // ATTACK_H

and to compile. If the compiler doesn't complain about duplicate definitions it means you forgot to compile the Class.cpp file, then you simply need to do it (add it to your Makefile/project/solution... which toolchain are you using?)

What's default HTML/CSS link color?

According to the official default HTML stylesheet, there is no defined default link color. However, you can find out the default your browser uses by either taking a screenshot and using the pipette tool in any decent graphic editor or using the developer tools of your browser (select an a element, look for computed values>color).

How to simplify a null-safe compareTo() implementation?

I always recommend using Apache commons since it will most likely be better than one you can write on your own. Plus you can then do 'real' work rather then reinventing.

The class you are interested in is the Null Comparator. It allows you to make nulls high or low. You also give it your own comparator to use when the two values are not null.

In your case you can have a static member variable that does the comparison and then your compareTo method just references that.

Somthing like

class Metadata implements Comparable<Metadata> {
private String name;
private String value;

static NullComparator nullAndCaseInsensitveComparator = new NullComparator(
        new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                // inputs can't be null
                return o1.compareToIgnoreCase(o2);
            }

        });

@Override
public int compareTo(Metadata other) {
    if (other == null) {
        return 1;
    }
    int res = nullAndCaseInsensitveComparator.compare(name, other.name);
    if (res != 0)
        return res;

    return nullAndCaseInsensitveComparator.compare(value, other.value);
}

}

Even if you decide to roll your own, keep this class in mind since it is very useful when ordering lists thatcontain null elements.

How to write MySQL query where A contains ( "a" or "b" )

I user for searching the size of motorcycle :

For example : Data = "Tire cycle size 70 / 90 - 16"

i can search with "70 90 16"

$searchTerms = preg_split("/[\s,-\/?!]+/", $itemName);

foreach ($searchTerms as $term) {
        $term = trim($term);
            if (!empty($term)) {
            $searchTermBits[] = "name LIKE '%$term%'";
            }
        }

$query = "SELECT * FROM item WHERE " .implode(' AND ', $searchTermBits);

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

Quickest way to compare two generic lists for differences

Use Except:

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.

If you want to combine these, you could create a method with the above and then a return statement:

return !firstNotSecond.Any() && !secondNotFirst.Any();

One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.

For example, with lists of [1, 2, 2, 2, 3] and [1], the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]. With my code it would just be [2, 3]. In many cases that won't be an issue, but it's worth being aware of.

How do I Set Background image in Flutter?

Other answers are great. This is another way it can be done.

  1. Here I use SizedBox.expand() to fill available space and for passing tight constraints for its children (Container).
  2. BoxFit.cover enum to Zoom the image and cover whole screen
 Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand( // -> 01
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
              fit: BoxFit.cover,    // -> 02
            ),
          ),
        ),
      ),
    );
  }

screenshot

How to send data to COM PORT using JAVA?

An alternative to javax.comm is the rxtx library which supports more platforms than javax.comm.

Windows command for file size only

This is not exactly what you were asking about and it can only be used from the command line (and may be useless in a batch file), but one quick way to check file size is just to use dir:

> dir Microsoft.WindowsAzure.Storage.xml

Results in:

Directory of C:\PathToTheFile

08/10/2015  10:57 AM         2,905,897 Microsoft.WindowsAzure.Storage.xml
               1 File(s)      2,905,897 bytes
               0 Dir(s)  759,192,064,000 bytes free

Use of Greater Than Symbol in XML

You can try to use CDATA to put all your symbols that don't work.

An example of something that will work in XML:

<![CDATA[
function matchwo(a,b) {
    if (a < b && a < 0) {
        return 1;
   } else {
       return 0;
   }
}
]]>

And of course you can use &lt; and &gt;.

How to set up a PostgreSQL database in Django

If you are using Fedora 20, Django 1.6.5, postgresql 9.3.* and you need the psycopg2 module, do this:

yum install postgresql-devel
easy_install psycopg2

If you are like me, you may have trouble finding the well documented libpq-dev rpm... The above worked for me just now.

mysqli_real_connect(): (HY000/2002): No such file or directory

First of all, make sure the mysql service is running:

ps elf|grep mysql

you will see an output like this if is running:

4 S root      9642     1  0  80   0 -  2859 do_wai 23:08 pts/0    00:00:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/lib/mysql/tomcat-machine.local.pid
4 S mysql     9716  9642  0  80   0 - 200986 poll_s 23:08 pts/0   00:00:00 /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/lib/mysql/tomcat-machine.local.err --pid-file=/var/lib/mysql/tomcat-machine.local.pid

then change localhost to 127.0.0.1 in config.inc.php

$cfg['Servers'][$i]['host'] = '127.0.0.1';

The default password for "root" user is empty "" do not type anything for the password

If it does not allow empty password you need to edit config.inc.php again and change:

$cfg['Servers'][$i]['AllowNoPassword'] = true;

The problem is a combination of config settings and MySQL not running. This was what helped me to fix this error.

How does functools partial do what it does?

In my opinion, it's a way to implement currying in python.

from functools import partial
def add(a,b):
    return a + b

def add2number(x,y,z):
    return x + y + z

if __name__ == "__main__":
    add2 = partial(add,2)
    print("result of add2 ",add2(1))
    add3 = partial(partial(add2number,1),2)
    print("result of add3",add3(1))

The result is 3 and 4.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Is there a replacement for unistd.h for Windows (Visual C)?

The equivalent of unistd.h on Windows is windows.h

How do I determine whether an array contains a particular value in Java?

  1. For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).

     Arrays.asList(...).contains(...)
    
  2. For fast performance if you repeatedly check against a larger set of elements

    • An array is the wrong structure. Use a TreeSet and add each element to it. It sorts elements and has a fast exist() method (binary search).

    • If the elements implement Comparable & you want the TreeSet sorted accordingly:

      ElementClass.compareTo() method must be compatable with ElementClass.equals(): see Triads not showing up to fight? (Java Set missing an item)

      TreeSet myElements = new TreeSet();
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
      // *Alternatively*, if an array is forceably provided from other code:
      myElements.addAll(Arrays.asList(myArray));
      
    • Otherwise, use your own Comparator:

      class MyComparator implements Comparator<ElementClass> {
           int compareTo(ElementClass element1; ElementClass element2) {
                // Your comparison of elements
                // Should be consistent with object equality
           }
      
           boolean equals(Object otherComparator) {
                // Your equality of comparators
           }
      }
      
      
      // construct TreeSet with the comparator
      TreeSet myElements = new TreeSet(new MyComparator());
      
      // Do this for each element (implementing *Comparable*)
      myElements.add(nextElement);
      
    • The payoff: check existence of some element:

      // Fast binary search through sorted elements (performance ~ log(size)):
      boolean containsElement = myElements.exists(someElement);
      

Adding JPanel to JFrame

Test2 test = new Test2();
...
frame.add(test, BorderLayout.CENTER);

Are you sure of this? test is NOT a component! To do what you're trying to do you should let Test2 extend JPanel !

How do I auto-resize an image to fit a 'div' container?

Currently there is no way to do this correctly in a deterministic way, with fixed-size images such as JPEGs or PNG files.

To resize an image proportionally, you have to set either the height or width to "100%", but not both. If you set both to "100%", your image will be stretched.

Choosing whether to do height or width depends on your image and container dimensions:

  1. If your image and container are both "portrait shaped" or both "landscape shaped" (taller than they are wide, or wider than they are tall, respectively), then it doesn't matter which of height or width are "%100".
  2. If your image is portrait, and your container is landscape, you must set height="100%" on the image.
  3. If your image is landscape, and your container is portrait, you must set width="100%" on the image.

If your image is an SVG, which is a variable-sized vector image format, you can have the expansion to fit the container happen automatically.

You just have to ensure that the SVG file has none of these properties set in the <svg> tag:

height
width
viewbox

Most vector drawing programs out there will set these properties when exporting an SVG file, so you will have to manually edit your file every time you export, or write a script to do it.

JSON.parse unexpected token s

What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.

so something is not a valid JSON but "something" is.

A valid JSON is -

JSON = null
    /* boolean literal */
    or true or false
    /* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
    or JSONNumber
    /* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
    or JSONString

    /* Property names must be double-quoted strings; trailing commas are forbidden. */
    or JSONObject
    or JSONArray

Examples -

JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null 
JSON.parse("'foo'"); // error since string should be wrapped by double quotes

You may want to look JSON.

How do I populate a JComboBox with an ArrayList?

Use the toArray() method of the ArrayList class and pass it into the constructor of the JComboBox

See the JavaDoc and tutorial for more info.

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Show a popup/message box from a Windows batch file

First of all, DOS has nothing to do with it, you probably want a Windows command line solution (again: no DOS, pure Windows, just not a Window, but a Console).

You can either use the VBScript method provided by boflynn or you can mis-use net send or msg. net send works only on older versions of windows:

net send localhost Some message to display

This also depends on the Messenger service to run, though.

For newer versions (XP and onward, apparently):

msg "%username%" Some message to display

It should be noted that a message box sent using msg.exe will only last for 60 seconds. This can however be overridden with the /time:xx switch.

Device not detected in Eclipse when connected with USB cable

After a long and frustrating search, finally I made my Micromax Funbook p362 to connect with eclipse and made it to suit for development.

*Installed Moborobo (All in one Android smart phone management tool). *Perform stop -server / start -server using ADB. *Reboot the device. *Restart the eclipse. *Device got detected.(Eclipse - list of adb devices)

How can I write an anonymous function in Java?

Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

private static String pretty(Node node) {
    return "Node: " + new Object() {
        String print(Node cur) {
            return cur.isTerminal() ?
                cur.name() :
                ("("+print(cur.left())+":"+print(cur.right())+")");
        }
    }.print(node);
}

(I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

Spring JPA selecting specific columns

In my opinion this is great solution:

interface PersonRepository extends Repository<Person, UUID> {

    <T> Collection<T> findByLastname(String lastname, Class<T> type);
}

and using it like so

void someMethod(PersonRepository people) {

  Collection<Person> aggregates =
    people.findByLastname("Matthews", Person.class);

  Collection<NamesOnly> aggregates =
    people.findByLastname("Matthews", NamesOnly.class);
}

What is MVC and what are the advantages of it?

![mvc architecture][1]

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

How to make php display \t \n as tab and new line instead of characters

You can use HTML,

foreach(...)
echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

How to use goto statement correctly

The Java keyword list specifies the goto keyword, but it is marked as "not used".

This was probably done in case it were to be added to a later version of Java.

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

Read tab-separated file line into array

You're very close:

while IFS=$'\t' read -r -a myArray
do
 echo "${myArray[0]}"
 echo "${myArray[1]}"
 echo "${myArray[2]}"
done < myfile

(The -r tells read that \ isn't special in the input data; the -a myArray tells it to split the input-line into words and store the results in myArray; and the IFS=$'\t' tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)

is there any IE8 only css hack?

If needed small changes in CSS use \9 it targets IE8 and below (IE6, IE7, IE8)

.element { 
   color:green \9;
 }

Best way is to use conditional comments in HTML, like this:

<!--[if IE 8]>
<style>...</style>
<![endif]-->

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

Change both Project and Package Properties ProtectionLevel to "DontSaveSensitive"

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

Some data I would leave in HTML, but it is better to define the src in CSS:

<img alt="Test Alt text" title="Title text" class="logo">

.logo {
    content:url('../images/logo.png');
}

"webxml attribute is required" error in Maven

As per the documentation, it says : Whether or not to fail the build if the web.xml file is missing. Set to false if you want you WAR built without a web.xml file. This may be useful if you are building an overlay that has no web.xml file. Default value is: true. User property is: failOnMissingWebXml.

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1.1</version>
    <extensions>false</extensions>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

Hope it makes more clear

Mongodb service won't start

When I ran mongod.exe from Windows Terminal I got a message Unrecognized option: mp. There was an empty mp: in the end of mongod.cfg. Removing that solved the problem for me.

How to get IntPtr from byte[] in C#

Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:

IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);

Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.

Edit: Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you

Angular, content type is not being sent with $http

         $http({
                method: 'GET',
                url:'/http://localhost:8080/example/test' + toto,
                data: '',
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(
                function(response) {
                    return response.data;
                }, 
                function(errResponse) {
                    console.error('Error !!');
                    return $q.reject(errResponse);
                }

Save file to specific folder with curl command

For powershell in Windows, you can add relative path + filename to --output flag:

curl -L  http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip

here build_firefox is relative folder.

Set Radiobuttonlist Selected from Codebehind

We can change the item by value, here is the trick:

radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2

php convert datetime to UTC

alternatively you can try this:

<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>

this will output :

2017-10-25 17:13:20 Asia/Singapore

you can use this inside the value attribute of a text input box if you only want to display a read-only date.

remove the 'e' if you do not wish to show your region/country.

Use of PUT vs PATCH methods in REST API real life scenarios

The difference between PUT and PATCH is that:

  1. PUT is required to be idempotent. In order to achieve that, you have to put the entire complete resource in the request body.
  2. PATCH can be non-idempotent. Which implies it can also be idempotent in some cases, such as the cases you described.

PATCH requires some "patch language" to tell the server how to modify the resource. The caller and the server need to define some "operations" such as "add", "replace", "delete". For example:

GET /contacts/1
{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "zip": "10001"
}

PATCH /contacts/1
{
 [{"operation": "add", "field": "address", "value": "123 main street"},
  {"operation": "replace", "field": "email", "value": "[email protected]"},
  {"operation": "delete", "field": "zip"}]
}

GET /contacts/1
{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "address": "123 main street",
}

Instead of using explicit "operation" fields, the patch language can make it implicit by defining conventions like:

in the PATCH request body:

  1. The existence of a field means "replace" or "add" that field.
  2. If the value of a field is null, it means delete that field.

With the above convention, the PATCH in the example can take the following form:

PATCH /contacts/1
{
  "address": "123 main street",
  "email": "[email protected]",
  "zip":
}

Which looks more concise and user-friendly. But the users need to be aware of the underlying convention.

With the operations I mentioned above, the PATCH is still idempotent. But if you define operations like: "increment" or "append", you can easily see it won't be idempotent anymore.

Bootstrap 3 jquery event for active tab change

Eric Saupe knows how to do it

_x000D_
_x000D_
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {_x000D_
  var target = $(e.target).attr("href") // activated tab_x000D_
  alert(target);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="myTab" class="nav nav-tabs">_x000D_
  <li class="active"><a href="#home" data-toggle="tab">Home</a></li>_x000D_
  <li class=""><a href="#profile" data-toggle="tab">Profile</a></li>_x000D_
</ul>_x000D_
<div id="myTabContent" class="tab-content">_x000D_
  <div class="tab-pane fade active in" id="home">_x000D_
    home tab!_x000D_
  </div>_x000D_
  <div class="tab-pane fade" id="profile">_x000D_
    profile tab!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

Base64 String throwing invalid character error

If removing \0 from the end of string is impossible, you can add your own character for each string you encode, and remove it on decode.

Convert unsigned int to signed int C

@Mysticial got it. A short is usually 16-bit and will illustrate the answer:

int main()  
{
    unsigned int x = 65529;
    int y = (int) x;
    printf("%d\n", y);

    unsigned short z = 65529;
    short zz = (short)z;
    printf("%d\n", zz);
}

65529
-7
Press any key to continue . . .


A little more detail. It's all about how signed numbers are stored in memory. Do a search for twos-complement notation for more detail, but here are the basics.

So let's look at 65529 decimal. It can be represented as FFF9h in hexadecimal. We can also represent that in binary as:

11111111 11111001

When we declare short zz = 65529;, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1, so it is treated as a negative number. That's why it prints out -7.

For an unsigned short, we don't care about sign since it's unsigned. So when we print it out using %d, we use all 16 bits, so it's interpreted as 65529.

How to change the style of a DatePicker in android?

Calendar calendar = Calendar.getInstance();

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, monthOfYear, dayOfMonth);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = simpleDateFormat.format(newDate.getTime());
  }
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

datePickerDialog.show();

And use this style:

<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
  <item name="colorAccent">@color/colorPrimary</item>
</style>

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Why the long code and not use the UIToolbar? since the warning is still persist?

UIToolbar is working for any iOS Version here's my sample code

UIToolbar *doneToolbar = [[UIToolbar alloc] initWithFrame:(CGRect){0, 0, 50, 50}]; // Create and init
doneToolbar.barStyle = UIBarStyleBlackTranslucent; // Specify the preferred barStyle
doneToolbar.items = @[
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], 
[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneEditAction)] // Add your target action
]; // Define items -- you can add more

yourField.inputAccessoryView = doneToolbar; // Now add toolbar to your field's inputview and run
[doneToolbar sizeToFit]; // call this to auto fit to the view

- (void)doneEditAction {
    [self.view endEditing:YES];
}

CAST DECIMAL to INT

From the article you linked to:

The type can be one of the following values:

BINARY[(N)]

CHAR[(N)]

DATE

DATETIME

DECIMAL[(M[,D])]

SIGNED [INTEGER]

TIME

UNSIGNED [INTEGER]

Try SIGNED instead of INT

How to export settings?

I'm preferred my own way to synchronize all Visual Studio Code extensions between laptops, using .dotfiles and small script to perform updates automatically. This way helps me every time when I want to install all extensions I have without any single mouse activity in Visual Studio Code after installing (via Homebrew).

So I just write each new added extension to .txt file stored at my .dotfiles folder. After that I pull master branch on another laptop to get up-to-date file with all extensions.

Using the script, which Big Rich had written before, with one more change, I can totally synchronise all extensions almost automatically.

Script

cat dart-extensions.txt | xargs -L 1 code --install-extension

And also there is one more way to automate that process. Here you can add a script which looks up a Visual Studio Code extension in realtime and each time when you take a diff between the code --list-extensions command and your .txt file in .dotfiles, you can easily update your file and push it to your remote repository.

how to make a cell of table hyperlink

Not exactly making the cell a link, but the table itself. I use this as a button in e-mails, giving me div-like controls.

_x000D_
_x000D_
<a href="https://www.foo.bar" target="_blank" style="color: white; font-weight: bolder; text-decoration: none;">
  <table style="margin-left: auto; margin-right: auto;" align="center">
    <tr>
      <td style="padding: 20px; height: 60px;" bgcolor="#00b389">Go to Foo Bar</td>
    </tr>
  </table>
</a>
_x000D_
_x000D_
_x000D_

How to have a transparent ImageButton: Android

Use "@null" . It worked for me.

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/bkash"
    android:id="@+id/bid1"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="@null" />

How do I open multiple instances of Visual Studio Code?

I came here to find out how to make VSCode (Mac OS) create a new window when a file or folder is opened and VSCode is already running. The same as GitHub Atom does. The answers above haven't answered my query, bit I've found answer myself so will share.

Setting: window.openFilesInNewWindow - if set to on, files will open in a new window. window.openFoldersInNewWindow - if set to on, folders will open in a new window.

Bonus to make it behave like Atom: Set window.newWindowDimensions to maximised.

Expanding tuples into arguments

Take a look at the Python tutorial section 4.7.3 and 4.7.4. It talks about passing tuples as arguments.

I would also consider using named parameters (and passing a dictionary) instead of using a tuple and passing a sequence. I find the use of positional arguments to be a bad practice when the positions are not intuitive or there are multiple parameters.

What is the C# equivalent of NaN or IsNumeric?

I like the extension method, but don't like throwing exceptions if possible. I opted for an extension method taking the best of 2 answers here.

    /// <summary>
    /// Extension method that works out if a string is numeric or not
    /// </summary>
    /// <param name="str">string that may be a number</param>
    /// <returns>true if numeric, false if not</returns>
    public static bool IsNumeric(this String str)
    {
        double myNum = 0;
        if (Double.TryParse(str, out myNum))
        {
            return true;
        }
        return false;
    }

Eclipse internal error while initializing Java tooling

Just delete the .metadata on workspace, and restart IDE and configure it again properly

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

Error: Local workspace file ('angular.json') could not be found

If you don't know the version ,current project has been made, you can omit --from command and type --migrate-only

ng update @angular/cli --migrate-only

React Native android build failed. SDK location not found

Copy your system's other android project local.properties and paste in android folder of React-native project it will work.

sdk.dir=C\:\\Users\\paul\\AppData\\Local\\Android\\Sdk

What are the differences between type() and isinstance()?

Differences between isinstance() and type() in Python?

Type-checking with

isinstance(obj, Base)

allows for instances of subclasses and multiple possible bases:

isinstance(obj, (Base1, Base2))

whereas type-checking with

type(obj) is Base

only supports the type referenced.


As a sidenote, is is likely more appropriate than

type(obj) == Base

because classes are singletons.

Avoid type-checking - use Polymorphism (duck-typing)

In Python, usually you want to allow any type for your arguments, treat it as expected, and if the object doesn't behave as expected, it will raise an appropriate error. This is known as polymorphism, also known as duck-typing.

def function_of_duck(duck):
    duck.quack()
    duck.swim()

If the code above works, we can presume our argument is a duck. Thus we can pass in other things are actual sub-types of duck:

function_of_duck(mallard)

or that work like a duck:

function_of_duck(object_that_quacks_and_swims_like_a_duck)

and our code still works.

However, there are some cases where it is desirable to explicitly type-check. Perhaps you have sensible things to do with different object types. For example, the Pandas Dataframe object can be constructed from dicts or records. In such a case, your code needs to know what type of argument it is getting so that it can properly handle it.

So, to answer the question:

Differences between isinstance() and type() in Python?

Allow me to demonstrate the difference:

type

Say you need to ensure a certain behavior if your function gets a certain kind of argument (a common use-case for constructors). If you check for type like this:

def foo(data):
    '''accepts a dict to construct something, string support in future'''
    if type(data) is not dict:
        # we're only going to test for dicts for now
        raise ValueError('only dicts are supported for now')

If we try to pass in a dict that is a subclass of dict (as we should be able to, if we're expecting our code to follow the principle of Liskov Substitution, that subtypes can be substituted for types) our code breaks!:

from collections import OrderedDict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

raises an error!

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
ValueError: argument must be a dict

isinstance

But if we use isinstance, we can support Liskov Substitution!:

def foo(a_dict):
    if not isinstance(a_dict, dict):
        raise ValueError('argument must be a dict')
    return a_dict

foo(OrderedDict([('foo', 'bar'), ('fizz', 'buzz')]))

returns OrderedDict([('foo', 'bar'), ('fizz', 'buzz')])

Abstract Base Classes

In fact, we can do even better. collections provides Abstract Base Classes that enforce minimal protocols for various types. In our case, if we only expect the Mapping protocol, we can do the following, and our code becomes even more flexible:

from collections import Mapping

def foo(a_dict):
    if not isinstance(a_dict, Mapping):
        raise ValueError('argument must be a dict')
    return a_dict

Response to comment:

It should be noted that type can be used to check against multiple classes using type(obj) in (A, B, C)

Yes, you can test for equality of types, but instead of the above, use the multiple bases for control flow, unless you are specifically only allowing those types:

isinstance(obj, (A, B, C))

The difference, again, is that isinstance supports subclasses that can be substituted for the parent without otherwise breaking the program, a property known as Liskov substitution.

Even better, though, invert your dependencies and don't check for specific types at all.

Conclusion

So since we want to support substituting subclasses, in most cases, we want to avoid type-checking with type and prefer type-checking with isinstance - unless you really need to know the precise class of an instance.

Display a float with two decimal places in Python

Using python string formatting.

>>> "%0.2f" % 3
'3.00'

How can I brew link a specific version?

brew switch libfoo mycopy

You can use brew switch to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/

This will list versions installed ( for example I had Cellar/sdl2/2.0.3, I've compiled into Cellar/sdl2/2.0.4)

brew info sdl2

Then to switch between them

brew switch sdl2 2.0.4
brew info 

Info now shows * next to the 2.0.4

To install under Cellar/<packagename>/<version> from source you can do for example

cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make

check where it gets installed with

make install -n

if all looks correct

make install

Then from cd $(brew --Cellar) do the switch between version.

I'm using brew version 0.9.5

vertical alignment of text element in SVG

attr("dominant-baseline", "central")

how do I use an enum value on a switch statement in C++

You're on the right track. You may read the user input into an integer and switch on that:

enum Choice
{
  EASY = 1, 
  MEDIUM = 2, 
  HARD = 3
};

int i = -1;

// ...<present the user with a menu>...

cin >> i;

switch(i)
{
  case EASY:
    cout << "Easy\n";
    break;
  case MEDIUM:
    cout << "Medium\n";
    break;
  case HARD:
    cout << "Hard\n";
    break;
  default:
    cout << "Invalid Selection\n";
    break;
}

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in Javascript from the browser... If I were you, I would use something like browserify. Write your code using commonjs modules and then compile the javascript file into one.

In your html load the javascript file that you compiled.

Switch php versions on commandline ubuntu 16.04

When installing laravel on Ubuntu 18.04, be default PHP 7.3.0RC3 install selected, but laravel and symfony will not install properly complaining about missin php-xml and php-zip, even though they are installed. You need to switch to php 7.1, using the instructions above or,

 sudo update-alternatives --set php /usr/bin/php7.1

now, running laravel new blog, will proceed correctly

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

You can also return all the information about the Foreign Keys by adapating @LittleSweetSeas answer:

SELECT 
   OBJECT_NAME(f.parent_object_id) ConsTable,
   OBJECT_NAME (f.referenced_object_id) refTable,
   COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM 
   sys.foreign_keys AS f
INNER JOIN 
   sys.foreign_key_columns AS fc 
      ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN 
   sys.tables t 
      ON t.OBJECT_ID = fc.referenced_object_id
order by
ConsTable

Find elements inside forms and iframe using Java and Selenium WebDriver

When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe

You can do it using:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

In case if your frameId is dynamic, and you only have one iframe, you can use something like:

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

TypeError: 'undefined' is not an object

I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?

You could check in the following way (extra = and making length a truthy evaluation)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {

[update]

I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub

My guess is that the error is not on the if statement but on the for(i... statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

Try setting autocomplete="new-password" as shown below:

<input type="password" name="pswd" id="password" maxlength="16" size="20" autocomplete="new-password" />

How do I get the list of keys in a Dictionary?

Marc Gravell's answer should work for you. myDictionary.Keys returns an object that implements ICollection<TKey>, IEnumerable<TKey> and their non-generic counterparts.

I just wanted to add that if you plan on accessing the value as well, you could loop through the dictionary like this (modified example):

Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);

foreach (KeyValuePair<string, int> item in data)
{
    Console.WriteLine(item.Key + ": " + item.Value);
}

Catch multiple exceptions at once?

How about

try
{
    WebId = Guid.Empty;
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}

How to return history of validation loss in Keras

Thanks to Alloush,

Following parameter must be included in model.fit():

validation_data = (x_test, y_test)

If it is not defined, val_acc and val_loss will not be exist at output.

What does "Git push non-fast-forward updates were rejected" mean?

you might want to use force with push operation in this case

git push origin master --force

How to implement an android:background that doesn't stretch?

Simply using ImageButton instead of Button fixes the problem.

<ImageButton android:layout_width="30dp"
             android:layout_height="30dp"
             android:src="@drawable/bgimage" />

and you can set

android:background="@null"

to remove button background if you want.

Quick Fix !! :-)

How do I use FileSystemObject in VBA?

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Else
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...
Loop

fsoStream.Close
Set FSO = Nothing

Hope it help!

Best regards

Fabio

error : expected unqualified-id before return in c++

You need to move " } " before the line of cout << endl; to the line before the first else .

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

Laravel PHP Command Not Found

type on terminal:

nano ~/.bash_profile 

then paste:

export PATH="/Users/yourusername/.composer/vendor/bin:$PATH"

then save (press ctrl+c, press Y, press enter)

now you are ready to use "laravel" on your terminal

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

Checking if output of a command contains a certain string in a shell script

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then
   echo "matched"
fi

and also:

./somecommand | grep -q 'string' && echo 'matched'

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

How to remove spaces from a string using JavaScript?

Following @rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case

So

var result = text.split(' ').join('')

operates faster than

var result = text.replace(/\s+/g, '')

On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.


On the other hand, \s+ handles wider variety of space characters. Among with \n and \t, it also matches \u00a0 character, and that is what &nbsp; is turned in, when getting text using textDomNode.nodeValue.

So I think that conclusion in here can be made as follows: if you only need to replace spaces ' ', use split/join. If there can be different symbols of symbol class - use replace(/\s+/g, '')

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

How to change root logging level programmatically for logback

I seem to be having success doing

org.jboss.logmanager.Logger logger = org.jboss.logmanager.Logger.getLogger("");
logger.setLevel(java.util.logging.Level.ALL);

Then to get detailed logging from netty, the following has done it

org.slf4j.impl.SimpleLogger.setLevel(org.slf4j.impl.SimpleLogger.TRACE);

Redirect parent window from an iframe action

window.top.location.href = "http://example.com";

window.top refers to the window object of the page at the top of the frames hierarchy.

Asynchronous Requests with Python requests

async is now an independent module : grequests.

See here : https://github.com/kennethreitz/grequests

And there: Ideal method for sending multiple HTTP requests over Python?

installation:

$ pip install grequests

usage:

build a stack:

import grequests

urls = [
    'http://www.heroku.com',
    'http://tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u) for u in urls)

send the stack

grequests.map(rs)

result looks like

[<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]

grequests don't seem to set a limitation for concurrent requests, ie when multiple requests are sent to the same server.

Messages Using Command prompt in Windows 7

You can use the net send command to send a message over a network.

example:

net send * How Are You

you can use the above statement to send a message to all members of your domain.But if you want to send a message to a single user named Mike, you can use

 net send mike hello!

this will send hello! to the user named Mike.

input file appears to be a text format dump. Please use psql

if you use pg_dump with -Fp to backup in plain text format, use following command:

cat db.txt | psql dbname

to copy all data to your database with name dbname

Difference between $(window).load() and $(document).ready() functions

document.ready (jQuery) document.ready will execute right after the HTML document is loaded property, and the DOM is ready.

DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents.

$(document).ready(function()
{
   // executes when HTML-Document is loaded and DOM is ready
   alert("(document).ready was called - document is ready!");
});

window.load (Built-in JavaScript) The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc. * window.load is a built-in JavaScript method, it is known to have some quirks in old browsers (IE6, IE8, old FF and Opera versions) but will generally work in all of them.

window.load can be used in the body's onload event like this (but I would strongly suggest you avoid mixing code like this in the HTML, as it is a source for confusion later on):

$(window).load(function() 
{
   // executes when complete page is fully loaded, including all frames, objects and images
   alert("(window).load was called - window is loaded!");
});

Eclipse - java.lang.ClassNotFoundException

Run project as Maven test, then Run as JUnit Test.

Adding a default value in dropdownlist after binding with database

After data-binding, do this:

ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code

Or follow Brian's second suggestion if you want to do it in markup.

You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".

<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" />

Which MIME type to use for a binary file that's specific to my program?

According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname is not allowed, but application/x-myappname is allowed and sounds most appropriate for you're application to me.