Programs & Examples On #Access modifiers

Access modifier is an OOP concept. It determines what level of access or visibility a particular property/method/class has.

What are the default access modifiers in C#?

top level class: internal
method: private
members (unless an interface or enum): private (including nested classes)
members (of interface or enum): public
constructor: private (note that if no constructor is explicitly defined, a public default constructor will be automatically defined)
delegate: internal
interface: internal
explicitly implemented interface member: public!

What is the difference between 'protected' and 'protected internal'?

There is still a lot of confusion in understanding the scope of "protected internal" accessors, though most have the definition defined correctly. This helped me to understand the confusion between "protected" and "protected internal":

public is really public inside and outside the assembly (public internal / public external)

protected is really protected inside and outside the assembly (protected internal / protected external) (not allowed on top level classes)

private is really private inside and outside the assembly (private internal / private external) (not allowed on top level classes)

internal is really public inside the assembly but excluded outside the assembly like private (public internal / excluded external)

protected internal is really public inside the assembly but protected outside the assembly (public internal / protected external) (not allowed on top level classes)

As you can see protected internal is a very strange beast. Not intuitive.

That now begs the question why didn't Microsoft create a (protected internal / excluded external), or I guess some kind of "private protected" or "internal protected"? lol. Seems incomplete?

Added to the confusion is the fact you can nest public or protected internal nested members inside protected, internal, or private types. Why would you access a nested "protected internal" inside an internal class that excludes outside assembly access?

Microsoft says such nested types are limited by their parent type scope, but that's not what the compiler says. You can compiled protected internals inside internal classes which should limit scope to just the assembly.

To me this feels like incomplete design. They should have simplified scope of all types to a system that clearly consider inheritance but also security and hierarchy of nested types. This would have made the sharing of objects extremely intuitive and granular rather than discovering accessibility of types and members based on an incomplete scoping system.

Class is inaccessible due to its protection level

The code you posted does not produce the error messages you quoted. You should provide a (small) example that actually exhibits the problem.

What is the equivalent of Java's final in C#?

What everyone here is missing is Java's guarantee of definite assignment for final member variables.

For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.

C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.

So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.

Internal vs. Private Access Modifiers

Find an explanation below. You can check this link for more details - http://www.dotnetbull.com/2013/10/public-protected-private-internal-access-modifier-in-c.html

Private: - Private members are only accessible within the own type (Own class).

Internal: - Internal member are accessible only within the assembly by inheritance (its derived type) or by instance of class.

enter image description here

Reference :

dotnetbull - what is access modifier in c#

What is the default access modifier in Java?

From a book named OCA Java SE 7 Programmer I:

The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package.

What are public, private and protected in object oriented programming?

They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

private - Only the current class will have access to the field or method.

protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

public - Any class can refer to the field or call the method.

This assumes these keywords are used as part of a field or method declaration within a class definition.

What is the difference between public, protected, package-private and private in Java?

In very short

  • public: accessible from everywhere.
  • protected: accessible by the classes of the same package and the subclasses residing in any package.
  • default (no modifier specified): accessible by the classes of the same package.
  • private: accessible within the same class only.

In C#, what is the difference between public, private, protected, and having no access modifier?

Public - If you can see the class, then you can see the method

Private - If you are part of the class, then you can see the method, otherwise not.

Protected - Same as Private, plus all descendants can also see the method.

Static (class) - Remember the distinction between "Class" and "Object" ? Forget all that. They are the same with "static"... the class is the one-and-only instance of itself.

Static (method) - Whenever you use this method, it will have a frame of reference independent of the actual instance of the class it is part of.

Practical uses for the "internal" keyword in C#

Another reason to use internal is if you obfuscate your binaries. The obfuscator knows that it's safe to scramble the class name of any internal classes, while the name of public classes can't be scrambled, because that could break existing references.

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

how to output every line in a file python

Loop through the file.

f = open("masters.txt")
lines = f.readlines()
for line in lines:
    print line

Why do we usually use || over |? What is the difference?

a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false

How to get the list of all printers in computer

Get Network and Local Printer List in ASP.NET

This method uses the Windows Management Instrumentation or the WMI interface. It’s a technology used to get information about various systems (hardware) running on a Windows Operating System.

private void GetAllPrinterList()
        {
            ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
            objScope.Connect();

            SelectQuery selectQuery = new SelectQuery();
            selectQuery.QueryString = "Select * from win32_Printer";
            ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
            ManagementObjectCollection MOC = MOS.Get();
            foreach (ManagementObject mo in MOC)
            {
                lstPrinterList.Items.Add(mo["Name"].ToString());
            }
        }

Click here to download source and application demo

Demo of application which listed network and local printer

enter image description here

php $_GET and undefined index

I recommend you check your arrays before you blindly access them :

if(isset($_GET['s'])){
    if ($_GET['s'] == 'jwshxnsyllabus')
        /* your code here*/
}

Another (quick) fix is to disable the error reporting by writing this on the top of the script :

error_reporting(0);  

In your case, it is very probable that your other server had the error reporting configuration in php.ini set to 0 as default.
By calling the error_reporting with 0 as parameter, you are turning off all notices/warnings and errors. For more details check the php manual.

Remeber that this is a quick fix and it's highly recommended to avoid errors rather than ignore them.

Android SDK manager won't open

Same problem here. Fixed! I installed the correct Java stuff, all for 64 bit, because my system is x64, and nothing happened. So I went to C:\Users\[my name] and deleted the directory .android that has been created the first time the SDK ran, apparently with some wrong configuration.

Then it worked. You can try that. Delete that folder or just move it to the desktop and run the SDK.

Python equivalent to 'hold on' in Matlab

check pyplot docs. For completeness,

import numpy as np
import matplotlib.pyplot as plt

#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

How can I add a table of contents to a Jupyter / JupyterLab notebook?

How about using a Browser plugin that gives you an overview of ANY html page. I have tried the following:

They both work pretty well for IPython Notebooks. I was reluctant to use the previous solutions as they seem a bit unstable and ended up using these extensions.

BATCH file asks for file or folder

The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.

Example:

xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"

How do I run a simple bit of code in a new thread?

Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.

ADB Android Device Unauthorized

I run into the same issues with nexus7.

Following worked for fixing this.

  1. Open Developer option in the Settings menu on your device.

  2. Switch off the button on the upper right of the screen.

  3. Delete all debug permission from the list of the menu.

  4. Switch on the button on the upper right of the screen.

now reconnect your device to your PC and everything should be fine.

Sorry for my poor english and some name of the menus(buttons) can be incorrect in your language because mine is Japanese.

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM

The Java Virtual Machine (JVM) is the virtual machine that runs the Java bytecodes. The JVM doesn't understand Java source code; that's why you need compile your *.java files to obtain *.class files that contain the bytecodes understood by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed, there are specific implementations of the JVM for different systems (Windows, Linux, macOS, see the Wikipedia list), the aim is that with the same bytecodes they all give the same results.

JDK and JRE

To explain the difference between JDK and JRE, the best is to read the Oracle documentation and consult the diagram:

Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

Java Development Kit (JDK)

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.

Note that Oracle is not the only one to provide JDKs.

OpenJDK

OpenJDK is an open-source implementation of the JDK and the base for the Oracle JDK. There is almost no difference between the Oracle JDK and the OpenJDK.

The differences are stated in this blog:

Q: What is the difference between the source code found in the OpenJDK repository, and the code you use to build the Oracle JDK?

A: It is very close - our build process for Oracle JDK releases builds on OpenJDK 7 by adding just a couple of pieces, like the deployment code, which includes Oracle's implementation of the Java Plugin and Java WebStart, as well as some closed source third party components like a graphics rasterizer, some open source third party components, like Rhino, and a few bits and pieces here and there, like additional documentation or third party fonts. Moving forward, our intent is to open source all pieces of the Oracle JDK except those that we consider commercial features such as JRockit Mission Control (not yet available in Oracle JDK), and replace encumbered third party components with open source alternatives to achieve closer parity between the code bases.

Update for JDK 11 - An article from Donald Smith try to disambiguate the difference between Oracle JDK and Oracle's OpenJDK : https://blogs.oracle.com/java-platform-group/oracle-jdk-releases-for-java-11-and-later

HashMap get/put complexity

It has already been mentioned that hashmaps are O(n/m) in average, if n is the number of items and m is the size. It has also been mentioned that in principle the whole thing could collapse into a singly linked list with O(n) query time. (This all assumes that calculating the hash is constant time).

However what isn't often mentioned is, that with probability at least 1-1/n (so for 1000 items that's a 99.9% chance) the largest bucket won't be filled more than O(logn)! Hence matching the average complexity of binary search trees. (And the constant is good, a tighter bound is (log n)*(m/n) + O(1)).

All that's required for this theoretical bound is that you use a reasonably good hash function (see Wikipedia: Universal Hashing. It can be as simple as a*x>>m). And of course that the person giving you the values to hash doesn't know how you have chosen your random constants.

TL;DR: With Very High Probability the worst case get/put complexity of a hashmap is O(logn).

git undo all uncommitted or unsaved changes

  • This will unstage all files you might have staged with git add:

    git reset
    
  • This will revert all local uncommitted changes (should be executed in repo root):

    git checkout .
    

    You can also revert uncommitted changes only to particular file or directory:

    git checkout [some_dir|file.txt]
    

    Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):

    git reset --hard HEAD
    
  • This will remove all local untracked files, so only git tracked files remain:

    git clean -fdx
    

    WARNING: -x will also remove all ignored files, including ones specified by .gitignore! You may want to use -n for preview of files to be deleted.


To sum it up: executing commands below is basically equivalent to fresh git clone from original source (but it does not re-download anything, so is much faster):

git reset
git checkout .
git clean -fdx

Typical usage for this would be in build scripts, when you must make sure that your tree is absolutely clean - does not have any modifications or locally created object files or build artefacts, and you want to make it work very fast and to not re-clone whole repository every single time.

Trim string in JavaScript?

The trim from jQuery is convenient if you are already using that framework.

$.trim('  your string   ');

I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)

Is it possible to open a Windows Explorer window from PowerShell?

Just use the Invoke-Item cmdlet. For example, if you want to open a explorer window on the current directory you can do:

Invoke-Item .

Escape double quotes in Java

Yes you will have to escape all double quotes by a backslash.

Nodejs convert string into UTF-8

I had the same problem, when i loaded a text file via fs.readFile(), I tried to set the encodeing to UTF8, it keeped the same. my solution now is this:

myString = JSON.parse( JSON.stringify( myString ) )

after this an Ö is realy interpreted as an Ö.

Append data to a POST NSURLRequest

If you don't wish to use 3rd party classes then the following is how you set the post body...

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                             delegate:self];

Simply append your key/value pair to the post string

Visual Studio 64 bit?

no, but it runs fine on win64, and can create win64 .EXEs

SQL Error: ORA-00942 table or view does not exist

Because this post is the top one found on stackoverflow when searching for "ORA-00942: table or view does not exist insert", I want to mention another possible cause of this error (at least in Oracle 12c): a table uses a sequence to set a default value and the user executing the insert query does not have select privilege on the sequence. This was my problem and it took me an unnecessarily long time to figure it out.

To reproduce the problem, execute the following SQL as user1:

create sequence seq_customer_id;

create table customer (
c_id number(10) default seq_customer_id.nextval primary key,
name varchar(100) not null,
surname varchar(100) not null
);

grant select, insert, update, delete on customer to user2;

Then, execute this insert statement as user2:

insert into user1.customer (name,surname) values ('michael','jackson');

The result will be "ORA-00942: table or view does not exist" even though user2 does have insert and select privileges on user1.customer table and is correctly prefixing the table with the schema owner name. To avoid the problem, you must grant select privilege on the sequence:

grant select on seq_customer_id to user2;

JVM heap parameters

Apart from standard Heap parameters -Xms and -Xmx it's also good to know -XX:PermSize and -XX:MaxPermSize, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.

Importing data from a JSON file into R

First install the rjson package:

install.packages("rjson")

Then:

library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

Update: since version 0.2.1

json_data <- fromJSON(file=json_file)

What is an IIS application pool?

Basically, an application pool is a way to create compartments in a web server through process boundaries, and route sets of URLs to each of these compartments. See more info here: http://technet.microsoft.com/en-us/library/cc735247(WS.10).aspx

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

You can not add ON DELETE CASCADE to an already existing constraint. You will have to drop and re-create the constraint. The documentation shows that the MODIFY CONSTRAINT clause can only modify the state of a constraint (i-e: ENABLED/DISABLED...).

Why use static_cast<int>(x) instead of (int)x?

static_cast means that you can't accidentally const_cast or reinterpret_cast, which is a good thing.

Changing the cursor in WPF sometimes works, sometimes doesn't

You can use a data trigger (with a view model) on the button to enable a wait cursor.

<Button x:Name="NextButton"
        Content="Go"
        Command="{Binding GoCommand }">
    <Button.Style>
         <Style TargetType="{x:Type Button}">
             <Setter Property="Cursor" Value="Arrow"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
                     <Setter Property="Cursor" Value="Wait"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
    </Button.Style>
</Button>

Here is the code from the view-model:

public class MainViewModel : ViewModelBase
{
   // most code removed for this example

   public MainViewModel()
   {
      GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
   }

   // flag used by data binding trigger
   private bool _isWorking = false;
   public bool IsWorking
   {
      get { return _isWorking; }
      set
      {
         _isWorking = value;
         OnPropertyChanged("IsWorking");
      }
   }

   // button click event gets processed here
   public ICommand GoCommand { get; private set; }
   private void OnGoCommand(object obj)
   {
      if ( _selectedCustomer != null )
      {
         // wait cursor ON
         IsWorking = true;
         _ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
         OnPropertyChanged("GridData");

         // wait cursor off
         IsWorking = false;
      }
   }
}

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

How Connect to remote host from Aptana Studio 3

There's also an option to Auto Sync built-in in Aptana.

step 1

step 2

How can I tell gcc not to inline a function?

static __attribute__ ((noinline))  void foo()
{

}

This is what worked for me.

How to print a date in a regular format?

You need to convert the date time object to a string.

The following code worked for me:

import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print collection

Let me know if you need any more help.

What is lexical scope?

Lexical scoping: Variables declared outside of a function are global variables and are visible everywhere in a JavaScript program. Variables declared inside a function have function scope and are visible only to code that appears inside that function.

Converting of Uri to String

String to Uri

Uri myUri = Uri.parse("https://www.google.com");

Uri to String

Uri uri;
String stringUri = uri.toString();

What are App Domains in Facebook Apps?

In this example:

http://www.example.com:80/somepage?parameter1="hello"&parameter2="world"

the bold part is the Domainname. 80 is rarely included. I post it since many people may wonder if 3000 or some other port is part of the domain if their not staging their app for production yet. Normally you don't specify it since 80 is the default, but if you just want to specify localhost just do it without the port number, it works just as fine. The adress, though, should be http://localhost:3000 (if you have it on that port).

TypeError: expected a character buffer object - while trying to save integer to textfile

Have you checked the docstring of write()? It says:

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

So you need to convert y to str first.

Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0) to get to the beginning of the file.`

Edit: As for the IOError, this issue seems related. A cite from there:

For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.

So, I suggest you try f.seek(0) and maybe the problem goes away.

Force HTML5 youtube video

If you're using the iframe embed api, you can put html5:1 as one of the playerVars arguments, like so:

player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: '<VIDEO ID>',
    playerVars: {
        html5: 1
    },
});

Totally works.

using if else with eval in aspx page

<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>

How can I determine browser window size on server side C#

You can use Javascript to get the viewport width and height. Then pass the values back via a hidden form input or ajax.

At its simplest

var width = $(window).width();
var height = $(window).height();

Complete method using hidden form inputs

Assuming you have: JQuery framework.

First, add these hidden form inputs to store the width and height until postback.

<asp:HiddenField ID="width" runat="server" />
<asp:HiddenField ID="height" runat="server" />

Next we want to get the window (viewport) width and height. JQuery has two methods for this, aptly named width() and height().

Add the following code to your .aspx file within the head element.

<script type="text/javascript">
$(document).ready(function() {

    $("#width").val() = $(window).width();
    $("#height").val() = $(window).height();    

});
</script>

Result

This will result in the width and height of the browser window being available on postback. Just access the hidden form inputs like this:

var TheBrowserWidth = width.Value;
var TheBrowserHeight = height.Value;

This method provides the height and width upon postback, but not on the intial page load.

Note on UpdatePanels: If you are posting back via UpdatePanels, I believe the hidden inputs need to be within the UpdatePanel.

Alternatively you can post back the values via an ajax call. This is useful if you want to react to window resizing.

Update for jquery 3.1.1

I had to change the JavaScript to:

$("#width").val($(window).width());
$("#height").val($(window).height());

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

JavaScript/jQuery - How to check if a string contain specific words

You might wanna use include method in JS.

var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.

PS: includes is case sensitive.

How can I make my match non greedy in vim?

What's wrong with

%s/style="[^"]*"//g

UICollectionView auto scroll to cell at IndexPath

New, Edited Answer:

Add this in viewDidLayoutSubviews

SWIFT

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    let indexPath = IndexPath(item: 12, section: 0)
    self.collectionView.scrollToItem(at: indexPath, at: [.centeredVertically, .centeredHorizontally], animated: true)
}

Normally, .centerVertically is the case

ObjC

-(void)viewDidLayoutSubviews {
   [super viewDidLayoutSubviews];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:12 inSection:0];
   [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically | UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

Old answer working for older iOS

Add this in viewWillAppear:

[self.view layoutIfNeeded];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];

What’s the best RESTful method to return total number of items in an object?

Seems easiest to just add a

GET
/api/members/count

and return the total count of members

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

I solved this error by doing this and it perfectly worked for me. I have created a node App which has the folder node-android/node-modules.So here inside the node-modules directory I have one more directory bson/ext/index.js open this file and you can find inside the catch block.

bson = require('../build/Release/bson');  

change the above line to

bson = require('../browser_build/bson');

and the error was gone for me and the app is running perfectly without any errors or warnings.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

    //sort
    int missingNum[2];//missing 2 numbers- can be applied to more than 2
    int j = 0;    
    for(int i = 0; i < length - 1; i++){
        if(arr[i+1] - arr[i] > 1 ) {
            missingNum[j] = arr[i] + 1;
            j++;
        }
    }

How do I select the "last child" with a specific class name in CSS?

You can't target the last instance of the class name in your list without JS.

However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list elements here: http://jsbin.com/vejixisudo/edit?html,css,output

Issue with background color and Google Chrome

Everybody has said your code is fine, and you know it works on other browsers without problems. So it's time to drop the science and just try stuff :)

Try putting the background color IN the body tag itself instead of/as-well-as in the CSS. Maybe insist again (redudantly) in Javascript. At some point, Chrome will have to place the background as you want it every time. Might be a timing-interpreting issue...

[Should any of this work, of course, you can toggle it on the server-side so the funny code only shows up in Chrome. And in a few months, when Chrome has changed and the problem disappears... well, worry about that later.]

C++ Loop through Map

As P0W has provided complete syntax for each C++ version, I would like to add couple of more points by looking at your code

  • Always take const & as argument as to avoid extra copies of the same object.
  • use unordered_map as its always faster to use. See this discussion

here is a sample code:

#include <iostream>
#include <unordered_map>
using namespace std;

void output(const auto& table)
{
   for (auto const & [k, v] : table)
   {
        std::cout << "Key: " << k << " Value: " << v << std::endl;
   }
}

int main() {
    std::unordered_map<string, int> mydata = {
        {"one", 1},
        {"two", 2},
        {"three", 3}
    };
    output(mydata);
    return 0;
}

How return error message in spring mvc @Controller

Here is an alternative. Create a generic exception that takes a status code and a message. Then create an exception handler. Use the exception handler to retrieve the information out of the exception and return to the caller of the service.

http://javaninja.net/2016/06/throwing-exceptions-messages-spring-mvc-controller/

public class ResourceException extends RuntimeException {

    private HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;

    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()}
     *                method.
     */
    public ResourceException(HttpStatus httpStatus, String message) {
        super(message);
        this.httpStatus = httpStatus;
    }
}

Then use an exception handler to retrieve the information and return it to the service caller.

@ControllerAdvice
public class ExceptionHandlerAdvice { 

    @ExceptionHandler(ResourceException.class)
    public ResponseEntity handleException(ResourceException e) {
        // log exception 
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }         
} 

Then create an exception when you need to.

throw new ResourceException(HttpStatus.NOT_FOUND, "We were unable to find the specified resource.");

HTML anchor link - href and onclick both?

If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false.

If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.

Adding space/padding to a UILabel

Just use autolayout:

let paddedWidth = myLabel.intrinsicContentSize.width + 2 * padding
myLabel.widthAnchor.constraint(equalToConstant: paddedWidth).isActive = true

Done.

Moment js get first and last day of current month

moment startOf() and endOf() is the answer you are searching for.. For Example:-

moment().startOf('year');    // set to January 1st, 12:00 am this year
moment().startOf('month');   // set to the first of this month, 12:00 am
moment().startOf('week');    // set to the first day of this week, 12:00 am
moment().startOf('day');     // set to 12:00 am today

How is using "<%=request.getContextPath()%>" better than "../"

request.getContextPath()- returns root path of your application, while ../ - returns parent directory of a file.

You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.

Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.

<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>

PS- This is the one reason I can figure out. Don't know if there is any more significance to it.

How to connect HTML Divs with Lines?

It's kind of a pain to position, but you could use 1px wide divs as lines and position and rotate them appropriately.

http://jsfiddle.net/sbaBG/1

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>

<div class="line" id="line1"></div>
<div class="line" id="line2"></div>
.box {
    border: 1px solid black;
    background-color: #ccc;
    width: 100px;
    height: 100px;
    position: absolute;
}
.line {
    width: 1px;
    height: 100px;
    background-color: black;
    position: absolute;
}
#box1 {
    top: 0;
    left: 0;
}
#box2 {
    top: 200px;
    left: 0;
}
#box3 {
    top: 250px;
    left: 200px;
}
#line1 {
    top: 100px;
    left: 50px;
}
#line2 {
    top: 220px;
    left: 150px;
    height: 115px;

    transform: rotate(120deg);
    -webkit-transform: rotate(120deg);
    -ms-transform: rotate(120deg);
}

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

How to solve Permission denied (publickey) error when using Git?

Its pretty straight forward. Type the below command

ssh-keygen -t rsa -b 4096 -C "[email protected]"

Generate the SSH key. Open the file and copy the contents. Go to GitHub setting page , and click on SSH key . Click on Add new SSH key, and paste the contents here. That's it :) You shouldn't see the issue again.

setState() inside of componentDidUpdate()

You can use setStateinside componentDidUpdate. The problem is that somehow you are creating an infinite loop because there's no break condition.

Based on the fact that you need values that are provided by the browser once the component is rendered, I think your approach about using componentDidUpdate is correct, it just needs better handling of the condition that triggers the setState.

Regular expression: find spaces (tabs/space) but not newlines

Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000) is not included in \s for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000 with \u0020), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000].

If you're using Perl or PCRE, you have the option of using the \h shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.

However, this \h shorthand has not been implemented for .NET and C#, as best I've been able to tell.

font awesome icon in select option

If you want the caret down symbol, remove the "appearence: none" it implies to remove webkit and moz- as well from select in css.

Generating random, unique values C#

unique random number from 0 to 9

      int sum = 0;
        int[] hue = new int[10];
        for (int i = 0; i < 10; i++)
        {

            int m;
            do
            {
                m = rand.Next(0, 10);
            } while (hue.Contains(m) && sum != 45);
            if (!hue.Contains(m))
            {
                hue[i] = m;
                sum = sum + m;
            }

        }

How to URL encode a string in Ruby

If you want to "encode" a full URL without having to think about manually splitting it into its different parts, I found the following worked in the same way that I used to use URI.encode:

URI.parse(my_url).to_s

Jquery to get SelectedText from dropdown

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-3.1.0.js"></script>
    <script>
        $(function () {
            $('#selectnumber').change(function(){
                alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());
            })
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <select id="selectnumber">
            <option value="1">one</option>
            <option value="2">two</option>
            <option value="3">three</option>
            <option value="4">four</option>
        </select>

    </div>
    </form>
</body>
</html>

Click to see Output Screen

Thanks...:)

How to check if any Checkbox is checked in Angular

Try to think in terms of a model and what happens to that model when a checkbox is checked.

Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:

<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />

and in the controller:

$scope.fooSelected = false;
$scope.baaSelected = false;

The next button should only be available under certain circumstances so add the ng-disabled directive to the button:

<button type='button' ng-disabled='nextButtonDisabled'></button>

Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:

$scope.$watch('[fooSelected,baaSelected]', function(){
    $scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );

The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.

Variables as commands in bash scripts

Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.

It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.

With perl, as my example, I'd be able to do something like:

@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );

The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

I created an alternate colors library for bootstrap 2.3.2 it's available and simple to use for anyone interested in more colors for the old glyphicons library.

Regular Expression to reformat a US phone number in Javascript

thinking backwards

Take the last digits only (up to 10) ignoring first "1".

function formatUSNumber(entry = '') {
  const match = entry
    .replace(/\D+/g, '').replace(/^1/, '')
    .match(/([^\d]*\d[^\d]*){1,10}$/)[0]
  const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
  const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
  const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''    
  return `${part1}${part2}${part3}`
}

example input / output as you type

formatUSNumber('+1333')
// (333)

formatUSNumber('333')
// (333)

formatUSNumber('333444')
// (333) 444

formatUSNumber('3334445555')
// (333) 444-5555

What does SQL clause "GROUP BY 1" mean?

It will group by the column position you put after the group by clause.

for example if you run 'SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1' it will group by SALESMAN_NAME.

One risk on doing that is if you run 'Select *' and for some reason you recreate the table with columns on a different order, it will give you a different result than you would expect.

Disable scrolling in webview?

studying the above answers almost worked for me ... but I still had a problem that I could 'fling' the view on 2.1 (seemed to be fixed with 2.2 & 2.3).

here is my final solution

public class MyWebView extends WebView
{
private boolean bAllowScroll = true;
@SuppressWarnings("unused") // it is used, just java is dumb
private long downtime;

public MyWebView(Context context, AttributeSet attrs)
{
    super(context, attrs);
}

public void setAllowScroll(int allowScroll)
{
    bAllowScroll = allowScroll!=0;
    if (!bAllowScroll)
        super.scrollTo(0,0);
    setHorizontalScrollBarEnabled(bAllowScroll);
    setVerticalScrollBarEnabled(bAllowScroll);
}

@Override
public boolean onTouchEvent(MotionEvent ev) 
{
    switch (ev.getAction())
    {
    case MotionEvent.ACTION_DOWN:
        if (!bAllowScroll)
            downtime = ev.getEventTime();
        break;
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
        if (!bAllowScroll)
        {
            try {
                Field fmNumSamples = ev.getClass().getDeclaredField("mNumSamples");
                fmNumSamples.setAccessible(true);
                Field fmTimeSamples = ev.getClass().getDeclaredField("mTimeSamples");
                fmTimeSamples.setAccessible(true);
                long newTimeSamples[] = new long[fmNumSamples.getInt(ev)];
                newTimeSamples[0] = ev.getEventTime()+250;
                fmTimeSamples.set(ev,newTimeSamples);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        break;
    }
    return super.onTouchEvent(ev);
}

@Override
public void flingScroll(int vx, int vy)
{
    if (bAllowScroll)
        super.flingScroll(vx,vy);
}

@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt)
{
    if (bAllowScroll)
        super.onScrollChanged(l, t, oldl, oldt);
    else if (l!=0 || t!=0)
        super.scrollTo(0,0);
}

@Override
public void scrollTo(int x, int y)
{
    if (bAllowScroll)
        super.scrollTo(x,y);
}

@Override
public void scrollBy(int x, int y)
{
    if (bAllowScroll)
        super.scrollBy(x,y);
}
}

How to limit depth for recursive file list?

Make use of find's options

There is actually no exec of /bin/ls needed;

Find has an option that does just that:

find . -maxdepth 2 -type d -ls

To see only the one level of subdirectories you are interested in, add -mindepth to the same level as -maxdepth:

find . -mindepth 2 -maxdepth 2 -type d -ls

Use output formatting

When the details that get shown should be different, -printf can show any detail about a file in custom format; To show the symbolic permissions and the owner name of the file, use -printf with %M and %u in the format.

I noticed later you want the full ownership information, which includes the group. Use %g in the format for the symbolic name, or %G for the group id (like also %U for numeric user id)

find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'

This should give you just the details you need, for just the right files.

I will give an example that shows actually different values for user and group:

$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data  www-data /tmp/user/33
drwx------ octopussy root     /tmp/user/126
drwx------ root      root     /tmp/user/0
drwx------ siegel    root     /tmp/user/1000
drwxrwxrwt root      root     /tmp/systemd-[...].service-HRUQmm/tmp

(Edited for readability: indented, shortened last line)


Notes on performance

Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:

Not only do we save creating a new process for each name - a huge task - the information does not even need to be read, as find already knows it.

What is Android's file system?

Johan is close - it depends on the hardware manufacturer. For example, Samsung Galaxy S phones uses Samsung RFS (proprietary). However, the Nexus S (also made by Samsung) with Android 2.3 uses Ext4 (presumably because Google told them to - the Nexus S is the current Google experience phone). Many community developers have also started moving to Ext4 because of this shift.

How to draw a path on a map using kml file?

Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:

 if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                    && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

GeoPoint can be less than zero as well, I switch mine to:

     if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
                    && gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {

Thank you :D

How to fetch data from local JSON file on react native?

Take a look at this Github issue:

https://github.com/facebook/react-native/issues/231

They are trying to require non-JSON files, in particular JSON. There is no method of doing this right now, so you either have to use AsyncStorage as @CocoOS mentioned, or you could write a small native module to do what you need to do.

The request was aborted: Could not create SSL/TLS secure channel

Delete this option from registry helped me in Windows Server 2012 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangAlgorithms

enter image description here

How to restart ADB manually from Android Studio

When I had this problem, I wrote adb kill-server and adb restart-server in terminal, but the problem appeared again the next day. Then I updated GPU debugging tools in the Android SDK manager and restarted the computer, which worked for me.

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

error: Unable to find vcvarsall.bat

If you want to compile with Visual Studio C++ instead of mingw...

  1. Run python.exe to display which version of VC++ it was compiled with (example shown below).

    It is important to use the corresponding version of the Visual C++ compiler that Python was compiled with since distilutils's get_build_version prevents mixing versions (per Piotr's warning).

    • Yellow (top) is Python 2.7, compiled with MSC v.1500 (Visual Studio C++ 2008)
    • Red (bottom) is Python 3.4.1, compiled with MSC v.1600 (Visual Studio C++ 2010)

    Example from the command line showing Python 2.7 compiled with MSC v.1500 and Python 3.4.1 compiled with MSC v.1600

  2. Use the table below[1] to match the internal VC++ version with the corresponding Visual Studio release:

    MSC v.1000 -> Visual C++ 4.x        
    MSC v.1100 -> Visual C++ 5          
    MSC v.1200 -> Visual C++ 6          
    MSC v.1300 -> Visual C++ .NET       
    MSC v.1310 -> Visual C++ .NET 2003  
    MSC v.1400 -> Visual C++ 2005  (8.0)
    MSC v.1500 -> Visual C++ 2008  (9.0)
    MSC v.1600 -> Visual C++ 2010 (10.0)
    MSC v.1700 -> Visual C++ 2012 (11.0)
    MSC v.1800 -> Visual C++ 2013 (12.0)
    MSC v.1900 -> Visual C++ 2015 (14.0)
    MSC v.1910 -> Visual C++ 2017 (15.0)
    MSC v.1911 -> Visual C++ 2017 (15.3)
    MSC v.1912 -> Visual C++ 2017 (15.5)
    MSC v.1913 -> Visual C++ 2017 (15.6)
    MSC v.1914 -> Visual C++ 2017 (15.7)
    MSC v.1915 -> Visual C++ 2017 (15.8)
    MSC v.1916 -> Visual C++ 2017 (15.9)   
    
  3. Download and install the corresponding version of Visual Studio C++ from the previous step.
    Additional notes for specific versions of VC++ are listed below.

    Notes for Visual Studio C++ 2008

    For only the 32-bit compilers, download Visual Studio C++ 2008 Express Edition.

    For the 64-bit compilers[2][3], download Windows SDK for Windows 7 and .NET Framework 3.5 SP1.

    • Uncheck everything except Developer Tools >> Visual C++ Compilers to save time and disk space from installing SDK tools you otherwise don't need.

    Notes for Visual Studio C++ 2010

    According to Microsoft, if you installed Visual Studio 2010 SP1, it may have removed the compilers and libraries for VC++.
    If that is the case, download Visual C++ 2010 SP1 Compiler Update.

    Notes for Visual Studio C++ 2015

    If you don't need the Visual Studio IDE, download Visual Studio C++ 2015 Build Tools.

    Notes for Visual Studio C++ 2017

    If you don't need the Visual Studio IDE, download Build Tools for Visual Studio 2017.

    Suggestion: If you have both a 32- and 64-bit Python installation, you may also want to use virtualenv to create separate Python environments so you can use one or the other at a time without messing with your path to choose which Python version to use.

According to @srodriguex, you may be able to skip manually loading the batch file (Steps 4-6) by instead copying a few batch files to where Python is searching by following this answer. If that doesn't work, here are the following steps that originally worked for me.

  1. Open up a cmd.exe

  2. Before you try installing something which requires C extensions, run the following batch file to load the VC++ compiler's environment into the session (i.e. environment variables, the path to the compiler, etc).

    Execute:

    • 32-bit Compilers:

      Note: 32-bit Windows installs will only have C:\Program Files\ as expected

      "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars32.bat"

    • 64-bit Compilers:

      "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars64.bat"

      Note: Yes, the native 64-bit compilers are in Program Files (x86). Don't ask me why.
      Additionally, if you are wondering what the difference between vcvars64.bat and vcvarsx86_amd64.bat or more importantly the difference between amd64 and x86_amd64, the former are for the native 64-bit compiler tools and the latter are the 64-bit cross compilers that can run on a 32-bit Windows installation.

    Update:
    If for some reason you are getting error: ... was unexpected at this time. where the ... is some series of characters, then you need to check that you path variable does not have any extraneous characters like extra quotations or stray characters. The batch file is not going to be able to update your session path if it can't make sense of it in the first place.

  3. If that went well, you should get one of the following messages depending on which version of VC++ and which command you ran:

    For the 32-bit compiler tools:
    Setting environment for using Microsoft Visual Studio 20xx x86 tools.

    For the 64-bit compiler tools:
    Setting environment for using Microsoft Visual Studio 20xx x64 tools.

  4. Now, run the setup via python setup.py install or pip install pkg-name

  5. Hope and cross your fingers that the planets are aligned correctly for VC++ to cooperate.

Visual Studio Code: format is not using indent settings

Visual Studio Code detects the current indentation per default and uses this - ignoring the .editorconfig

Set also "editor.detectIndentation" to false

(Files -> Preferences -> Settings)

screenshot

Global Angular CLI version greater than local version

Two ways to solve this global and local angular CLI version issue.
1. Keep a specific angular-cli version for both environments.
2. Goto latest angular-cli version for both environments.

1. Specific angular-cli version

First, find out which angular version you want to keep on the global and local environment.

ng --version

for example: here we keeping local angular CLI version 8.3.27

So, we have to change the global version also on 8.3.27. use cmd>

npm install --save-dev @angular/[email protected] -g

here, '-g' flag for a set global angular-cli version.

2. Goto latest angular version for both CLI environment.

npm install --save-dev @angular/cli@latest -g  
npm install --save-dev @angular/cli@latest 

Upgrade Node.js to the latest version on Mac OS

I am able to upgrade the node using following command

nvm install node --reinstall-packages-from=node

MySQL - Using COUNT(*) in the WHERE clause

try this;

select gid
from `gd`
group by gid 
having count(*) > 10
order by lastupdated desc

When and why to 'return false' in JavaScript?

I also came to this page after searching "js, when to use 'return false;' Among the other search results was a page I found far more useful and straightforward, on Chris Coyier's CSS-Tricks site: The difference between ‘return false;’ and ‘e.preventDefault();’

The gist of his article is:

function() { return false; }

// IS EQUAL TO

function(e) { e.preventDefault(); e.stopPropagation(); }

though I would still recommend reading the whole article.

Update: After arguing the merits of using return false; as a replacement for e.preventDefault(); & e.stopPropagation(); one of my co-workers pointed out that return false also stops callback execution, as outlined in this article: jQuery Events: Stop (Mis)Using Return False.

Eclipse internal error while initializing Java tooling

  1. Close Eclipse.
  2. Go to workspace folder in windows explorer and delete following folders:
    • .metadata
    • .recommenders
    • RemoteSystemsTempFiles
    • Servers
  3. Open Eclipse and provide the same workspace folder again during launch.

How to access the correct `this` inside a callback?

The trouble with "context"

The term "context" is sometimes used to refer to the object referenced by this. Its use is inappropriate because it doesn't fit either semantically or technically with ECMAScript's this.

"Context" means the circumstances surrounding something that adds meaning, or some preceding and following information that gives extra meaning. The term "context" is used in ECMAScript to refer to execution context, which is all the parameters, scope, and this within the scope of some executing code.

This is shown in ECMA-262 section 10.4.2:

Set the ThisBinding to the same value as the ThisBinding of the calling execution context

which clearly indicates that this is part of an execution context.

An execution context provides the surrounding information that adds meaning to the code that is being executed. It includes much more information than just the thisBinding.

So the value of this isn't "context", it's just one part of an execution context. It's essentially a local variable that can be set by the call to any object and in strict mode, to any value at all.

Running a shell script through Cygwin on Windows

If you have access to the Notepad++ editor on Windows there is a feature that allows you to easily get around this problem:

  1. Open the file that's giving the error in Notepad++.
  2. Go under the "Edit" Menu and choose "EOL Conversion"
  3. There is an option there for "UNIX/OSX Format." Choose that option.
  4. Re-save the file.

I did this and it solved my problems.

Hope this helps!

Read more at http://danieladeniji.wordpress.com/2013/03/07/microsoft-windows-cygwin-error-r-command-not-found/

How to set JAVA_HOME in Linux for all users

None of the other answers were "sticking" for me in RHEL 7, even setting JAVA_HOME and PATH directly in /etc/profile or ~/.bash_profile would not work. Each time I tried to check if JAVA_HOME was set, it would come up blank:

$ echo $JAVA_HOME
    (<-- no output)

What I had to do was set up a script in /etc/profile.d/jdk_home.sh:

#!/bin/sh
export JAVA_HOME=/opt/ibm/java-x86_64-60/
export PATH=$JAVA_HOME/bin:$PATH

I initially neglected the first line (the #!/bin/sh), and it won't work without it.

Now it's working:

$ echo $JAVA_HOME
/opt/ibm/java-x86_64-60/

Corrupt jar file

If the jar file has any extra bytes at the end, explorers like 7-Zip can open it, but it will be treated as corrupt. I use an online upload system that automatically adds a single extra LF character ('\n', 0x0a) to the end of every jar file. With such files, there are a variety solutions to run the file:

  • Use prayagubd's approach and specify the .jar as the classpath and name of the main class at the command prompt
  • Remove the extra byte at the end of the file (with a hex-editor or a command like head -c -1 myjar.jar), and then execute the jar by double-clicking or with java -jar myfile.jar as normal.
  • Change the extension from .jar to .zip, extract the files, and recreate the .zip file, being sure that the META-INF folder is in the top-level.
  • Changing the .jar extension to .zip, deleting an uneeded file from within the .jar, and change the extension back to .jar

All of these solutions require that the structure of the .zip and the META-INF file is essentially correct. They have only been tested with a single extra byte at the end of the zip "corrupting" it.

I got myself in a real mess by applying head -c -1 *.jar > tmp.jar twice. head inserted the ASCII text ==> myjar.jar <== at the start of the file, completely corrupting it.

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

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)

Include PHP file into HTML file

You'll have to configure the server to interpret .html files as .php files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

Serialize form data to JSON

Well, here's a handy plugin for it: https://github.com/macek/jquery-serialize-object

The issue for it is:

Moving ahead, on top of core serialization, .serializeObject will support correct serializaton for boolean and number values, resulting valid types for both cases.

Look forward to these in >= 2.1.0

Getting value from table cell in JavaScript...not jQuery

I know this is like years old post but since there is no selected answer I hope this answer may give you what you are expecting...

if(document.getElementsByTagName){  
    var table = document.getElementById('table className');
    for (var i = 0, row; row = table.rows[i]; i++) {
    //rows would be accessed using the "row" variable assigned in the for loop
     for (var j = 0, col; col = row.cells[j]; j++) {
     //columns would be accessed using the "col" variable assigned in the for loop
        alert('col html>>'+col.innerHTML);    //Will give you the html content of the td
        alert('col>>'+col.innerText);    //Will give you the td value
        }
      }
    }
}

How to round up with excel VBA round()?



Try this function, it's ok to round up a double

'---------------Start -------------
Function Round_Up(ByVal d As Double) As Integer
    Dim result As Integer
    result = Math.Round(d)
    If result >= d Then
        Round_Up = result
    Else
        Round_Up = result + 1
    End If
End Function
'-----------------End----------------

server error:405 - HTTP verb used to access this page is not allowed

It means litraly that, your trying to use the wrong http verb when accessing some http content. A lot of content on webservices you need to use a POST to consume. I suspect your trying to access the facebook API using the wrong http verb.

How to make an AJAX call without jQuery?

I was looking for a way to include promises with ajax and exclude jQuery. There's an article on HTML5 Rocks that talks about ES6 promises. (You could polyfill with a promise library like Q) You can use the code snippet that I copied from the article.

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

Note: I also wrote an article about this.

How do I import a specific version of a package using go get?

From Go 1.5 there's the "vendor experiment" that helps you manage dependencies. As of Go 1.6 this is no longer an experiment. Theres also some other options on the Go wiki..

Edit: as mentioned in this answer gopkg.in is a good option for pinning github-depdencies pre-1.5.

Pass multiple values with onClick in HTML link

If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:

<a href=# onclick="return ReAssign(valuationId,user)">Re-Assign</a>

If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:

<?php
    echo '<a href=# onclick="return ReAssign(\'' + $valuationId + '\',\'' + $user + '\')">Re-Assign</a>';
?>

The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:

var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId + '\',\'' + user + '\')">Re-Assign</a> </td>  </tr>');

The moral of the story is

'someString(\''+'otherString'+','+'yetAnotherString'+'\')'

Will get evaluated as:

someString('otherString,yetAnotherString');

Whereas you would need:

someString('otherString','yetAnotherString');

How to call a SOAP web service on Android

About a year ago I was reading this thread trying to figure out how to do SOAP calls on Android - the suggestions to build my own using HttpClient resulted in me building my own SOAP library for Android:

IceSoap

Basically it allows you to build up envelopes to send via a simple Java API, then automatically parses them into objects that you define via XPath... for example:

<Dictionary>
    <Id></Id>
    <Name></Name>
</Dictionary>

Becomes:

@XMLObject("//Dictionary")
public class Dictionary {
    @XMLField("Id")
    private String id;

    @XMLField("Name")
    private String name;
}

I was using it for my own project but I figured it might help some other people so I've spent some time separating it out and documenting it. I'd really love it if some of your poor souls who stumble on this thread while googling "SOAP Android" could give it a go and get some benefit.

Add text to textarea - Jquery

That should work. Better if you pass a function to val:

$('#replyBox').val(function(i, text) {
    return text + quote;
});

This way you avoid searching the element and calling val twice.

Bootstrap 3: Text overlay on image

Is this what you're after?

http://jsfiddle.net/dCNXU/1/

I added :text-align:center to the div and image

Conda environments not showing up in Jupyter Notebook

Just run conda install ipykernel in your new environment, only then you will get a kernel with this env. This works even if you have different versions installed in each envs and it doesn't install jupyter notebook again. You can start youe notebook from any env you will be able to see newly added kernels.

Draw a curve with css

@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.

_x000D_
_x000D_
.box {_x000D_
  width: 500px;_x000D_
  height: 100px;_x000D_
  border: solid 5px #000;_x000D_
  border-color: transparent transparent #000 transparent;_x000D_
  border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

JavaScript: Global variables after Ajax requests

AJAX stands for Asynchronous JavaScript and XML. Thus, the post to the server happens out-of-sync with the rest of the function. Try some code like this instead (it just breaks the shorthand $.post out into the longer $.ajax call and adds the async option).

var it_works = false;

$.ajax({
  type: 'POST',
  async: false,
  url: "some_file.php",
  data: "",
  success: function() {it_works = true;}
});

alert(it_works);

Hope this helps!

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

How to execute AngularJS controller function on page load?

angular.element(document).ready(function () {

    // your code here

});

Why is it bad practice to call System.gc()?

Sometimes (not often!) you do truly know more about past, current and future memory usage then the run time does. This does not happen very often, and I would claim never in a web application while normal pages are being served.

Many year ago I work on a report generator, that

  • Had a single thread
  • Read the “report request” from a queue
  • Loaded the data needed for the report from the database
  • Generated the report and emailed it out.
  • Repeated forever, sleeping when there were no outstanding requests.
  • It did not reuse any data between reports and did not do any cashing.

Firstly as it was not real time and the users expected to wait for a report, a delay while the GC run was not an issue, but we needed to produce reports at a rate that was faster than they were requested.

Looking at the above outline of the process, it is clear that.

  • We know there would be very few live objects just after a report had been emailed out, as the next request had not started being processed yet.
  • It is well known that the cost of running a garbage collection cycle is depending on the number of live objects, the amount of garbage has little effect on the cost of a GC run.
  • That when the queue is empty there is nothing better to do then run the GC.

Therefore clearly it was well worth while doing a GC run whenever the request queue was empty; there was no downside to this.

It may be worth doing a GC run after each report is emailed, as we know this is a good time for a GC run. However if the computer had enough ram, better results would be obtained by delaying the GC run.

This behaviour was configured on a per installation bases, for some customers enabling a forced GC after each report greatly speeded up the protection of reports. (I expect this was due to low memory on their server and it running lots of other processes, so hence a well time forced GC reduced paging.)

We never detected an installation that did not benefit was a forced GC run every time the work queue was empty.

But, let be clear, the above is not a common case.

Visual Studio Post Build Event - Copy to Relative Directory Location

Here is what you want to put in the project's Post-build event command line:

copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"

EDIT: Or if your target name is different than the Project Name.

copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

How can I render inline JavaScript with Jade / Pug?

script(nonce="some-nonce").
  console.log("test");

//- Workaround
<script nonce="some-nonce">console.log("test");</script>

How do I restart nginx only after the configuration test was successful on Ubuntu?

alias nginx.start='sudo nginx -c /etc/nginx/nginx.conf'
alias nginx.stop='sudo nginx -s stop'
alias nginx.reload='sudo nginx -s reload'
alias nginx.config='sudo nginx -t'
alias nginx.restart='nginx.config && nginx.stop && nginx.start'
alias nginx.errors='tail -250f /var/logs/nginx.error.log'
alias nginx.access='tail -250f /var/logs/nginx.access.log'
alias nginx.logs.default.access='tail -250f /var/logs/nginx.default.access.log'
alias nginx.logs.default-ssl.access='tail -250f /var/logs/nginx.default.ssl.log'

and then use commands "nginx.reload" etc..

PHP - SSL certificate error: unable to get local issuer certificate

Disclaimer: This code makes your server insecure.

I had the same problem in Mandrill.php file after line number 65 where it says $this->ch = curl_init();

Add following two lines:

curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);

This solved my problem and also sent email using localhost but I suggest to NOT use it on live version live. On your live server the code should work without this code.

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

Something I stumbled upon today for a DLL I knew was working fine with my VS2013 project, but not with VS2015:

Go to: Project -> XXXX Properties -> Build -> Uncheck "Prefer 32-bit"

This answer is way overdue and probably won't do any good, but if you. But I hope this will help somebody someday.

What's the "Content-Length" field in HTTP header?

From this page

The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

Tricks to manage the available memory in an R session

For both speed and memory purposes, when building a large data frame via some complex series of steps, I'll periodically flush it (the in-progress data set being built) to disk, appending to anything that came before, and then restart it. This way the intermediate steps are only working on smallish data frames (which is good as, e.g., rbind slows down considerably with larger objects). The entire data set can be read back in at the end of the process, when all the intermediate objects have been removed.

dfinal <- NULL
first <- TRUE
tempfile <- "dfinal_temp.csv"
for( i in bigloop ) {
    if( !i %% 10000 ) { 
        print( i, "; flushing to disk..." )
        write.table( dfinal, file=tempfile, append=!first, col.names=first )
        first <- FALSE
        dfinal <- NULL   # nuke it
    }

    # ... complex operations here that add data to 'dfinal' data frame  
}
print( "Loop done; flushing to disk and re-reading entire data set..." )
write.table( dfinal, file=tempfile, append=TRUE, col.names=FALSE )
dfinal <- read.table( tempfile )

How to perform a for-each loop over all the files under a specified path?

Use command substitution instead of quotes to execute find instead of passing the command as a string:

for line in $(find . -iname '*.txt'); do 
     echo $line
     ls -l $line; 
done

Trying to use Spring Boot REST to Read JSON String from POST

To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode. The appropriate converter is automatically configured.

    @PostMapping(value="/process")
    public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
        System.out.println(payload);
    }

How to get method parameter names?

Here is something I think will work for what you want, using a decorator.

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

Run it, it will yield the following output:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);

Apply CSS rules to a nested class inside a div

If you need to target multiple classes use:

#main_text .title, #main_text .title2 {
  /* Properties */
}

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

For swift 3.0 and above

public static func getTopViewController() -> UIViewController?{
if var topController = UIApplication.shared.keyWindow?.rootViewController
{
  while (topController.presentedViewController != nil)
  {
    topController = topController.presentedViewController!
  }
  return topController
}
return nil}

Replace multiple strings with multiple other strings

I expanded on @BenMcCormicks a bit. His worked for regular strings but not if I had escaped characters or wildcards. Here's what I did

str = "[curl] 6: blah blah 234433 blah blah";
mapObj = {'\\[curl] *': '', '\\d: *': ''};


function replaceAll (str, mapObj) {

    var arr = Object.keys(mapObj),
        re;

    $.each(arr, function (key, value) {
        re = new RegExp(value, "g");
        str = str.replace(re, function (matched) {
            return mapObj[value];
        });
    });

    return str;

}
replaceAll(str, mapObj)

returns "blah blah 234433 blah blah"

This way it will match the key in the mapObj and not the matched word'

AngularJS is rendering <br> as text not as a newline

You need to either use ng-bind-html-unsafe ... or you need to include the ngSanitize module and use ng-bind-html:

with ng-bind-html-unsafe

Use this if you trust the source of the HTML you're rendering it will render the raw output of whatever you put into it.

<div><h4>Categories</h4><span ng-bind-html-unsafe="q.CATEGORY"></span></div>

OR with ng-bind-html

Use this if you DON'T trust the source of the HTML (i.e. it's user input). It will sanitize the html to make sure it doesn't include things like script tags or other sources of potential security risks.

Make sure you include this:

<script src="http://code.angularjs.org/1.0.4/angular-sanitize.min.js"></script>

Then reference it in your application module:

var app = angular.module('myApp', ['ngSanitize']);

THEN use it:

<div><h4>Categories</h4><span ng-bind-html="q.CATEGORY"></span></div>

How do I Sort a Multidimensional Array in PHP

Here is a php4/php5 class that will sort one or more fields:

// a sorter class
//  php4 and php5 compatible
class Sorter {

  var $sort_fields;
  var $backwards = false;
  var $numeric = false;

  function sort() {
    $args = func_get_args();
    $array = $args[0];
    if (!$array) return array();
    $this->sort_fields = array_slice($args, 1);
    if (!$this->sort_fields) return $array();

    if ($this->numeric) {
      usort($array, array($this, 'numericCompare'));
    } else {
      usort($array, array($this, 'stringCompare'));
    }
    return $array;
  }

  function numericCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      if ($a[$sort_field] == $b[$sort_field]) {
        continue;
      }
      return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
    }
    return 0;
  }

  function stringCompare($a, $b) {
    foreach($this->sort_fields as $sort_field) {
      $cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
      if ($cmp_result == 0) continue;

      return ($this->backwards ? -$cmp_result : $cmp_result);
    }
    return 0;
  }
}

/////////////////////
// usage examples

// some starting data
$start_data = array(
  array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),
  array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),
  array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),
);

// sort by last_name, then first_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort by first_name, then last_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'first_name', 'last_name'));

// sort by last_name, then first_name (backwards)
$sorter = new Sorter();
$sorter->backwards = true;
print_r($sorter->sort($start_data, 'last_name', 'first_name'));

// sort numerically by age
$sorter = new Sorter();
$sorter->numeric = true;
print_r($sorter->sort($start_data, 'age'));

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Maximum call stack size exceeded on npm install

I have overcome this issue by doing following:

  • Delete all the content of the npm dependencies. You can find the default install location according to this thread: https://stackoverflow.com/a/5926706/1850297

  • Before you run npm install command, I suggest to run npm cache clean --force

How to extract code of .apk file which is not working?

step 1:

enter image description hereDownload dex2jar here. Create a java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .

Copy apk file into java project

Run it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files

step 2: Download java decompiler here

How do I convert a pandas Series or index to a Numpy array?

I converted the pandas dataframe to list and then used the basic list.index(). Something like this:

dd = list(zone[0]) #Where zone[0] is some specific column of the table
idx = dd.index(filename[i])

You have you index value as idx.

One line if statement not working

Both the shell and C one-line constructs work (ruby 1.9.3p429):

# Shell format
irb(main):022:0> true && "Yes" || "No"
=> "Yes"
irb(main):023:0> false && "Yes" || "No"
=> "No"

# C format
irb(main):024:0> true ? "Yes" : "No"
=> "Yes"
irb(main):025:0> false ? "Yes" : "No"
=> "No"

How to set a reminder in Android?

Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.

You've got a couple of choices;

  1. Calling the intent to add an event on the calendar
    This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:

    Calendar cal = Calendar.getInstance();              
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", false);
    intent.putExtra("rrule", "FREQ=DAILY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "A Test Event from android app");
    startActivity(intent);
    

    Or the more complicated one:

  2. Get a reference to the calendar with this method
    (It is highly recommended not to use this method, because it could break on newer Android versions):

    private String getCalendarUriBase(Activity act) {
    
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = act.managedQuery(calendars, null, null, null, null);
        } catch (Exception e) {
        }
        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = act.managedQuery(calendars, null, null, null, null);
            } catch (Exception e) {
            }
            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }
        }
        return calendarUriBase;
    }
    

    and add an event and a reminder this way:

    // get calendar
    Calendar cal = Calendar.getInstance();     
    Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
    ContentResolver cr = getContentResolver();
    
    // event insert
    ContentValues values = new ContentValues();
    values.put("calendar_id", 1);
    values.put("title", "Reminder Title");
    values.put("allDay", 0);
    values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
    values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
    values.put("description", "Reminder description");
    values.put("visibility", 0);
    values.put("hasAlarm", 1);
    Uri event = cr.insert(EVENTS_URI, values);
    
    // reminder insert
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
    values = new ContentValues();
    values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
    values.put( "method", 1 );
    values.put( "minutes", 10 );
    cr.insert( REMINDERS_URI, values );
    

    You'll also need to add these permissions to your manifest for this method:

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

Update: ICS Issues

The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.

More infos about this can be found at this blog post.

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

Center Oversized Image in Div

Building on @yunzen's great answer:

I'm guessing many people searching for this topic are trying use a large image as a "hero" background image, for example on a homepage. In this case, they would often want text to appear over the image and to have it scale down well on mobile devices.

Here is the perfect CSS for such a background image (use it on the <img> tag):

/* Set left edge of inner element to 50% of the parent element */
margin-left: 50%;

/* Move to the left by 50% of own width */
transform: translateX(-50%);

/* Scale image...(101% - instead of 100% - avoids possible 1px white border on left of image due to rounding error */
width: 101%;

/* ...but don't scale it too small on mobile devices - adjust this as needed */
min-width: 1086px;

/* allow content below image to appear on top of image */
position: absolute;
z-index: -1;

/* OPTIONAL - try with/without based on your needs */
top: 0;

/* OPTIONAL - use if your outer element containing the img has "text-align: center" */
left: 0;

How can I run multiple curl requests processed sequentially?

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

In react/redux/webpack/babel build fixed this error by removing script tag type text/babel

got error:

<script type="text/babel" src="/js/bundle.js"></script>

no error:

<script src="/js/bundle.js"></script>

How to check if an element does NOT have a specific class?

There are more complex scenarios where this doesn't work. What if you want to select an element with class A that doesn't contain elements with class B. You end up needing something more like:

If parent element does not contain certain child element; jQuery

javascript node.js next()

It's basically like a callback that express.js use after a certain part of the code is executed and done, you can use it to make sure that part of code is done and what you wanna do next thing, but always be mindful you only can do one res.send in your each REST block...

So you can do something like this as a simple next() example:

app.get("/", (req, res, next) => {
  console.log("req:", req, "res:", res);
  res.send(["data": "whatever"]);
  next();
},(req, res) =>
  console.log("it's all done!");
);

It's also very useful when you'd like to have a middleware in your app...

To load the middleware function, call app.use(), specifying the middleware function. For example, the following code loads the myLogger middleware function before the route to the root path (/).

var express = require('express');
var app = express();

var myLogger = function (req, res, next) {
  console.log('LOGGED');
  next();
}

app.use(myLogger);

app.get('/', function (req, res) {
  res.send('Hello World!');
})

app.listen(3000);

Install / upgrade gradle on Mac OS X

I had downloaded it from http://gradle.org/gradle-download/. I use Homebrew, but I missed installing gradle using it.

To save some MBs by downloading it over again using Homebrew, I symlinked the gradle binary from the downloaded (and extracted) zip archive in the /usr/local/bin/. This is the same place where Homebrew symlinks all other binaries.

cd /usr/local/bin/
ln -s ~/Downloads/gradle-2.12/bin/gradle

Now check whether it works or not:

gradle -v

How to rename a file using svn?

It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:

$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory

$ svn status
?       etc/nagios/hosts/us0101/ccs

$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'

$ svn mkdir etc/nagios/hosts/us0101/ccs
A         etc/nagios/hosts/us0101/ccs

$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A         etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D         etc/nagios/hosts/us0101/cs/us0101ccs001.cfg

$ svn status
A       etc/nagios/hosts/us0101/ccs
A  +    etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
        > moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D       etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
        > moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg

GET parameters in the URL with CodeIgniter

"don't you get annoyed by the re-send data requests if ever you press back after a form submission"

you can get around this by doing a redirect from the page that processes your form submission to the success page. the last "action" was the loading of the success page, not the form submission, which means if users do an F5 it will just reload that page and not submit the form again.

Input type number "only numeric value" validation

I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.

Sample use: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>

Directive definition:

import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';

@Directive({
  selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {

  constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }

  /* 
  - Angular doesn't fire "change" events for invalid <input type="number">
  - We have to check the DOM object for browser native invalid state
  - Add custom validator that checks native invalidity
  */
  ngAfterViewInit() {
    var control: FormControl = this.cn.control;

    // Bridge native invalid to ng-invalid via Validators
    const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
    const v_fn = control.validator;

    control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
    setTimeout(()=>control.updateValueAndValidity(), 0);
  }
}

The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.

On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".

I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.

Something like this:

<my-input-number formControlName="num" placeholder="0">

PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).

What are the options for storing hierarchical data in a relational database?

This is a very partial answer to your question, but I hope still useful.

Microsoft SQL Server 2008 implements two features that are extremely useful for managing hierarchical data:

  • the HierarchyId data type.
  • common table expressions, using the with keyword.

Have a look at "Model Your Data Hierarchies With SQL Server 2008" by Kent Tegels on MSDN for starts. See also my own question: Recursive same-table query in SQL Server 2008

Why does this AttributeError in python occur?

This happens because the scipy module doesn't have any attribute named sparse. That attribute only gets defined when you import scipy.sparse.

Submodules don't automatically get imported when you just import scipy; you need to import them explicitly. The same holds for most packages, although a package can choose to import its own submodules if it wants to. (For example, if scipy/__init__.py included a statement import scipy.sparse, then the sparse submodule would be imported whenever you import scipy.)

Convert nullable bool? to bool

System.Convert works fine by me.

using System; ... Bool fixed = Convert.ToBoolean(NullableBool);

Nginx - Customizing 404 page

The "error_page" parameter makes a redirect, converting the request method to "GET", it is not a custom response page.

The easiest solution is

     server{
         root /var/www/html;
         location ~ \.php {
            if (!-f $document_root/$fastcgi_script_name){
                return 404;
            }
            fastcgi_pass   127.0.0.1:9000;
            include fastcgi_params.default;
            fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
        }

By the way, if you want Nginx to process 404 status returned by PHP scripts, you need to add

[fastcgi_intercept_errors][1] on;

E.g.

     location ~ \.php {
            #...
            error_page  404   404.html;
            fastcgi_intercept_errors on;
         }

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

How to get the difference between two arrays of objects in JavaScript

you can do diff a on b and diff b on a, then merge both results

_x000D_
_x000D_
let a = [_x000D_
    { value: "0", display: "Jamsheer" },_x000D_
    { value: "1", display: "Muhammed" },_x000D_
    { value: "2", display: "Ravi" },_x000D_
    { value: "3", display: "Ajmal" },_x000D_
    { value: "4", display: "Ryan" }_x000D_
]_x000D_
_x000D_
let b = [_x000D_
    { value: "0", display: "Jamsheer" },_x000D_
    { value: "1", display: "Muhammed" },_x000D_
    { value: "2", display: "Ravi" },_x000D_
    { value: "3", display: "Ajmal" }_x000D_
]_x000D_
_x000D_
// b diff a_x000D_
let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));_x000D_
_x000D_
// a diff b_x000D_
let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));  _x000D_
_x000D_
// show merge _x000D_
console.log([...resultA, ...resultB]);
_x000D_
_x000D_
_x000D_

Finding the length of an integer in C

C:

Why not just take the base-10 log of the absolute value of the number, round it down, and add one? This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions.

The log10, abs, and floor functions are provided by math.h. For example:

int nDigits = floor(log10(abs(the_integer))) + 1;

You should wrap this in a clause ensuring that the_integer != 0, since log10(0) returns -HUGE_VAL according to man 3 log.

Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign.

Java:

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;

N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.

Add regression line equation and R^2 on graph

Inspired by the equation style provided in this answer, a more generic approach (more than one predictor + latex output as option) can be:

print_equation= function(model, latex= FALSE, ...){
    dots <- list(...)
    cc= model$coefficients
    var_sign= as.character(sign(cc[-1]))%>%gsub("1","",.)%>%gsub("-"," - ",.)
    var_sign[var_sign==""]= ' + '

    f_args_abs= f_args= dots
    f_args$x= cc
    f_args_abs$x= abs(cc)
    cc_= do.call(format, args= f_args)
    cc_abs= do.call(format, args= f_args_abs)
    pred_vars=
        cc_abs%>%
        paste(., x_vars, sep= star)%>%
        paste(var_sign,.)%>%paste(., collapse= "")

    if(latex){
        star= " \\cdot "
        y_var= strsplit(as.character(model$call$formula), "~")[[2]]%>%
            paste0("\\hat{",.,"_{i}}")
        x_vars= names(cc_)[-1]%>%paste0(.,"_{i}")
    }else{
        star= " * "
        y_var= strsplit(as.character(model$call$formula), "~")[[2]]        
        x_vars= names(cc_)[-1]
    }

    equ= paste(y_var,"=",cc_[1],pred_vars)
    if(latex){
        equ= paste0(equ," + \\hat{\\varepsilon_{i}} \\quad where \\quad \\varepsilon \\sim \\mathcal{N}(0,",
                    summary(MetamodelKdifEryth)$sigma,")")%>%paste0("$",.,"$")
    }
    cat(equ)
}

The model argument expects an lm object, the latex argument is a boolean to ask for a simple character or a latex-formated equation, and the ... argument pass its values to the format function.

I also added an option to output it as latex so you can use this function in a rmarkdown like this:


```{r echo=FALSE, results='asis'}
print_equation(model = lm_mod, latex = TRUE)
```

Now using it:

df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$z <- 8 + 3 * df$x + rnorm(100, sd = 40)
lm_mod= lm(y~x+z, data = df)

print_equation(model = lm_mod, latex = FALSE)

This code yields: y = 11.3382963933174 + 2.5893419 * x + 0.1002227 * z

And if we ask for a latex equation, rounding the parameters to 3 digits:

print_equation(model = lm_mod, latex = TRUE, digits= 3)

This yields: latex equation

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

How to access the value of a promise?

When a promise is resolved/rejected, it will call its success/error handler:

var promiseB = promiseA.then(function(result) {
   // do something with result
});

The then method also returns a promise: promiseB, which will be resolved/rejected depending on the return value from the success/error handler from promiseA.

There are three possible values that promiseA's success/error handlers can return that will affect promiseB's outcome:

1. Return nothing --> PromiseB is resolved immediately, 
   and undefined is passed to the success handler of promiseB
2. Return a value --> PromiseB is resolved immediately,
   and the value is passed to the success handler of promiseB
3. Return a promise --> When resolved, promiseB will be resolved. 
   When rejected, promiseB will be rejected. The value passed to
   the promiseB's then handler will be the result of the promise

Armed with this understanding, you can make sense of the following:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

The then call returns promiseB immediately. When promiseA is resolved, it will pass the result to promiseA's success handler. Since the return value is promiseA's result + 1, the success handler is returning a value (option 2 above), so promiseB will resolve immediately, and promiseB's success handler will be passed promiseA's result + 1.

Simplest way to display current month and year like "Aug 2016" in PHP?

Here is a simple and more update format of getting the data:

   $now = new \DateTime('now');
   $month = $now->format('m');
   $year = $now->format('Y');

How to get an isoformat datetime string including the default timezone?

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like

datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString when you need to display the name to the user.

Use name when you need the name for your program itself, e.g. to identify and differentiate between different enum values.

How can I display an image from a file in Jupyter Notebook?

Courtesy of this page, I found this worked when the suggestions above didn't:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

VARCHAR to DECIMAL

Implemented using Custom Function. This will check whether the string value can be converted to Decimal safely

CREATE FUNCTION [dbo].[TryParseAsDecimal]
(
    @Value      NVARCHAR(4000)
    ,@Precision INT
    ,@Scale     INT
)

RETURNS BIT
AS
BEGIN

    IF(ISNUMERIC(@Value) =0) BEGIN
        RETURN CAST(0 AS BIT)
    END
    SELECT @Value = REPLACE(@Value,',','') --Removes the comma

    --This function validates only the first part eg '1234567.8901111111'
    --It validates only the values before the '.' ie '1234567.'
    DECLARE @Index          INT
    DECLARE @Part1Length    INT 
    DECLARE @Part1          VARCHAR(4000)   

    SELECT @Index = CHARINDEX('.', @Value, 0)
    IF (@Index>0) BEGIN
        --If decimal places, extract the left part only and cast it to avoid leading zeros (eg.'0000000001' => '1')
        SELECT @Part1 =LEFT(@Value, @Index-1);
        SELECT @Part1=SUBSTRING(@Part1, PATINDEX('%[^0]%', @Part1+'.'), LEN(@Part1));
        SELECT @Part1Length = LEN(@Part1);
    END
    ELSE BEGIN
        SELECT @Part1 =CAST(@Value AS DECIMAL);
        SELECT @Part1Length= LEN(@Part1)
    END 

    IF (@Part1Length > (@Precision-@Scale)) BEGIN
        RETURN CAST(0 AS BIT)
    END

    RETURN CAST(1 AS BIT)

END

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

Where is the php.ini file on a Linux/CentOS PC?

#php -i | grep php.ini also will work too!

Double precision - decimal places

An IEEE double has 53 significant bits (that's the value of DBL_MANT_DIG in <cfloat>). That's approximately 15.95 decimal digits (log10(253)); the implementation sets DBL_DIG to 15, not 16, because it has to round down. So you have nearly an extra decimal digit of precision (beyond what's implied by DBL_DIG==15) because of that.

The nextafter() function computes the nearest representable number to a given number; it can be used to show just how precise a given number is.

This program:

#include <cstdio>
#include <cfloat>
#include <cmath>

int main() {
    double x = 1.0/7.0;
    printf("FLT_RADIX = %d\n", FLT_RADIX);
    printf("DBL_DIG = %d\n", DBL_DIG);
    printf("DBL_MANT_DIG = %d\n", DBL_MANT_DIG);
    printf("%.17g\n%.17g\n%.17g\n", nextafter(x, 0.0), x, nextafter(x, 1.0));
}

gives me this output on my system:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.14285714285714282
0.14285714285714285
0.14285714285714288

(You can replace %.17g by, say, %.64g to see more digits, none of which are significant.)

As you can see, the last displayed decimal digit changes by 3 with each consecutive value. The fact that the last displayed digit of 1.0/7.0 (5) happens to match the mathematical value is largely coincidental; it was a lucky guess. And the correct rounded digit is 6, not 5. Replacing 1.0/7.0 by 1.0/3.0 gives this output:

FLT_RADIX = 2
DBL_DIG = 15
DBL_MANT_DIG = 53
0.33333333333333326
0.33333333333333331
0.33333333333333337

which shows about 16 decimal digits of precision, as you'd expect.

Clone Object without reference javascript

If you use an = statement to assign a value to a var with an object on the right side, javascript will not copy but reference the object.

You can use lodash's clone method

var obj = {a: 25, b: 50, c: 75};
var A = _.clone(obj);

Or lodash's cloneDeep method if your object has multiple object levels

var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.cloneDeep(obj);

Or lodash's merge method if you mean to extend the source object

var obj = {a: 25, b: {a: 1, b: 2}, c: 75};
var A = _.merge({}, obj, {newkey: "newvalue"});

Or you can use jQuerys extend method:

var obj = {a: 25, b: 50, c: 75};
var A = $.extend(true,{},obj);

Here is jQuery 1.11 extend method's source code :

jQuery.extend = jQuery.fn.extend = function() {
    var src, copyIsArray, copy, name, options, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;

        // skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }

    for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In my case the tensorflow install was looking for cudart64_101.dll

enter image description here

The 101 part of cudart64_101 is the Cuda version - here 101 = 10.1

I had downloaded 11.x, so the version of cudart64 on my system was cudart64_110.dll

enter image description here

This is the wrong file!! cudart64_101.dll ? cudart64_110.dll

Solution

Download Cuda 10.1 from https://developer.nvidia.com/

Install (mine crashes with NSight Visual Studio Integration, so I switched that off)

enter image description here

When the install has finished you should have a Cuda 10.1 folder, and in the bin the dll the system was complaining about being missing

enter image description here

Check that the path to the 10.1 bin folder is registered as a system environmental variable, so it will be checked when loading the library

enter image description here

You may need a reboot if the path is not picked up by the system straight away

enter image description here

JavaScript Infinitely Looping slideshow with delays?

Here:

window.onload = function start() {
    slide();
}
function slide() {
    var num = 0;
    for (num=0;num==10;) {
        setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
        setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
        setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
        setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
    }
}

That makes it keep looping alright! That's why it isn't runnable here.

Check if a number is odd or even in python

Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and operator:

if x & 1:
    return 'odd'
else:
    return 'even'

Using Bitwise AND operator

  • The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.
  • If a number is odd & (bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.

Highest Salary in each department

The below query will display employee name with their respective department name in which that particular employee name is having highest salary.

with T as
(select empname, employee.deptno, salary
from employee
where salary in (select max(salary)
from employee
group by deptno))
select empname, deptname, salary
from T, department
where T.deptno=department.deptno;

I executed the above query successfully on Oracle database.

Getting error "The package appears to be corrupt" while installing apk file

This is weird. I don't know why this was happening with me while generating signed apk but below steps worked for me.

  1. Go to file and select invalidate caches/restarts
  2. After that go to build select clean project
  3. And then select Rebuild project

That's it.

Change multiple files

I'm surprised nobody has mentioned the -exec argument to find, which is intended for this type of use-case, although it will start a process for each matching file name:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} \;

Alternatively, one could use xargs, which will invoke fewer processes:

find . -type f -name 'xa*' | xargs sed -i 's/asd/dsg/g'

Or more simply use the + exec variant instead of ; in find to allow find to provide more than one file per subprocess call:

find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} +

How to change Java version used by TOMCAT?

In Eclipse it is very easy to point Tomcat to a new JVM (in this example JRE6). My problem was I couldn't find where to do it. Here is the trick:

  1. On the ECLIPSE top menu FILE pull down tab, select NEW, -->Other
  2. ...on the New Server: Select A Wizard window, select: Server-> Server... click NEXT
  3. . on the New Server: Define a New Server window, select Apache> Tomcat 7 Server
  4. ..now click the line in blue and underlined entitled: Configure Runtime Environments
  5. on the Server Runtime Environments window,
  6. ..select Apache, expand it(click on the arrow to the left), select TOMCAT v7.0, and click EDIT.
  7. you will see a window called EDIT SERVER RUNTIME ENVIRONMENT: TOMCAT SERVER
  8. On this screen there is a pulldown labeled JREs.
  9. You should find your JRE listed like JRE1.6.0.33. If not use the Installed JRE button.
  10. Select the desired JRE. Click the FINISH button.
  11. Gracefully exit, in the Server: Server Runtime Environments window, click OK
  12. in the New Server: Define a new Server window, hit NEXT
  13. in the New Server: Add and Remove Window, select apps and install them on the server.
  14. in the New Server: Add and Remove Window, click Finish

That's all. Interesting, only steps 7-10 seem to matter, and they will change the JRE used on all servers you have previously defined to use TOMCAT v7.0. The rest of the steps are just because I can't find any other way to get to the screen except by defining a new server. Does anyone else know an easier way?

PHPDoc type hinting for array of objects?

<?php foreach($this->models as /** @var Model_Object_WheelModel */ $model): ?>
    <?php
    // Type hinting now works:
    $model->getImage();
    ?>
<?php endforeach; ?>

How to convert any Object to String?

To convert any object to string there are several methods in Java

String convertedToString = String.valueOf(Object);  //method 1

String convertedToString = "" + Object;   //method 2

String convertedToString = Object.toString();  //method 3

I would prefer the first and third

EDIT
If working in kotlin, the official android language

val number: Int = 12345
String convertAndAppendToString = "number = $number"   //method 1

String convertObjectMemberToString = "number = ${Object.number}" //method 2

String convertedToString = Object.toString()  //method 3

Using JAXB to unmarshal/marshal a List<String>

From a personal blog post, it is not necessary to create a specific JaxbList < T > object.

Assuming an object with a list of strings:

@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}

A JAXB round trip:

public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}

Produces the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

Inputting a default image in case the src attribute of an html <img> is not valid?

This works well for me. Maybe you wanna use JQuery to hook the event.

 <img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">

Updated with jacquargs error guard

Updated: CSS only solution I recently saw Vitaly Friedman demo a great CSS solution I wasn't aware of. The idea is to apply the content property to the broken image. Normally :after or :before do not apply to images, but when they're broken, they're applied.

<img src="nothere.jpg">
<style>
img:before {
    content: ' ';
    display: block;
    position: absolute;
    height: 50px;
    width: 50px;
    background-image: url(ishere.jpg);
</style>

Demo: https://jsfiddle.net/uz2gmh2k/2/

As the fiddle shows, the broken image itself is not removed, but this will probably solve the problem for most cases without any JS nor gobs of CSS. If you need to apply different images in different locations, simply differentiate with a class: .my-special-case img:before { ...

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);
}

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

What exactly is RESTful programming?

REST is an architectural pattern and style of writing distributed applications. It is not a programming style in the narrow sense.

Saying you use the REST style is similar to saying that you built a house in a particular style: for example Tudor or Victorian. Both REST as an software style and Tudor or Victorian as a home style can be defined by the qualities and constraints that make them up. For example REST must have Client Server separation where messages are self-describing. Tudor style homes have Overlapping gables and Roofs that are steeply pitched with front facing gables. You can read Roy's dissertation to learn more about the constraints and qualities that make up REST.

REST unlike home styles has had a tough time being consistently and practically applied. This may have been intentional. Leaving its actual implementation up to the designer. So you are free to do what you want so as long as you meet the constraints set out in the dissertation you are creating REST Systems.

Bonus:

The entire web is based on REST (or REST was based on the web). Therefore as a web developer you might want aware of that although it's not necessary to write good web apps.

How to read integer values from text file

I would use nearly the same way but with list as buffer for read integers:

static Object[] readFile(String fileName) {
    Scanner scanner = new Scanner(new File(fileName));
    List<Integer> tall = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
        tall.add(scanner.nextInt());
    }

    return tall.toArray();
}

Moment.js with ReactJS (ES6)

So, I had to format this Epoch Timestamp date format to a legit date format in my ReactJS project. I did the following:

  1. import moment from 'moment' -- given you have moment js installed via NPM, if not head to this link

  2. For Example :

    If I have an Epoch date timestamp like 1595314414299, then I try this in a console to see the result -

_x000D_
_x000D_
  var dateInEpochTS = 1595314414299
  var now = moment(dateInEpochTS).format('MMM DD YYYY h:mm A');
  var now2 = moment(dateInEpochTS).format('dddd, MMMM Do, YYYY h:mm:ss A');
  console.log("NOW");
  console.log(now);
  console.log("NOW2");
  console.log(now2);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

Expected Output

"NOW"
"Jul 21 2020 12:23 PM"
"NOW2"
"Tuesday, July 21st, 2020 12:23:34 PM"

sudo echo "something" >> /etc/privilegedFile doesn't work

Can you change the ownership of the file then change it back after using cat >> to append?

sudo chown youruser /etc/hosts  
sudo cat /downloaded/hostsadditions >> /etc/hosts  
sudo chown root /etc/hosts  

Something like this work for you?

Live search through table rows

I'm not sure how efficient this is but this works:

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index != 0) {

            $row = $(this);

            var id = $row.find("td:first").text();

            if (id.indexOf(value) != 0) {
                $(this).hide();
            }
            else {
                $(this).show();
            }
        }
    });
});?

DEMO - Live search on table


I did add some simplistic highlighting logic which you or future users might find handy.

One of the ways to add some basic highlighting is to wrap em tags around the matched text and using CSS apply a yellow background to the matched text i.e: (em{ background-color: yellow }), similar to this:

// removes highlighting by replacing each em tag within the specified elements with it's content
function removeHighlighting(highlightedElements){
    highlightedElements.each(function(){
        var element = $(this);
        element.replaceWith(element.html());
    })
}

// add highlighting by wrapping the matched text into an em tag, replacing the current elements, html value with it
function addHighlighting(element, textToHighlight){
    var text = element.text();
    var highlightedText = '<em>' + textToHighlight + '</em>';
    var newText = text.replace(textToHighlight, highlightedText);
    
    element.html(newText);
}

$("#search").on("keyup", function() {
    var value = $(this).val();
    
    // remove all highlighted text passing all em tags
    removeHighlighting($("table tr em"));

    $("table tr").each(function(index) {
        if (index !== 0) {
            $row = $(this);
            
            var $tdElement = $row.find("td:first");
            var id = $tdElement.text();
            var matchedIndex = id.indexOf(value);
            
            if (matchedIndex != 0) {
                $row.hide();
            }
            else {
                //highlight matching text, passing element and matched text
                addHighlighting($tdElement, value);
                $row.show();
            }
        }
    });
});

Demo - applying some simple highlighting


How to execute XPath one-liners from shell?

Here's one xmlstarlet use case to extract data from nested elements elem1, elem2 to one line of text from this type of XML (also showing how to handle namespaces):

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<mydoctype xmlns="http://xml-namespace-uri" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xml-namespace-uri http://xsd-uri" format="20171221A" date="2018-05-15">

  <elem1 time="0.586" length="10.586">
      <elem2 value="cue-in" type="outro" />
  </elem1>

</mydoctype>

The output will be

0.586 10.586 cue-in outro

In this snippet, -m matches the nested elem2, -v outputs attribute values (with expressions and relative addressing), -o literal text, -n adds a newline:

xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2' \
 -v ../@time -o " " -v '../@time + ../@length' -o " " -v @value -o " " -v @type -n file.xml

If more attributes are needed from elem1, one can do it like this (also showing the concat() function):

xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2/..' \
 -v 'concat(@time, " ", @time + @length, " ", ns:elem2/@value, " ", ns:elem2/@type)' -n file.xml

Note the (IMO unnecessary) complication with namespaces (ns, declared with -N), that had me almost giving up on xpath and xmlstarlet, and writing a quick ad-hoc converter.

Modifying location.hash without page scrolling

Okay, this is a rather old topic but I thought I'd chip in as the 'correct' answer doesn't work well with CSS.

This solution basically prevents the click event from moving the page so we can get the scroll position first. Then we manually add the hash and the browser automatically triggers a hashchange event. We capture the hashchange event and scroll back to the correct position. A callback separates and prevents your code causing a delay by keeping your hash hacking in one place.

var hashThis = function( $elem, callback ){
    var scrollLocation;
    $( $elem ).on( "click", function( event ){
        event.preventDefault();
        scrollLocation = $( window ).scrollTop();
        window.location.hash = $( event.target ).attr('href').substr(1);
    });
    $( window ).on( "hashchange", function( event ){
        $( window ).scrollTop( scrollLocation );
        if( typeof callback === "function" ){
            callback();
        }
    });
}
hashThis( $( ".myAnchor" ), function(){
    // do something useful!
});

Official reasons for "Software caused connection abort: socket write error"

This error can occur when the local network system aborts a connection, such as when WinSock closes an established connection after data retransmission fails (receiver never acknowledges data sent on a datastream socket).

See this MSDN article. See also Some information about 'Software caused connection abort'.

TypeError: module.__init__() takes at most 2 arguments (3 given)

from Object import Object

or

From Class_Name import Class_name

If Object is a .py file.

Bootstrap 3 Flush footer to bottom. not fixed

For Bootstrap:

<div class="navbar-fixed-bottom row-fluid">
  <div class="navbar-inner">
    <div class="container">
      Text
    </div>
  </div>
</div>

C# Generics and Type Checking

The typeof operator...

typeof(T)

... won't work with the c# switch statement. But how about this? The following post contains a static class...

Is there a better alternative than this to 'switch on type'?

...that will let you write code like this:

TypeSwitch.Do(
    sender,
    TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
    TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
    TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));

SQL Server JOIN missing NULL values

Try using additional condition in join:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 
INNER JOIN Table2
ON (Table1.Col1 = Table2.Col1 
    OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
   )

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

How to clean up R memory (without the need to restart my PC)?

memory.size(max=T) # gives the amount of memory obtained by the OS
[1] 1800
memory.size(max=F) # gives the amount of memory being used
[1] 261.17

Using Paul's example,

m = matrix(runif(10e7), 10000, 1000)

Now

memory.size(max=F)
[1] 1024.18

To clear up the memory

gc()
memory.size(max=F)
[1] 184.86

In other words, the memory should now be clear again. If you loop a code, it is a good idea to add a gc() as the last line of your loop, so that the memory is cleared up before starting the next iteration.

getting the error: expected identifier or ‘(’ before ‘{’ token

{
int main(void);

should be

int main(void)
{

Then I let you fix the next compilation errors of your program...

Turn off warnings and errors on PHP and MySQL

Always show errors on a testing server. Never show errors on a production server.

Write a script to determine whether the page is on a local, testing, or live server, and set $state to "local", "testing", or "live". Then:

if( $state == "local" || $state == "testing" )
{
    ini_set( "display_errors", "1" );
    error_reporting( E_ALL & ~E_NOTICE );
}
else
{
    error_reporting( 0 );
}

Is there any difference between a GUID and a UUID?

One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.

The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input. - rfc4122#section-3

How do I download a file using VBA (without Internet Explorer)

A modified version of above solution to make it more dynamic.

Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
    On Error GoTo Failed
    DownloadFileA = False
    'As directory must exist, this is a check
    If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
    Dim returnValue As Long
    returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
    'If return value is 0 and the file exist, then it is considered as downloaded correctly
    DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
    Exit Function

Failed:
End Function

Change EditText hint color when using TextInputLayout

android:textColorHint="#FFFFFF" sometime works and sometime doesnt. For me below solution works perfectly

Try The Below Code It Works In your XML file and TextLabel theme is defined in style.xml

 <android.support.design.widget.TextInputLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:theme="@style/MyTextLabel">

     <EditText
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:hint="Floating Label"
         android:id="@+id/edtText"/>

 </android.support.design.widget.TextInputLayout>

In Styles Folder TextLabel Code

 <style name="MyTextLabel" parent="TextAppearance.AppCompat">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">@color/Color Name</item> 
<!--The size of the text appear on label in false state -->
    <item name="android:textSize">20sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">@color/Color Name</item>
    <item name="colorControlNormal">@color/Color Name</item>
    <item name="colorControlActivated">@color/Color Name</item>
 </style>

If you just want to change the color of label in false state then colorAccent , colorControlNormal and colorControlActivated are not required

Where does R store packages?

You do not want the '='

Use .libPaths("C:/R/library") in you Rprofile.site file

And make sure you have correct " symbol (Shift-2)

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

Mockito verify order / sequence of method calls

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}
}

public class Bar {
  public void firstThenSecond(Foo foo) {
    foo.first();
    foo.second();
  }
}

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  @Test
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);
    bar.firstThenSecond(mockFoo);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS
    orderVerifier.verify(mockFoo).first();
    orderVerifier.verify(mockFoo).second();

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();
  }
}

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE allitems
CHANGE itemid itemid INT(10) AUTO_INCREMENT;

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

What's the difference between "git reset" and "git checkout"?

The key difference in a nutshell is that reset moves the current branch reference, while checkout does not (it moves HEAD).

As the Pro Git book explains under Reset Demystified,

The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does); reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch (i.e. you’re currently on the master branch), running git reset 9e5e6a4 will start by making master point to 9e5e6a4. [emphasis added]

See also VonC's answer for a very helpful text and diagram excerpt from the same article, which I won't duplicate here.

Of course there are a lot more details about what effects checkout and reset can have on the index and the working tree, depending on what parameters are used. There can be lots of similarities and differences between the two commands. But as I see it, the most crucial difference is whether they move the tip of the current branch.

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

Rotating videos with FFmpeg

An additional solution with a different approach from the last mentioned solutions, is to check if your camera driver support the v4l2 camera controls (which is very common).
In the terminal just type:

v4l2-ctl -L

If your camera driver supports the v4l2 camera controls, you should get something like this (the list below depends on the controls that your camera driver supports):

               contrast (int)    : min=0 max=255 step=1 default=0 value=0 flags=slider
             saturation (int)    : min=0 max=255 step=1 default=64 value=64 flags=slider
                    hue (int)    : min=0 max=359 step=1 default=0 value=0 flags=slider
white_balance_automatic (bool)   : default=1 value=1 flags=update
            red_balance (int)    : min=0 max=4095 step=1 default=0 value=128 flags=inactive, slider
           blue_balance (int)    : min=0 max=4095 step=1 default=0 value=128 flags=inactive, slider
               exposure (int)    : min=0 max=65535 step=1 default=0 value=885 flags=inactive, volatile
         gain_automatic (bool)   : default=1 value=1 flags=update
                   gain (int)    : min=0 max=1023 step=1 default=0 value=32 flags=inactive, volatile
        horizontal_flip (bool)   : default=0 value=0
          vertical_flip (bool)   : default=0 value=0

And if you are lucky it supports horizontal_flip and vertical_flip.
Then all you need to do is to set the horizontal_flip by:

v4l2-ctl --set-ctrl horizontal_flip=1

or the vertical_flip by:

v4l2-ctl --set-ctrl vertical_flip=1

and then you can call your video device to capture a new video (see example below), and the video will be rotated/flipped.

ffmpeg -f v4l2 -video_size 640x480 -i /dev/video0 -vcodec libx264 -f mpegts input.mp4

Of-course that if you need to process an already existing video, than this method is not the solution you are looking for.

The advantage in this approach is that we flip the image in the sensor level, so the sensor of the driver already gives us the image flipped, and that's saves the application (like FFmpeg) any further and unnecessary processing.

How to move the layout up when the soft keyboard is shown android

only

android:windowSoftInputMode="adjustResize"

in your activity tag inside Manifest file will do the trick

MSVCP140.dll missing

Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.

In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation on runtime library choose /MTd for debug mode and /MT for release mode.

This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.

Save PL/pgSQL output from PostgreSQL to a CSV file

Do you want the resulting file on the server, or on the client?

Server side

If you want something easy to re-use or automate, you can use Postgresql's built in COPY command. e.g.

Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',' HEADER;

This approach runs entirely on the remote server - it can't write to your local PC. It also needs to be run as a Postgres "superuser" (normally called "root") because Postgres can't stop it doing nasty things with that machine's local filesystem.

That doesn't actually mean you have to be connected as a superuser (automating that would be a security risk of a different kind), because you can use the SECURITY DEFINER option to CREATE FUNCTION to make a function which runs as though you were a superuser.

The crucial part is that your function is there to perform additional checks, not just by-pass the security - so you could write a function which exports the exact data you need, or you could write something which can accept various options as long as they meet a strict whitelist. You need to check two things:

  1. Which files should the user be allowed to read/write on disk? This might be a particular directory, for instance, and the filename might have to have a suitable prefix or extension.
  2. Which tables should the user be able to read/write in the database? This would normally be defined by GRANTs in the database, but the function is now running as a superuser, so tables which would normally be "out of bounds" will be fully accessible. You probably don’t want to let someone invoke your function and add rows on the end of your “users” table…

I've written a blog post expanding on this approach, including some examples of functions that export (or import) files and tables meeting strict conditions.


Client side

The other approach is to do the file handling on the client side, i.e. in your application or script. The Postgres server doesn't need to know what file you're copying to, it just spits out the data and the client puts it somewhere.

The underlying syntax for this is the COPY TO STDOUT command, and graphical tools like pgAdmin will wrap it for you in a nice dialog.

The psql command-line client has a special "meta-command" called \copy, which takes all the same options as the "real" COPY, but is run inside the client:

\copy (Select * From foo) To '/tmp/test.csv' With CSV

Note that there is no terminating ;, because meta-commands are terminated by newline, unlike SQL commands.

From the docs:

Do not confuse COPY with the psql instruction \copy. \copy invokes COPY FROM STDIN or COPY TO STDOUT, and then fetches/stores the data in a file accessible to the psql client. Thus, file accessibility and access rights depend on the client rather than the server when \copy is used.

Your application programming language may also have support for pushing or fetching the data, but you cannot generally use COPY FROM STDIN/TO STDOUT within a standard SQL statement, because there is no way of connecting the input/output stream. PHP's PostgreSQL handler (not PDO) includes very basic pg_copy_from and pg_copy_to functions which copy to/from a PHP array, which may not be efficient for large data sets.