Programs & Examples On #Dokan

Microsoft Windows library to program file system drivers in user space

How can I transition height: 0; to height: auto; using CSS?

Source

This is so late, but for the sake of future researchers, I'll post my answer. I believe most of you looking for height : 0 is for the sake of td or tr toggle transition animation or something similar. But it is not possible to make it using just height, max-height, line-height on td or tr, but you can use the following tricks to make it:

  • Wrapping all td contents into div and use height: 0 + overflow: hidden + white-space: nowrap on divs , and the animation/transition of your choice
  • Use transform: scaleY ( ?° ?? ?°)

How to use executables from a package installed locally in node_modules?

update: If you're on the recent npm (version >5.2)

You can use:

npx <command>

npx looks for command in .bin directory of your node_modules

old answer:

For Windows

Store the following in a file called npm-exec.bat and add it to your %PATH%

@echo off
set cmd="npm bin"
FOR /F "tokens=*" %%i IN (' %cmd% ') DO SET modules=%%i
"%modules%"\%*

Usage

Then you can use it like npm-exec <command> <arg0> <arg1> ...

For example

To execute wdio installed in local node_modules directory, do:

npm-exec wdio wdio.conf.js

i.e. it will run .\node_modules\.bin\wdio wdio.conf.js

What is the difference between the dot (.) operator and -> in C++?

The -> operator is used when we are working with a pointer and the dot is used otherwise. So if we have a struct class like:

struct class{ int num_students; int yr_grad; };

and we have an instance of a class* curr_class (class pointer), then to get access to number of students we would do

cout << curr_class->num_students << endl;

In case we had a simple class object , say class_2016, we would do

cout << class_2016.num_students << endl;

For the pointer to class the -> operator is equivalent to

(*obj).mem_var

Note: For a class, the way to access member functions of the class will also be the same way

Append an int to a std::string

I have a feeling that your ClientID is not of a string type (zero-terminated char* or std::string) but some integral type (e.g. int) so you need to convert number to the string first:

std::stringstream ss;
ss << ClientID;
query.append(ss.str());

But you can use operator+ as well (instead of append):

query += ss.str();

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

Hello here is a simple solution,

Just go to File -> Convert to a C/C++ Autotools Project Select your project files appropriately.

Inclusions will be added to your project file

Static Block in Java

A static block executes once in the life cycle of any program, another property of static block is that it executes before the main method.

Hiding the address bar of a browser (popup)

It's different in every browser.

Some years ago, what you tried, was right. But nowadays it is regarded as a security risk by browser vendors that one cannot see the browsers address bar (for phishing reasons) and so they (or most of them) made the decision to always show the browser address bar. Which is good in my eyes.

How can I format decimal property to currency?

A decimal type can not contain formatting information. You can create another property, say FormattedProperty of a string type that does what you want.

Git add all subdirectories

I can't say for sure if this is the case, but what appeared to be a problem for me was having .gitignore files in some of the subdirectories. Again, I can't guarantee this, but everything worked after these were deleted.

How to check the extension of a filename in a bash script?

You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

file -ib "$file"

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

passing form data to another HTML page

Use "Get" Method to send the value of a particular field through the browser:

<form action="display.html" method="GET">
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>

JPA OneToMany not deleting child

You can try this:

@OneToOne(cascade = CascadeType.REFRESH) 

or

@OneToMany(cascade = CascadeType.REFRESH)

How to adjust layout when soft keyboard appears

Add this line in your Manifest where your Activity is called

android:windowSoftInputMode="adjustPan|adjustResize"

or

you can add this line in your onCreate

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

If you have no FIRST/FIRST conflicts and no FIRST/FOLLOW conflicts, your grammar is LL(1).

An example of a FIRST/FIRST conflict:

S -> Xb | Yc
X -> a 
Y -> a 

By seeing only the first input symbol a, you cannot know whether to apply the production S -> Xb or S -> Yc, because a is in the FIRST set of both X and Y.

An example of a FIRST/FOLLOW conflict:

S -> AB 
A -> fe | epsilon 
B -> fg 

By seeing only the first input symbol f, you cannot decide whether to apply the production A -> fe or A -> epsilon, because f is in both the FIRST set of A and the FOLLOW set of A (A can be parsed as epsilon and B as f).

Notice that if you have no epsilon-productions you cannot have a FIRST/FOLLOW conflict.

HTML colspan in CSS

To provide an up-to-date answer: The best way to do this today is to use css grid layout like this:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto;
  grid-template-areas: 
    "top-left top-middle top-right"
    "bottom bottom bottom"
}

.item-a {
  grid-area: top-left;
}
.item-b {
  grid-area: top-middle;
}
.item-c {
  grid-area: top-right;
}
.item-d {
  grid-area: bottom;
}

and the HTML

<div class="container">
  <div class="item-a">1</div>
  <div class="item-b">2</div>
  <div class="item-c">3</div>
  <div class="item-d">123</div>
</div>

How to get current user, and how to use User class in MVC5?

If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

...

User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

If you're in a class other than a Controller, use

HttpContext.Current.User.Identity.GetUserId();

In the default template of MVC 5, user ID is a GUID stored as a string.

No best practice yet, but found some valuable info on extending the user profile:

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

Derived from Denis Tulskiy's answer, this method generates the seed.

public static long generateSeed(String goal, long start, long finish) {
    char[] input = goal.toCharArray();
    char[] pool = new char[input.length];
    label:
        for (long seed = start; seed < finish; seed++) {
            Random random = new Random(seed);

            for (int i = 0; i < input.length; i++)
                pool[i] = (char) (random.nextInt(27)+'`');

            if (random.nextInt(27) == 0) {
                for (int i = 0; i < input.length; i++) {
                    if (input[i] != pool[i])
                        continue label;
                }
                return seed;
            }

        }

    throw new NoSuchElementException("Sorry :/");
}

image.onload event and browser cache

If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete also.

code sample:

$("img").one("load", function() {
   //do stuff
}).each(function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
     $(this).load();
});

Which is the default location for keystore/truststore of Java applications?

Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).

javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456

Then load the properties to your environment from your code. This makes your application configurable.

FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);

Increase max execution time for php

well, there are two way to change max_execution_time.
1. You can directly set it in php.ini file.
2. Secondly, you can add following line in your code.

ini_set('max_execution_time', '100')

Php multiple delimiters in explode

Try about using:

$output = preg_split('/ (@|vs) /', $input);

Create Word Document using PHP in Linux

OpenOffice templates + OOo command line interface.

  1. Create manually an ODT template with placeholders, like [%value-to-replace%]
  2. When instantiating the template with real data in PHP, unzip the template ODT (it's a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.
  3. Zip the ODT back
  4. Run the conversion ODT -> DOC via OpenOffice command line interface.

There are tools and libraries available to ease each of those steps.

May be that helps.

How can I make this try_files directive work?

a very common try_files line which can be applied on your condition is

location / {
    try_files $uri $uri/ /test/index.html;
}

you probably understand the first part, location / matches all locations, unless it's matched by a more specific location, like location /test for example

The second part ( the try_files ) means when you receive a URI that's matched by this block try $uri first, for example http://example.com/images/image.jpg nginx will try to check if there's a file inside /images called image.jpg if found it will serve it first.

Second condition is $uri/ which means if you didn't find the first condition $uri try the URI as a directory, for example http://example.com/images/, ngixn will first check if a file called images exists then it wont find it, then goes to second check $uri/ and see if there's a directory called images exists then it will try serving it.

Side note: if you don't have autoindex on you'll probably get a 403 forbidden error, because directory listing is forbidden by default.

EDIT: I forgot to mention that if you have index defined, nginx will try to check if the index exists inside this folder before trying directory listing.

Third condition /test/index.html is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html inside the folder test and serve it if it exists.

If the third condition fails too, then nginx will serve the 404 error page.

Also there's something called named locations, like this

location @error {
}

You can call it with try_files like this

try_files $uri $uri/ @error;

TIP: If you only have 1 condition you want to serve, like for example inside folder images you only want to either serve the image or go to 404 error, you can write a line like this

location /images {
    try_files $uri =404;
}

which means either serve the file or serve a 404 error, you can't use only $uri by it self without =404 because you need to have a fallback option.
You can also choose which ever error code you want, like for example:

location /images {
    try_files $uri =403;
}

This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..

What is an opaque response, and what purpose does it serve?

There's also solution for Node JS app. CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.

The url to proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".

This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example to avoid a direct visit from the browser. https://robwu.nl/cors-anywhere.html

Check if file is already open

I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.

You might get some mileage out of java.nio.channels.FileLock, although the javadoc is loaded with caveats.

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

What are the situations where "yield from" is useful?

Every situation where you have a loop like this:

for x in subgenerator:
  yield x

As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the .throw()/.send()/.close() mechanisms introduced by PEP 342. To do this properly, rather complicated code is necessary.

What is the classic use case?

Consider that you want to extract information from a recursive data structure. Let's say we want to get all leaf nodes in a tree:

def traverse_tree(node):
  if not node.children:
    yield node
  for child in node.children:
    yield from traverse_tree(child)

Even more important is the fact that until the yield from, there was no simple method of refactoring the generator code. Suppose you have a (senseless) generator like this:

def get_list_values(lst):
  for item in lst:
    yield int(item)
  for item in lst:
    yield str(item)
  for item in lst:
    yield float(item)

Now you decide to factor out these loops into separate generators. Without yield from, this is ugly, up to the point where you will think twice whether you actually want to do it. With yield from, it's actually nice to look at:

def get_list_values(lst):
  for sub in [get_list_values_as_int, 
              get_list_values_as_str, 
              get_list_values_as_float]:
    yield from sub(lst)

Why is it compared to micro-threads?

I think what this section in the PEP is talking about is that every generator does have its own isolated execution context. Together with the fact that execution is switched between the generator-iterator and the caller using yield and __next__(), respectively, this is similar to threads, where the operating system switches the executing thread from time to time, along with the execution context (stack, registers, ...).

The effect of this is also comparable: Both the generator-iterator and the caller progress in their execution state at the same time, their executions are interleaved. For example, if the generator does some kind of computation and the caller prints out the results, you'll see the results as soon as they're available. This is a form of concurrency.

That analogy isn't anything specific to yield from, though - it's rather a general property of generators in Python.

What primitive data type is time_t?

It's platform-specific. But you can cast it to a known type.

printf("%lld\n", (long long) time(NULL));

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

Rotate camera in Three.js with mouse

Here's a project with a rotating camera. Looking through the source it seems to just move the camera position in a circle.

function onDocumentMouseMove( event ) {

    event.preventDefault();

    if ( isMouseDown ) {

        theta = - ( ( event.clientX - onMouseDownPosition.x ) * 0.5 )
                + onMouseDownTheta;
        phi = ( ( event.clientY - onMouseDownPosition.y ) * 0.5 )
              + onMouseDownPhi;

        phi = Math.min( 180, Math.max( 0, phi ) );

        camera.position.x = radious * Math.sin( theta * Math.PI / 360 )
                            * Math.cos( phi * Math.PI / 360 );
        camera.position.y = radious * Math.sin( phi * Math.PI / 360 );
        camera.position.z = radious * Math.cos( theta * Math.PI / 360 )
                            * Math.cos( phi * Math.PI / 360 );
        camera.updateMatrix();

    }

    mouse3D = projector.unprojectVector(
        new THREE.Vector3(
            ( event.clientX / renderer.domElement.width ) * 2 - 1,
            - ( event.clientY / renderer.domElement.height ) * 2 + 1,
            0.5
        ),
        camera
    );
    ray.direction = mouse3D.subSelf( camera.position ).normalize();

    interact();
    render();

}

Here's another demo and in this one I think it just creates a new THREE.TrackballControls object with the camera as a parameter, which is probably the better way to go.

controls = new THREE.TrackballControls( camera );
controls.target.set( 0, 0, 0 )

Difference between abstraction and encapsulation?

Let me try this with simple code example

Abstraction = Data Hiding + Encapsulation

 // Abstraction
    interface IOperation
    {
        int GetSumOfNumbers();
    }
    internal class OperationEven : IOperation
    {
        // data hiding
        private IEnumerable<int> numbers;

        public OperationEven(IEnumerable<int> numbers)
        {
            this.numbers = numbers;
        }
        // Encapsulation
        public int GetSumOfNumbers()
        {
            return this.numbers.Where(i => i % 2 == 0).Sum();
        }
    }

nuget 'packages' element is not declared warning

This happens because VS doesn't know the schema of this file. Note that this file is more of an implementation detail, and not something you normally need to open directly. Instead, you can use the NuGet dialog to manage the packages installed in a project.

CodeIgniter: How to use WHERE clause and OR clause

You can use this :

$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

  1. If you have released to Apple TestFlight for testing

    You have to click the link each time and select No, only after that, your tester can see the build. This is quite annoying if you want to get your build delivered as soon as possible.

    enter image description here

  2. Do this for the next build, (If do this before the build then this error will not occur)

The solution is add the following setting to your iOS Info.plist:

    <key>ITSAppUsesNonExemptEncryption</key>
    <false/>

enter image description here

Can not add "Missing Compliance", see this Missing Compliance

Get decimal portion of a number with JavaScript

I am using:

var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;

if( str.indexOf('.') != -1 ){ //check if has decimal
    var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}

Input: -556.123444444

Result: 123444444

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

I had an issue and fixed it after spending 2 hours to find. My environment as below:

cocoapod 0.39.0

swift 2.x

XCode 7.3.1

Steps:

  1. project path: project_name/project_name/your_bridging_header.h
  2. In Swift section at Build Setting, Objective-C Bridging Header should be: project_name/your_bridging_header.h
  3. In your_bridging_header.h, change all declarations from .h to #import
  4. In class which is being used your_3rd_party. Declare import your_3rd_party

How can I echo the whole content of a .html file in PHP?

You should use readfile():

readfile("/path/to/file");

This will read the file and send it to the browser in one command. This is essentially the same as:

echo file_get_contents("/path/to/file");

except that file_get_contents() may cause the script to crash for large files, while readfile() won't.

Google Chromecast sender error if Chromecast extension is not installed or using incognito

By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

android: changing option menu items programmatically

Kotlin Code for accessing toolbar OptionsMenu items programmatically & change the text/icon ,..:

1-We have our menu item in menu items file like: menu.xml, sample code for this:

 <?xml version="1.0" encoding="utf-8"?> 
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/balance"
      android:title="0"
      android:orderInCategory="100"
      app:showAsAction="always" />
 </menu>

2- Define a variable for accessing menu object in class :

var menu: Menu? = null

3- initial it in onCreateOptionsMenu :

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    this.menu = menu
    return true
}

4- Access the menu items inside your code or fun :

private fun initialBalanceMenuItemOnToolbar() {
var menuItemBalance = menu?.findItem(R.id.balance)
    menuItemBalance?.title = Balance?.toString() ?: 0.toString()
    // for change icon : menuWalletBalance?.icon
}

Change the class from factor to numeric of many columns in a data frame

you can use unfactor() function from "varhandle" package form CRAN:

library("varhandle")

my_iris <- data.frame(Sepal.Length = factor(iris$Sepal.Length),
                      sample_id = factor(1:nrow(iris)))

my_iris <- unfactor(my_iris)

How can you get the Manifest Version number from the App's (Layout) XML variables?

IF you are using Gradle you can use the build.gradle file to programmatically add value to the xml resources at compile time.

Example Code extracted from: https://medium.com/@manas/manage-your-android-app-s-versioncode-versionname-with-gradle-7f9c5dcf09bf

buildTypes {
    debug {
        versionNameSuffix ".debug"
        resValue "string", "app_version", "${defaultConfig.versionName}${versionNameSuffix}"
    }
    release {
        resValue "string", "app_version", "${defaultConfig.versionName}"
    }
}

now use @string/app_version as needed in XML

It will add .debug to the version name as describe in the linked article when in debug mode.

How to delete directory content in Java?

Use FileUtils with FileUtils.deleteDirectory();

Eclipse gives “Java was started but returned exit code 13”

Instead of opening eclipse.exe , first open folder named configuration then you will get log file like 1401241141809.log ; open that log (open latest one) detail error will be listed there. Ex: java.lang.UnsatisfiedLinkError: Cannot load 64-bit SWT libraries on 32-bit JVM

means you need to have JVM and SDK of same version.

How can I read a large text file line by line using Java?

Once Java 8 is out (March 2014) you'll be able to use streams:

try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
  lines.forEachOrdered(line -> process(line));
}

Printing all the lines in the file:

try (Stream<String> lines = Files.lines(file, Charset.defaultCharset())) {
  lines.forEachOrdered(System.out::println);
}

Convert file: Uri to File in Android

If you have a Uri that conforms to the DocumentContract then you probably don't want to use File. If you are on kotlin, use DocumentFile to do stuff you would in the old World use File for, and use ContentResolver to get streams.

Everything else is pretty much guaranteed to break.

Node.js spawn child process and get terminal output live

Adding an answer related to child_process.exec as I too had needed live feedback and wasn't getting any until after the script finished. This also supplements my comment to the accepted answer, but as it's formatted it will a bit more understandable and easier to read.

Basically, I have a npm script that calls Gulp, invoking a task which subsequently uses child_process.exec to execute a bash or batch script depending on the OS. Either script runs a build process via Gulp and then makes some calls to some binaries that work with the Gulp output.

It's exactly like the others (spawn, etc.), but for the sake of completion, here's exactly how to do it:

// INCLUDES
import * as childProcess from 'child_process'; // ES6 Syntax


// GLOBALS
let exec = childProcess.exec; // Or use 'var' for more proper 
                              // semantics, though 'let' is 
                              // true-to-scope


// Assign exec to a variable, or chain stdout at the end of the call
// to exec - the choice, yours (i.e. exec( ... ).stdout.on( ... ); )
let childProcess = exec
(
    './binary command -- --argument argumentValue',
    ( error, stdout, stderr ) =>
    {
        if( error )
        {
            // This won't show up until the process completes:
            console.log( '[ERROR]: "' + error.name + '" - ' + error.message );
            console.log( '[STACK]: ' + error.stack );

            console.log( stdout );
            console.log( stderr );
            callback();            // Gulp stuff
            return;
        }

        // Neither will this:
        console.log( stdout );
        console.log( stderr );
        callback();                // Gulp stuff
    }
);

Now its as simple as adding an event listener. For stdout:

childProcess.stdout.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live':
        console.log( '[STDOUT]: ' + data );
    }
);

And for stderr:

childProcess.stderr.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live' too:
        console.log( '[STDERR]: ' + data );
    }
);

Not too bad at all - HTH

How to get multiple select box values using jQuery?

Get selected values in comma separator

var Accessids = "";
$(".multi_select .btn-group>ul>li input:checked").each(function(i,obj)
{
    Accessids=Accessids+$(obj).val()+",";
});
Accessids = Accessids.substring(0,Accessids.length - 1);
console.log(Accessids);

How to reverse a 'rails generate'

If you use Rails, use rails d controller Users.

And, if you use Zeus, use zeus d controller Users.

On the other hand, if you are using git or SVN, revert your changes with the commit number. This is much faster.

What difference does .AsNoTracking() make?

see this page Entity Framework and AsNoTracking

What AsNoTracking Does

Entity Framework exposes a number of performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking(). This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query. However, it also means that you can't update these entities without reattaching them to the tracking graph.

there are significant performance gains to be had by using AsNoTracking

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

jquery - Click event not working for dynamically created button

You could also create the input button in this way:

var button = '<input type="button" id="questionButton" value='+variable+'> <br />';


It might be the syntax of the Button creation that is off somehow.

SQLException : String or binary data would be truncated

Simply Used this: MessageBox.Show(cmd4.CommandText.ToString()); in c#.net and this will show you main query , Copy it and run in database .

How to subtract 30 days from the current date using SQL Server

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

Run .jar from batch-file

you shoult try this one :

java -cp youJarName.jar your.package.your.MainClass

MySQL timezone change?

If SET time_zone or SET GLOBAL time_zone does not work, you can change as below:

  • Change timezone system, example: ubuntu... $ sudo dpkg-reconfigure tzdata

  • Restart the server or you can restart apache2 and mysql (/etc/init.d/mysql restart)

Why is using "for...in" for array iteration a bad idea?

Because for...in enumerates through the object that holds the array, not the array itself. If I add a function to the arrays prototype chain, that will also be included. I.e.

Array.prototype.myOwnFunction = function() { alert(this); }
a = new Array();
a[0] = 'foo';
a[1] = 'bar';
for(x in a){
 document.write(x + ' = ' + a[x]);
}

This will write:

0 = foo
1 = bar
myOwnFunction = function() { alert(this); }

And since you can never be sure that nothing will be added to the prototype chain just use a for loop to enumerate the array:

for(i=0,x=a.length;i<x;i++){
 document.write(i + ' = ' + a[i]);
}

This will write:

0 = foo
1 = bar

CSS ''background-color" attribute not working on checkbox inside <div>

A checkbox does not have background color.

But to add the effect, you may wrap each checkbox with a div that has color:

<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>
<div class="evenRow">
    <input type="checkbox" />
</div>
<div class="oddRow">
    <input type="checkbox" />
</div>

How to check whether Kafka Server is running?

I used the AdminClient api.

Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("connections.max.idle.ms", 10000);
properties.put("request.timeout.ms", 5000);
try (AdminClient client = KafkaAdminClient.create(properties))
{
    ListTopicsResult topics = client.listTopics();
    Set<String> names = topics.names().get();
    if (names.isEmpty())
    {
        // case: if no topic found.
    }
    return true;
}
catch (InterruptedException | ExecutionException e)
{
    // Kafka is not available
}

Erasing elements from a vector

Calling erase will invalidate iterators, you could use:

void erase(std::vector<int>& myNumbers_in, int number_in)
{
    std::vector<int>::iterator iter = myNumbers_in.begin();
    while (iter != myNumbers_in.end())
    {
        if (*iter == number_in)
        {
            iter = myNumbers_in.erase(iter);
        }
        else
        {
           ++iter;
        }
    }

}

Or you could use std::remove_if together with a functor and std::vector::erase:

struct Eraser
{
    Eraser(int number_in) : number_in(number_in) {}
    int number_in;
    bool operator()(int i) const
    {
        return i == number_in;
    }
};

std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());

Instead of writing your own functor in this case you could use std::remove:

std::vector<int> myNumbers;
myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());

In C++11 you could use a lambda instead of a functor:

std::vector<int> myNumbers;
myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());

In C++17 std::experimental::erase and std::experimental::erase_if are also available, in C++20 these are (finally) renamed to std::erase and std::erase_if (note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support):

std::vector<int> myNumbers;
std::erase_if(myNumbers, Eraser(number_in)); // or use lambda

or:

std::vector<int> myNumbers;
std::erase(myNumbers, number_in);

How to change text color of simple list item

In simple word "you can't do it through simple setListAdapter" . you must used custom listview for freely changes in text color or in any other views

for Custom Listview you can go with this link

how do I initialize a float to its max/min value?

To manually find the minimum of an array you don't need to know the minimum value of float:

float myFloats[];
...
float minimum = myFloats[0];
for (int i = 0; i < myFloatsSize; ++i)
{
  if (myFloats[i] < minimum)
  {
    minimum = myFloats[i];
  }
}

And similar code for the maximum value.

php & mysql query not echoing in html with tags?

Change <?php echo $proxy ?> to ' . $proxy . '.

You use <?php when you're outputting HTML by leaving PHP mode with ?>. When you using echo, you have to use concatenation, or wrap your string in double quotes and use interpolation.

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

Haven't you heard about the Comparable interface being implemented by String ? If no, try to use

"abcda".compareTo("abcza")

And it will output a good root for a solution to your problem.

Easy way to make a confirmation dialog in Angular?

you can use window.confirm inside your function combined with if condition

 delete(whatever:any){
    if(window.confirm('Are sure you want to delete this item ?')){
    //put your delete method logic here
   }
}

when you call the delete method it will popup a confirmation message and when you press ok it will perform all the logic inside the if condition.

How to make div occupy remaining height?

You could use calc function to calculate remaining height for 2nd div.

_x000D_
_x000D_
*{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
#div1{_x000D_
  height: 50px;_x000D_
  background: skyblue;_x000D_
}_x000D_
_x000D_
#div2{_x000D_
  height: calc(100vh - 50px);_x000D_
  background: blue;_x000D_
}
_x000D_
<div id="div1"></div>_x000D_
<div id="div2"></div>
_x000D_
_x000D_
_x000D_

How to tar certain file types in all subdirectories?

This will handle paths with spaces:

find ./ -type f -name "*.php" -o -name "*.html" -exec tar uvf myarchives.tar {} +

Storing a file in a database as opposed to the file system?

Have a look at this answer:

Storing Images in DB - Yea or Nay?

Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually.

There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea.

Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database.

DIV table colspan: how?

In order to get "colspan" functionality out of div based tabular layout, you need to abandon the use of the display:table | display:row styles. Especially in cases where each data item spans more than one row and you need different sized "cells" in each row.

How to get text of an element in Selenium WebDriver, without including child element text?

Here's a general solution:

def get_text_excluding_children(driver, element):
    return driver.execute_script("""
    return jQuery(arguments[0]).contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    }).text();
    """, element)

The element passed to the function can be something obtained from the find_element...() methods (i.e. it can be a WebElement object).

Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:

return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
    if (child.nodeType === Node.TEXT_NODE)
        ret += child.textContent;
    child = child.nextSibling;
}
return ret;
""", element) 

I'm actually using this code in a test suite.

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

Jan 2020 Update

@Flimm has explained all the differences very well. Generally, we want to know the difference between all tools because we want to decide what's best for us. So, the next question would be: which one to use? I suggest you choose one of the two official ways to manage virtual environments:

Clear an input field with Reactjs?

Also after React v 16.8+ you have an ability to use hooks

import React, {useState} from 'react';

const ControlledInputs = () => {
  const [firstName, setFirstName] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (firstName) {
      console.log('firstName :>> ', firstName);
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
          <label htmlFor="firstName">Name: </label>
          <input
            type="text"
            id="firstName"
            name="firstName"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
        <button type="submit">add person</button>
      </form>
    </>
  );
};

Connect to external server by using phpMyAdmin

at version 4.0 or above, we need to create one 'config.inc.php' or rename the 'config.sample.inc.php' to 'config.inc.php';

In my case, I also work with one mysql server for each environment (dev and production):

/* others code*/  
$whoIam = gethostname();
switch($whoIam) {
    case 'devHost':
        $cfg['Servers'][$i]['host'] = 'localhost';
        break;
    case 'MasterServer':
        $cfg['Servers'][$i]['host'] = 'masterMysqlServer';
        break;
} /* others code*/ 

String Comparison in Java

The wording "comparison" is mildly misleading. You are not comparing for strict equality but for which string comes first in the dictionary (lexicon).

This is the feature that allows collections of strings to be sortable.

Note that this is very dependent on the active locale. For instance, here in Denmark we have a character "å" which used to be spelled as "aa" and is very distinct from two single a's (EDIT: If pronounced as "å"!). Hence Danish sorting rules treat two consequtive a's identically to an "å", which means that it goes after z. This also means that Danish dictionaries are sorted differently than English or Swedish ones.

Use of String.Format in JavaScript?

if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
              ? args[number]
              : match
            ;
        });
    };
}

Usage:

'{0}-{1}'.format('a','b');
// Result: 'a-b'

JSFiddle

Mailx send html message

I had successfully used the following on Arch Linux (where the -a flag is used for attachments) for several years:

mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html

This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s subject. Presumably, this was done to improve security.

Instead of relying on hacking the subject line, I now use a bash subshell:

(
    echo -e "Content-Type: text/html\n"
    cat mail.html
 ) | mail -s "The Subject" -t [email protected]

And since we are really only using mailx's subject flag, it seems there is no reason not to switch to sendmail as suggested by @dogbane:

(
    echo "To: [email protected]"
    echo "Subject: The Subject"
    echo "Content-Type: text/html"
    echo
    cat mail.html
) | sendmail -t

The use of bash subshells avoids having to create a temporary file.

Deserialize Java 8 LocalDateTime with JacksonMapper

You can implement your JsonSerializer

See:

That your propertie in bean

@JsonProperty("start_date")
@JsonFormat("YYYY-MM-dd HH:mm")
@JsonSerialize(using = DateSerializer.class)
private Date startDate;

That way implement your custom class

public class DateSerializer extends JsonSerializer<Date> implements ContextualSerializer<Date> {

    private final String format;

    private DateSerializer(final String format) {
        this.format = format;
    }

    public DateSerializer() {
        this.format = null;
    }

    @Override
    public void serialize(final Date value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
        jgen.writeString(new SimpleDateFormat(format).format(value));
    }

    @Override
    public JsonSerializer<Date> createContextual(final SerializationConfig serializationConfig, final BeanProperty beanProperty) throws JsonMappingException {
        final AnnotatedElement annotated = beanProperty.getMember().getAnnotated();
        return new DateSerializer(annotated.getAnnotation(JsonFormat.class).value());
    }

}

Try this after post result for us.

What is event bubbling and capturing?

If there are two elements element 1 and element 2. Element 2 is inside element 1 and we attach an event handler with both the elements lets say onClick. Now when we click on element 2 then eventHandler for both the elements will be executed. Now here the question is in which order the event will execute. If the event attached with element 1 executes first it is called event capturing and if the event attached with element 2 executes first this is called event bubbling. As per W3C the event will start in the capturing phase until it reaches the target comes back to the element and then it starts bubbling

The capturing and bubbling states are known by the useCapture parameter of addEventListener method

eventTarget.addEventListener(type,listener,[,useCapture]);

By Default useCapture is false. It means it is in the bubbling phase.

_x000D_
_x000D_
var div1 = document.querySelector("#div1");_x000D_
var div2 = document.querySelector("#div2");_x000D_
_x000D_
div1.addEventListener("click", function (event) {_x000D_
  alert("you clicked on div 1");_x000D_
}, true);_x000D_
_x000D_
div2.addEventListener("click", function (event) {_x000D_
  alert("you clicked on div 2");_x000D_
}, false);
_x000D_
#div1{_x000D_
  background-color:red;_x000D_
  padding: 24px;_x000D_
}_x000D_
_x000D_
#div2{_x000D_
  background-color:green;_x000D_
}
_x000D_
<div id="div1">_x000D_
  div 1_x000D_
  <div id="div2">_x000D_
    div 2_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please try with changing true and false.

Correct format specifier for double in printf

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

How to record phone calls in android?

The answer of pratt is bit uncomplete, because when you restart your device your app will working stop, recording stop, its become useless.

i m adding some line that copy in your project for complete working of Pratt answer.

<receiver
        android:name=".DeviceAdminDemo"
        android:permission="android.permission.BIND_DEVICE_ADMIN">
        <meta-data
            android:name="android.app.admin"
            android:resource="@xml/device_admin" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLED" />
            <action android:name="android.app.action.DEVICE_ADMIN_DISABLE_REQUESTED" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.HOME" />
        </intent-filter>
    </receiver>

put this code in onReceive of DeviceAdminDemo

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    context.stopService(new Intent(context, TService.class));
    Intent myIntent = new Intent(context, TService.class);
    context.startService(myIntent);

}

iOS: set font size of UILabel Programmatically

Swift 3.0 / Swift 4.2 / Swift 5.0

labelName.font = labelName.font.withSize(15)

How do I check if the Java JDK is installed on Mac?

If you are on Mac OS Big Sur, then you probably have a messed up java installation. I found info on how to fix the issue with this article: https://knasmueller.net/how-to-install-java-openjdk-15-on-macos-big-sur

  1. Download the .tar.gz file of the JDK on https://jdk.java.net/15/
  2. Navigate to the download folder, and run these commands (move the .tar.gz file, extract it and remove it after extraction):
sudo mv openjdk-15.0.2_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines/
cd /Library/Java/JavaVirtualMachines/
sudo tar -xzf openjdk-15.0.2_osx-x64_bin.tar.gz
sudo rm openjdk-15.0.2_osx-x64_bin.tar.gz

Note: it might be 15.0.3 or higher, depending on the date of your download.

  1. run /usr/libexec/java_home -v15 and copy the output
  2. add this line to your .bash_profile or .zshrc file, depending on which shell you are using. You will probably have only one of these files existing in your home directory (~/.bash_profile or ~/.zshrc).
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home
  1. save the changes and make them effective right away by running: source ~/.bash_profile or source ~/.zshrc
  2. check that java is working - run java -v

Logical XOR operator in C++?

Proper manual logical XOR implementation depends on how closely you want to mimic the general behavior of other logical operators (|| and &&) with your XOR. There are two important things about these operators: 1) they guarantee short-circuit evaluation, 2) they introduce a sequence point, 3) they evaluate their operands only once.

XOR evaluation, as you understand, cannot be short-circuited since the result always depends on both operands. So 1 is out of question. But what about 2? If you don't care about 2, then with normalized (i.e. bool) values operator != does the job of XOR in terms of the result. And the operands can be easily normalized with unary !, if necessary. Thus !A != !B implements the proper XOR in that regard.

But if you care about the extra sequence point though, neither != nor bitwise ^ is the proper way to implement XOR. One possible way to do XOR(a, b) correctly might look as follows

a ? !b : b

This is actually as close as you can get to making a homemade XOR "similar" to || and &&. This will only work, of course, if you implement your XOR as a macro. A function won't do, since the sequencing will not apply to function's arguments.

Someone might say though, that the only reason of having a sequence point at each && and || is to support the short-circuited evaluation, and thus XOR does not need one. This makes sense, actually. Yet, it is worth considering having a XOR with a sequence point in the middle. For example, the following expression

++x > 1 && x < 5

has defined behavior and specificed result in C/C++ (with regard to sequencing at least). So, one might reasonably expect the same from user-defined logical XOR, as in

XOR(++x > 1, x < 5)

while a !=-based XOR doesn't have this property.

How to capture and save an image using custom camera in Android?

please see below answer.

Custom_CameraActivity.java

public class Custom_CameraActivity extends Activity {
    private Camera mCamera;
    private CameraPreview mCameraPreview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);

        Button captureButton = (Button) findViewById(R.id.button_capture);
        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, mPicture);
            }
        });
    }

    /**
     * Helper method to access the camera returns null if it cannot get the
     * camera or does not exist
     * 
     * @return
     */
    private Camera getCameraInstance() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {
            // cannot get camera or does not exist
        }
        return camera;
    }

    PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }
    };

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }
}

CameraPreview.java

public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        this.mCamera = camera;
        this.mSurfaceHolder = this.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (IOException e) {
            // left blank for now
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mCamera.stopPreview();
        mCamera.release();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
            int width, int height) {
        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Capture" />

</LinearLayout>

Add Below Lines to your androidmanifest.xml file

<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Firebase Storage How to store and Retrieve images

Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.

Can Windows' built-in ZIP compression be scripted?

There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.

The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.

Unzipping is easier - just treat it as a directory.

In case the web pages are lost again, here are a few of the relevant code snippets:

ZIP

Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function

Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "\")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub

UNZIP

Sub Unzip1()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefPath As String
    Dim strDate As String

    Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                        MultiSelect:=False)
    If Fname = False Then
        'Do nothing
    Else
        'Root folder for the new folder.
        'You can also use DefPath = "C:\Users\Ron\test\"
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If

        'Create the folder name
        strDate = Format(Now, " dd-mm-yy h-mm-ss")
        FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"

        'Make the normal folder in DefPath
        MkDir FileNameFolder

        'Extract the files into the newly created folder
        Set oApp = CreateObject("Shell.Application")

        oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        'If you want to extract only one file you can use this:
        'oApp.Namespace(FileNameFolder).CopyHere _
         'oApp.Namespace(Fname).items.Item("test.txt")

        MsgBox "You find the files here: " & FileNameFolder

        On Error Resume Next
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
End Sub

HTML5 - mp4 video does not play in IE9

Internet Explorer and Edge do not support some MP4 formats that Chrome does. You can use ffprobe to see the exact MP4 format. In my case I have these two videos:

Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf56.40.101
  Duration: 00:00:12.10, start: 0.000000, bitrate: 287 kb/s
    Stream #0:0(und): Video: h264 (High 4:4:4 Predictive) (avc1 / 0x31637661), yuv444p, 1000x1000 [SAR 1:1 DAR 1:1], 281 kb/s, 60 fps, 60 tbr, 15360 tbn, 120 tbc (default)
    Metadata:
      handler_name    : VideoHandler


Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'b.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.66.102
  Duration: 00:00:33.83, start: 0.000000, bitrate: 505 kb/s
    Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 1280x680, 504 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
    Metadata:
      handler_name    : VideoHandler

Both play fine in Chrome, but the first one fails in IE and Edge. The problem is that IE and Edge don't support yuv444. You can convert to a shittier colourspace like this:

ffmpeg -i input.mp4 -pix_fmt yuv420p output.mp4

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

Calendar Recurring/Repeating Events - Best Storage Method

The two examples you've given are very simple; they can be represented as a simple interval (the first being four days, the second being 14 days). How you model this will depend entirely on the complexity of your recurrences. If what you have above is truly that simple, then store a start date and the number of days in the repeat interval.

If, however, you need to support things like

Event A repeats every month on the 3rd of the month starting on March 3, 2011

Or

Event A repeats second Friday of the month starting on March 11, 2011

Then that's a much more complex pattern.

How should I multiple insert multiple records?

static void InsertSettings(IEnumerable<Entry> settings) {
    using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
        oConnection.Open();
        using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
            using (SqlCommand oCommand = oConnection.CreateCommand()) {
                oCommand.Transaction = oTransaction;
                oCommand.CommandType = CommandType.Text;
                oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
                oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
                oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
                try {
                    foreach (var oSetting in settings) {
                        oCommand.Parameters[0].Value = oSetting.Key;
                        oCommand.Parameters[1].Value = oSetting.Value;
                        if (oCommand.ExecuteNonQuery() != 1) {
                            //'handled as needed, 
                            //' but this snippet will throw an exception to force a rollback
                            throw new InvalidProgramException();
                        }
                    }
                    oTransaction.Commit();
                } catch (Exception) {
                    oTransaction.Rollback();
                    throw;
                }
            }
        }
    }
}

Difference between HashMap, LinkedHashMap and TreeMap

The most important among all the three is how they save the order of the entries.

HashMap - Does not save the order of the entries. eg.

public static void main(String[] args){
        HashMap<String,Integer> hashMap = new HashMap<>();
        hashMap.put("First",1);// First ---> 1 is put first in the map
        hashMap.put("Second",2);//Second ---> 2 is put second in the map
        hashMap.put("Third",3); // Third--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : hashMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

Output for HashMap

LinkedHashMap : It save the order in which entries were made. eg:

public static void main(String[] args){
        LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("First",1);// First ---> 1 is put first in the map
        linkedHashMap.put("Second",2);//Second ---> 2 is put second in the map
        linkedHashMap.put("Third",3); // Third--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : linkedHashMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

Output of LinkedHashMap

TreeMap : It saves the entries in ascending order of the keys. eg:

public static void main(String[] args) throws IOException {
        TreeMap<String,Integer> treeMap = new TreeMap<>();
        treeMap.put("A",1);// A---> 1 is put first in the map
        treeMap.put("C",2);//C---> 2 is put second in the map
        treeMap.put("B",3); //B--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : treeMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

Output of TreeMap

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

I am thinking about something else, if you are trying to login with a different username that doesn't exist this is the message you will get.

So I assume you may be trying to ssh with ec2-user but I recall recently most of centos AMIs for example are using centos user instead of ec2-user

so if you are ssh -i file.pem centos@public_IP please tell me you aretrying to ssh with the right user name otherwise this may be a strong reason of you see such error message even with the right permissions on your ~/.ssh/id_rsa or file.pem

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

RedirectToAction("actionName", "controllerName");

It has other overloads as well, please check up!

Also, If you are new and you are not using T4MVC, then I would recommend you to use it!

It gives you intellisence for actions,Controllers,views etc (no more magic strings)

Tomcat request timeout

You can set the default time out in the server.xml

<Connector URIEncoding="UTF-8" 
    acceptCount="100" 
    connectionTimeout="20000" 
    disableUploadTimeout="true" 
    enableLookups="false" 
    maxHttpHeaderSize="8192" 
    maxSpareThreads="75" 
    maxThreads="150" 
    minSpareThreads="25" 
    port="7777" 
    redirectPort="8443"/>

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

To fix this install the specific typescript version 3.1.6

npm i [email protected] --save-dev --save-exact

What is a reasonable length limit on person "Name" fields?

depending on who is going to be using your database, for example African names will do with varchar(20) for last name and first name separated. however it is different from nation to nation but for the sake saving your database resources and memory, separate last name and first name fields and use varchar(30) think that will work.

Outline effect to text

I got better results with 6 different shadows:

.strokeThis{
    text-shadow:
    -1px -1px 0 #ff0,
    0px -1px 0 #ff0,
    1px -1px 0 #ff0,
    -1px 1px 0 #ff0,
    0px 1px 0 #ff0,
    1px 1px 0 #ff0;
}

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

How to set DateTime to null

You can write DateTime? newdate = null;

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

cc1plus: error: unrecognized command line option "-std=c++11" with g++

Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.

In versions pre-G++ 4.7, you'll have to use -std=c++0x, for more recent versions you can use -std=c++11.

Very Simple Image Slider/Slideshow with left and right button. No autoplay

<script type="text/javascript">
                    $(document).ready(function(e) {
                        $(".mqimg").mouseover(function()
                        {
                            $("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />"); 
                        })
                        $(".mqimg").mouseout(function()
                        {
                            $("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
                        })
                    });
                    </script>
                    <style>
                    .mqimg{ cursor:pointer;}
                    </style>
                    <div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
                    <div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />

How do you run `apt-get` in a dockerfile behind a proxy?

and If you want to set proxy for wget you should put these line in your Dockerfile

ENV http_proxy YOUR-PROXY-IP:PORT/
ENV https_proxy YOUR-PROXY-IP:PORT/
ENV all_proxy YOUR-PROXY-IP:PORT/

No module named 'pymysql'

After trying a few things, and coming across PyMySQL Github, this worked:

sudo pip install PyMySQL

And to import use:

import pymysql

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

Easiest way to get text from the user:

EditText Variable1 = findViewById(R.id.enter_name);
String Variable2 = Variable1.getText().toString();

How to scroll HTML page to given anchor?

A pure javascript solution without JQuery. Tested on Chrome & I.e, not tested on IOS

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

demo: https://jsfiddle.net/jd7q25hg/12/

Implicit function declarations in C

An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.

It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.

Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.

Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.

Bootstrap: how do I change the width of the container?

Container sizes

@container-large-desktop
(1140px + @grid-gutter-width) -> (970px + @grid-gutter-width)

in section Container sizes, change 1140 to 970

I hope its help you.


thank you for your correct. link for customize bootstrap: https://getbootstrap.com/docs/3.4/customize/

Find Facebook user (url to profile page) by known email address

The definitive answer to this is from Facebook themselves. In post today at https://developers.facebook.com/bugs/335452696581712 a Facebook dev says

The ability to pass in an e-mail address into the "user" search type was
removed on July 10, 2013. This search type only returns results that match
a user's name (including alternate name).

So, alas, the simple answer is you can no longer search for users by their email address. This sucks, but that's Facebook's new rules.

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

Disabled form inputs do not appear in the request

In addition to Tom Blodget's response, you may simply add @HtmlBeginForm as the form action, like this:

 <form id="form" method="post" action="@Html.BeginForm("action", "controller", FormMethod.Post, new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" })"

Error Message : Cannot find or open the PDB file

Working with VS 2013. Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off It will disable the display of modules loaded.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

According to the API

totalMemory()

Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

maxMemory()

Returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.

freeMemory()

Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory.

In reference to your question, maxMemory() returns the -Xmx value.

You may be wondering why there is a totalMemory() AND a maxMemory(). The answer is that the JVM allocates memory lazily. Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory() corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();

Setting the default active profile in Spring-boot

If you are using AWS Lambda with SprintBoot, then you must declare the following under environment variables:

key: JAVA_TOOL_OPTIONS & value: -Dspring.profiles.active=dev

Is there any way to do HTTP PUT in python

You should have a look at the httplib module. It should let you make whatever sort of HTTP request you want.

Alternative to the HTML Bold tag

What you use instead of the b element depends on the semantics of that element's content.

  • The elements b and strong have co-existed for a long time by now. In HTML 4.01, which has been superseded by HTML5, strong was meant to be used for "strong emphasis", i.e. stronger emphasis than the em element (which just indicated emphasis). In HTML 5.2, strong "represents strong importance, seriousness, or urgency for its contents"; the aspects of "seriousness" and "urgency" are new in the specification compared to HTML 4.01. So if you used b to represent content that was important, serious or urgent, it is recommended that you use strong instead. If you want, you can differentiate between these different semantics by adding meaningful class attributes, e.g. <strong class="urgent">...</strong> and <strong class="warning">...</strong> and use appropriate CSS selectors to style these types of "emphasis" different, e.g. using different colours and font sizes (e.g. in your CSS file: strong.warning { color: red; background-color: transparent; border: 2px solid red; }.).
    Another alternative to b is the em element, which in HTML 5.2 "represents stress emphasis of its contents". Note that this element is usually rendered in italics (and has therefore often been recommended as a replacement for the i element).
    I would resist the temptation to follow the advice from some of the other answers to write something like <strong class="bold">...</strong>. Firstly, the class attribute doesn't mean anything in non-visual contexts (listening to an ePub book, text to speech generally, screen readers, Braille); secondly, people maintaining the code will need to read the actual content to figure out why something was bolded.
  • If you used b for entire paragraphs or headings (as opposed to shorter spans of texts, which is the use case in the previous bullet point), I would replace it with appropriate class attributes or, if applicable, WAI-ARIA roles such as alert for a live region "with important, and usually time-sensitive, information". As mentioned above, you should use "semantic" class attribute values, so that people maintaining the code (including your future self) can figure out why something was bolded.
  • Not all uses of the b may represent something semantic. For example, when you are converting printed documents into HTML, text may be bolded for reasons that have nothing to do with emphasis or importance but as a visual guide. For example, the headwords in dictionaries aren't any more "serious", "urgent" than the other content, so you may keep the b element and optionallly add a meaningful class attribute, e.g. <b class="headword"> or replace the tag with <span class="headword"> based on the argument that b has no meaning in non-visual contexts.

In your CSS file (instead of using style attributes, as some of the other answers have recommended), you have several options for styling the "bold" or important text:

  • specifying different colours (foreground and/or background);
  • specifying different font faces;
  • specifying borders (see example above);
  • using different font weights using the font-weight property, which allows more values than just normal and bold, namely normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900,
  • etc.

Note that support for numeric font-weight values has not always been great.

Python 3 - Encode/Decode vs Bytes/Str

To add to add to the previous answer, there is even a fourth way that can be used

import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)

How can I remove a commit on GitHub?

In GitHub Desktop you can just right click the commit and revert it, which will create a new commit that undoes the changes.

The accidental commit will still be in your history (which may be an issue if, for instance, you've accidentally commited an API key or password) but the code will be reverted.

This is the simplest and easiest option, the accepted answer is more comprehensive.

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Well, after some struggling, what worked for me was completely removing the current JDK, as described here:

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/PrivilegedHelperTools/com.oracle.java.JavaUpdateHelper
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.JavaUpdateHelper.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist

Then installed 1.7.0_21, which was downloaded from here.

Now java -version prompts:

java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b12)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

What's the -practical- difference between a Bare and non-Bare repository?

The distinction between a bare and non-bare Git repository is artificial and misleading since a workspace is not part of the repository and a repository doesn't require a workspace. Strictly speaking, a Git repository includes those objects that describe the state of the repository. These objects may exist in any directory, but typically exist in the .git directory in the top-level directory of the workspace. The workspace is a directory tree that represents a particular commit in the repository, but it may exist in any directory or not at all. Environment variable $GIT_DIR links a workspace to the repository from which it originates.

Git commands git clone and git init both have options --bare that create repositories without an initial workspace. It's unfortunate that Git conflates the two separate, but related concepts of workspace and repository and then uses the confusing term bare to separate the two ideas.

How to check if a std::thread is still running?

Surely have a mutex-wrapped variable initialised to false, that the thread sets to true as the last thing it does before exiting. Is that atomic enough for your needs?

Print: Entry, ":CFBundleIdentifier", Does Not Exist

I also get same error while running project react-native run-ios

But when i run project from xcode, that is work for me.

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

How to see docker image contents

With Docker EE for Windows (17.06.2-ee-6 on Hyper-V Server 2016) all contents of Windows Containers can be examined at C:\ProgramData\docker\windowsfilter\ path of the host OS.

No special mounting needed.

Folder prefix can be found by container id from docker ps -a output.

Preloading @font-face fonts?

Via Google's webfontloader

var fontDownloadCount = 0;
WebFont.load({
    custom: {
        families: ['fontfamily1', 'fontfamily2']
    },
    fontinactive: function() {
        fontDownloadCount++;
        if (fontDownloadCount == 2) {
            // all fonts have been loaded and now you can do what you want
        }
    }
});

How to subtract n days from current date in java?

this will subtract ten days of the current date (before Java 8):

int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();

If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):

LocalDate tenDaysAgo = LocalDate.now().minusDays(10);

For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date

Submit form on pressing Enter with AngularJS

FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>

(just switch out the jQuery click action for whatever you like, and add data-easy-dismiss to your modal tag)

app.directive('easyDismiss', function() {
    return {
        restrict: 'A',
        link: function ($scope, $element) {

            var clickSubmit = function (e) {
                if (e.which == 13) {
                    $element.find('[type="submit"]').click();
                }
            };

            $element.on('show.bs.modal', function() {
                $(document).on('keypress', clickSubmit);
            });

            $element.on('hide.bs.modal', function() {
                $(document).off('keypress', clickSubmit);
            });
        }
    };
});

How to uninstall with msiexec using product id guid without .msi file present

Thanks all for the help - turns out it was a WiX issue.

When the Product ID GUID was left explicit & hardcoded as in the question, the resulting .msi had no ProductCode property but a Product ID property instead when inspected with orca.

Once I changed the GUID to '*' to auto-generate, the ProductCode showed up and all works fine with syntax confirmed by the other answers.

How to increment a JavaScript variable using a button press event

The purist way to do this would be to add event handlers to the button, instead of mixing behavior with the content (LSM, Layered Semantic Markup)

<input type="button" value="Increment" id="increment"/>

<script type="text/javascript">
    var count = 0;
    // JQuery way
    $('#increment').click(function (e) {
        e.preventDefault();
        count++;
    });
    // YUI way
    YAHOO.util.Event.on('increment', 'click', function (e) {
        YAHOO.util.Event.preventDefault(e);
        count++;
    });
    // Simple way
    document.getElementById('increment').onclick = function (e) {
        count++;
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    };
</script>

nano error: Error opening terminal: xterm-256color

You can add the following in your .bashrc

if [ "$TERM" = xterm ]; then TERM=xterm-256color; fi

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.

screenshot

What's the best way to calculate the size of a directory in .NET?

Multi thread example to calculate directory size from Microsoft Docs, which would be faster

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      long totalSize = 0;

      String[] args = Environment.GetCommandLineArgs();
      if (args.Length == 1) {
         Console.WriteLine("There are no command line arguments.");
         return;
      }
      if (! Directory.Exists(args[1])) {
         Console.WriteLine("The directory does not exist.");
         return;
      }

      String[] files = Directory.GetFiles(args[1]);
      Parallel.For(0, files.Length,
                   index => { FileInfo fi = new FileInfo(files[index]);
                              long size = fi.Length;
                              Interlocked.Add(ref totalSize, size);
                   } );
      Console.WriteLine("Directory '{0}':", args[1]);
      Console.WriteLine("{0:N0} files, {1:N0} bytes", files.Length, totalSize);
   }
}
// The example displaysoutput like the following:
//       Directory 'c:\windows\':
//       32 files, 6,587,222 bytes

This example only calculate the files in current folder, so if you want to calculate all the files recursively, you can change the

String[] files = Directory.GetFiles(args[1]);

to

String[] files = Directory.GetFiles(args[1], "*", SearchOption.AllDirectories);

SQL Server loop - how do I loop through a set of records

I think this is the easy way example to iterate item.

declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'

while (select count(*) from #TempTable) > 0
begin
    select top 1 @cateid = CateID from #TempTable
    print(@cateid)

    --DO SOMETHING HERE

    delete #TempTable where CateID = @cateid
end

drop table #TempTable

Dead simple example of using Multiprocessing Queue, Pool and Locking

Here is an example from my code (for threaded pool, but just change class name and you'll have process pool):

def execute_run(rp): 
   ... do something 

pool = ThreadPoolExecutor(6)
for mat in TESTED_MATERIAL:
    for en in TESTED_ENERGIES:
        for ecut in TESTED_E_CUT:
            rp = RunParams(
                simulations, DEST_DIR,
                PARTICLE, mat, 960, 0.125, ecut, en
            )
            pool.submit(execute_run, rp)
pool.join()

Basically:

  • pool = ThreadPoolExecutor(6) creates a pool for 6 threads
  • Then you have bunch of for's that add tasks to the pool
  • pool.submit(execute_run, rp) adds a task to pool, first arogument is a function called in in a thread/process, rest of the arguments are passed to the called function.
  • pool.join waits until all tasks are done.

Ping a site in Python?

It's hard to say what your question is, but there are some alternatives.

If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.

This will be much faster than using os.system("ping " + ip ).

If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.

For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n") and then read the reply.

If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.

For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html is always popular) and read the response.

There are still more potential meaning of "ping" including "traceroute" and "finger".

iOS 9 not opening Instagram app with URL SCHEME

iOS 9 has made a small change to the handling of URL scheme. You must whitelist the url's that your app will call out to using the LSApplicationQueriesSchemes key in your Info.plist.

Please see post here: http://awkwardhare.com/post/121196006730/quick-take-on-ios-9-url-scheme-changes

The main conclusion is that:

If you call the “canOpenURL” method on a URL that is not in your whitelist, it will return “NO”, even if there is an app installed that has registered to handle this scheme. A “This app is not allowed to query for scheme xxx” syslog entry will appear.

If you call the “openURL” method on a URL that is not in your whitelist, it will fail silently. A “This app is not allowed to query for scheme xxx” syslog entry will appear.

The author also speculates that this is a bug with the OS and Apple will fix this in a subsequent release.

Extract values in Pandas value_counts()

If anyone missed it out in the comments, try this:

dataframe[column].value_counts().to_frame()

Dealing with multiple Python versions and PIP?

for example, if you set other versions (e.g. 3.5) as default and want to install pip for python 2.7:

  1. download pip at https://pypi.python.org/pypi/pip (tar)
  2. unzip tar file
  3. cd to the file’s directory
  4. sudo python2.7 setup.py install

How do you get the index of the current iteration of a foreach loop?

This way you can use the index and value using LINQ:

ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element =>
    {
        // element.Index
        // element.Value

    });

Python convert tuple to string

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

How to skip a iteration/loop in while-loop

while (rs.next())
{
  if (f.exists() && !f.isDirectory())
    continue;

  //proceed
}

Reset Entity-Framework Migrations

Considering this still shows up when we search for EF in .NET Core, I'll post my answer here (Since it has haunted me a lot). Note that there are some subtleties with the EF 6 .NET version (No initial command, and you will need to delete "Snapshot" files)

(Tested in .NET Core 2.1)

Here are the steps:

  1. Delete the _efmigrationhistory table.
  2. Search for your entire solution for files that contain Snapshot in their name, such as ApplicationDbContextSnapshot.cs, and delete them.
  3. Rebuild your solution
  4. Run Add-Migration InitialMigration

Please note: You must delete ALL the Snapshot files. I spent countless hours just deleting the database... This will generate an empty migration if you don't do it.

Also, in #3 you can just name your migration however you want.

Here are some additional resources: asp.net CORE Migrations generated empty

Reset Entity Framework 7 migrations

Swift Error: Editor placeholder in source file

Go to Product > Clean Build Folder

how to make a cell of table hyperlink

I have also been looking for a solution, and just found this code on another site:

<td style="cursor:pointer" onclick="location.href='mylink.html'">link</td>

if statement in ng-click

You can put conditionals inside tags. Try:

ng-class="{true:'active',false:'disable'}[list_status=='show']"

'method' object is not subscriptable. Don't know what's wrong

You need to use parentheses: myList.insert([1, 2, 3]). When you leave out the parentheses, python thinks you are trying to access myList.insert at position 1, 2, 3, because that's what brackets are used for when they are right next to a variable.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Groovy - Convert object to JSON string

Do you mean like:

import groovy.json.*

class Me {
    String name
}

def o = new Me( name: 'tim' )

println new JsonBuilder( o ).toPrettyString()

Javascript / Chrome - How to copy an object from the webkit inspector as code

Using "Store as a Global Variable" works, but it only gets the final instance of the object, and not the moment the object is being logged (since you're likely wanting to compare changes to the object as they happen). To get the object at its exact point in time of being modified, I use this...

function logObject(object) {
    console.info(JSON.stringify(object).replace(/,/g, ",\n"));
}

Call it like so...

logObject(puzzle);

You may want to remove the .replace(/./g, ",\n") regex if your data happens to have comma's in it.

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

How to fix "unable to open stdio.h in Turbo C" error?

Make sure the folder with the standard header files is in the projects path.

I don't know where this is in Turbo C, but I would think there's a way of doing this.

How to overload functions in javascript?

In javascript you can implement the function just once and invoke the function without the parameters myFunc() You then check to see if options is 'undefined'

function myFunc(options){
 if(typeof options != 'undefined'){
  //code
 }
}

How to copy file from host to container using Dockerfile

I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4: docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02

How do I concatenate two strings in C?

Without GNU extension:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    res = malloc(strlen(str1) + strlen(str2) + 1);
    if (!res) {
        fprintf(stderr, "malloc() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    strcpy(res, str1);
    strcat(res, str2);

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

Alternatively with GNU extension:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    if (-1 == asprintf(&res, "%s%s", str1, str2)) {
        fprintf(stderr, "asprintf() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

See malloc, free and asprintf for more details.

HTML5 event handling(onfocus and onfocusout) using angular 2

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

How can I check if a key exists in a dictionary?

if key in array:
  # do something

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

MVC3 EditorFor readOnly

i think this is simple than other by using [Editable(false)] attribute

for example:

 public class MyModel
    {
        [Editable(false)]
        public string userName { get; set; }
    }

Is there a "theirs" version of "git merge -s ours"?

When merging topic branch "B" in "A" using git merge, I get some conflicts. I >know all the conflicts can be solved using the version in "B".

I am aware of git merge -s ours. But what I want is something like git merge >-s their.

I'm assuming that you created a branch off of master and now want to merge back into master, overriding any of the old stuff in master. That's exactly what I wanted to do when I came across this post.

Do exactly what it is you want to do, Except merge the one branch into the other first. I just did this, and it worked great.

git checkout Branch
git merge master -s ours

Then, checkout master and merge your branch in it (it will go smoothly now):

git checkout master
git merge Branch

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

jQuery UI Dialog individual CSS styling

According to the UI dialog documentation, the dialog plugin generates something like this:

<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable ui-resizable">
   <div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">
      <span id="ui-dialog-title-dialog" class="ui-dialog-title">Dialog title</span>
      <a class="ui-dialog-titlebar-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick">close</span></a>
   </div>
   <div class="ui-dialog-content ui-widget-content" id="dialog_style1">
      <p>One content</p>
   </div>
</div>

That means what you can add to any class to exactly to first or second dialog using jQuery's closest() method. For example:

$('#dialog_style1').closest('.ui-dialog').addClass('dialog_style1');

$('#dialog_style2').closest('.ui-dialog').addClass('dialog_style2');

and then CSS it.

How can I display a list view in an Android Alert Dialog?

Used below code to display custom list in AlertDialog

AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);
builderSingle.setIcon(R.drawable.ic_launcher);
builderSingle.setTitle("Select One Name:-");

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Hardik");
arrayAdapter.add("Archit");
arrayAdapter.add("Jignesh");
arrayAdapter.add("Umang");
arrayAdapter.add("Gatti");

builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String strName = arrayAdapter.getItem(which);
                AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);
                builderInner.setMessage(strName);
                builderInner.setTitle("Your Selected Item is");
                builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,int which) {
                                dialog.dismiss();
                            }
                        });
                builderInner.show();
            }
        });
builderSingle.show();

How to avoid "StaleElementReferenceException" in Selenium?

I've found solution here. In my case element becomes inaccessible in case of leaving current window, tab or page and coming back again.

.ignoring(StaleElement...), .refreshed(...) and elementToBeClicable(...) did not help and I was getting exception on act.doubleClick(element).build().perform(); string.

Using function in my main test class:

openForm(someXpath);

My BaseTest function:

int defaultTime = 15;

boolean openForm(String myXpath) throws Exception {
    int count = 0;
    boolean clicked = false;
    while (count < 4 || !clicked) {
        try {
            WebElement element = getWebElClickable(myXpath,defaultTime);
            act.doubleClick(element).build().perform();
            clicked = true;
            print("Element have been clicked!");
            break;
        } catch (StaleElementReferenceException sere) {
            sere.toString();
            print("Trying to recover from: "+sere.getMessage());
            count=count+1;
        }
    }

My BaseClass function:

protected WebElement getWebElClickable(String xpath, int waitSeconds) {
        wait = new WebDriverWait(driver, waitSeconds);
        return wait.ignoring(StaleElementReferenceException.class).until(
                ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(By.xpath(xpath))));
    }

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

Best practice to run Linux service as a different user

Just to add some other things to watch out for:

  • Sudo in a init.d script is no good since it needs a tty ("sudo: sorry, you must have a tty to run sudo")
  • If you are daemonizing a java application, you might want to consider Java Service Wrapper (which provides a mechanism for setting the user id)
  • Another alternative could be su --session-command=[cmd] [user]

How to base64 encode image in linux bash / shell

There is a Linux command for that: base64

base64 DSC_0251.JPG >DSC_0251.b64

To assign result to variable use

test=`base64 DSC_0251.JPG`

How to use npm with node.exe?

I just installed latest version of node (0.6.12) in Windows 7 using msi (node-v0.6.12.msi).

npm is already shipped with it, no need to include it separately.

I was facing permission issue while running npm (npm install mysql), from the path where my nodejs resided, i.e. C:\Program Files (x86)\nodejs

Then I followed below steps:

1) Added C:\Program Files (x86)\nodejs\npm in environment variables - Path system variable.

2) went back to only C:\ in command prompt and gave the command - npm install mysql - and voila! it worked..

Hope this helps.

draw diagonal lines in div background with CSS

An svg dynamic solution for any screen is the following:

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" stroke-width="1" stroke="#000">
  <line x1="0" y1="0" x2="100%" y2="100%"/>
  <line x1="100%" y1="0" x2="0" y2="100%"/>
</svg>

And if you want to keep it in background use the position: absolute with top and left 0.

Default string initialization: NULL or Empty?

I think there's no reason not to use null for an unassigned (or at this place in a program flow not occurring) value. If you want to distinguish, there's ==null. If you just want to check for a certain value and don't care whether it's null or something different, String.Equals("XXX",MyStringVar) does just fine.

Copy Notepad++ text with formatting?

For those who do not see Plugins->NPPExport,

Download Plugin Manager from this. Extract contents and place under C/ProgramFile/NP++ installation, plugins & updater folder. Restart NP++. You should be able to see Plugins->Plugin Manager then. You can download any plugin, including NPPExport and install it to see the Copy command.

ImportError: No module named _ssl

Either install the supplementary packages for python-ssl using your package manager or recompile Python using -with-ssl (requires OpenSSL headers/libs installed).

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

In my case the answer is pretty simple. Please check carefully the hardcoded url port: it is 8080. For some reason the value has changed to: for example 3030.

Just refresh the port in your ajax url string to the appropriate one.

conn = new WebSocket('ws://localhost:3030'); //should solve the issue

Reading a key from the Web.Config using ConfigurationManager

with assuming below setting in .config file:

<configuration>
   <appSettings>
     <add key="PFUserName" value="myusername"/>
     <add key="PFPassWord" value="mypassword"/>
   </appSettings> 
</configuration>

try this:

public class myController : Controller
{
    NameValueCollection myKeys = ConfigurationManager.AppSettings;

    public void MyMethod()
    {
        var myUsername = myKeys["PFUserName"];
        var myPassword = myKeys["PFPassWord"];
    }
}

Make: how to continue after a command fails?

To get make to actually ignore errors on a single line, you can simply suffix it with ; true, setting the return value to 0. For example:

rm .lambda .lambda_t .activity .activity_t_lambda 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

How to test if a file is a directory in a batch script?

If you can cd into it, it's a directory:

set cwd=%cd%

cd /D "%1" 2> nul
@IF %errorlevel%==0 GOTO end

cd /D "%~dp1"
@echo This is a file.

@goto end2
:end
@echo This is a directory
:end2

@REM restore prior directory
@cd %cwd%

Auto number column in SharePoint list

it's in there by default. It's the id field.

How to amend a commit without changing commit message (reusing the previous one)?

Since git 1.7.9 version you can also use git commit --amend --no-edit to get your result.

Note that this will not include metadata from the other commit such as the timestamp which may or may not be important to you.

How to convert/parse from String to char in java?

import java.io.*;
class ss1 
{
    public static void main(String args[]) 
    {
        String a = new String("sample");
        System.out.println("Result: ");
        for(int i=0;i<a.length();i++)
        {
            System.out.println(a.charAt(i));
        }
    }
}

How to display HTML <FORM> as inline element?

Move your form tag just outside the paragraph and set margins / padding to zero:

<form style="margin: 0; padding: 0;">
  <p>
    Read this sentence 
    <input style="display: inline;" type="submit" value="or push this button" />
  </p>
</form>

In Visual Studio Code How do I merge between two local branches?

Update June 2017 (from VSCode 1.14)

The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch" command.
And PR 27405 added handling the diff3-style merge correctly.

Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers

https://code.visualstudio.com/assets/updates/1_18/merge.png

From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.


Original answer 2016:

The Version Control doc does not mention merge commands, only merge status and conflict support.

Even the latest 1.3 June release does not bring anything new to the VCS front.

This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool, because:

Is this feature being included in the next iteration, by any chance?

Probably not, this is a big endeavour, since a merge UI needs to be implemented.

That leaves the actual merge to be initiated from command line only.

Python Git Module experiences?

This is a pretty old question, and while looking for Git libraries, I found one that was made this year (2013) called Gittle.

It worked great for me (where the others I tried were flaky), and seems to cover most of the common actions.

Some examples from the README:

from gittle import Gittle

# Clone a repository
repo_path = '/tmp/gittle_bare'
repo_url = 'git://github.com/FriendCode/gittle.git'
repo = Gittle.clone(repo_url, repo_path)

# Stage multiple files
repo.stage(['other1.txt', 'other2.txt'])

# Do the commit
repo.commit(name="Samy Pesse", email="[email protected]", message="This is a commit")

# Authentication with RSA private key
key_file = open('/Users/Me/keys/rsa/private_rsa')
repo.auth(pkey=key_file)

# Do push
repo.push()

How can I view the allocation unit size of a NTFS partition in Vista?

Easiest way, confirmed on 2012r2.

  1. Go to "This PC"
  2. Right click on the Disk
  3. Click on Format

Under drop down "allocation unit size" will be the value of what the Allocation of the Unit size disk already is.

Can HTML checkboxes be set to readonly?

<input type="checkbox" readonly="readonly" name="..." />

with jquery:

$(':checkbox[readonly]').click(function(){
            return false;
        });

it still might be a good idea to give some visual hint (css, text,...), that the control won't accept inputs.

use current date as default value for a column

I have also come across this need for my database project. I decided to share my findings here.

1) There is no way to a NOT NULL field without a default when data already exists (Can I add a not null column without DEFAULT value)

2) This topic has been addressed for a long time. Here is a 2008 question (Add a column with a default value to an existing table in SQL Server)

3) The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified. (https://www.w3schools.com/sql/sql_default.asp)

4) The Visual Studio Database Project that I use for development is really good about generating change scripts for you. This is the change script created for my DB promotion:

GO
PRINT N'Altering [dbo].[PROD_WHSE_ACTUAL]...';

GO
ALTER TABLE [dbo].[PROD_WHSE_ACTUAL]
    ADD [DATE] DATE DEFAULT getdate() NOT NULL;

-

Here are the steps I took to update my database using Visual Studio for development.

1) Add default value (Visual Studio SSDT: DB Project: table designer) enter image description here

2) Use the Schema Comparison tool to generate the change script.

code already provided above

3) View the data BEFORE applying the change. enter image description here

4) View the data AFTER applying the change. enter image description here

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Given a class, see if instance has method (Ruby)

While respond_to? will return true only for public methods, checking for "method definition" on a class may also pertain to private methods.

On Ruby v2.0+ checking both public and private sets can be achieved with

Foo.private_instance_methods.include?(:bar) || Foo.instance_methods.include?(:bar)

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

Most efficient way to reverse a numpy array

np.fliplr() flips the array left to right.

Note that for 1d arrays, you need to trick it a bit:

arr1d = np.array(some_sequence)
reversed_arr = np.fliplr([arr1d])[0]

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Where is this year() function from?

You could also use the reshape2 package for this task:

require(reshape2)
df_melt <- melt(df1, id = c("date", "year", "month"))
dcast(df_melt, year + month ~ variable, sum)
#  year month         x1           x2
1  2000     1  -80.83405 -224.9540159
2  2000     2 -223.76331 -288.2418017
3  2000     3 -188.83930 -481.5601913
4  2000     4 -197.47797 -473.7137420
5  2000     5 -259.07928 -372.4563522

How to set HTML5 required attribute in Javascript?

What matters isn't the attribute but the property, and its value is a boolean.

You can set it using

 document.getElementById("edName").required = true;

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

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

Why there is no ConcurrentHashSet against ConcurrentHashMap

There's no built in type for ConcurrentHashSet because you can always derive a set from a map. Since there are many types of maps, you use a method to produce a set from a given map (or map class).

Prior to Java 8, you produce a concurrent hash set backed by a concurrent hash map, by using Collections.newSetFromMap(map)

In Java 8 (pointed out by @Matt), you can get a concurrent hash set view via ConcurrentHashMap.newKeySet(). This is a bit simpler than the old newSetFromMap which required you to pass in an empty map object. But it is specific to ConcurrentHashMap.

Anyway, the Java designers could have created a new set interface every time a new map interface was created, but that pattern would be impossible to enforce when third parties create their own maps. It is better to have the static methods that derive new sets; that approach always works, even when you create your own map implementations.