Programs & Examples On #Classnotfoundexception

The Java exception thrown when an application tries to load a class by name but is not able to find the class.

java.lang.ClassNotFoundException on working app

Check if the package name in the class matches the package name in the manifest file. This worked for me

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

For me, it was because I ran

$ phpunit .

instead of

$ phpunit

when I already had a configured phpunit.xml file in the working directory.

A child container failed during start java.util.concurrent.ExecutionException

You must have packaged the servlet-api.jar along with the other libraries in your war file. You can verify this by opening up your war file and navigating to the WEB-INF/lib folder.

Ideally, you should not provide the servlet-api jar. The container, in your case Tomcat, is responsible for providing it at deploy time to your application. If you try to provide it as well, then issues arise due to version mismatch etc. Best practise is to just avoid packaging it. Remove it from the WEB-INF/lib.

Additional Information

If you are using maven for your packaging, then simply add the provided tag with the dependency and maven will make sure not to package it in the final war file. Something like

<dependency>
    <artifact>..
    <group> ...
    <version> ...
    <scope>provided</scope>
</<dependency>

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

A NoClassDefFoundError (NCDFE) happens when your code runs "new Y()" and it can't find the Y class.

It may simply be that Y is missing from your class loader like the other comments suggest, but it could be that the Y class isn't signed or has an invalid signature, or that Y is loaded by a different classloader not visible to your code, or even that Y depends on Z which couldn't be loaded for any of the above reasons.

If this happens, then the JVM will remember the result of loading X (NCDFE) and it will simply throw a new NCDFE every time you ask for Y without telling you why:

class a {
  static class b {}
  public static void main(String args[]) {
    System.out.println("First attempt new b():");
    try {new b(); } catch(Throwable t) {t.printStackTrace();}
    System.out.println("\nSecond attempt new b():");
    try {new b(); } catch(Throwable t) {t.printStackTrace();}
  }
}

save this as a.java somewhere

The code simply tries to instantiate a new "b" class twice, other than that, it doesn't have any bugs, and it doesn't do anything.

Compile the code with javac a.java, Then run a by invoking java -cp . a -- it should just print out two lines of text, and it should run fine without errors.

Then delete the "a$b.class" file (or fill it with garbage, or copy a.class over it) to simulate the missing or corrupted class. Here's what happens:

First attempt new b():
java.lang.NoClassDefFoundError: a$b
    at a.main(a.java:5)
Caused by: java.lang.ClassNotFoundException: a$b
    at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    ... 1 more

Second attempt new b():
java.lang.NoClassDefFoundError: a$b
    at a.main(a.java:7)

The first invocation results in a ClassNotFoundException (thrown by the class loader when it can't find the class), which must be wrapped in an unchecked NoClassDefFoundError, since the code in question (new b()) should just work.

The second attempt will of course fail too, but as you can see the wrapped exception is no more, because the ClassLoader seems to remember failed class loaders. You see only the NCDFE with absolutely no clue as to what really happened.

So if you ever see a NCDFE with no root cause, you need to see if you can track back to the very first time the class was loaded to find the cause of the error.

How do I resolve ClassNotFoundException?

This is the best solution I found so far.

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this: enter image description here

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command: enter image description here

NOTE: You have to execute the above java command no matter what your current location is. But this is not the case for javac. For compiling you can even directly go into the directory where you have your .java files and directly execute javac ClassName.java.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

If you are using Jersey 2.x use following dependency:

<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet-core</artifactId>
   <version>2.XX</version>
</dependency>  

Where XX could be any particular version you look for. Jersey Containers.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Put mysql-connector-java-5.1.38-bin.jar to the C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib folder.by doing this program with execute

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

By default, Tomcat container doesn’t contain any jstl library. To fix it, declares jstl.jar in your Maven pom.xml file if you are working in Maven project or add it to your application's classpath

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I faced the same problem.

Just removed the server from configuration and added it back after restarting eclipse by adding it to the server runtime environment.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

Right click the project in the Explorer: Build Path -> Order and Export -> Select JRE System Library [jdk] and click Bottom button.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

Method 1: Download ojdbc.jar

add ojdbc6.jar to deployment assembly. Right click on project->properties->select deployment assembly->click on 'Add' ->select 'Archives from File System'->browse to the folder where ojdbc6.jar is saved.->add the jar->click finish->Apply/OK.

Method 2:

if you want to add ojdbc.jar to your maven dependencies you follow this link: http://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/ . . Even if you're using a maven project it is not necessary to add ojdbc to maven dependencies(method 2), method 1 (adding directly to deployment assembly) works just fine.

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

The servlet class should be in the WEB-INF/classes not WEB-INF/src.

Returning Arrays in Java

You have a couple of basic misconceptions about Java:

I want it to return the array without having to explicitly tell the console to print.

1) Java does not work that way. Nothing ever gets printed implicitly. (Java does not support an interactive interpreter with a "repl" loop ... like Python, Ruby, etc.)

2) The "main" doesn't "return" anything. The method signature is:

  public static void main(String[] args)

and the void means "no value is returned". (And, sorry, no you can't replace the void with something else. If you do then the java command won't recognize the "main" method.)

3) If (hypothetically) you did want your "main" method to return something, and you altered the declaration to allow that, then you still would need to use a return statement to tell it what value to return. Unlike some language, Java does not treat the value of the last statement of a method as the return value for the method. You have to use a return statement ...

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

I know this question is already been answered but for new comers those two solutions may help:

  1. Make sure your gmail is allowing low secure apps to sign in, you can turn it on here: https://www.google.com/settings/security/lesssecureapps.
  2. Change your password.

How to give spacing between buttons using bootstrap

You can achieved by use bootstrap Spacing. Bootstrap Spacing includes a wide range of shorthand responsive margin and padding. In below example mr-1 set the margin or padding to $spacer * .25.

Example:

<button class="btn btn-outline-primary mr-1" href="#">Sign up</button>
<button class="btn btn-outline-primary" href="#">Login</button>

You can read more at Bootstrap Spacing.

Password Protect a SQLite DB. Is it possible?

You can password protect a SQLite3 DB. Before doing any operations, set the password as follows.

SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();

then next time you can access it like

conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();

This wont allow any GUI editor to view your data. Some editors can decrypt the DB if you provide the password. The algorithm used is RSA.

Later if you wish to change the password, use

conn.ChangePassword("new_password");

To reset or remove password, use

conn.ChangePassword(String.Empty);

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

You mean that want to get status codes?

VolleyError has a member variable type of NetworkResponse and it is public.

You can access error.networkResponse.statusCode for http error code.

I hope it is helpful for you.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Using a SELECT statement within a WHERE clause

It's called correlated subquery. It has it's uses.

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

HAProxy redirecting http to https (ssl)

Can be done like this -

  frontend http-in
   bind *:80
   mode http
   redirect scheme https code 301

Any traffic hitting http will redirect to https

Wrap text in <td> tag

Apply classes to your TDs, apply the appropriate widths (remember to leave one of them without a width so it assumes the remainder of the width), then apply the appropriate styles. Copy and paste the code below into an editor and view in a browser to see it function.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
td { vertical-align: top; }
.leftcolumn { background: #CCC; width: 20%; padding: 10px; }
.centercolumn { background: #999; padding: 10px; width: 15%; }
.rightcolumn { background: #666; padding: 10px; }
-->
</style>
</head>

<body>
<table border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td class="leftcolumn">This is the left column. It is set to 20% width.</td>
    <td class="centercolumn">
        <p>Hi,</p>
        <p>I want to wrap a text that is added to the TD. I have tried with style="word-wrap: break-word;" width="15%". But the wrap is not happening. Is it mandatory to give 100% width ? But I have got other controls to display so only 15% width available.</p>
        <p>Need help.</p>
        <p>TIA.</p>
    </td>
    <td class="rightcolumn">This is the right column, it has no width so it assumes the remainder from the 15% and 20% assumed by the others. By default, if a width is applied and no white-space declarations are made, your text will automatically wrap.</td>
  </tr>
</table>
</body>
</html>

Axios Delete request with body and headers?

For those who tried everything above and still don't see the payload with the request - make sure you have:

"axios": "^0.21.1" (not 0.20.0)

Then, the above solutions work

axios.delete("URL", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      data: {
        var1: "var1",
        var2: "var2"
      },
    })

You can access the payload with

req.body.var1, req.body.var2

Here's the issue:

https://github.com/axios/axios/issues/3335

How do I make a transparent canvas in html5?

Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:

#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas

I'm not sure but it looks like that the background-color is inherited as transparent from the body.

How do I access an access array item by index in handlebars?

If you want to use dynamic variables

This won't work:

{{#each obj[key]}}
...
{{/each}}

You need to do:

{{#each (lookup obj key)}}
...
{{/each}}

see handlebars lookup helper and handlebars subexpressions.

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

Purpose of installing Twitter Bootstrap through npm?

  1. The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.

    Now, the point of bootstrap's npm package

    is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.

  2. How to use it

    Imagine the following project structure:

    project
    |-- node_modules
    |-- public
    |   |-- css
    |   |-- img
    |   |-- js
    |   |-- index.html
    |-- package.json
    
    

In your index.html you can reference both css and js files like this:

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Which is the simplest way, and correct for the .css files. But it is much better to include the bootstrap.js file like this somewhere in your public/js/*.js files:

var bootstrap = require('bootstrap');

And you include this code only in those javascript files where you actually need bootstrap.js. Browserify takes care of including this file for you.

Now, the drawback is that you now have your front-end files as node_modules dependencies, and the node_modules folder is usually not checked in with git. I think this is the most controversial part, with many opinions and solutions.


UPDATE March 2017

Almost two years have passed since I wrote this answer and an update is in place.

Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.

Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:

const bootstrap = require('bootstrap');

As for the css files, webpack has so called "loaders". They allow you write this in your js code:

require('bootstrap/dist/css/bootstrap.css');

and the css files will be "magically" included in your build. They will be dynamically added as <style /> tags when your app runs, but you can configure webpack to export them as a separate css file. You can read more about that in webpack's documentation.

In conclusion.

  1. You should "bundle" your app code with a bundler
  2. You shouldn't commit neither node_modules nor the dynamically built files to git. You can add a build script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.

Top 1 with a left join

Because the TOP 1 from the ordered sub-query does not have profile_id = 'u162231993' Remove where u.id = 'u162231993' and see results then.

Run the sub-query separately to understand what's going on.

CSS - Make divs align horizontally

you can use the clip property:

#container {
  position: absolute;
  clip: rect(0px,200px,100px,0px);
  overflow: hidden;
  background: red;
}

note the position: absolute and overflow: hidden needed in order to get clip to work.

How to conclude your merge of a file?

Check status (git status) of your repository. Every unmerged file (after you resolve conficts by yourself) should be added (git add), and if there is no unmerged file you should git commit

Java - checking if parseInt throws exception

instead of trying & catching expressions.. its better to run regex on the string to ensure that it is a valid number..

no operator "<<" matches these operands

If you want to use std::string reliably, you must #include <string>.

Using Jasmine to spy on a function without an object

TypeScript users:

I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.

In the test file, convert the import of the function from this:

import {foo} from '../foo_functions';

x = foo(y);

To this:

import * as FooFunctions from '../foo_functions';

x = FooFunctions.foo(y);

Then you can spy on FooFunctions.foo :)

spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();

Select count(*) from multiple tables

Just because it's slightly different:

SELECT 'table_1' AS table_name, COUNT(*) FROM table_1
UNION
SELECT 'table_2' AS table_name, COUNT(*) FROM table_2
UNION
SELECT 'table_3' AS table_name, COUNT(*) FROM table_3

It gives the answers transposed (one row per table instead of one column), otherwise I don't think it's much different. I think performance-wise they should be equivalent.

jQuery click event not working in mobile browsers

You can use jQuery Mobile vclick event:

Normalized event for handling touchend or mouse click events on touch devices.

$(document).ready(function(){
   $('.publications').vclick(function() {
       $('#filter_wrapper').show();
   });
 });

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Checkout subdirectories in Git?

There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.

If you insist (or really need it), though, you could make a git repository with just mytheme and myplugins directories and symlink those from within the WordPress install.


MDCore wrote:

making a commit to, e.g., mytheme will increment the revision number for myplugin

Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.

The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.

Git really really wants you to use separate repositories for separate entities.

submodules

Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.

SQL providerName in web.config

 WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;

How do I horizontally center an absolute positioned element inside a 100% width div?

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...

How to Troubleshoot Intermittent SQL Timeout Errors

My experience with these issues (not on SQL Server though) is that overdone multi-tasking is often the cause of the problem. If there is similar/connected data/tables queried at (almost) the same time by many connections, the DBMS may have trouble keeping all the isolation at check. This is not that much of an issue of disk usage as to making some connections wait for things to be done by other ones. Synchronization is very expensive in terms of CPU usage.

The 100 connections is way too much in my opinion. (In my experience again) even 20 connections asked to be done by one machine may be overly optimistic.

Access is denied when attaching a database

Every time I have run into this issue was when attempting to attach a database that is in a different directory from the default database directory that is setup in SQL server.

I would highly recommend that instead of jacking with permissions on various directories and accounts that you simply move your data file into the directory that sql server expects to find it.

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

The MediaStore API is probably throwing away the alpha channel (i.e. decoding to RGB565). If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);

or

http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html

Gradle does not find tools.jar

I had this problem when I was trying to run commands through CLI.

It was a problem with system looking at the JRE folder i.e. D:\Program Files\Java\jre8\bin. If we look in there, there is no Tools.jar, hence the error.

You need to find where the JDK is, in my case: D:\Program Files\Java\jdk1.8.0_11, and if you look in the lib directory, you will see Tools.jar.

What I did I created a new environment variable JAVA_HOME: enter image description here

And then you need to edit your PATH variable to include JAVA_HOME, i.e. %JAVA_HOME%/bin; enter image description here

Re-open command prompt and should run.

JSON find in JavaScript

If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions is messy and less maintainable than the alternative.

Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:

// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
    db = fdb.db('myTestDatabase'),
    coll;

// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});

// Insert our records into the collection
coll.insert([
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]);

// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
    name: /my nam/i
});

console.log(searchResultArray);

/* Outputs
[
    {"name":"my Name","id":12,"type":"car owner"},
    {"name":"my Name2","id":13,"type":"car owner2"},
    {"name":"my Name4","id":14,"type":"car owner3"},
    {"name":"my Name4","id":15,"type":"car owner5"}
]
*/

Disclaimer: I am the developer of ForerunnerDB.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

We're using Jira 6.2 and I use this query:

updatedDate > startOfDay(-1d) AND updatedDate < endOfDay(-1)

to return all of the issues that were updated from the previous day. You can combine with whichever queries you want to return the appropriate issues for the previous day.

Photoshop text tool adds punctuation to the beginning of text

This is a paragraph option. Go to Window>Paragraph then a small window will pop up. You will have two buttons on the bottom. One with a arrow on the left of P and one on the right. Select the right one.

How to open maximized window with Javascript?

var params = [
    'height='+screen.height,
    'width='+screen.width,
    'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
     // and any other options from
     // https://developer.mozilla.org/en/DOM/window.open

var popup = window.open('http://www.google.com', 'popup_window', params); 
popup.moveTo(0,0);

Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)

edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.

How to split one string into multiple variables in bash shell?

Sounds like a job for set with a custom IFS.

IFS=-
set $STR
var1=$1
var2=$2

(You will want to do this in a function with a local IFS so you don't mess up other parts of your script where you require IFS to be what you expect.)

How to get the full url in Express?

Just the code below was enough for me!

const baseUrl = `${request.protocol}://${request.headers.host}`;
// http://127.0.0.1:3333

How to set width of a div in percent in JavaScript?

document.getElementById('header').style.width = '50%';

If you are using Firebug or the Chrome/Safari Developer tools, execute the above in the console, and you'll see the Stack Overflow header shrink by 50%.

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

Appending HTML string to the DOM

The idea is to use innerHTML on an intermediary element and then move all of its child nodes to where you really want them via appendChild.

var target = document.getElementById('test');
var str = '<p>Just some <span>text</span> here</p>';

var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
  target.appendChild(temp.firstChild);
}

This avoids wiping out any event handlers on div#test but still allows you to append a string of HTML.

One-line list comprehension: if-else variants

x if y else z is the syntax for the expression you're returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a "complex" one, which happens to involve an if-else.

How to validate an e-mail address in swift?

Swift 5

 func isValidEmailAddress(emailAddressString: String) -> Bool {

 var returnValue = true
 let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"

 do {
        let regex = try NSRegularExpression(pattern: emailRegEx)
        let nsString = emailAddressString as NSString
        let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))

        if results.count == 0
        {
            returnValue = false
        }

    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        returnValue = false
    }

    return  returnValue
}

Then:

let validEmail = isValidEmailAddress(emailAddressString: "[email protected]")
print(validEmail)

javascript date + 7 days

The simple way to get a date x days in the future is to increment the date:

function addDays(dateObj, numDays) {
  return dateObj.setDate(dateObj.getDate() + numDays);
}

Note that this modifies the supplied date object, e.g.

function addDays(dateObj, numDays) {
   dateObj.setDate(dateObj.getDate() + numDays);
   return dateObj;
}

var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);

alert(
    'Today: ' + now +
    '\nTomorrow: ' + tomorrow +
    '\nNext week: ' + nextWeek
);

URL rewriting with PHP

this is an .htaccess file that forward almost all to index.php

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php

then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever

fe_sendauth: no password supplied

After making changes to the pg_hba.conf or postgresql.conf files, the cluster needs to be reloaded to pick up the changes.

From the command line: pg_ctl reload

From within a db (as superuser): select pg_reload_conf();

From PGAdmin: right-click db name, select "Reload Configuration"

Note: the reload is not sufficient for changes like enabling archiving, changing shared_buffers, etc -- those require a cluster restart.

Ping a site in Python?

See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.

import ping, socket
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

The source code itself is easy to read, see the implementations of verbose_ping and of Ping.do for inspiration.

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

Does bootstrap have builtin padding and margin classes?

For bootstrap 4 we have new classes named with following notation

m - for classes that set margin
p - for classes that set padding

Specify Top, bottom,left, right, left & right, top & bottom using below letters

t - for classes that set margin-top (mt) or padding-top (pt)
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom

Specify size using following numbers

0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3

Actual Code from bootstrap 4 css file

.mt-0 {
  margin-top: 0 !important;
}

.ml-1 {
  margin-left: ($spacer * .25) !important;
}

.px-2 {
  padding-left: ($spacer * .5) !important;
  padding-right: ($spacer * .5) !important;
}

.p-3 {
  padding: $spacer !important;
}

Usage

So when you need some padding left just add any class from pl-0 to pl-5 based on your need

If you need margin on top just add any class from mt-0 to mt-5 based on your need

<div class="col-sm-6 mt-5"> this div will have margin top added </div>
<div class="col-sm-6 pl-5"> this div will have padding left added </div>

Bootstrap 4 CDN

How to get date in BAT file

set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

This is possible in HTML5. Example (PHP 5.4):

<!doctype html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="my_file[]" multiple>
            <input type="submit" value="Upload">
        </form>
        <?php
            if (isset($_FILES['my_file'])) {
                $myFile = $_FILES['my_file'];
                $fileCount = count($myFile["name"]);

                for ($i = 0; $i < $fileCount; $i++) {
                    ?>
                        <p>File #<?= $i+1 ?>:</p>
                        <p>
                            Name: <?= $myFile["name"][$i] ?><br>
                            Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
                            Type: <?= $myFile["type"][$i] ?><br>
                            Size: <?= $myFile["size"][$i] ?><br>
                            Error: <?= $myFile["error"][$i] ?><br>
                        </p>
                    <?php
                }
            }
        ?>
    </body>
</html>

Here's what it looks like in Chrome after selecting 2 items in the file dialog:

chrome multiple file select

And here's what it looks like after clicking the "Upload" button.

submitting multiple files to PHP

This is just a sketch of a fully working answer. See PHP Manual: Handling file uploads for more information on proper, secure handling of file uploads in PHP.

Editing the git commit message in GitHub

I was facing the same problem.

See in your github for a particular branch and you will come to know the commit id of the very first commit in that branch. do a rebase to that:

git rebase -i

editor will open up. Do a track of your commits from github UI and opened editor and change the messages.

Insertion sort vs Bubble Sort Algorithms

insertion sort:

1.In the insertion sort swapping is not required.

2.the time complexity of insertion sort is O(n)for best case and O(n^2) worst case.

3.less complex as compared to bubble sort.

4.example: insert books in library, arrange cards.

bubble sort: 1.Swapping required in bubble sort.

2.the time complexity of bubble sort is O(n)for best case and O(n^2) worst case.

3.more complex as compared to insertion sort.

How do I obtain crash-data from my Android application?

Thanks resources present in Stackoverflow in helping me to find this answer.

You can find your remotely Android crash reports directly into your email. remmember you have to put your email inside CustomExceptionHandler class.

public static String sendErrorLogsTo = "[email protected]" ;

Steps required :

1st) in onCreate of your activity use this section of your code.

    if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(this));
    }   

2nd) use this overridden version of CustomExceptionHandler class of ( rrainn ), according to my phpscript.

package com.vxmobilecomm.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.util.Log;

public class CustomExceptionHandler implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler defaultUEH;
    public static String sendErrorLogsTo = "[email protected]" ;

    Activity activity;

    public CustomExceptionHandler(Activity activity) {
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        this.activity = activity;
    }

    public void uncaughtException(Thread t, Throwable e) {

        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        e.printStackTrace(printWriter);
        String stacktrace = result.toString();
        printWriter.close();
        String filename = "error" + System.nanoTime() + ".stacktrace";

        Log.e("Hi", "url != null");
        sendToServer(stacktrace, filename);

        StackTraceElement[] arr = e.getStackTrace();
        String report = e.toString() + "\n\n";
        report += "--------- Stack trace ---------\n\n";
        for (int i = 0; i < arr.length; i++) {
            report += "    " + arr[i].toString() + "\n";
        }
        report += "-------------------------------\n\n";

        report += "--------- Cause ---------\n\n";
        Throwable cause = e.getCause();
        if (cause != null) {
            report += cause.toString() + "\n\n";
            arr = cause.getStackTrace();
            for (int i = 0; i < arr.length; i++) {
                report += "    " + arr[i].toString() + "\n";
            }
        }
        report += "-------------------------------\n\n";

        defaultUEH.uncaughtException(t, e);
    }

    private void sendToServer(String stacktrace, String filename) {
        AsyncTaskClass async = new AsyncTaskClass(stacktrace, filename,
                getAppLable(activity));
        async.execute("");
    }

    public String getAppLable(Context pContext) {
        PackageManager lPackageManager = pContext.getPackageManager();
        ApplicationInfo lApplicationInfo = null;
        try {
            lApplicationInfo = lPackageManager.getApplicationInfo(
                    pContext.getApplicationInfo().packageName, 0);
        } catch (final NameNotFoundException e) {
        }
        return (String) (lApplicationInfo != null ? lPackageManager
                .getApplicationLabel(lApplicationInfo) : "Unknown");
    }

    public class AsyncTaskClass extends AsyncTask<String, String, InputStream> {
        InputStream is = null;
        String stacktrace;
        final String filename;
        String applicationName;

        AsyncTaskClass(final String stacktrace, final String filename,
                String applicationName) {
            this.applicationName = applicationName;
            this.stacktrace = stacktrace;
            this.filename = filename;
        }

        @Override
        protected InputStream doInBackground(String... params) 
        { 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://suo-yang.com/books/sendErrorLog/sendErrorLogs.php?");

            Log.i("Error", stacktrace);

            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                        6);

                nameValuePairs.add(new BasicNameValuePair("data", stacktrace));
                nameValuePairs.add(new BasicNameValuePair("to",sendErrorLogsTo));
                nameValuePairs.add(new BasicNameValuePair("subject",applicationName));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);

                HttpEntity entity1 = response.getEntity();

                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(
                        entity1);

                is = bufHttpEntity.getContent();

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return is;
        }

        @Override
        protected void onPostExecute(InputStream result) {
            super.onPostExecute(result);

            Log.e("Stream Data", getStringFromInputStream(is));
        }
    }

    // convert InputStream to String
    private static String getStringFromInputStream(InputStream is) {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();

    }
}

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

@Html.Partial returns view in HTML-encoded string and use same view TextWriter object. @Html.RenderPartial this method return void. @Html.RenderPartial is faster than @Html.Partial

The syntax for PartialView:

 [HttpGet] 
 public ActionResult AnyActionMethod
 {
     return PartialView();
 }

Simple JavaScript Checkbox Validation

If the check box's ID "Delete" then for the "onclick" event of the submit button the javascript function can be as follows:

html:
<input type="checkbox" name="Delete" value="Delete" id="Delete"></td>
<input type="button" value="Delete" name="delBtn" id="delBtn" onclick="deleteData()">

script:
<script type="text/Javascript">
    function deleteData() {
        if(!document.getElementById('Delete').checked){
            alert('Checkbox not checked');
            return false;
        }
</script>

$ is not a function - jQuery error

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

No connection could be made because the target machine actively refused it 127.0.0.1

Add new WebProxy() for the proxy setting , where you are creating a web request.

Example :-

  string url =  "Your URL";
  System.Net.WebRequest req = System.Net.WebRequest.Create(url);
  req.Proxy = new WebProxy();
  System.Net.WebResponse resp = req.GetResponse();

Where req.Proxy = new WebProxy() handle the proxy setting & helps the code to work fine.

How to fluently build JSON in Java?

If you are using Jackson do a lot of JsonNode building in code, you may be interesting in the following set of utilities. The benefit of using them is that they support a more natural chaining style that better shows the structure of the JSON under construction.

Here is an example usage:

import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;

...

val request = object("x", "1").with("y", array(object("z", "2"))).end();

Which is equivalent to the following JSON:

{"x":"1", "y": [{"z": "2"}]}

Here are the classes:

import static lombok.AccessLevel.PRIVATE;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

/**
 * Convenience {@link JsonNode} builder.
 */
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {

  /**
   * Factory methods for an {@link ObjectNode} builder.
   */

  public static ObjectNodeBuilder object() {
    return object(JsonNodeFactory.instance);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
    return object(k1, v1).with(k2, v2);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
      @NonNull String k3, String v3) {
    return object(k1, v1, k2, v2).with(k3, v3);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
    return object().with(k1, builder);
  }

  public static ObjectNodeBuilder object(JsonNodeFactory factory) {
    return new ObjectNodeBuilder(factory);
  }

  /**
   * Factory methods for an {@link ArrayNode} builder.
   */

  public static ArrayNodeBuilder array() {
    return array(JsonNodeFactory.instance);
  }

  public static ArrayNodeBuilder array(@NonNull boolean... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull int... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull String... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
    return array().with(builders);
  }

  public static ArrayNodeBuilder array(JsonNodeFactory factory) {
    return new ArrayNodeBuilder(factory);
  }

  public interface JsonNodeBuilder<T extends JsonNode> {

    /**
     * Construct and return the {@link JsonNode} instance.
     */
    T end();

  }

  @RequiredArgsConstructor
  private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {

    /**
     * The source of values.
     */
    @NonNull
    protected final JsonNodeFactory factory;

    /**
     * The value under construction.
     */
    @NonNull
    protected final T node;

    /**
     * Returns a valid JSON string, so long as {@code POJONode}s not used.
     */
    @Override
    public String toString() {
      return node.toString();
    }

  }

  public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {

    private ObjectNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.objectNode());
    }

    public ObjectNodeBuilder withNull(@NonNull String field) {
      return with(field, factory.nullNode());
    }

    public ObjectNodeBuilder with(@NonNull String field, int value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, float value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, boolean value) {
      return with(field, factory.booleanNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, String value) {
      return with(field, factory.textNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
      node.set(field, value);
      return this;
    }

    public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
      return with(field, builder.end());
    }

    public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
      return with(field, factory.pojoNode(pojo));
    }

    @Override
    public ObjectNode end() {
      return node;
    }

  }

  public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {

    private ArrayNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.arrayNode());
    }

    public ArrayNodeBuilder with(boolean value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull boolean... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(int value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull int... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(float value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(String value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull String... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNode value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull JsonNode... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
      return with(value.end());
    }

    public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
      for (val builder : builders)
        with(builder);
      return this;
    }

    @Override
    public ArrayNode end() {
      return node;
    }

  }

}

Note that the implementation uses Lombok, but you can easily desugar it to fill in the Java boilerplate.

Find mouse position relative to element

There is no answer in pure javascript that returns relative coordinates when the reference element is nested inside others which can be with absolute positioning. Here is a solution to this scenario:

function getRelativeCoordinates (event, referenceElement) {

  const position = {
    x: event.pageX,
    y: event.pageY
  };

  const offset = {
    left: referenceElement.offsetLeft,
    top: referenceElement.offsetTop
  };

  let reference = referenceElement.offsetParent;

  while(reference){
    offset.left += reference.offsetLeft;
    offset.top += reference.offsetTop;
    reference = reference.offsetParent;
  }

  return { 
    x: position.x - offset.left,
    y: position.y - offset.top,
  }; 

}

Why use the 'ref' keyword when passing an object?

Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.

How to change letter spacing in a Textview?

As android doesn't support such a thing, you can do it manually with FontCreator. It has good options for font modifying. I used this tool to build a custom font, even if it takes some times but you can always use it in your projects.

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

How to create a DateTime equal to 15 minutes ago?

If you are using time.time() and wants timestamp as output

Simply use

CONSTANT_SECONDS = 900 # time  in seconds (900 seconds = 15 min)

current_time = int(time.time())
time_before_15_min = current_time - CONSTANT_SECONDS

You can change 900 seconds as per your required time.

Difference in make_shared and normal shared_ptr in C++

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

Where do the heap-allocations happen?

std::shared_ptr manages two entities:

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

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

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

Update I: Exception-Safety

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

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

Consider this example,

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

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

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

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

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

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

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

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

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

Update II: Disadvantage of std::make_shared

Quoting Casey's comments:

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

Why do instances of weak_ptrs keep the control block alive?

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

Back to std::make_shared

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

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

How to use AND in IF Statement

If there are no typos in the question, you got the conditions wrong:

You said this:

IF cells (i,"A") contains the text 'Miami'

...but your code says:

If Cells(i, "A") <> "Miami"

--> <> means that the value of the cell is not equal to "Miami", so you're not checking what you think you are checking.

I guess you want this instead:

If Cells(i, "A") like "*Miami*"

EDIT:

Sorry, but I can't really help you more. As I already said in a comment, I'm no Excel VBA expert.
Normally I would open Excel now and try your code myself, but I don't even have Excel on any of my machines at home (I use OpenOffice).

Just one general thing: can you identify the row that does not work?
Maybe this helps someone else to answer the question.

Does it ever execute (or at least try to execute) the Cells(i, "C").Value = "BA" line?
Or is the If Cells(i, "A") like "*Miami*" stuff already False?
If yes, try checking just one cell and see if that works.

Wpf DataGrid Add new row

Try this MSDN blog

Also, try the following example:

Xaml:

   <DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
            <DataGridTextColumn Header="Account" IsReadOnly="True"  Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

CS:

 /// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        var data = new Test { Test1 = "Test1", Test2 = "Test2" };

        DataGridTest.Items.Add(data);
    }
}

public class Test
{
    public string Test1 { get; set; }
    public string Test2 { get; set; }
}

Sum of Numbers C++

I have the following formula that works without loops. I discovered it while trying to find a formula for factorials:

#include <iostream>
using namespace std;

int main() {
    unsigned int positiveInteger;
    cout << "Please input an integer up to 100." << endl;
    cin >> positiveInteger;

    cout << (positiveInteger * (positiveInteger + 1)) / 2;
    return 0;
}

how to use font awesome in own css?

The spirit of Web font is to use cache as much as possible, therefore you should use CDN version between <head></head> instead of hosting yourself:

<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

Also, make sure you loaded your CSS AFTER the above line, or your custom font CSS won't work.

Reference: Font Awesome Get Started

Could not find or load main class with a Jar File

I had a weird issue when an incorrect entry in MANIFEST.MF was causing loading failure. This was when I was trying to launch a very simply scala program:

Incorrect:

Main-Class: jarek.ResourceCache
Class-Path: D:/lang/scala/lib/scala-library.jar

Correct:

Main-Class: jarek.ResourceCache
Class-Path: file:///D:/lang/scala/lib/scala-library.jar

With an incorrect version, I was getting a cryptic message, the same the OP did. Probably it should say something like malformed url exception while parsing manifest file.

Using an absolute path in the manifest file is what IntelliJ uses to provide a long classpath for a program.

How can I run another application within a panel of my C# program?

I know this is possible if the other application can attach itself to a win32 window handle. For example, we have a separate C# application that hosts a DirectX application inside one of its windows. I'm not familiar with the exact details of how this is implemented, but I think just passing the win32 Handle of your panel to the other application is enough for that application to attach its DirectX surface.

Adjust UILabel height to text

The Swift 4.1 extension method to calculate label height:

extension UILabel {

    func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat {
        let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.byWordWrapping
        label.font = font
        label.text = text

        label.sizeToFit()
        return label.frame.height
    }

}

Add MIME mapping in web.config for IIS Express

I'm not using IIS Express but developing against my Local Full IIS 7.

So if anyone else get's here trying to do that, I had to add the mime type for woff via IIS Manager

Mime Types >> Click Add link on right and then enter Extension: .woff MIME type: application/font-woff

top nav bar blocking top content of the page

you should add

#page {
  padding-top: 65px
}

to not destroy a sticky footer or something else

Rounded Corners Image in Flutter

For image use this

ClipOval(
    child: Image.network(
        'https://url to your image',
        fit: BoxFit.fill,
    ),
);

While for Asset Image use this

ClipOval(
    child: Image.asset(
        'Path to your image',
        fit: BoxFit.cover,
    ),
)

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

How can I find the version of the Fedora I use?

These commands worked for Artik 10 :

  • cat /etc/fedora-release
  • cat /etc/issue
  • hostnamectl

and these others didn't :

  • lsb_release -a
  • uname -a

Include php files when they are in different folders

Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.

How to get the cursor to change to the hand when hovering a <button> tag

All u need is just use one of the attribute of CSS , which is---->

cursor:pointer

just use this property in css , no matter its inline or internal or external

for example(for inline css)

<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>

How to truncate string using SQL server

If you only want to return a few characters of your long string, you can use:

select 
  left(col, 15) + '...' col
from yourtable

See SQL Fiddle with Demo.

This will return the first 15 characters of the string and then concatenates the ... to the end of it.

If you want to to make sure than strings less than 15 do not get the ... then you can use:

select 
  case 
    when len(col)>=15
    then left(col, 15) + '...' 
    else col end col
from yourtable

See SQL Fiddle with Demo

How to update Python?

The best solution is to install the different Python versions in multiple paths.

eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.

Read this for more info: How to run multiple Python versions on Windows

How do I return a string from a regex match in python?

Note that re.match(pattern, string, flags=0) only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0) instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object. Then you can extract the matching string with match_object.group(0) as the folks suggested.

Adding a slide effect to bootstrap dropdown

Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:

.dropdown .dropdown-menu {
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;

    max-height: 0;
    display: block;
    overflow: hidden;
    opacity: 0;
}

.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
    max-height: 300px;
    opacity: 1;
}

The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.

It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.

Here is small example: DEMO


! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.

Setting default value in select drop-down using Angularjs

You can do it with following code(track by),

<select ng-model="modelName" ng-options="data.name for data in list track by data.id" ></select>

How to run html file on localhost?

You can try installing one of the following localhost softwares:

  1. xampp
  2. wamp
  3. ammps server
  4. laragon

There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com)

Spring Boot - Loading Initial Data

You can create a data.sql file in your src/main/resources folder and it will be automatically executed on startup. In this file you can add some insert statements, eg.:

INSERT INTO users (username, firstname, lastname) VALUES
  ('lala', 'lala', 'lala'),
  ('lolo', 'lolo', 'lolo');

Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:

CREATE TABLE task (
  id          INTEGER PRIMARY KEY,
  description VARCHAR(64) NOT NULL,
  completed   BIT NOT NULL);

Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:

spring.jpa.hibernate.ddl-auto=none

More information can be found at the documentation about Database initialization.


If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:

spring.datasource.initialization-mode=always

If you're using multiple database vendors, you can name your file data-h2.sql or data-mysql.sql depending on which database platform you want to use.

To make that work, you'll have to configure the spring.datasource.platform property though:

spring.datasource.platform=h2

Hide separator line on one UITableViewCell

The much more simple and logical is to do this:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc] initWithFrame:CGRectZero];
}

In most cases you don't want to see only the last table view cell separator. And this approach removes only the last table view cell separator, and you don't need to think about Auto Layout issues (i.e. rotating device) or hardcode values to set up separator insets.

How to evaluate a math expression given in string form?

It's too late to answer but I came across same situation to evaluate expression in java, it might help someone

MVEL does runtime evaluation of expressions, we can write a java code in String to get it evaluated in this.

    String expressionStr = "x+y";
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("x", 10);
    vars.put("y", 20);
    ExecutableStatement statement = (ExecutableStatement) MVEL.compileExpression(expressionStr);
    Object result = MVEL.executeExpression(statement, vars);

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

jquery ajax function not working

my html and js code

<script>
$(".editTest23").change(function () {

        var test_date = $(this).data('');id
        // alert(status_id);    

        $.ajax({
            type: "POST",
            url: "Doctor/getTestData",
            data: {
                test_data: test_date,
            },
            dataType: "text",
            success: function (data) {
                $('#prepend_here_test1').html(data);
            }
        });
        // you have missed this bracket
        return false;
    });
</script>

in php code

    foreach($patitent_data as $result){

        $result_html .="<tr class='test_record'>\
        <td><input type='text' name='test_name' value='$result->test_name' class='form-control'></td>\
        <td><textarea class='form-control' name='instruction'> $result->instruction </textarea>\
        </td>\
        <td><button class='close remove_test_record' aria-hidden='true'>&times;</button></td>\
     </tr>";
    }

    echo json_encode($result_html)

What is the proper way to comment functions in Python?

While I agree that this should not be a comment, but a docstring as most (all?) answers suggest, I want to add numpydoc (a docstring style guide).

If you do it like this, you can (1) automatically generate documentation and (2) people recognize this and have an easier time to read your code.

Disable time in bootstrap date time picker

    $(function () {
        $('#datetimepicker9').datetimepicker({
            viewMode: 'years',
            format: 'DD/MM/YYYY' /*Add this line to remove time format*/
        });
    });

JSON Parse File Path

Loading local JSON file

Use something like this

$.getJSON("../../data/file.json", function(json) {
    console.log(json); // this will show the info in firebug console 
    alert(json);
});

UTF-8 text is garbled when form is posted as multipart/form-data

In case someone stumbled upon this problem when working on Grails (or pure Spring) web application, here is the post that helped me:

http://forum.spring.io/forum/spring-projects/web/2491-solved-character-encoding-and-multipart-forms

To set default encoding to UTF-8 (instead of the ISO-8859-1) for multipart requests, I added the following code in resources.groovy (Spring DSL):

multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
    defaultEncoding = 'UTF-8'
}

Image re-size to 50% of original size in HTML

We can do this by css3 too. Try this:

.halfsize {
    -moz-transform:scale(0.5);
    -webkit-transform:scale(0.5);
    transform:scale(0.5);
}

<img class="halfsize" src="image4.jpg">
  • subjected to browser compatibility

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

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

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

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How to order citations by appearance using BibTeX?

I use natbib in combination with bibliographystyle{apa}. Eg:

\begin{document}

The body of the document goes here...

\newpage

\bibliography{bibliography} % Or whatever you decided to call your .bib file 

\usepackage[round, comma, sort&compress ]{natbib} 

bibliographystyle{apa}
\end{document}

UIDevice uniqueIdentifier deprecated - What to do now?

A UUID created by CFUUIDCreate is unique if a user uninstalls and re-installs the app: you will get a new one each time.

But you might want it to be not unique, i. e. it should stay the same when the user uninstalls and re-installs the app. This requires a bit of effort, since the most reliable per-device-identifier seems to be the MAC address. You could query the MAC and use that as UUID.

Edit: One needs to always query the MAC of the same interface, of course. I guess the best bet is with en0. The MAC is always present, even if the interface has no IP/is down.

Edit 2: As was pointed out by others, the preferred solution since iOS 6 is -[UIDevice identifierForVendor]. In most cases, you should be able use it as a drop-in replacement to the old -[UIDevice uniqueIdentifier] (but a UUID that is created when the app starts for the first time is what Apple seems to want you to use).

Edit 3: So this major point doesn't get lost in the comment noise: do not use the MAC as UUID, create a hash using the MAC. That hash will always create the same result every time, even across reinstalls and apps (if the hashing is done in the same way). Anyways, nowadays (2013) this isn't necessary any more except if you need a "stable" device identifier on iOS < 6.0.

Edit 4: In iOS 7, Apple now always returns a fixed value when querying the MAC to specifically thwart the MAC as base for an ID scheme. So you now really should use -[UIDevice identifierForVendor] or create a per-install UUID.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

getPathInfo() gives the extra path information after the URI, used to access your Servlet, where as getRequestURI() gives the complete URI.

I would have thought they would be different, given a Servlet must be configured with its own URI pattern in the first place; I don't think I've ever served a Servlet from root (/).

For example if Servlet 'Foo' is mapped to URI '/foo' then I would have thought the URI:

/foo/path/to/resource

Would result in:

RequestURI = /foo/path/to/resource

and

PathInfo = /path/to/resource

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

JPA : How to convert a native query result set to POJO class collection

JPA provides an SqlResultSetMapping that allows you to map whatever returns from your native query into an Entity or a custom class.

EDIT JPA 1.0 does not allow mapping to non-entity classes. Only in JPA 2.1 a ConstructorResult has been added to map return values a java class.

Also, for OP's problem with getting count it should be enough to define a result set mapping with a single ColumnResult

How to install php-curl in Ubuntu 16.04

In Ubuntu 16.04 default PHP version is 7.0, if you want to use different version then you need to install PHP package according to PHP version:

  • PHP 7.4: sudo apt-get install php7.4-curl
  • PHP 7.3: sudo apt-get install php7.3-curl
  • PHP 7.2: sudo apt-get install php7.2-curl
  • PHP 7.1: sudo apt-get install php7.1-curl
  • PHP 7.0: sudo apt-get install php7.0-curl
  • PHP 5.6: sudo apt-get install php5.6-curl
  • PHP 5.5: sudo apt-get install php5.5-curl

Python : List of dict, if exists increment a dict value, if not append a new dict

This always works fine for me:

for url in list_of_urls:
    urls.setdefault(url, 0)
    urls[url] += 1

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

How to connect to MongoDB in Windows?

Follow

  1. Create default db folder.

    c:\data\db

    and also log folder

    c:\data\log\mongo.log

    or use following commands in command-prompt

    mkdir c:\data\log    
    mkdir c:\data\db
    
  2. Create config file in bin folder of mongo (or you may in save your desired destination).

    Add following in text file named "mongod" and save it as
    mongod.cfg
    dbpath=c:\data\db
    logpath=c:\data\log\mongo.log

    or use following commands in command-prompt

    echo dbpath=c:\data\db>> "mongod.cfg"
    echo logpath=c:\data\log\mongo.log>> "mongod.cfg"
    
  3. Now open command-prompt (administrator) and run the following command to start mongo server

    mongod
    
  4. Open another command-prompt (don't close 1st prompt) and run client command:

    mongo
    

Hope this will help or you have done this already.

LIMIT 10..20 in SQL Server

Use all SQL server: ;with tbl as (SELECT ROW_NUMBER() over(order by(select 1)) as RowIndex,* from table) select top 10 * from tbl where RowIndex>=10

How to print last two columns using awk

using gawk exhibits the problem:

 gawk '{ print $NF-1, $NF}' filename
1 2
2 3
-1 one
-1 three
# cat filename
1 2
2 3
one
one two three

I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? per:

http://www.opengroup.org/onlinepubs/009695399/utilities/awk.html

There is no direction one way or the other. Not good. gawk implies subtraction, other awks imply field number or subtraction. hmm.

What is the use of System.in.read()?

import java.io.IOException;

class ExamTest{

    public static void main(String args[]) throws IOException{
        int sn=System.in.read();
        System.out.println(sn);
    }
}

If you want get char input you have to cast like this: char sn=(char) System.in.read()

The value byte is returned as int in the range 0 to 255. However, unlike in other languages’ methods, System.in.read() reads only a byte at a time.

Nexus 5 USB driver

Is it your first android connected to your computer? Sometimes windows drivers need to be erased. Refer http://forum.xda-developers.com/showthread.php?t=2512549

"Continue" (to next iteration) on VBScript

Implement the iteration as a recursive function.

Function Iterate( i , N )
  If i == N Then
      Exit Function
  End If
  [Code]
  If Condition1 Then
     Call Iterate( i+1, N );
     Exit Function
  End If

  [Code]
  If Condition2 Then
     Call Iterate( i+1, N );
     Exit Function
  End If
  Call Iterate( i+1, N );
End Function

Start with a call to Iterate( 1, N )

Notepad++ change text color?

You can Change it from:

Menu Settings -> Style Configurator

See on screenshot:

enter image description here

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.

This happens even if you set

crossOrigin: false;

or even if you ommit it.

The reason is simply that localhost != localhost:57124. Try sending it only to localhost without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

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

The problem is an expired intermediate certificate that is no longer used and must be deleted. Here is a blog post from Digicert explaining the issue and how to resolve it.

https://blog.digicert.com/expired-intermediate-certificate/

I was seeing the issue with Github not loading via SSL in both Safari and the command line with git pull. Once I deleted the old expired cert everything was fine.

How to simulate a mouse click using JavaScript?

Based on Derek's answer, I verified that

document.getElementById('testTarget')
  .dispatchEvent(new MouseEvent('click', {shiftKey: true}))

works as expected even with key modifiers. And this is not a deprecated API, as far as I can see. You can verify on this page as well.

How to read large text file on windows?

I hate to promote my own stuff (well, not really), but PowerPad can open very large files.

Otherwise, I'd recommend a hex editor.

Get line number while using grep

grep -A20 -B20 pattern file.txt

Search pattern and show 20 lines after and before pattern

Regex to check if valid URL that ends in .jpg, .png, or .gif

^((http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.(jpg|png|gif))

How do I remove the top margin in a web page?

It is a <p> element that creates the top margin. You removed all top margins except of that element.

How to get the current time as datetime

You can use in swift 4 or 5 like bellow

let date = Date()
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = df.string(from: date)

Ouput will be like bellow

2019-12-20 09:40:08

set div height using jquery (stretch div height)

The correct way to do this is with good-old CSS:

#content{
    width:100%;
    position:absolute;
    top:35px;
    bottom:35px;
}

And the bonus is that you don't need to attach to the window.onresize event! Everything will adjust as the document reflows. All for the low-low price of four lines of CSS!

Enum "Inheritance"

You can perform inheritance in enum, however it's limited to following types only . int, uint, byte, sbyte, short, ushort, long, ulong

E.g.

public enum Car:int{
Toyota,
Benz,
}

How to watch and reload ts-node when TypeScript files change

I've dumped nodemon and ts-node in favor of a much better alternative, ts-node-dev https://github.com/whitecolor/ts-node-dev

Just run ts-node-dev src/index.ts

How can I loop over entries in JSON?

Try this :

import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
    print 'No Data!'
else:
    for rows in json_object['team']:
        print 'Team ID:' + rows['team_id']
        print 'Team Name:' + rows['team_name']
        print 'Team URL:' + rows['team_icon_url']

How can I create a unique constraint on my column (SQL Server 2008 R2)?

To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.

But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.

Not able to access adb in OS X through Terminal, "command not found"

  1. Simply install adb with brew

    brew cask install android-platform-tools

  2. Check if adb is installed

    adb devices

How can I get the number of days between 2 dates in Oracle 11g?

This will work i have tested myself.
It gives difference between sysdate and date fetched from column admitdate

  TABLE SCHEMA:
    CREATE TABLE "ADMIN"."DUESTESTING" 
    (   
  "TOTAL" NUMBER(*,0), 
"DUES" NUMBER(*,0), 
"ADMITDATE" TIMESTAMP (6), 
"DISCHARGEDATE" TIMESTAMP (6)
    )

EXAMPLE:
select TO_NUMBER(trunc(sysdate) - to_date(to_char(admitdate, 'yyyy-mm-dd'),'yyyy-mm-dd')) from admin.duestesting where total=300

Use ASP.NET MVC validation with jquery ajax?

Client Side

Using the jQuery.validate library should be pretty simple to set up.

Specify the following settings in your Web.config file:

<appSettings>
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings>

When you build up your view, you would define things like this:

@Html.LabelFor(Model => Model.EditPostViewModel.Title, true)
@Html.TextBoxFor(Model => Model.EditPostViewModel.Title, 
                                new { @class = "tb1", @Style = "width:400px;" })
@Html.ValidationMessageFor(Model => Model.EditPostViewModel.Title)

NOTE: These need to be defined within a form element

Then you would need to include the following libraries:

<script src='@Url.Content("~/Scripts/jquery.validate.js")' type='text/javascript'></script>
<script src='@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")' type='text/javascript'></script>

This should be able to set you up for client side validation

Resources

Server Side

NOTE: This is only for additional server side validation on top of jQuery.validation library

Perhaps something like this could help:

[ValidateAjax]
public JsonResult Edit(EditPostViewModel data)
{
    //Save data
    return Json(new { Success = true } );
}

Where ValidateAjax is an attribute defined as:

public class ValidateAjaxAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
            return;

        var modelState = filterContext.Controller.ViewData.ModelState;
        if (!modelState.IsValid)
        {
            var errorModel = 
                    from x in modelState.Keys
                    where modelState[x].Errors.Count > 0
                    select new
                           {
                               key = x,
                               errors = modelState[x].Errors.
                                                      Select(y => y.ErrorMessage).
                                                      ToArray()
                           };
            filterContext.Result = new JsonResult()
                                       {
                                           Data = errorModel
                                       };
            filterContext.HttpContext.Response.StatusCode = 
                                                  (int) HttpStatusCode.BadRequest;
        }
    }
}

What this does is return a JSON object specifying all of your model errors.

Example response would be

[{
    "key":"Name",
    "errors":["The Name field is required."]
},
{
    "key":"Description",
    "errors":["The Description field is required."]
}]

This would be returned to your error handling callback of the $.ajax call

You can loop through the returned data to set the error messages as needed based on the Keys returned (I think something like $('input[name="' + err.key + '"]') would find your input element

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Use underscore inside Angular controllers

If you don't mind using lodash try out https://github.com/rockabox/ng-lodash it wraps lodash completely so it is the only dependency and you don't need to load any other script files such as lodash.

Lodash is completely off of the window scope and no "hoping" that it's been loaded prior to your module.

Check if object value exists within a Javascript array of objects and if not add a new object to array

Here is an ES6 method chain using .map() and .includes():

const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

const checkForUser = (newUsername) => {
      arr.map(user => {
        return user.username
      }).includes(newUsername)
    }

if (!checkForUser('fred')){
  // add fred
}
  1. Map over existing users to create array of username strings.
  2. Check if that array of usernames includes the new username
  3. If it's not present, add the new user

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

Follow the tutorial you listed above for setting up your key preferences in iterm2.

  1. Create a new shorcut key
  2. Choose "Send escape sequence" as the action
  3. Then, to set cmd-left, in the text below that:
    • Enter [H for line start
      OR
    • Enter [F for line end

Assign a variable inside a Block to a variable outside a Block

To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-

__block Person *aPerson = nil;

jQuery Set Select Index

you can set selectoption variable value dynamically as well as option will be selected.You can try following code

code:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML CODE:

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

list.clear() vs list = new ArrayList<Integer>();

Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.

List al= new ArrayList();
        for(int i=0;i<100;i++)
        {
            //List al= new ArrayList();

            for(int j=0;j<10;j++)
            {
                al.add(Integer.parseInt("" +j+i));
                //System.out.println("Obj val " +al.get(j));
            }
            //System.out.println("Hashcode : " + al.hashCode());
            al.clear();

        }

and to my surprise. the memory allocation didnt change much.

With New Arraylist approach.

Before loop total free memory: 64,909 ::

After loop total free memory: 64,775 ::

with Clear approach,

Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::

So this says there is not much difference in using arraylist.clear from memory utilization perspective.

CardView Corner Radius

You can put your ImageView inside a CardView, and add those properties to the ImageView:

android:cropToPadding="true"
android:paddingBottom="15dp"

That way you will get rid of the rounded bottom corner, but keep in mind that this comes in the price of having a small portion of your image cut off.

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

@Media min-width & max-width

The correct value for the content attribute should include initial-scale instead:

_x000D_
_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
                                                   ^^^^^^^^^^^^^^^
_x000D_
_x000D_
_x000D_

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.

To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.

And for reference on how to use this and iterate through for a certain file extension as example you could do this:

#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
    return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
        || Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion

private void button1_Click(object sender, EventArgs e)
{
    //NOTE: I recommend you add path checking first here, added the below as example ONLY.
    string ZIPfileLocationHere = @"C:\Users\Name\Desktop\test.zip";
    string EXTRACTIONLocationHere = @"C:\Users\Name\Desktop";

    //Opens existing zip file.
    ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);

    //Read all directory contents.
    List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

    foreach (ZipStorer.ZipFileEntry entry in dir)
    {
        try
        {
            //If the files in the zip are "*.png or *.PNG" extract them.
            string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
            if (HasPNGExtension(path))
            {
                //Extract the file.
                zip.ExtractFile(entry, path);
            }
        }
        catch (InvalidDataException)
        {
            MessageBox.Show("Error: The ZIP file is invalid or corrupted");
            continue;
        }
        catch
        {
            MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
            continue;
        }
    }
    zip.Close();
}

Stash just a single file

I think stash -p is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:

Stash is really just a very simple alternative to the only slightly more complex branch sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.

# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master

go about and do what you want, and then later simply rebase and/or merge the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.

Oracle "Partition By" Keyword

I think, this example suggests a small nuance on how the partitioning works and how group by works. My example is from Oracle 12, if my example happens to be a compiling bug.

I tried :

SELECT t.data_key
,      SUM ( CASE when t.state = 'A' THEN 1 ELSE 0 END) 
OVER   (PARTITION BY t.data_key) count_a_rows
,      SUM ( CASE when t.state = 'B' THEN 1 ELSE 0 END) 
OVER   (PARTITION BY t.data_key) count_b_rows
,      SUM ( CASE when t.state = 'C' THEN 1 ELSE 0 END) 
OVER   (PARTITION BY t.data_key) count_c_rows
,      COUNT (1) total_rows
from mytable t
group by t.data_key  ---- This does not compile as the compiler feels that t.state isn't in the group by and doesn't recognize the aggregation I'm looking for

This however works as expected :

SELECT distinct t.data_key
,      SUM ( CASE when t.state = 'A' THEN 1 ELSE 0 END) 
OVER   (PARTITION BY t.data_key) count_a_rows
,      SUM ( CASE when t.state = 'B' THEN 1 ELSE 0 END) 
OVER   (PARTITION BY t.data_key) count_b_rows
,      SUM ( CASE when t.state = 'C' THEN 1 ELSE 0 END) 
OVER   (PARTITION BY t.data_key) count_c_rows
,      COUNT (1) total_rows
from mytable t;

Producing the number of elements in each state based on the external key "data_key". So, if, data_key = 'APPLE' had 3 rows with state 'A', 2 rows with state 'B', a row with state 'C', the corresponding row for 'APPLE' would be 'APPLE', 3, 2, 1, 6.

How to sign an android apk file

Here is a guide on how to manually sign an APK. It includes info about the new apk-signer introduced in build-tools 24.0.3 (10/2016)

Automated Process:

Use this tool (uses the new apksigner from Google):

https://github.com/patrickfav/uber-apk-signer

Disclaimer: Im the developer :)

Manual Process:

Step 1: Generate Keystore (only once)

You need to generate a keystore once and use it to sign your unsigned apk. Use the keytool provided by the JDK found in %JAVA_HOME%/bin/

keytool -genkey -v -keystore my.keystore -keyalg RSA -keysize 2048 -validity 10000 -alias app

Step 2 or 4: Zipalign

zipalign which is a tool provided by the Android SDK found in e.g. %ANDROID_HOME%/sdk/build-tools/24.0.2/ is a mandatory optimzation step if you want to upload the apk to the Play Store.

zipalign -p 4 my.apk my-aligned.apk

Note: when using the old jarsigner you need to zipalign AFTER signing. When using the new apksigner method you do it BEFORE signing (confusing, I know). Invoking zipalign before apksigner works fine because apksigner preserves APK alignment and compression (unlike jarsigner).

You can verify the alignment with

zipalign -c 4 my-aligned.apk

Step 3: Sign & Verify

Using build-tools 24.0.2 and older

Use jarsigner which, like the keytool, comes with the JDK distribution found in %JAVA_HOME%/bin/ and use it like so:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my.keystore my-app.apk my_alias_name

and can be verified with

jarsigner -verify -verbose my_application.apk

Using build-tools 24.0.3 and newer

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files (See here and here for more details). Threfore Google implemented their own apk signer called apksigner (duh!) The script file can be found in %ANDROID_HOME%/sdk/build-tools/24.0.3/ (the .jar is in the /lib subfolder). Use it like this

apksigner sign --ks my.keystore my-app.apk --ks-key-alias alias_name

and can be verified with

apksigner verify my-app.apk

The official documentation can be found here.

Using Mysql in the command line in osx - command not found?

for me the following commands worked:

$ brew install mysql

$ brew services start mysql

Why don’t my SVG images scale using the CSS "width" property?

I had to figure it out myself but some svgs your need to match the viewBox & width+height in.

E.g. if it already has width="x" height="y" then =>

add <svg ... viewBox="0 0 [width] [height]">

and the opposite.

After that it will scale with <svg ... style="width: xxx; height: yyy;">

List file names based on a filename pattern and file content?

It can be done without find as well by using grep's "--include" option.

grep man page says:

--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).

So to do a recursive search for a string in a file matching a specific pattern, it will look something like this:

grep -r --include=<pattern> <string> <directory>

For example, to recursively search for string "mytarget" in all Makefiles:

grep -r --include="Makefile" "mytarget" ./

Or to search in all files starting with "Make" in filename:

grep -r --include="Make*" "mytarget" ./

How to capitalize the first letter of text in a TextView in an Android Application

The accepted answer is good, but if you are using it to get values from a textView in android, it would be good to check if the string is empty. If the string is empty it would throw an exception.

private String capitizeString(String name){
    String captilizedString="";
    if(!name.trim().equals("")){
       captilizedString = name.substring(0,1).toUpperCase() + name.substring(1);
    }
    return captilizedString;
}

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

Is there a way of setting culture for a whole application? All current threads and new threads?

Working solution to set CultureInfo for all threads and windows.

  1. Open App.xaml file and add a new "Startup" attribute to assign startup event handler for the app:
<Application ........
             Startup="Application_Startup"
>
  1. Open App.xaml.cs file and add this code to created startup handler (Application_Startup in this case). The class App will look like this:
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-US");
            System.Globalization.CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
            System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;
        }
    }

The module was expected to contain an assembly manifest

In my case, I was using InstallUtil.exe which was causing an error. To install the .Net Core service in window best way to use sc command.

More information here Exe installation throwing error The module was expected to contain an assembly manifest .Net Core

React - Component Full Screen (with height 100%)

try <div style = {{height:"100vh"}}> </div>

Presenting modal in iOS 13 fullscreen

This worked for me

let vc = self.storyboard?.instantiateViewController(withIdentifier: "storyboardID_cameraview1") as! CameraViewController
  
vc.modalPresentationStyle = .fullScreen
    
self.present(vc, animated: true, completion: nil)`

DBCC CHECKIDENT Sets Identity to 0

See also here: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/06/26/fun-with-dbcc-chekident.aspx

This is documented behavior, why do you run CHECKIDENT if you recreate the table, in that case skip the step or use TRUNCATE (if you don't have FK relationships)

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

Entity Framework 6 Code first Default value

After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.

1- Create custom code generator and override Generate for a ColumnModel.

   public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{

    protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
    {

        if (column.Annotations.Keys.Contains("Default"))
        {
            var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
            column.DefaultValue = value;
        }


        base.Generate(column, writer, emitName);
    }

}

2- Assign the new code generator:

public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
    public Configuration()
    {
        CodeGenerator = new ExtendedMigrationCodeGenerator();
        AutomaticMigrationsEnabled = false;
    }
}

3- Use fluent api to created the Annotation:

public static void Configure(DbModelBuilder builder){    
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);            
}

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

How to change the Text color of Menu item in Android?

The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :

First, look at the definition of the themes in Android :

<style name="Theme.IconMenu">
<!-- Menu/item attributes -->
<item name="android:itemTextAppearance">@android:style/TextAppearance.Widget.IconMenu.Item</item>
<item name="android:itemBackground">@android:drawable/menu_selector</item>
<item name="android:itemIconDisabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:horizontalDivider">@android:drawable/divider_horizontal_bright</item>
<item name="android:verticalDivider">@android:drawable/divider_vertical_bright</item>
<item name="android:windowAnimationStyle">@android:style/Animation.OptionsPanel</item>
<item name="android:moreIcon">@android:drawable/ic_menu_more</item>
<item name="android:background">@null</item>
</style>

So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :

<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>

So now we have the name of the color in question, if you look in the color folder of the resources of the system :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/bright_foreground_light_disabled" /> 
<item android:state_window_focused="false" android:color="@android:color/bright_foreground_light" /> 
<item android:state_pressed="true" android:color="@android:color/bright_foreground_light" /> 
<item android:state_selected="true" android:color="@android:color/bright_foreground_light" /> 
<item android:color="@android:color/bright_foreground_light" /> 
<!--  not selected --> 
</selector>

Finally, here is what you need to do :

Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!

Datetime in C# add days

You need to catch the return value.

The DateTime.AddDays method returns an object who's value is the sum of the date and time of the instance and the added value.

endDate = endDate.AddDays(addedDays);

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

How can I override Bootstrap CSS styles?

  1. Inspect the target button on the console.
  2. Go to elements tab then hover over the code and be sure to find the default id or class used by the bootstrap.
  3. Use jQuery/javascript to overwrite the style/text by calling the function.

See this example:

  $(document).ready(function(){
      $(".dropdown-toggle").css({ 
        "color": "#212529",
        "background-color": "#ffc107",
        "border-color": "#ffc107"
       });
      $(".multiselect-selected-text").text('Select Tags');
  });

What is the first character in the sort order used by Windows Explorer?

If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:

Behavior of this function, and therefore the results it returns, can change from release to release. ...

Python argparse command line flags without arguments

Adding a quick snippet to have it ready to execute:

Source: myparser.py

import argparse
parser = argparse.ArgumentParser(description="Flip a switch by setting a flag")
parser.add_argument('-w', action='store_true')

args = parser.parse_args()
print args.w

Usage:

python myparser.py -w
>> True

Blocks and yields in Ruby

It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.

I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:

>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"

Whereas 1.9 would give you:

>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"

I don't have 1.9 on this machine so the above might have an error in it.

How to ssh from within a bash script?

There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )

# ~/.ssh/config 
ControlMaster auto
ControlPath ~/.ssh/pool/%r@%h

then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.

You can then stop your script from working when somebody has not already opened the channel by:

ssh ... -o KbdInteractiveAuthentication=no ....

LINQ to read XML

Try this.

using System.Xml.Linq;

void Main()
{
    StringBuilder result = new StringBuilder();

    //Load xml
    XDocument xdoc = XDocument.Load("data.xml");

    //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
               select new { 
                   Header = lv1.Attribute("name").Value,
                   Children = lv1.Descendants("level2")
               };

    //Loop through results
    foreach (var lv1 in lv1s){
            result.AppendLine(lv1.Header);
            foreach(var lv2 in lv1.Children)
                 result.AppendLine("     " + lv2.Attribute("name").Value);
    }

    Console.WriteLine(result);
}

DISTINCT clause with WHERE

You can use ROW_NUMBER(). You can specify where conditions as well. (e.g. Name LIKE'MyName% in the following query)

SELECT  *
FROM    (SELECT ID, Name, Email,
            ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID) AS RowNumber
     FROM   MyTable
     WHERE  Name LIKE 'MyName%') AS a
WHERE   a.RowNumber = 1

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

pandas >= 0.24

Deprecate your usage of .values in favour of these methods!

From v0.24.0 onwards, we will have two brand spanking new, preferred methods for obtaining NumPy arrays from Index, Series, and DataFrame objects: they are to_numpy(), and .array. Regarding usage, the docs mention:

We haven’t removed or deprecated Series.values or DataFrame.values, but we highly recommend and using .array or .to_numpy() instead.

See this section of the v0.24.0 release notes for more information.


to_numpy() Method

df.index.to_numpy()
# array(['a', 'b'], dtype=object)

df['A'].to_numpy()
#  array([1, 4])

By default, a view is returned. Any modifications made will affect the original.

v = df.index.to_numpy()
v[0] = -1

df
    A  B
-1  1  2
b   4  5

If you need a copy instead, use to_numpy(copy=True);

v = df.index.to_numpy(copy=True)
v[-1] = -123

df
   A  B
a  1  2
b  4  5

Note that this function also works for DataFrames (while .array does not).


array Attribute
This attribute returns an ExtensionArray object that backs the Index/Series.

pd.__version__
# '0.24.0rc1'

# Setup.
df = pd.DataFrame([[1, 2], [4, 5]], columns=['A', 'B'], index=['a', 'b'])
df

   A  B
a  1  2
b  4  5

df.index.array    
# <PandasArray>
# ['a', 'b']
# Length: 2, dtype: object

df['A'].array
# <PandasArray>
# [1, 4]
# Length: 2, dtype: int64

From here, it is possible to get a list using list:

list(df.index.array)
# ['a', 'b']

list(df['A'].array)
# [1, 4]

or, just directly call .tolist():

df.index.tolist()
# ['a', 'b']

df['A'].tolist()
# [1, 4]

Regarding what is returned, the docs mention,

For Series and Indexes backed by normal NumPy arrays, Series.array will return a new arrays.PandasArray, which is a thin (no-copy) wrapper around a numpy.ndarray. arrays.PandasArray isn’t especially useful on its own, but it does provide the same interface as any extension array defined in pandas or by a third-party library.

So, to summarise, .array will return either

  1. The existing ExtensionArray backing the Index/Series, or
  2. If there is a NumPy array backing the series, a new ExtensionArray object is created as a thin wrapper over the underlying array.

Rationale for adding TWO new methods
These functions were added as a result of discussions under two GitHub issues GH19954 and GH23623.

Specifically, the docs mention the rationale:

[...] with .values it was unclear whether the returned value would be the actual array, some transformation of it, or one of pandas custom arrays (like Categorical). For example, with PeriodIndex, .values generates a new ndarray of period objects each time. [...]

These two functions aim to improve the consistency of the API, which is a major step in the right direction.

Lastly, .values will not be deprecated in the current version, but I expect this may happen at some point in the future, so I would urge users to migrate towards the newer API, as soon as you can.

Get the previous month's first and last day dates in c#

var today = DateTime.Today;
var month = new DateTime(today.Year, today.Month, 1);       
var first = month.AddMonths(-1);
var last = month.AddDays(-1);

In-line them if you really need one or two lines.

How to filter object array based on attributes?

I'm surprised no one has posted the one-line response:

const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

...and just so you can read it easier:

const filteredHomes = json.homes.filter( x => 
  x.price <= 1000 && 
  x.sqft >= 500 && 
  x.num_of_beds >=2 && 
  x.num_of_baths >= 2.5
);

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

Save file to specific folder with curl command

I don't think you can give a path to curl, but you can CD to the location, download and CD back.

cd target/path && { curl -O URL ; cd -; }

Or using subshell.

(cd target/path && curl -O URL)

Both ways will only download if path exists. -O keeps remote file name. After download it will return to original location.

If you need to set filename explicitly, you can use small -o option:

curl -o target/path/filename URL

HTML input file selection event not firing upon selecting the same file

Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).

          scope.onClick = function() {
            input[0].value = "";
                input.click();
            };

Move a view up only when the keyboard covers an input field

Why not implement this in a UITableViewController instead? The keyboard won't hide any text fields when its shown.

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

Can't bind to 'dataSource' since it isn't a known property of 'table'

Remember to add MatTableModule in your app.module's imports i.e.

In Angular 9+

import { MatTableModule } from '@angular/material/table'  

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ]
})

Less than Angular 9

import { MatTableModule } from '@angular/material'  

@NgModule({
  imports: [
    // ...
    MatTableModule
    // ...
  ]
})

How to Clone Objects

What you are looking is for a Cloning. You will need to Implement IClonable and then do the Cloning.

Example:

class Person() : ICloneable
{
    public string head;
    public string feet; 

    #region ICloneable Members

    public object Clone()
    {
        return this.MemberwiseClone();
    }

    #endregion
}

Then You can simply call the Clone method to do a ShallowCopy (In this particular Case also a DeepCopy)

Person a = new Person() { head = "big", feet = "small" };
Person b = (Person) a.Clone();  

You can use the MemberwiseClone method of the Object class to do the cloning.

Get Absolute URL from Relative path (refactored method)

The final version taking care of all previous complaints (ports, logical url, relative url, existing absolute url...etc.) considering the current handler is the page:

public static string ConvertToAbsoluteUrl(string url)
{
    if (!IsAbsoluteUrl(url))
    {
        if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Handler is System.Web.UI.Page)
        {
            var originalUrl = HttpContext.Current.Request.Url;
            return string.Format("{0}://{1}{2}{3}", originalUrl.Scheme, originalUrl.Host, !originalUrl.IsDefaultPort ? (":" + originalUrl.Port) : string.Empty, ((System.Web.UI.Page)HttpContext.Current.Handler).ResolveUrl(url));
        }
        throw new Exception("Invalid context!");
    }
    else
        return url;
}

private static bool IsAbsoluteUrl(string url)
{
    Uri result;
    return Uri.TryCreate(url, UriKind.Absolute, out result);
}

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

Grab a segment of an array in Java without creating a new array on heap

How about a thin List wrapper?

List<Byte> getSubArrayList(byte[] array, int offset, int size) {
   return new AbstractList<Byte>() {
      Byte get(int index) {
         if (index < 0 || index >= size) 
           throw new IndexOutOfBoundsException();
         return array[offset+index];
      }
      int size() {
         return size;
      }
   };
}

(Untested)

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

How to use JavaScript regex over multiple lines?

I have tested it (Chrome) and it working for me( both [^] and [^\0]), by changing the dot (.) by either [^\0] or [^] , because dot doesn't match line break (See here: http://www.regular-expressions.info/dot.html).

_x000D_
_x000D_
var ss= "<pre>aaaa\nbbb\nccc</pre>ddd";_x000D_
var arr= ss.match( /<pre[^\0]*?<\/pre>/gm );_x000D_
alert(arr);     //Working
_x000D_
_x000D_
_x000D_

jQuery get the name of a select option

In your codethis refers to the select element not to the selected option

to refer the selected option you can do this -

$(this).find('option:selected').attr("name");

Storing images in SQL Server?

In my experience, storing to the url to the images stored in another location is the best way for a simple project.

how to hide a vertical scroll bar when not needed

Add this class in .css class

.scrol  { 
font: bold 14px Arial; 
border:1px solid black; 
width:100% ; 
color:#616D7E; 
height:20px; 
overflow:scroll; 
overflow-y:scroll;
overflow-x:hidden;
}

and use the class in div. like here.

<div> <p class = "scrol" id = "title">-</p></div>

I have attached image , you see the out put of the above code enter image description here

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Declaring static constants in ES6 classes?

You can create a way to define static constants on a class using an odd feature of ES6 classes. Since statics are inherited by their subclasses, you can do the following:

const withConsts = (map, BaseClass = Object) => {
  class ConstClass extends BaseClass { }
  Object.keys(map).forEach(key => {
    Object.defineProperty(ConstClass, key, {
      value: map[key],
      writable : false,
      enumerable : true,
      configurable : false
    });
  });
  return ConstClass;
};

class MyClass extends withConsts({ MY_CONST: 'this is defined' }) {
  foo() {
    console.log(MyClass.MY_CONST);
  }
}

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

It works for me.....

I went to the settings on my phone and deleted my gmail account then re-added and synced the account and it worked for me.

settings>accounts>delete account settings>accounts>add account>sync and follow screen prompts

hope it works for you, i was receiving the df-dferh-01 error as well and couldnt buy in app purchases and this did the trick

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

Reload the current page:
F5
or
CTRL + R


Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R

jQuery if div contains this text, replace that part of the text

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

<div class="text_div">
    This div <span>contains</span> some text.
</div>

You can then easily change its contents with jQuery:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

PHP, get file name without file extension

If you don't know which extension you have, then you can try this:

$ext = strtolower(substr('yourFileName.ext', strrpos('yourFileName.ext', '.') + 1));
echo basename('yourFileName.ext','.'.$ext); // output: "youFileName" only

Working with all possibilities:

image.jpg // output: "image"
filename.image.png // output: "filename.image"
index.php // output: "index"

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

Django - Did you forget to register or load this tag?

You need to change:

{% endblock content %}

to

{% endblock %}

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

In the (admitted rare) case that a local datatime is wanted (I, for example, store local time in one of my database since all I care is what time in the day is was and I don't keep track of where I was in term of time zones...), you can define the column as

"timestamp" TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M','now', 'localtime'))

The %Y-%m-%dT%H:%M part is of course optional; it is just how I like my time to be stored. [Also, if my impression is correct, there is no "DATETIME" datatype in sqlite, so it does not really matter whether TEXT or DATETIME is used as data type in column declaration.]

Create a menu Bar in WPF?

<StackPanel VerticalAlignment="Top">
    <Menu Width="Auto" Height="20">
        <MenuItem Header="_File">
            <MenuItem x:Name="AppExit" Header="E_xit" HorizontalAlignment="Left" Width="140" Click="AppExit_Click"/>
        </MenuItem>
        <MenuItem Header="_Tools">
            <MenuItem x:Name="Options" Header="_Options" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
        <MenuItem Header="_Help">
            <MenuItem x:Name="About" Header="&amp;About" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
    </Menu>
    <Label Content="Label"/>
</StackPanel>