Programs & Examples On #Microkernel

Microkernel is a highly limited kernel that usually only supports address space management, thread management and inter-process communication when other parts of the OS run in userspace.

Could not load type from assembly error

You might be able to resolve this with binding redirects in *.config. http://blogs.msdn.com/b/dougste/archive/2006/09/05/741329.aspx has a good discussion around using older .net components in newer frameworks. http://msdn.microsoft.com/en-us/library/eftw1fys(vs.71).aspx

Cannot find module '@angular/compiler'

Try this

  1. npm uninstall angular-cli
  2. npm install @angular/cli --save-dev

Oracle Error ORA-06512

ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).

In a comment you said

"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"

Well, your code does this:

IF ((pNum < 12) OR (pNum > 14)) THEN     
    RAISE vSOME_EX;

That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?

ORA-06510: PL/SQL: unhandled user-defined exception

If so, all you need to do is add an exception block to handle the error. Perhaps:

PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
    vSOME_EX EXCEPTION;

BEGIN 
    IF ((pNum < 12) OR (pNum > 14)) THEN     
        RAISE vSOME_EX;
    ELSE  
        EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
    END IF;
exception
    when vsome_ex then
         raise_application_error(-20000
                                 , 'This is not a valid table:  M'||pNum||'GR');

END PX;

The documentation covers handling PL/SQL exceptions in depth.

Regex match one of two words

This will do:

/^(apple|banana)$/

to exclude from captured strings (e.g. $1,$2):

(?:apple|banana)

CSS3 Box Shadow on Top, Left, and Right Only

The following code did it for me to make a shadow inset of the right side:

-moz-box-shadow: inset -10px 0px 10px -10px #000;
-webkit-box-shadow: inset -10px 0px 10px -10px #000;
box-shadow: inset -10px 0px 10px -10px #000;

Hope it will help!!!!

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

You might want to use the standard template library. It might be slower than the above mentioned code. However, it seems to me clearer and easier to understand.

 #include<bitset>
 #include<iostream>


 template<size_t N>
 const std::bitset<N> reverse(const std::bitset<N>& ordered)
 {
      std::bitset<N> reversed;
      for(size_t i = 0, j = N - 1; i < N; ++i, --j)
           reversed[j] = ordered[i];
      return reversed;
 };


 // test the function
 int main()
 {
      unsigned long num; 
      const size_t N = sizeof(num)*8;

      std::cin >> num;
      std::cout << std::showbase << std::hex;
      std::cout << "ordered  = " << num << std::endl;
      std::cout << "reversed = " << reverse<N>(num).to_ulong()  << std::endl;
      std::cout << "double_reversed = " << reverse<N>(reverse<N>(num)).to_ulong() << std::endl;  
 }

phpMyAdmin on MySQL 8.0

To fix this issue I just run one query in my mysql console.

For this login to mysql console using this

mysql -u {username} -p{password}

After this I just run one query as given below:-

ALTER user '{USERNAME}'@'localhost' identified with mysql_native_password by '{PASSWORD}';

when I run this query I got message that query executed. Then login to PHPMYADMIN with username/password.

How does autowiring work in Spring?

Keep in mind that you must enable the @Autowired annotation by adding element <context:annotation-config/> into the spring configuration file. This will register the AutowiredAnnotationBeanPostProcessor which takes care the processing of annotation.

And then you can autowire your service by using the field injection method.

public class YourController{

 @Autowired
 private UserService userService; 

}

I found this from the post Spring @autowired annotation

How to activate an Anaconda environment

I've tried to activate env from Jenkins job (in bash) with conda activate base and it failed, so after many tries, this one worked for me (CentOS 7) :

source /opt/anaconda2/bin/activate base

How can I share Jupyter notebooks with non-programmers?

A great way of doing this on WordPress consists of the following steps:

Step 1: Open your Jupyter notebook in a text editor and copy the content which may look like so: Your .ipynb file may look like this when opened in a text editor

Step 2: Ctrl + A and Ctrl + C this content. Then Ctrl + V this to a GitHub Gist that you should create.

Step 3: Create a public gist and embed the gist like you always embed gists on WordPress, viz., go to the HTML editor and add like so:

[gist gist_url]

I have actually implemented this on my blog. You can find the post here

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Converting NSData to NSString in Objective c

in objective C:

NSData *tmpData;
NSString *tmpString = [NSString stringWithFormat:@"%@", tmpData];
NSLog(tmpString)

Error in model.frame.default: variable lengths differ

Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.

Remove NAs

df2<-df1[complete.cases(df1),]

Run the main model

model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)

Obtain residuals

resid2 <- residuals(model2,type="deviance")

Update model2 by including the lag 1 residuals

model2_1 <- update(model2,.~.+ Lag(resid2,1),  na.action=na.omit)

Mongoose's find method with $or condition does not work properly

I implore everyone to use Mongoose's query builder language and promises instead of callbacks:

User.find().or([{ name: param }, { nickname: param }])
    .then(users => { /*logic here*/ })
    .catch(error => { /*error logic here*/ })

Read more about Mongoose Queries.

Resizing an iframe based on content

This is slightly tricky as you have to know when the iframe page has loaded, which is difficuly when you're not in control of its content. Its possible to add an onload handler to the iframe, but I've tried this in the past and it has vastly different behaviour across browsers (not guess who's the most annoying...). You'd probably have to add a function to the iframe page that performs the resize and inject some script into the content that either listens to load events or resize events, which then calls the previous function. I'm thinking add a function to the page since you want to make sure its secure, but I have no idea how easy it will be to do.

Remove insignificant trailing zeros from a number?

If you cannot use Floats for any reason (like money-floats involved) and are already starting from a string representing a correct number, you could find this solution handy. It converts a string representing a number to a string representing number w/out trailing zeroes.

function removeTrailingZeroes( strAmount ) {
    // remove all trailing zeroes in the decimal part
    var strDecSepCd = '.'; // decimal separator
    var iDSPosition = strAmount.indexOf( strDecSepCd ); // decimal separator positions
    if ( iDSPosition !== -1 ) {
        var strDecPart = strAmount.substr( iDSPosition ); // including the decimal separator

        var i = strDecPart.length - 1;
        for ( ; i >= 0 ; i-- ) {
            if ( strDecPart.charAt(i) !== '0') {
                break;
            }
        }

        if ( i=== 0 ) {
            return strAmount.substring(0, iDSPosition);
        } else {
            // return INTPART and DS + DECPART including the rightmost significant number
            return strAmount.substring(0, iDSPosition) + strDecPart.substring(0,i + 1);
        }
    }

    return strAmount;
}

How to apply two CSS classes to a single element

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

Why is __dirname not defined in node REPL?

Seems like you could also do this:

__dirname=fs.realpathSync('.');

of course, dont forget fs=require('fs')

(it's not really global in node scripts exactly, its just defined on the module level)

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Very simple :

In your Super POM parent or setting.xml, use

        <repository>
        <id>central</id>
        <releases>
            <updatePolicy>never</updatePolicy>
        </releases>
        <snapshots>
            <updatePolicy>never</updatePolicy>
        </snapshots>
        <url>http://repo1.maven.org/maven2</url>
        <layout>legacy</layout>
    </repository>

It's my tips

What's default HTML/CSS link color?

For me, on Chrome (updated June 2018) the color for an unvisited link is #2779F6. You can always get this by zooming in really close, taking a screenshot, and visiting a website like html-color-codes.info that will convert a screenshot to a color code.

Android EditText for password with android:hint

I had the same issue and found a solution :

Previous code:

    <EditText 
    android:layout_height="wrap_content"
    android:gravity="center" 
    android:inputType ="password" 
    android:layout_width="fill_parent"
    android:id="@+id/password" 
    android:hint="password" 
    android:maxLines="1">
    </EditText>

Solution:

<EditText 
android:layout_height="wrap_content"
android:gravity="center" 
android:password="true" 
android:layout_width="fill_parent"
android:id="@+id/password" 
android:hint="password" 
android:maxLines="1">
</EditText>

The previous code does not show the 'hint', but when I changed it to the last one it started showing...

hope this be helpful to someone...

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

Javascript onload not working

Try this one:

<body onload="imageRefreshBig();">

Also you might want to check Javascript console for errors (in Chrome it's under Shift + Ctrl + J).

Java Long primitive type maximum limit

It will overflow and wrap around to Long.MIN_VALUE.

Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.

How to get the indexpath.row when an element is activated?

Very Simple getting Index Path swift 4, 5

let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: "buttonTapped:", forControlEvents: 
UIControlEvents.TouchUpInside)

How to get IndexPath Inside Btn Click :

func buttonTapped(_ sender: UIButton) {
     print(sender.tag)  
}

What is the difference between XAMPP or WAMP Server & IIS?

WAMP stands for Windows,Apache,Mysql,Php

XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)

Advantages of XAMPP:

  • It is cross-platform software

  • It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.

  • it is easy to configure and use.

Advantages of WAMP:

  • It is easy to Use. (Changing Configuration)

  • WAMP is Available for both 64 bit and 32-bit system.

if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.

i suggest using laragon :

Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.

Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.

Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.

Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.

Advantages of Laragon:

  • Pretty URLs
    Use app.test instead of localhost/app.

  • Portable
    You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.

  • Isolated
    Laragon has an isolated environment with your OS - it will keep your system clean.

  • Easy Operation

    Unlike others which pre-config for you, Laragon auto-configsall the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.

  • Modern & Powerful
    Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed. Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.

Converting Long to Date in Java returns 1970

Try this with adjusting the date format.

long longtime = 1212580300;
SimpleDateFormat dateFormat = new SimpleDateFormat("MMddyyHHmm");
Date date = (Date) dateFormat.parseObject(longtime + "");
System.out.println(date);

Note: Check for 24 hours or 12 hours cycle.

An existing connection was forcibly closed by the remote host - WCF

I just had this error now in server only and the solution was to set a maxItemsInObjectGraph attribute in wcf web.config under <behavior> tag:

<dataContractSerializer maxItemsInObjectGraph="2147483646"/>

PyCharm import external library

In order to reference an external library in a project File -> Settings -> Project -> Project structure -> select the folder and mark as a source

How to take input in an array + PYTHON?

You want this - enter N and then take N number of elements.I am considering your input case is just like this

5
2 3 6 6 5

have this in this way in python 3.x (for python 2.x use raw_input() instead if input())

Python 3

n = int(input())
arr = input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Python 2

n = int(raw_input())
arr = raw_input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

How to stop the Timer in android?

I had a similar problem: every time I push a particular button, I create a new Timer.

my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}

Exiting from that activity I deleted the timer:

if(my_timer!=null){
my_timer.cancel();
my_timer = null;
}

But it was not enough because the cancel() method only canceled the latest Timer. The older ones were ignored an didn't stop running. The purge() method was not useful for me. I solved the problem just checking the Timer instantiation:

if(my_timer == null){
my_timer = new Timer("MY_TIMER");
my_timer.schedule(new TimerTask() {
...
}
}

Why use Ruby's attr_accessor, attr_reader and attr_writer?

All of the answers above are correct; attr_reader and attr_writer are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

I get the same error when I run Oracle XE instance on the same machine. As my database is Oracle, I preferred changing Glassfish's default port:

  1. Locate domain.xml inside Glassfish installation folders.
  2. Change the the port on the below line:

_x000D_
_x000D_
  <network-listener port="9090" protocol="http-listener-1" transport="tcp" name="http-listener-1" thread-pool="http-thread-pool"></network-listener>_x000D_
        
_x000D_
_x000D_
_x000D_

ls command: how can I get a recursive full-path listing, one line per file?

Recursive list of all files from current location:

ls -l $(find . -type f)

Google Geocoding API - REQUEST_DENIED

If none of given solutions fixed the error, the issue probably about Google Cloud Billing settings. You must enable Billing on the Google Cloud Project at billing/enable.

Learn more

{
    "error_message" : "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started",
    "results" : [],
    "status" : "REQUEST_DENIED"
}

How do I center text vertically and horizontally in Flutter?

Put the Text in a Center:

Container(
      height: 45,
      color: Colors.black,
      child: Center(
        child: Text(
            'test',
            style: TextStyle(color: Colors.white),
        ),
      ),
    );

Read input numbers separated by spaces

By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:

do {
   cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
   cin >> num;

   // reset your variables

   // your function stuff (calculations)
}
while (true); // or some condition

How to draw a standard normal distribution in R

I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code

x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)

I'm sure you can work the rest out yourself, for the title you might want to look for something called main= and y-axis labels are also up to you.

If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, ) section? Finally, if you want to know more about what dnorm is doing I suggest you look here

When should I use git pull --rebase?

I think you should use git pull --rebase when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.

As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.

This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.

(*) While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase either, which is what the question is about ;)

How to get root view controller?

if you are trying to access the rootViewController you set in your appDelegate. try this:

Objective-C

YourViewController *rootController = (YourViewController*)[[(YourAppDelegate*)
                                   [[UIApplication sharedApplication]delegate] window] rootViewController];

Swift

let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController

Swift 3

let appDelegate  = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! YourViewController

Swift 4 & 4.2

let viewController = UIApplication.shared.keyWindow!.rootViewController as! YourViewController

Swift 5 & 5.1 & 5.2

let viewController = UIApplication.shared.windows.first!.rootViewController as! YourViewController

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

The solution to this problem is very simple. Double click on your tomcat server. It will open the server configuration. Under server options check ‘Publish module contents to separate XML files’ checkbox. Restart your server. This time your page will come without any issues.

GROUP BY having MAX date

Fast and easy with HAVING:

SELECT * FROM tblpm n 
FROM tblpm GROUP BY control_number 
HAVING date_updated=MAX(date_updated);

In the context of HAVING, MAX finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated). If there's a tie for latest within a group, both will pass the HAVING filter, but GROUP BY means that only one will appear in the returned table.

add commas to a number in jQuery

I'm guessing that you're doing some sort of localization, so have a look at this script.

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

Running Node.Js on Android

the tutorial of how to build NodeJS for Android https://github.com/dna2github/dna2oslab/tree/master/android/build
there are several versions v0.12, v4, v6, v7

It is easy to run compiled binary on Android; for example run compiled Nginx: https://github.com/dna2github/dna2mtgol/tree/master/fileShare

You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.

java: use StringBuilder to insert at the beginning

As an alternative solution you can use a LIFO structure (like a stack) to store all the strings and when you are done just take them all out and put them into the StringBuilder. It naturally reverses the order of the items (strings) placed in it.

Stack<String> textStack = new Stack<String>();
// push the strings to the stack
while(!isReadingTextDone()) {
    String text = readText();
    textStack.push(text);
}
// pop the strings and add to the text builder
String builder = new StringBuilder(); 
while (!textStack.empty()) {
      builder.append(textStack.pop());
}
// get the final string
String finalText =  builder.toString();

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file /usr/share/phpmyadmin/libraries/sql.lib.php using this command:

sudo nano +613 /usr/share/phpmyadmin/libraries/sql.lib.php

On line 613 the count function always evaluates to true since there is no closing parenthesis after $analyzed_sql_results['select_expr']. Making the below replacements resolves this, then you will need to delete the last closing parenthesis on line 614, as it's now an extra parenthesis.

Replace:

((empty($analyzed_sql_results['select_expr']))
    || (count($analyzed_sql_results['select_expr'] == 1)
        && ($analyzed_sql_results['select_expr'][0] == '*')))

With:

((empty($analyzed_sql_results['select_expr']))
    || (count($analyzed_sql_results['select_expr']) == 1)
        && ($analyzed_sql_results['select_expr'][0] == '*'))

Restart the server apache:

sudo service apache2 restart

Copy or rsync command

For a local copy, the only advantage of rsync is that it will avoid copying if the file already exists in the destination directory. The definition of "already exists" is (a) same file name (b) same size (c) same timestamp. (Maybe same owner/group; I am not sure...)

The "rsync algorithm" is great for incremental updates of a file over a slow network link, but it will not buy you much for a local copy, as it needs to read the existing (partial) file to run it's "diff" computation.

So if you are running this sort of command frequently, and the set of changed files is small relative to the total number of files, you should find that rsync is faster than cp. (Also rsync has a --delete option that you might find useful.)

jQuery bind/unbind 'scroll' event on $(window)

try this:

$(window).unbind('scroll');

it works in my project

How to set zoom level in google map

Your code below is zooming the map to fit the specified bounds:

addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);

If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  bounds.extend(pt);
}

If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.

If you will only ever have one marker, don't use fitBounds. Call setCenter, setZoom with the marker position and your desired zoom level.

function addMarker(lat, lng, info) {
  var pt = new google.maps.LatLng(lat, lng);
  map.setCenter(pt);
  map.setZoom(your desired zoom);
}

_x000D_
_x000D_
html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
_x000D_
<html>

<head>
  <script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
  <script type="text/javascript">
    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
    var center = null;
    var map = null;
    var currentPopup;
    var bounds = new google.maps.LatLngBounds();

    function addMarker(lat, lng, info) {
      var pt = new google.maps.LatLng(lat, lng);
      map.setCenter(pt);
      map.setZoom(5);
      var marker = new google.maps.Marker({
        position: pt,
        icon: icon,
        map: map
      });
      var popup = new google.maps.InfoWindow({
        content: info,
        maxWidth: 300
      });
      google.maps.event.addListener(marker, "click", function() {
        if (currentPopup != null) {
          currentPopup.close();
          currentPopup = null;
        }
        popup.open(map, marker);
        currentPopup = popup;
      });
      google.maps.event.addListener(popup, "closeclick", function() {
        map.panTo(center);
        currentPopup = null;
      });
    }

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(0, 0),
        zoom: 1,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
        },
        navigationControl: true,
        navigationControlOptions: {
          style: google.maps.NavigationControlStyle.SMALL
        }
      });
      addMarker(27.703402, 85.311668, 'New Road');
      // center = bounds.getCenter();
      // map.fitBounds(bounds);

    }
  </script>
</head>

<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
  <div id="map"></div>
</body>

</html>
_x000D_
_x000D_
_x000D_

How do you install Boost on MacOS?

Fink appears to have a full set of Boost packages...

With fink installed and running just do

fink install boost1.35.nopython

at the terminal and accept the dependencies it insists on. Or use

fink list boost

to get a list of different packages that are availible.

Non greedy (reluctant) regex matching in sed?

Simulating lazy (un-greedy) quantifier in sed

And all other regex flavors!

  1. Finding first occurrence of an expression:

    • POSIX ERE (using -r option)

      Regex:

        (EXPRESSION).*|.
      

      Sed:

        sed -r ?'s/(EXPRESSION).*|./\1/g' # Global `g` modifier should be on
      

      Example (finding first sequence of digits) Live demo:

        $ sed -r 's/([0-9]+).*|./\1/g' <<< 'foo 12 bar 34'
      
        12
      

      How does it work?

      This regex benefits from an alternation |. At each position engine tries to pick the longest match (this is a POSIX standard which is followed by couple of other engines as well) which means it goes with . until a match is found for ([0-9]+).*. But order is important too.

      enter image description here

      Since global flag is set, engine tries to continue matching character by character up to the end of input string or our target. As soon as the first and only capturing group of left side of alternation is matched (EXPRESSION) rest of line is consumed immediately as well .*. We now hold our value in the first capturing group.

    • POSIX BRE

      Regex:

        \(\(\(EXPRESSION\).*\)*.\)*
      

      Sed:

        sed 's/\(\(\(EXPRESSION\).*\)*.\)*/\3/'
      

      Example (finding first sequence of digits):

        $ sed 's/\(\(\([0-9]\{1,\}\).*\)*.\)*/\3/' <<< 'foo 12 bar 34'
      
        12
      

      This one is like ERE version but with no alternation involved. That's all. At each single position engine tries to match a digit.

      enter image description here

      If it is found, other following digits are consumed and captured and the rest of line is matched immediately otherwise since * means more or zero it skips over second capturing group \(\([0-9]\{1,\}\).*\)* and arrives at a dot . to match a single character and this process continues.

  2. Finding first occurrence of a delimited expression:

    This approach will match the very first occurrence of a string that is delimited. We can call it a block of string.

    sed 's/\(END-DELIMITER-EXPRESSION\).*/\1/; \
         s/\(\(START-DELIMITER-EXPRESSION.*\)*.\)*/\1/g'
    

    Input string:

    foobar start block #1 end barfoo start block #2 end
    

    -EDE: end

    -SDE: start

    $ sed 's/\(end\).*/\1/; s/\(\(start.*\)*.\)*/\1/g'
    

    Output:

    start block #1 end
    

    First regex \(end\).* matches and captures first end delimiter end and substitues all match with recent captured characters which is the end delimiter. At this stage our output is: foobar start block #1 end.

    enter image description here

    Then the result is passed to second regex \(\(start.*\)*.\)* that is same as POSIX BRE version above. It matches a single character if start delimiter start is not matched otherwise it matches and captures the start delimiter and matches the rest of characters.

    enter image description here


Directly answering your question

Using approach #2 (delimited expression) you should select two appropriate expressions:

  • EDE: [^:/]\/

  • SDE: http:

Usage:

$ sed 's/\([^:/]\/\).*/\1/g; s/\(\(http:.*\)*.\)*/\1/' <<< 'http://www.suepearson.co.uk/product/174/71/3816/'

Output:

http://www.suepearson.co.uk/

Note: this will not work with identical delimiters.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Magento addFieldToFilter: Two fields, match as OR, not AND

To filter by multiple attributes use something like:

//for AND
    $collection = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter('my_field1', 'my_value1')
    ->addFieldToFilter('my_field2', 'my_value2');

    echo $collection->getSelect()->__toString();

//for OR - please note 'attribute' is the key name and must remain the same, only replace //the value (my_field1, my_field2) with your attribute name


    $collection = Mage::getModel('sales/order')->getCollection()
        ->addAttributeToSelect('*')
        ->addFieldToFilter(
            array(
                array('attribute'=>'my_field1','eq'=>'my_value1'),
                array('attribute'=>'my_field2', 'eq'=>'my_value2')
            )
        );

For more information check: http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection_Db.html#_getConditionSql

React: "this" is undefined inside a component function

I ran into a similar bind in a render function and ended up passing the context of this in the following way:

{someList.map(function(listItem) {
  // your code
}, this)}

I've also used:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

How to set size for local image using knitr for markdown?

Un updated answer: in knitr 1.17 you can simply use

![Image Title](path/to/your/image){width=250px}

edit as per comment from @jsb

Note this works only without spaces, e.g. {width=250px} not {width = 250px}

How to hide only the Close (x) button?

Well, you can hide it, by removing the entire system menu:

private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.Style &= ~WS_SYSMENU;
        return cp;
    }
}

Of course, doing so removes the minimize and maximize buttons.

If you keep the system menu but remove the close item then the close button remains but is disabled.

The final alternative is to paint the non-client area yourself. That's pretty hard to get right.

How to get EditText value and display it on screen through TextView?

First get the value from edit text in a String variable

String value = edttxt.getText().toString();

Then set that value to textView

txtview.setText(value);

Where edttxt refers to edit text field in XML file and txtview refers to textfield in XML file to show the value

how to rotate text left 90 degree and cell size is adjusted according to text in html

Unfortunately while I thought these answers may have worked for me, I struggled with a solution, as I'm using tables inside responsive tables - where the overflow-x is played with.

So, with that in mind, have a look at this link for a cleaner way, which doesn't have the weird width overflow issues. It worked for me in the end and was very easy to implement.

https://css-tricks.com/rotated-table-column-headers/

How to get thread id of a pthread in linux c program?

You can use pthread_self()

The parent gets to know the thread id after the pthread_create() is executed sucessfully, but while executing the thread if we want to access the thread id we have to use the function pthread_self().

How to insert strings containing slashes with sed?

Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.

So if you use sed to return some HTML templates (on a server), use double backslash instead of single:

var htmlTemplate = "<div style=\\"color:green;\\"></div>";

Android Studio: /dev/kvm device permission denied

This is because /dev/kvm is not accessible. To make is accessible from android studio run the below command

sudo chmod 777 -R /dev/kvm

It will ask for your password. After that restart Android Studio.

KVM is required to rum emulator. If you have not install it yet then install it

sudo apt install qemu-kvm

Assigning the return value of new by reference is deprecated

just remove new in the $obj_md =& new MDB2();

What Scala web-frameworks are available?

There's also Pinky, which used to be on bitbucket but got transfered to github.

By the way, github is a great place to search for Scala projects, as there's a lot being put there.

How do I set the focus to the first input element in an HTML form independent from the id?

Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

How do you convert WSDLs to Java classes using Eclipse?

Options are:

Read through the above links before taking a call

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

How to display a pdf in a modal window?

You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.

Regular Expression for password validation

I would check them one-by-one; i.e. look for a number \d+, then if that fails you can tell the user they need to add a digit. This avoids returning an "Invalid" error without hinting to the user whats wrong with it.

Select2 open dropdown on focus

Somehow select2Focus didn't work here with empty selection, couldn't figured out the issue, therefore I added manual control when after focus event auto open get's triggered.

Here is coffeescript:

$("#myid").select2()
  .on 'select2-blur', ->
    $(this).data('select2-auto-open', 'true')
  .on 'select2-focus', ->
    $(this).data('select2').open() if $(this).data('select2-auto-open') != 'false'
  .on 'select2-selecting', ->
    $(this).data('select2-auto-open', 'false')

How to allow only numbers in textbox in mvc4 razor

Maybe you can use the [Integer] data annotation (If you use the DataAnnotationsExtensions http://dataannotationsextensions.org/) . However, this wil only check if the value is an integer, nót if it is filled in (So you may also need the [Required] attribute).

If you enable Unobtrusive Validation it will validate it clientside, but you should also use Modelstate.Valid in your POST action to decline it in case people have Javascript disabled.

Is there a way to specify which pytest tests to run from a file?

Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.

And it also limited by my using legacy compatibility mode vs unittest scripts, so not guaranteeing it would work with native pytest.

Here goes:

  1. create a new dictory, say subset_tests_directory.
  2. ln -s tests_directory/foo.py
  3. ln -s tests_directory/bar.py

  4. be careful about imports which implicitly assume files are in test_directory. I had to fix several of those by running python foo.py, from within subset_tests_directory and correcting as needed.

  5. Once the test scripts execute correctly, just cd subset_tests_directory and pytest there. Pytest will only pick up the scripts it sees.

Another possibility is symlinking within your current test directory, say as ln -s foo.py subset_foo.py then pytest subset*.py. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.

Difference between VARCHAR and TEXT in MySQL

TL;DR

TEXT

  • fixed max size of 65535 characters (you cannot limit the max size)
  • takes 2 + c bytes of disk space, where c is the length of the stored string.
  • cannot be (fully) part of an index. One would need to specify a prefix length.

VARCHAR(M)

  • variable max size of M characters
  • M needs to be between 1 and 65535
  • takes 1 + c bytes (for M ≤ 255) or 2 + c (for 256 ≤ M ≤ 65535) bytes of disk space where c is the length of the stored string
  • can be part of an index

More Details

TEXT has a fixed max size of 2¹6-1 = 65535 characters.
VARCHAR has a variable max size M up to M = 2¹6-1.
So you cannot choose the size of TEXT but you can for a VARCHAR.

The other difference is, that you cannot put an index (except for a fulltext index) on a TEXT column.
So if you want to have an index on the column, you have to use VARCHAR. But notice that the length of an index is also limited, so if your VARCHAR column is too long you have to use only the first few characters of the VARCHAR column in your index (See the documentation for CREATE INDEX).

But you also want to use VARCHAR, if you know that the maximum length of the possible input string is only M, e.g. a phone number or a name or something like this. Then you can use VARCHAR(30) instead of TINYTEXT or TEXT and if someone tries to save the text of all three "Lord of the Ring" books in your phone number column you only store the first 30 characters :)

Edit: If the text you want to store in the database is longer than 65535 characters, you have to choose MEDIUMTEXT or LONGTEXT, but be careful: MEDIUMTEXT stores strings up to 16 MB, LONGTEXT up to 4 GB. If you use LONGTEXT and get the data via PHP (at least if you use mysqli without store_result), you maybe get a memory allocation error, because PHP tries to allocate 4 GB of memory to be sure the whole string can be buffered. This maybe also happens in other languages than PHP.

However, you should always check the input (Is it too long? Does it contain strange code?) before storing it in the database.

Notice: For both types, the required disk space depends only on the length of the stored string and not on the maximum length.
E.g. if you use the charset latin1 and store the text "Test" in VARCHAR(30), VARCHAR(100) and TINYTEXT, it always requires 5 bytes (1 byte to store the length of the string and 1 byte for each character). If you store the same text in a VARCHAR(2000) or a TEXT column, it would also require the same space, but, in this case, it would be 6 bytes (2 bytes to store the string length and 1 byte for each character).

For more information have a look at the documentation.

Finally, I want to add a notice, that both, TEXT and VARCHAR are variable length data types, and so they most likely minimize the space you need to store the data. But this comes with a trade-off for performance. If you need better performance, you have to use a fixed length type like CHAR. You can read more about this here.

Better way to set distance between flexbox items

Well, the simplest solution regarding to your CSS, imo, is to add spacers into HTML:

<div id='box'>
  <div class='item'></div>
  <div style='width: 5px;'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>

so, you may control it with inline-style or class names.. sometimes, it's also possible to do spacing with padding.

here is the example

SDK Manager.exe doesn't work

Finally got this torterous SDK to run.

When installing 32bit Java on 64bit windows system, set ANDROID_SWT to e:\android-sdk\tools\lib\x86

not ..\x86_64

Dear Android SDK team,

I genuinely hope some serious attention is being paid to these problems. SDK should be effortless to set up. This is how you lose customers to other platforms where this kind of thing is a one-click ordeal.

I was going to buy another android device to test my game on, but after last 2 days trying to traverse the maze of your incompetence I think i'll just stick with iOS as my main development target.

How to remove blank lines from a Unix file

You can sed's -i option to edit in-place without using temporary file:

 sed -i '/^$/d' file

Why does one use dependency injection?

First, I want to explain an assumption that I make for this answer. It is not always true, but quite often:

Interfaces are adjectives; classes are nouns.

(Actually, there are interfaces that are nouns as well, but I want to generalize here.)

So, e.g. an interface may be something such as IDisposable, IEnumerable or IPrintable. A class is an actual implementation of one or more of these interfaces: List or Map may both be implementations of IEnumerable.

To get the point: Often your classes depend on each other. E.g. you could have a Database class which accesses your database (hah, surprise! ;-)), but you also want this class to do logging about accessing the database. Suppose you have another class Logger, then Database has a dependency to Logger.

So far, so good.

You can model this dependency inside your Database class with the following line:

var logger = new Logger();

and everything is fine. It is fine up to the day when you realize that you need a bunch of loggers: Sometimes you want to log to the console, sometimes to the file system, sometimes using TCP/IP and a remote logging server, and so on ...

And of course you do NOT want to change all your code (meanwhile you have gazillions of it) and replace all lines

var logger = new Logger();

by:

var logger = new TcpLogger();

First, this is no fun. Second, this is error-prone. Third, this is stupid, repetitive work for a trained monkey. So what do you do?

Obviously it's a quite good idea to introduce an interface ICanLog (or similar) that is implemented by all the various loggers. So step 1 in your code is that you do:

ICanLog logger = new Logger();

Now the type inference doesn't change type any more, you always have one single interface to develop against. The next step is that you do not want to have new Logger() over and over again. So you put the reliability to create new instances to a single, central factory class, and you get code such as:

ICanLog logger = LoggerFactory.Create();

The factory itself decides what kind of logger to create. Your code doesn't care any longer, and if you want to change the type of logger being used, you change it once: Inside the factory.

Now, of course, you can generalize this factory, and make it work for any type:

ICanLog logger = TypeFactory.Create<ICanLog>();

Somewhere this TypeFactory needs configuration data which actual class to instantiate when a specific interface type is requested, so you need a mapping. Of course you can do this mapping inside your code, but then a type change means recompiling. But you could also put this mapping inside an XML file, e.g.. This allows you to change the actually used class even after compile time (!), that means dynamically, without recompiling!

To give you a useful example for this: Think of a software that does not log normally, but when your customer calls and asks for help because he has a problem, all you send to him is an updated XML config file, and now he has logging enabled, and your support can use the log files to help your customer.

And now, when you replace names a little bit, you end up with a simple implementation of a Service Locator, which is one of two patterns for Inversion of Control (since you invert control over who decides what exact class to instantiate).

All in all this reduces dependencies in your code, but now all your code has a dependency to the central, single service locator.

Dependency injection is now the next step in this line: Just get rid of this single dependency to the service locator: Instead of various classes asking the service locator for an implementation for a specific interface, you - once again - revert control over who instantiates what.

With dependency injection, your Database class now has a constructor that requires a parameter of type ICanLog:

public Database(ICanLog logger) { ... }

Now your database always has a logger to use, but it does not know any more where this logger comes from.

And this is where a DI framework comes into play: You configure your mappings once again, and then ask your DI framework to instantiate your application for you. As the Application class requires an ICanPersistData implementation, an instance of Database is injected - but for that it must first create an instance of the kind of logger which is configured for ICanLog. And so on ...

So, to cut a long story short: Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks).

In practice, there are things you can not do without a service locator (e.g., if you do not know in advance how many instances you do need of a specific interface: A DI framework always injects only one instance per parameter, but you can call a service locator inside a loop, of course), hence most often each DI framework also provides a service locator.

But basically, that's it.

P.S.: What I described here is a technique called constructor injection, there is also property injection where not constructor parameters, but properties are being used for defining and resolving dependencies. Think of property injection as an optional dependency, and of constructor injection as mandatory dependencies. But discussion on this is beyond the scope of this question.

Print "\n" or newline characters as part of the output on terminal

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

Telling Python to save a .txt file to a certain directory on Windows and Mac

Using an absolute or relative string as the filename.

name_of_file = input("What is the name of the file: ")
completeName = '/home/user/Documents'+ name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = input("Write what you want into the field")
file1.write(toFile)
file1.close()

SQL JOIN vs IN performance?

A interesting writeup on the logical differences: SQL Server: JOIN vs IN vs EXISTS - the logical difference

I am pretty sure that assuming that the relations and indexes are maintained a Join will perform better overall (more effort goes into working with that operation then others). If you think about it conceptually then its the difference between 2 queries and 1 query.

You need to hook it up to the Query Analyzer and try it and see the difference. Also look at the Query Execution Plan and try to minimize steps.

When to use the different log levels

G'day,

As a corollary to this question, communicate your interpretations of the log levels and make sure that all people on a project are aligned in their interpretation of the levels.

It's painful to see a vast variety of log messages where the severities and the selected log levels are inconsistent.

Provide examples if possible of the different logging levels. And be consistent in the info to be logged in a message.

HTH

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

jQuery: find element by text

In jQuery documentation it says:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination

Therefore it is not enough that you use :contains() selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}

Stop handler.postDelayed()

this may be old, but for those looking for answer you can use this...

public void stopHandler() {
   handler.removeMessages(0);
}

cheers

Add (insert) a column between two columns in a data.frame

You can use the append() function to insert items into vectors or lists (dataframes are lists). Simply:

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))

df <- as.data.frame(append(df, list(d=df$b+df$c), after=2))

Or, if you want to specify the position by name use which:

df <- as.data.frame(append(df, list(d=df$b+df$c), after=which(names(df)=="b")))

tar: add all files and directories in current directory INCLUDING .svn and so on

Yet another solution, assuming the number of items in the folder is not huge:

tar -czf workspace.tar.gz `ls -A`

(ls -A prints normal and hidden files but not "." and ".." as ls -a does.)

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

How to assign colors to categorical variables in ggplot2 that have stable mapping?

The easiest solution is to convert your categorical variable to a factor prior to the subsetting. Bottomline is that you need a factor variable with exact the same levels in all your subsets.

library(ggplot2)
dataset <- data.frame(category = rep(LETTERS[1:5], 100), 
    x = rnorm(500, mean = rep(1:5, 100)), y = rnorm(500, mean = rep(1:5, 100)))
dataset$fCategory <- factor(dataset$category)
subdata <- subset(dataset, category %in% c("A", "D", "E"))

With a character variable

ggplot(dataset, aes(x = x, y = y, colour = category)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = category)) + geom_point()

With a factor variable

ggplot(dataset, aes(x = x, y = y, colour = fCategory)) + geom_point()
ggplot(subdata, aes(x = x, y = y, colour = fCategory)) + geom_point()

Looping through the content of a file in Bash

Suppose you have this file:

$ cat /tmp/test.txt
Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR

There are four elements that will alter the meaning of the file output read by many Bash solutions:

  1. The blank line 4;
  2. Leading or trailing spaces on two lines;
  3. Maintaining the meaning of individual lines (i.e., each line is a record);
  4. The line 6 not terminated with a CR.

If you want the text file line by line including blank lines and terminating lines without CR, you must use a while loop and you must have an alternate test for the final line.

Here are the methods that may change the file (in comparison to what cat returns):

1) Lose the last line and leading and trailing spaces:

$ while read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'

(If you do while IFS= read -r p; do printf "%s\n" "'$p'"; done </tmp/test.txt instead, you preserve the leading and trailing spaces but still lose the last line if it is not terminated with CR)

2) Using process substitution with cat will reads the entire file in one gulp and loses the meaning of individual lines:

$ for p in "$(cat /tmp/test.txt)"; do printf "%s\n" "'$p'"; done
'Line 1
    Line 2 has leading space
Line 3 followed by blank line

Line 5 (follows a blank line) and has trailing space    
Line 6 has no ending CR'

(If you remove the " from $(cat /tmp/test.txt) you read the file word by word rather than one gulp. Also probably not what is intended...)


The most robust and simplest way to read a file line-by-line and preserve all spacing is:

$ while IFS= read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'    Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space    '
'Line 6 has no ending CR'

If you want to strip leading and trading spaces, remove the IFS= part:

$ while read -r line || [[ -n $line ]]; do printf "'%s'\n" "$line"; done </tmp/test.txt
'Line 1'
'Line 2 has leading space'
'Line 3 followed by blank line'
''
'Line 5 (follows a blank line) and has trailing space'
'Line 6 has no ending CR'

(A text file without a terminating \n, while fairly common, is considered broken under POSIX. If you can count on the trailing \n you do not need || [[ -n $line ]] in the while loop.)

More at the BASH FAQ

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

is python capable of running on multiple cores?

example code taking all 4 cores on my ubuntu 14.04, python 2.7 64 bit.

import time
import threading


def t():
    with open('/dev/urandom') as f:
        for x in xrange(100):
            f.read(4 * 65535)

if __name__ == '__main__':
    start_time = time.time()
    t()
    t()
    t()
    t()
    print "Sequential run time: %.2f seconds" % (time.time() - start_time)

    start_time = time.time()
    t1 = threading.Thread(target=t)
    t2 = threading.Thread(target=t)
    t3 = threading.Thread(target=t)
    t4 = threading.Thread(target=t)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    print "Parallel run time: %.2f seconds" % (time.time() - start_time)

result:

$ python 1.py
Sequential run time: 3.69 seconds
Parallel run time: 4.82 seconds

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

How do you return a JSON object from a Java Servlet

I do exactly what you suggest (return a String).

You might consider setting the MIME type to indicate you're returning JSON, though (according to this other stackoverflow post it's "application/json").

Bootstrap 3 - Responsive mp4-video

It is to my understanding that you want to embed a video on your site that:

  • Is responsive
  • Allows both autoplay and loop
  • Uses Bootstrap

This Demo Here does just that. You have to place another embed class outside of the object/embed/iframe tag as per the the instructions here - but you're also able to use a video tag instead of the object tag even though it's not specified.

<div align="center" class="embed-responsive embed-responsive-16by9">
    <video autoplay loop class="embed-responsive-item">
        <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
    </video>
</div>

PDF to byte array and vice versa

You basically need a helper method to read a stream into memory. This works pretty well:

public static byte[] readFully(InputStream stream) throws IOException
{
    byte[] buffer = new byte[8192];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    int bytesRead;
    while ((bytesRead = stream.read(buffer)) != -1)
    {
        baos.write(buffer, 0, bytesRead);
    }
    return baos.toByteArray();
}

Then you'd call it with:

public static byte[] loadFile(String sourcePath) throws IOException
{
    InputStream inputStream = null;
    try 
    {
        inputStream = new FileInputStream(sourcePath);
        return readFully(inputStream);
    } 
    finally
    {
        if (inputStream != null)
        {
            inputStream.close();
        }
    }
}

Don't mix up text and binary data - it only leads to tears.

Maximum value of maxRequestLength?

Right value is below. (Tried)

maxRequestLength="2147483647" targetFramework="4.5.2"/>

Why does this code using random strings print "hello world"?

I was intrigued by this, I ran this random word generator on a dictionary word list. Range: Integer.MIN_VALUE to Integer.MAX_VALUE

I got 15131 hits.

int[] arrInt = {-2146926310, -1885533740, -274140519, 
                -2145247212, -1845077092, -2143584283,
                -2147483454, -2138225126, -2147375969};

for(int seed : arrInt){
    System.out.print(randomString(seed) + " ");
}

Prints

the quick browny fox jumps over a lazy dog 

Stop and Start a service via batch or cmd file?

Using the return codes from net start and net stop seems like the best method to me. Try a look at this: Net Start return codes.

How to push elements in JSON from javascript array

You can directly access BODY.values:

for (var ln = 0; ln < names.length; ln++) {
  var item1 = {
    "person": {
      "_path": "/people/"+names[ln],
    },
  };

  BODY.values.push(item1);
}

bootstrap button shows blue outline when clicked

This was happening to me in Chrome (though not in Firefox). I've found out that the outline property was being set by Bootstrap as outline: 5px auto -webkit-focus-ring-color;. Solved by overriding the outline property later in my custom CSS as follows:

.btn.active.focus, .btn.active:focus, .btn.focus, .btn:active.focus, .btn:active:focus, .btn:focus {
    outline: 0;
}

GitHub: How to make a fork of public repository private?

GitHub now has an import option that lets you choose whatever you want your new imported repository public or private

Github Repository import

How to use OrderBy with findAll in Spring Data

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public List<StudentEntity> findAllByOrderByIdAsc();
}

The code above should work. I'm using something similar:

public List<Pilot> findTop10ByOrderByLevelDesc();

It returns 10 rows with the highest level.

IMPORTANT: Since I've been told that it's easy to miss the key point of this answer, here's a little clarification:

findAllByOrderByIdAsc(); // don't miss "by"
       ^

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;

Validate that text field is numeric usiung jQuery

You don't need a regex for this one. Use the isNAN() JavaScript function.

The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.

if (isNaN($('#Field').val()) == false) {

    // It's a number
}

Change label text using JavaScript

Have you tried .innerText or .value instead of .innerHTML?

Check if textbox has empty value

The check can be done like this:

if (!!inp.val()) {

}

and even shorter:

if (inp.val()) {

}

why are there two different kinds of for loops in java?

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

for (int i=0;i<myString.length;i++) { 
  System.out.println(myString[i]); 
}

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff

for (String string : list) {
  System.out.println(string);
}

instead of

for (int i=0; i<list.size();i++) {
  System.out.println(list.get(i));
}

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  String string=it.next();
  System.out.println(string);
}

In the end it's just syntactic sugar, but rather convenient.

Remove all multiple spaces in Javascript and replace with single space

There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

str.replace( /\s\s+/g, ' ' )

See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space

Check if a property exists in a class

I got this error: "Type does not contain a definition for GetProperty" when tying the accepted answer.

This is what i ended up with:

using System.Reflection;

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null)
{

}

Java inner class and static nested class

Ummm... an inner class IS a nested class... do you mean anonymous class and inner class?

Edit: If you actually meant inner vs anonymous... an inner class is just a class defined within a class such as:

public class A {
    public class B {
    }
}

Whereas an anonymous class is an extension of a class defined anonymously, so no actual "class is defined, as in:

public class A {
}

A anon = new A() { /* you could change behavior of A here */ };

Further Edit:

Wikipedia claims there is a difference in Java, but I've been working with Java for 8 years, and it's the first I heard such a distinction... not to mention there are no references there to back up the claim... bottom line, an inner class is a class defined within a class (static or not), and nested is just another term to mean the same thing.

There is a subtle difference between static and non-static nested class... basically non-static inner classes have implicit access to instance fields and methods of the enclosing class (thus they cannot be constructed in a static context, it will be a compiler error). Static nested classes, on the other hand, don't have implicit access to instance fields and methods, and CAN be constructed in a static context.

How to Correctly Use Lists in R?

why do these two different operators, [ ], and [[ ]], return the same result?

x = list(1, 2, 3, 4)
  1. [ ] provides sub setting operation. In general sub set of any object will have the same type as the original object. Therefore, x[1] provides a list. Similarly x[1:2] is a subset of original list, therefore it is a list. Ex.

    x[1:2]
    
    [[1]] [1] 1
    
    [[2]] [1] 2
    
  2. [[ ]] is for extracting an element from the list. x[[1]] is valid and extract the first element from the list. x[[1:2]] is not valid as [[ ]] does not provide sub setting like [ ].

     x[[2]] [1] 2 
    
    > x[[2:3]] Error in x[[2:3]] : subscript out of bounds
    

convert '1' to '0001' in JavaScript

Just to demonstrate the flexibility of javascript: you can use a oneliner for this

function padLeft(nr, n, str){
    return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
    return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5));       //=> '00023'
console.log((23).padLeft(5));     //=> '00023'
console.log((23).padLeft(5,' ')); //=> '   23'
console.log(padLeft(23,5,'>>'));  //=> '>>>>>>23'

If you want to use this for negative numbers also:

Number.prototype.padLeft = function (n,str) {
    return (this < 0 ? '-' : '') + 
            Array(n-String(Math.abs(this)).length+1)
             .join(str||'0') + 
           (Math.abs(this));
}
console.log((-23).padLeft(5));     //=> '-00023'

Alternative if you don't want to use Array:

number.prototype.padLeft = function (len,chr) {
 var self = Math.abs(this)+'';
 return (this<0 && '-' || '')+
         (String(Math.pow( 10, (len || 2)-self.length))
           .slice(1).replace(/0/g,chr||'0') + self);
}

Removing an activity from the history stack

Try this:

intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)

it is API Level 1, check the link.

Delete entire row if cell contains the string X

Try this ...

Dim r as Range
Dim x as Integer

For x = 5000 to 4 step -1 '---> or change as you want //Thanx 4 KazJaw

  set r = range("E" & format(x))
  if ucase(r.Value) = "NONE" then
    Rows(x).EntireRow.Delete
  end if 

Next

What's a simple way to get a text input popup dialog box on an iPhone

Add views to a UIAlertView like this. In iOS 5 there are some "magic" things that do it for you (but that's all under NDA).

How to filter by IP address in Wireshark?

You can also limit the filter to only part of the ip address.

E.G. To filter 123.*.*.* you can use ip.addr == 123.0.0.0/8. Similar effects can be achieved with /16 and /24.

See WireShark man pages (filters) and look for Classless InterDomain Routing (CIDR) notation.

... the number after the slash represents the number of bits used to represent the network.

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How do I use a PriorityQueue?

Just pass appropriate Comparator to the constructor:

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

The only difference between offer and add is the interface they belong to. offer belongs to Queue<E>, whereas add is originally seen in Collection<E> interface. Apart from that both methods do exactly the same thing - insert the specified element into priority queue.

How to combine multiple inline style objects?

To Expand on what @PythonIsGreat said, I create a global function that will do it for me:

var css = function(){
    var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
    return $.extend.apply(null, args);
}

This deeply extends the objects into a new object and allows for a variable number of objects as parameters. This allows you to do something like this:

return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);

var styles = {
  base:{
    //whatever
  },
  first:{
    //whatever
  },
  second:{
    //whatever
  }
}

How to change plot background color?

If you already have axes object, just like in Nick T's answer, you can also use

 ax.patch.set_facecolor('black')

Android: ListView elements with multiple clickable buttons

I don't have much experience than above users but I faced this same issue and I Solved this with below Solution

<Button
        android:id="@+id/btnRemove"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/btnEdit"
        android:layout_weight="1"
        android:background="@drawable/btn"
        android:text="@string/remove" 
        android:onClick="btnRemoveClick"
        />

btnRemoveClick Click event

public void btnRemoveClick(View v)
{
    final int position = listviewItem.getPositionForView((View) v.getParent()); 
    listItem.remove(position);
    ItemAdapter.notifyDataSetChanged();

}

Generate random string/characters in JavaScript

const c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
const s = [...Array(5)].map(_ => c[~~(Math.random()*c.length)]).join('')

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

What is (x & 1) and (x >>= 1)?

It is similar to x = (x >> 1).

(operand1)(operator)=(operand2)  implies(=>)  (operand1)=(operand1)(operator)(operand2) 

It shifts the binary value of x by one to the right.

E.g.

int x=3;    // binary form (011) 
x = x >> 1; // zero shifted in from the left, 1 shifted out to the right:
            // x=1, binary form (001)

How to loop and render elements in React.js without an array of objects to map?

Here is more functional example with some ES6 features:

'use strict';

const React = require('react');

function renderArticles(articles) {
    if (articles.length > 0) {      
        return articles.map((article, index) => (
            <Article key={index} article={article} />
        ));
    }
    else return [];
}

const Article = ({article}) => {
    return ( 
        <article key={article.id}>
            <a href={article.link}>{article.title}</a>
            <p>{article.description}</p>
        </article>
    );
};

const Articles = React.createClass({
    render() {
        const articles = renderArticles(this.props.articles);

        return (
            <section>
                { articles }
            </section>
        );
    }
});

module.exports = Articles;

Remove all line breaks from a long string of text

updated based on Xbello comment:

string = my_string.rstrip('\r\n')

read more here

Match at every second occurrence

Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d)

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

How to jquery alert confirm box "yes" & "no"

This plugin can help you,

craftpip/jquery-confirm

Its easy to setup and has great set of features.

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    buttons: {
        confirm: function () {
            $.alert('Confirmed!');
        },
        cancel: function () {
            $.alert('Canceled!');
        },
        somethingElse: {
            text: 'Something else',
            btnClass: 'btn-blue',
            keys: ['enter', 'shift'], // trigger when enter or shift is pressed
            action: function(){
                $.alert('Something else?');
            }
        }
    }
});

Other than this you can also load your content from a remote url.

$.confirm({
    content: 'url:hugedata.html' // location of your hugedata.html.
});

Remove an element from a Bash array

This is the most direct way to unset a value if you know it's position.

$ array=(one two three)
$ echo ${#array[@]}
3
$ unset 'array[1]'
$ echo ${array[@]}
one three
$ echo ${#array[@]}
2

transform object to array with lodash

2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:

_x000D_
_x000D_
// import { toArray, map } from 'lodash'_x000D_
const map = _.map_x000D_
_x000D_
const input = {_x000D_
  key: {_x000D_
    value: 'value'_x000D_
  }_x000D_
}_x000D_
_x000D_
const output = map(input, (value, key) => ({_x000D_
  key,_x000D_
  ...value_x000D_
}))_x000D_
_x000D_
console.log(output)_x000D_
// >> [{key: 'key', value: 'value'}])
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

I haven't been able to get it to work without specifying a width but the following css worked

.wrapper {
    background: #DDD;
    padding: 10px;
    display: inline-block;
    height: 20px;
    width: auto;
}

.contents {
    background: #c3c;
    overflow: hidden;
    white-space: nowrap;
    display: inline-block;
    visibility: hidden;
    width: 1px;
    -webkit-transition: width 1s ease-in-out, visibility 1s linear;
    -moz-transition: width 1s ease-in-out, visibility 1s linear;
    -o-transition: width 1s ease-in-out, visibility 1s linear;
    transition: width 1s ease-in-out, visibility 1s linear;
}

.wrapper:hover .contents {
    width: 200px;
    visibility: visible;
}

I'm not sure you will be able to get it working without setting a width on it.

How to get Device Information in Android

Try this:

// Code For IMEI AND IMSI NUMBER

String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();

YouTube Video Embedded via iframe Ignoring z-index?

Try adding wmode, it seems to have two parameters.

&wmode=Opaque

&wmode=transparent

I can't find a technical reason why it works, or much more explanation but take at look at this query.

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/lzQgAR_J1PI?wmode=transparent" frameborder="0" wmode="Opaque">

or this

//Fix z-index youtube video embedding
$(document).ready(function (){
    $('iframe').each(function(){
        var url = $(this).attr("src");
        $(this).attr("src",url+"?wmode=transparent");
    });
});

Including jars in classpath on commandline (javac or apt)

In windows:

java -cp C:/.../jardir1/*;C:/.../jardir2/* class_with_main_method

make sure that the class with the main function is in one of the included jars

Stack smashing detected

You could try to debug the problem using valgrind:

The Valgrind distribution currently includes six production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache profiler, and a heap profiler. It also includes two experimental tools: a heap/stack/global array overrun detector, and a SimPoint basic block vector generator. It runs on the following platforms: X86/Linux, AMD64/Linux, PPC32/Linux, PPC64/Linux, and X86/Darwin (Mac OS X).

jQuery - Follow the cursor with a DIV

This works for me. Has a nice delayed action going on.

var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;

$(document).mousemove(function(e){
    $mouseX = e.pageX;
    $mouseY = e.pageY;    
});

var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
}, 30);

Nice and simples

How to change the font size on a matplotlib plot

The changes to the rcParams are very granular, most of the time all you want is just scaling all of the font sizes so they can be seen better in your figure. The figure size is a good trick but then you have to carry it for all of your figures. Another way (not purely matplotlib, or maybe overkill if you don't use seaborn) is to just set the font scale with seaborn:

sns.set_context('paper', font_scale=1.4)

DISCLAIMER: I know, if you only use matplotlib then probably you don't want to install a whole module for just scaling your plots (I mean why not) or if you use seaborn, then you have more control over the options. But there's the case where you have the seaborn in your data science virtual env but not using it in this notebook. Anyway, yet another solution.

error::make_unique is not a member of ‘std’

1.gcc version >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>

How does delete[] know it's an array?

just define a destructor inside a class and execute your code with both syntax

delete pointer

delete [] pointer

according to the output u can find the solutions

What is the equivalent of Java static methods in Kotlin?

All static member and function should be inside companion block

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
    }

    fun staticMethod() {
    }
  }

Reason: no suitable image found

It occurred on my side when building an app in the command line via xcodebuild and xcrun PackageApplication, signing the app with an enterprise profile. On our CI build servers, the certificate was set to "Always Trust" in the keychain (select certificate -> Get Info -> Trust -> "Use System Default" can be changed to "Always Trust"). I had to set it back to "Use System Default" in order to make this work. Initially we set this to "Always Trust" to work-around the keychain dialogs that appear after software updates and certificate updates.

How to generate .NET 4.0 classes from xsd?

I use XSD in a batch script to generate .xsd file and classes from XML directly :

set XmlFilename=Your__Xml__Here
set WorkingFolder=Your__Xml__Path_Here

set XmlExtension=.xml
set XsdExtension=.xsd

set XSD="C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1\Tools\xsd.exe"

set XmlFilePath=%WorkingFolder%%XmlFilename%%XmlExtension%
set XsdFilePath=%WorkingFolder%%XmlFilename%%XsdExtension%

%XSD% %XmlFilePath% /out:%WorkingFolder%
%XSD% %XsdFilePath% /c /out:%WorkingFolder%

What's the difference between "app.render" and "res.render" in express.js?

Here are some differences:

  1. You can call app.render on root level and res.render only inside a route/middleware.

  2. app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

    Take a look at the following examples.

    • app.render

      app.render('index', {title: 'res vs app render'}, function(err, html) {
          console.log(html)
      });
      
      // logs the following string (from default index.jade)
      <!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>
      
    • res.render without third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'})
      })
      
      // also renders index.jade but sends it to the client 
      // with status 200 and content-type text/html on GET /render
      
    • res.render with third parameter

      app.get('/render', function(req, res) {
          res.render('index', {title: 'res vs app render'}, function(err, html) {
              console.log(html);
              res.send('done');
          })
      })
      
      // logs the same as app.render and sends "done" to the client instead 
      // of the content of index.jade
      
  3. res.render uses app.render internally to render template files.

  4. You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    For example inside an external route:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }
    

throwing exceptions out of a destructor

I currently follow the policy (that so many are saying) that classes shouldn't actively throw exceptions from their destructors but should instead provide a public "close" method to perform the operation that could fail...

...but I do believe destructors for container-type classes, like a vector, should not mask exceptions thrown from classes they contain. In this case, I actually use a "free/close" method that calls itself recursively. Yes, I said recursively. There's a method to this madness. Exception propagation relies on there being a stack: If a single exception occurs, then both the remaining destructors will still run and the pending exception will propagate once the routine returns, which is great. If multiple exceptions occur, then (depending on the compiler) either that first exception will propagate or the program will terminate, which is okay. If so many exceptions occur that the recursion overflows the stack then something is seriously wrong, and someone's going to find out about it, which is also okay. Personally, I err on the side of errors blowing up rather than being hidden, secret, and insidious.

The point is that the container remains neutral, and it's up to the contained classes to decide whether they behave or misbehave with regard to throwing exceptions from their destructors.

Transport security has blocked a cleartext HTTP

I do not like editing the plist directly. You can easily add it to the plist using the GUI:

  • Click on the Info.plist in the Navigator on the left.
  • Now change the data in the main area:

    • On the last line add the +
    • Enter the name of the group: App Transport Security Settings
    • Right click on the group and select Add Row
    • Enter Allow Arbitrary Loads
    • Set the value on the right to YES

Example

Simplest/cleanest way to implement a singleton in JavaScript

I believe this is the simplest/cleanest and most intuitive way though it requires ECMAScript 2016 (ES7):

export default class Singleton {

  static instance;

  constructor(){
    if(instance){
      return instance;
    }

    this.state = "duke";
    this.instance = this;
  }

}

The source code is from: adam-bien.com

How to compile C++ under Ubuntu Linux?

g++ is the C++ compiler under linux. The code looks right. It is possible that you are missing a library reference which is used as such:

g++ -l{library name here (math fns use "m")} codefile.cpp

Where does Visual Studio look for C++ header files?

If the project came with a Visual Studio project file, then that should already be configured to find the headers for you. If not, you'll have to add the include file directory to the project settings by right-clicking the project and selecting Properties, clicking on "C/C++", and adding the directory containing the include files to the "Additional Include Directories" edit box.

How to declare a variable in MySQL?

For any person using @variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.

Set @Ids = '';

select 
  @Ids := concat_ws(',',@Ids,tbl.Id),
  tbl.Col1,
  ...
from mytable tbl;

Using Django time/date widgets in custom form

Here's another 2020 solution, inspired by @Sandeep's. Using the MinimalSplitDateTimeMultiWidget found in this gist, in our Form as below, we can use modern browser date and time selectors (via eg 'type': 'date'). We don't need any JS.

class EditAssessmentBaseForm(forms.ModelForm):
    class Meta:
        model = Assessment
        fields = '__all__'

    begin = DateTimeField(widget=MinimalSplitDateTimeMultiWidget())

enter image description here

Why is volatile needed in C?

In simple terms, it tells the compiler not to do any optimisation on a particular variable. Variables which are mapped to device register are modified indirectly by the device. In this case, volatile must be used.

How to verify if nginx is running or not?

This is probably system-dependent, but this is the simplest way I've found.

if [ -e /var/run/nginx.pid ]; then echo "nginx is running"; fi

That's the best solution for scripting.

Rails: Why "sudo" command is not recognized?

sudo is a command for Linux so it cant be used in windows so you will get that error

How do I use System.getProperty("line.separator").toString()?

Try

rows = tabDelimitedTable.split("[" + newLine + "]");

This should solve the regex problem.

Also not that important but return type of

System.getProperty("line.separator")

is String so no need to call toString().

What is the difference between <p> and <div>?

<p> is semantically used for text, paragraphs usually.

<div> is used for a block or area in a webpage. For example it could be used to make the area of a header.

They could probably be used interchangeably, but you shouldn't.

How to disassemble a memory range with GDB?

gdb disassemble has a /m to include source code alongside the instructions. This is equivalent of objdump -S, with the extra benefit of confining to just the one function (or address-range) of interest.

Can functions be passed as parameters?

Here is a simple example:

    package main

    import "fmt"

    func plusTwo() (func(v int) (int)) {
        return func(v int) (int) {
            return v+2
        }
    }

    func plusX(x int) (func(v int) (int)) {
       return func(v int) (int) {
           return v+x
       }
    }

    func main() {
        p := plusTwo()
        fmt.Printf("3+2: %d\n", p(3))

        px := plusX(3)
        fmt.Printf("3+3: %d\n", px(3))
    }

How can I generate Unix timestamps?

In Linux or MacOS you can use:

date +%s

where

  • +%s, seconds since 1970-01-01 00:00:00 UTC. (GNU Coreutils 8.24 Date manual)

Example output now 1454000043.

how to convert a string date into datetime format in python?

You should use datetime.datetime.strptime:

import datetime

dt = datetime.datetime.strptime(string_date, fmt)

fmt will need to be the appropriate format for your string. You'll find the reference on how to build your format here.

Suppress warning messages using mysql from within Terminal, but password written in bash script

Here is a solution for Docker in a script /bin/sh :

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "[client]" > /root/mysql-credentials.cnf'

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "user=root" >> /root/mysql-credentials.cnf'

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "password=$MYSQL_ROOT_PASSWORD" >> /root/mysql-credentials.cnf'

docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec mysqldump --defaults-extra-file=/root/mysql-credentials.cnf --all-databases'

Replace [MYSQL_CONTAINER_NAME] and be sure that the environment variable MYSQL_ROOT_PASSWORD is set in your container.

Hope it will help you like it could help me !

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I tried the following:

  • Restarted my device
  • Deleted previous APK
  • Rebuild my APK
  • Uninstall my previous copy in the device
  • Reinstall

Check if it works the same with you.

Using "like" wildcard in prepared statement

String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";


PreparedStatement preparedStatement=con.prepareStatement(query);


// where seleced and SelectedStr are String Variables in my program

jQuery if checkbox is checked

if ($('input.checkbox_check').is(':checked')) {

Java switch statement: Constant expression required, but it IS constant

You can use an enum like in this example:

public class MainClass {
enum Choice { Choice1, Choice2, Choice3 }
public static void main(String[] args) {
Choice ch = Choice.Choice1;

switch(ch) {
  case Choice1:
    System.out.println("Choice1 selected");
    break;
 case Choice2:
   System.out.println("Choice2 selected");
   break;
 case Choice3:
   System.out.println("Choice3 selected");
   break;
    }
  }
}

Source: Switch statement with enum

Preferred way of getting the selected item of a JComboBox

The first method is right.

The second method kills kittens if you attempt to do anything with x after the fact other than Object methods.

Why do I need to do `--set-upstream` all the time?

All i wanted was doing something like this:

git checkout -b my-branch
git commit -a -m "my commit"
git push

Since i didn't found a better solution, i've just created an bash alias on ~/.bashrc:

alias push="git push -u origin HEAD"

now just doing a push command does the job (you can add this alias on ~/.gitconfig too with another name, such as pushup)

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.

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Transparent background on winforms?

My solution was extremely close to Joel's (Not Etherton, just plain Joel):

public partial class WaitingDialog : Form
{
    public WaitingDialog()
    {
        InitializeComponent();

        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;
        this.TransparencyKey = Color.Transparent; // I had to add this to get it to work.

        // Other stuff
    }

    protected override void OnPaintBackground(PaintEventArgs e) { /* Ignore */ }
}

How to vertically center a container in Bootstrap?

add Bootstrap.css then add this to your css

_x000D_
_x000D_
   _x000D_
html, body{height:100%; margin:0;padding:0}_x000D_
 _x000D_
.container-fluid{_x000D_
  height:100%;_x000D_
  display:table;_x000D_
  width: 100%;_x000D_
  padding: 0;_x000D_
}_x000D_
 _x000D_
.row-fluid {height: 100%; display:table-cell; vertical-align: middle;}_x000D_
 _x000D_
 _x000D_
_x000D_
.centering {_x000D_
  float:none;_x000D_
  margin:0 auto;_x000D_
}
_x000D_
Now call in your page _x000D_
_x000D_
<div class="container-fluid">_x000D_
    <div class="row-fluid">_x000D_
        <div class="centering text-center">_x000D_
           Am in the Center Now :-)_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

I prefer using the value returned by System.currentTimeMillis() for all kinds of calculations and only use Calendar or Date if I need to really display a value that is read by humans. This will also prevent 99% of your daylight-saving-time bugs. :)

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

Highlight a word with jQuery

I have created a repository on similar concept that changes the colors of the texts whose colors are recognised by html5 (we don't have to use actual #rrggbb values and could just use the names as html5 standardised about 140 of them)

colors.js colors.js

_x000D_
_x000D_
$( document ).ready(function() {_x000D_
 _x000D_
 function hiliter(word, element) {_x000D_
  var rgxp = new RegExp("\\b" + word + "\\b" , 'gi'); // g modifier for global and i for case insensitive _x000D_
  var repl = '<span class="myClass">' + word + '</span>';_x000D_
  element.innerHTML = element.innerHTML.replace(rgxp, repl);_x000D_
   _x000D_
   };_x000D_
_x000D_
 hiliter('dolor', document.getElementById('dolor'));_x000D_
});
_x000D_
.myClass{_x000D_
_x000D_
background-color:red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
 <head>_x000D_
  <title>highlight</title>_x000D_
  _x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>_x000D_
 _x000D_
   <link href="main.css" type="text/css"  rel="stylesheet"/>_x000D_
   _x000D_
 </head>_x000D_
 <body id='dolor'>_x000D_
<p >_x000D_
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit._x000D_
</p>_x000D_
<p>_x000D_
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero._x000D_
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris._x000D_
</p>_x000D_
 <script type="text/javascript" src="main.js" charset="utf-8"></script>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Sample random rows in dataframe

Select a Random sample from a tibble type in R:

library("tibble")    
a <- your_tibble[sample(1:nrow(your_tibble), 150),]

nrow takes a tibble and returns the number of rows. The first parameter passed to sample is a range from 1 to the end of your tibble. The second parameter passed to sample, 150, is how many random samplings you want. The square bracket slicing specifies the rows of the indices returned. Variable 'a' gets the value of the random sampling.

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How can I convert ticks to a date format?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:

DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

How can one print a size_t variable portably using the printf family?

For those talking about doing this in C++ which doesn't necessarily support the C99 extensions, then I heartily recommend boost::format. This makes the size_t type size question moot:

std::cout << boost::format("Sizeof(Var) is %d\n") % sizeof(Var);

Since you don't need size specifiers in boost::format, you can just worry about how you want to display the value.

Increase permgen space

On Debian-like distributions you set that in /etc/default/tomcat[67]

The 'json' native gem requires installed build tools

Follow the Instructions from the Ruby Installer Developer Kit Wiki:

  1. Download Ruby 1.9.3 from rubyinstaller.org
  2. Download DevKit file from rubyinstaller.org
  3. Extract DevKit to path C:\Ruby193\DevKit
  4. Run cd C:\Ruby193\DevKit
  5. Run ruby dk.rb init
  6. Run ruby dk.rb review
  7. Run ruby dk.rb install

To return to the problem at hand, you should be able to install JSON (or otherwise test that your DevKit successfully installed) by running the following commands which will perform an install of the JSON gem and then use it:

gem install json --platform=ruby
ruby -rubygems -e "require 'json'; puts JSON.load('[42]').inspect"

ORA-28000: the account is locked error getting frequently

Here other solution to only unlock the blocked user. From your command prompt log as SYSDBA:

sqlplus "/ as sysdba"

Then type the following command:

alter user <your_username> account unlock;

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.

Is there a rule-of-thumb for how to divide a dataset into training and validation sets?

There are two competing concerns: with less training data, your parameter estimates have greater variance. With less testing data, your performance statistic will have greater variance. Broadly speaking you should be concerned with dividing data such that neither variance is too high, which is more to do with the absolute number of instances in each category rather than the percentage.

If you have a total of 100 instances, you're probably stuck with cross validation as no single split is going to give you satisfactory variance in your estimates. If you have 100,000 instances, it doesn't really matter whether you choose an 80:20 split or a 90:10 split (indeed you may choose to use less training data if your method is particularly computationally intensive).

Assuming you have enough data to do proper held-out test data (rather than cross-validation), the following is an instructive way to get a handle on variances:

  1. Split your data into training and testing (80/20 is indeed a good starting point)
  2. Split the training data into training and validation (again, 80/20 is a fair split).
  3. Subsample random selections of your training data, train the classifier with this, and record the performance on the validation set
  4. Try a series of runs with different amounts of training data: randomly sample 20% of it, say, 10 times and observe performance on the validation data, then do the same with 40%, 60%, 80%. You should see both greater performance with more data, but also lower variance across the different random samples
  5. To get a handle on variance due to the size of test data, perform the same procedure in reverse. Train on all of your training data, then randomly sample a percentage of your validation data a number of times, and observe performance. You should now find that the mean performance on small samples of your validation data is roughly the same as the performance on all the validation data, but the variance is much higher with smaller numbers of test samples

How can I add a column that doesn't allow nulls in a Postgresql database?

Specifying a default value would also work, assuming a default value is appropriate.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

If you've SQLServer Reporting Services running locally then you need to stop that also..

How to add/update child entities when updating a parent entity in EF

Here is my code that works just fine.

public async Task<bool> UpdateDeviceShutdownAsync(Guid id, DateTime shutdownAtTime, int areaID, decimal mileage,
        decimal motohours, int driverID, List<int> commission,
        string shutdownPlaceDescr, int deviceShutdownTypeID, string deviceShutdownDesc,
        bool isTransportation, string violationConditions, DateTime shutdownStartTime,
        DateTime shutdownEndTime, string notes, List<Guid> faultIDs )
        {
            try
            {
                using (var db = new GJobEntities())
                {
                    var isExisting = await db.DeviceShutdowns.FirstOrDefaultAsync(x => x.ID == id);

                    if (isExisting != null)
                    {
                        isExisting.AreaID = areaID;
                        isExisting.DriverID = driverID;
                        isExisting.IsTransportation = isTransportation;
                        isExisting.Mileage = mileage;
                        isExisting.Motohours = motohours;
                        isExisting.Notes = notes;                    
                        isExisting.DeviceShutdownDesc = deviceShutdownDesc;
                        isExisting.DeviceShutdownTypeID = deviceShutdownTypeID;
                        isExisting.ShutdownAtTime = shutdownAtTime;
                        isExisting.ShutdownEndTime = shutdownEndTime;
                        isExisting.ShutdownStartTime = shutdownStartTime;
                        isExisting.ShutdownPlaceDescr = shutdownPlaceDescr;
                        isExisting.ViolationConditions = violationConditions;

                        // Delete children
                        foreach (var existingChild in isExisting.DeviceShutdownFaults.ToList())
                        {
                            db.DeviceShutdownFaults.Remove(existingChild);
                        }

                        if (faultIDs != null && faultIDs.Any())
                        {
                            foreach (var faultItem in faultIDs)
                            {
                                var newChild = new DeviceShutdownFault
                                {
                                    ID = Guid.NewGuid(),
                                    DDFaultID = faultItem,
                                    DeviceShutdownID = isExisting.ID,
                                };

                                isExisting.DeviceShutdownFaults.Add(newChild);
                            }
                        }

                        // Delete all children
                        foreach (var existingChild in isExisting.DeviceShutdownComissions.ToList())
                        {
                            db.DeviceShutdownComissions.Remove(existingChild);
                        }

                        // Add all new children
                        if (commission != null && commission.Any())
                        {
                            foreach (var cItem in commission)
                            {
                                var newChild = new DeviceShutdownComission
                                {
                                    ID = Guid.NewGuid(),
                                    PersonalID = cItem,
                                    DeviceShutdownID = isExisting.ID,
                                };

                                isExisting.DeviceShutdownComissions.Add(newChild);
                            }
                        }

                        await db.SaveChangesAsync();

                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return false;
        }

Two arrays in foreach loop

Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

becomes:

$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');

Which is the fastest algorithm to find prime numbers?

#include<stdio.h>
main()
{
    long long unsigned x,y,b,z,e,r,c;
    scanf("%llu",&x);
    if(x<2)return 0;
    scanf("%llu",&y);
    if(y<x)return 0;
    if(x==2)printf("|2");
    if(x%2==0)x+=1;
    if(y%2==0)y-=1;
    for(b=x;b<=y;b+=2)
    {
        z=b;e=0;
        for(c=2;c*c<=z;c++)
        {
            if(z%c==0)e++;
            if(e>0)z=3;
        }
        if(e==0)
        {
            printf("|%llu",z);
            r+=1;
        }
    }
    printf("|\n%llu outputs...\n",r);
    scanf("%llu",&r);
}    

VBA vlookup reference in different sheet

The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use. Please read this explanation and its conclusion, which I guess will give essential information.

The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:

  1. The value is actually not present (pointed out by chris nielsen).

  2. You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range. Code accounting for this (and items below) follows:

    Sub srch()
        Dim ws1 As Worksheet, ws2 As Worksheet
        Dim srchres As Variant
    
        Set ws1 = Worksheets("Sheet1")
        Set ws2 = Worksheets("Sheet2")
    
        On Error Resume Next
        srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
        On Error GoTo 0
        If (IsEmpty(srchres)) Then
          ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
        Else
          ws2.Range("E2").Value = srchres
        End If
    End Sub
    

I will point out a few additional notable points:

  1. Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).

  2. This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).

  3. Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.

  4. Both solutions by L42 qualify Ranges suitably.

  5. You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

How to pad a string to a fixed length with spaces in Python?

string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces

This will add the number of spaces needed, provided the field has length >= the length of the name provided

Passing Arrays to Function in C++

The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.