Programs & Examples On #Brightness

An attribute of visual perception in which a source appears to be radiating or reflecting light.

Button Width Match Parent

For match_parent you can use

SizedBox(
  width: double.infinity, // match_parent
  child: RaisedButton(...)
)

For any particular value you can use

SizedBox(
  width: 100, // specific value
  child: RaisedButton(...)
)

How to cat <<EOF >> a file containing code?

I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.

If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.

#!/bin/bash

FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""

cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}  
EOF

Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt

This can also be used to output blocks of text to the console with the same rules by omitting the file name

#!/bin/bash

VAR_EXAMPLE="\"string\""

cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console 
EOF

Will output "${VAR_EXAMPLE}="string" to console" to the console

How to Decrease Image Brightness in CSS

In short, place black behind the image, and lower the opactiy. You can do this by wrapping the image within a div, and then lowering the opacity of the image.

For example:

<!DOCTYPE html>

<style>
    .img-wrap {
        background: black;
        display: inline-block;
        line-height: 0;
    }
        .img-wrap > img {
            opacity: 0.8;
        }
</style>

<div class="img-wrap">
    <img src="http://mikecane.files.wordpress.com/2007/03/kitten.jpg" />
</div>

Here is a JSFiddle.

Setting Camera Parameters in OpenCV/Python

To avoid using integer values to identify the VideoCapture properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS in OpenCV 2.4 and cv2.CAP_PROP_FPS in OpenCV 3.0. (See also Stefan's comment below.)

Here a utility function that works for both OpenCV 2.4 and 3.0:

# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
  return getattr(cv2 if OPCV3 else cv2.cv,
    ("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)

OPCV3 is set earlier in my utilities code like this:

from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')

Capturing a single image from my webcam in Java or Python

I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.

You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:

from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave

graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Isn't it difficult even for humans to distinguish between a bottle and a can in the second image (provided the transparent region of the bottle is hidden)?

They are almost the same except for a very small region (that is, width at the top of the can is a little small while the wrapper of the bottle is the same width throughout, but a minor change right?)

The first thing that came to my mind was to check for the red top of bottle. But it is still a problem, if there is no top for the bottle, or if it is partially hidden (as mentioned above).

The second thing I thought was about the transparency of bottle. OpenCV has some works on finding transparent objects in an image. Check the below links.

Particularly look at this to see how accurately they detect glass:

See their implementation result:

Enter image description here

They say it is the implementation of the paper "A Geodesic Active Contour Framework for Finding Glass" by K. McHenry and J. Ponce, CVPR 2006.

It might be helpful in your case a little bit, but problem arises again if the bottle is filled.

So I think here, you can search for the transparent body of the bottles first or for a red region connected to two transparent objects laterally which is obviously the bottle. (When working ideally, an image as follows.)

Enter image description here

Now you can remove the yellow region, that is, the label of the bottle and run your algorithm to find the can.

Anyway, this solution also has different problems like in the other solutions.

  1. It works only if your bottle is empty. In that case, you will have to search for the red region between the two black colors (if the Coca Cola liquid is black).
  2. Another problem if transparent part is covered.

But anyway, if there are none of the above problems in the pictures, this seems be to a better way.

Android: How to turn screen on and off programmatically?

The best way to do it ( using rooted devices) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    .
    .
    .

    int flags = WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
    getWindow().addFlags(flags); // this is how your app will wake up the screen
    //you will call this activity later

   .
   .
   .
}

Now we have this two functions:

private void turnOffScreen(){

  try{
     Class c = Class.forName("android.os.PowerManager");
     PowerManager  mPowerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
     for(Method m : c.getDeclaredMethods()){
        if(m.getName().equals("goToSleep")){
          m.setAccessible(true);
          if(m.getParameterTypes().length == 1){
            m.invoke(mPowerManager,SystemClock.uptimeMillis()-2);
          }
        }
     } 
  } catch (Exception e){
  }
}

And this:

public void turnOnScreen(){
  Intent i = new Intent(this,YOURACTIVITYWITHFLAGS.class);
  startActivity(i);
}

Sorry for my bad english.

How to set background image of a view?

use this

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Default"]];

Converting RGB to grayscale/intensity

The specific numbers in the question are from CCIR 601 (see the Wikipedia link below).

If you convert RGB -> grayscale with slightly different numbers / different methods, you won't see much difference at all on a normal computer screen under normal lighting conditions -- try it.

Here are some more links on color in general:

Wikipedia Luma

Bruce Lindbloom 's outstanding web site

chapter 4 on Color in the book by Colin Ware, "Information Visualization", isbn 1-55860-819-2; this long link to Ware in books.google.com may or may not work

cambridgeincolor : excellent, well-written "tutorials on how to acquire, interpret and process digital photographs using a visually-oriented approach that emphasizes concept over procedure"

Should you run into "linear" vs "nonlinear" RGB, here's part of an old note to myself on this. Repeat, in practice you won't see much difference.


RGB -> ^gamma -> Y -> L*

In color science, the common RGB values, as in html rgb( 10%, 20%, 30% ), are called "nonlinear" or Gamma corrected. "Linear" values are defined as

Rlin = R^gamma,  Glin = G^gamma,  Blin = B^gamma

where gamma is 2.2 for many PCs. The usual R G B are sometimes written as R' G' B' (R' = Rlin ^ (1/gamma)) (purists tongue-click) but here I'll drop the '.

Brightness on a CRT display is proportional to RGBlin = RGB ^ gamma, so 50% gray on a CRT is quite dark: .5 ^ 2.2 = 22% of maximum brightness. (LCD displays are more complex; furthermore, some graphics cards compensate for gamma.)

To get the measure of lightness called L* from RGB, first divide R G B by 255, and compute

Y = .2126 * R^gamma + .7152 * G^gamma + .0722 * B^gamma

This is Y in XYZ color space; it is a measure of color "luminance". (The real formulas are not exactly x^gamma, but close; stick with x^gamma for a first pass.)

Finally,

L* = 116 * Y ^ 1/3 - 16

"... aspires to perceptual uniformity [and] closely matches human perception of lightness." -- Wikipedia Lab color space

Formula to determine brightness of RGB color

For clarity, the formulas that use a square root need to be

sqrt(coefficient * (colour_value^2))

not

sqrt((coefficient * colour_value))^2

The proof of this lies in the conversion of a R=G=B triad to greyscale R. That will only be true if you square the colour value, not the colour value times coefficient. See Nine Shades of Greyscale

How to change value of object which is inside an array using JavaScript or jQuery?

given the following data, we want to replace berries in the summerFruits list with watermelon.

const summerFruits = [
{id:1,name:'apple'}, 
{id:2, name:'orange'}, 
{id:3, name: 'berries'}];

const fruit = {id:3, name: 'watermelon'};

Two ways you can do this.

First approach:

//create a copy of summer fruits.
const summerFruitsCopy = [...summerFruits];

//find index of item to be replaced
const targetIndex = summerFruits.findIndex(f=>f.id===3); 

//replace the object with a new one.
summerFruitsCopy[targetIndex] = fruit;

Second approach: using map, and spread:

const summerFruitsCopy = summerFruits.map(fruitItem => 
fruitItem .id === fruit.id ? 
    {...summerFruits, ...fruit} : fruitItem );

summerFruitsCopy list will now return an array with updated object.

Merge 2 DataTables and store in a new one

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.

How do I use a pipe to redirect the output of one command to the input of another?

This should work:

for /F "tokens=*" %i in ('temperature') do prismcom.exe usb %i

If running in a batch file, you need to use %%i instead of just %i (in both places).

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

Share Text on Facebook from Android App via ACTION_SEND

So I have a work around, but it assumes you have control over the page you're sharing...

If you format your EXTRA_TEXT like so...

String myText = "Hey!\nThis is a neat pic!";
String extraText = "http://www.example.com/myPicPage.html?extraText=\n\n" + myText;

... then on non-Facebook apps, your text should appear something like this:

http://www.example.com/myPicPage.html?extraText=

Hey!
This is a neat pic!

Now if you update your website such that requests with the extraText query parameter return the contents of extraText in the page's meta data.

<!-- Make sure to sanitize your inputs! e.g. http://xkcd.com/327/ -->
<meta name="title" content="Hey! this is a neat pic!">

Then when Facebook escapes that url to generate the dialog, it'll read the title meta data and embed it into your share dialog.

I realize this is a pretty yuck solution, so take with a grain of salt...

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

Using ping in c#

private void button26_Click(object sender, EventArgs e)
{
    System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
    proc.FileName = @"C:\windows\system32\cmd.exe";
    proc.Arguments = "/c ping -t " + tx1.Text + " ";
    System.Diagnostics.Process.Start(proc);
    tx1.Focus();
}

private void button27_Click(object sender, EventArgs e)
{
    System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
    proc.FileName = @"C:\windows\system32\cmd.exe";
    proc.Arguments = "/c ping  " + tx2.Text + " ";
    System.Diagnostics.Process.Start(proc);
    tx2.Focus();
}

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

http://en.wikipedia.org/wiki/Visual_C++

You are using Visual C++ 2012 which is v110. v120 means Visual C++ 2013.

So either you change the project settings to use toolset v110, or you install Visual Studio 2013 on this machine and use VS2013 to compile it.

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

Vertically aligning CSS :before and :after content

I spent a good amount of time trying to work this out today, and couldn't get things working using line-height or vertical-align. The easiest solution I was able to find was to set the <a/> to be relatively positioned so it would contain absolutes, and the :after to be positioned absolutely taking it out of the flow.

a{
    position:relative;
    padding-right:18px;
}
a:after{
    position:absolute;
    content:url(image.png);
}

The after image seemed to automatically center in that case, at least under Firefox/Chrome. Such may be a bit sloppier for browsers not supporting :after, due to the excess spacing on the <a/>.

HTML5 Audio stop function

In IE 11 I used combined variant:

player.currentTime = 0; 
player.pause(); 
player.currentTime = 0;

Only 2 times repeat prevents IE from continuing loading media stream after pause() and flooding a disk by that.

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

Spring cannot find bean xml configuration file when it does exist

You have looked at src directory. The xml file indeed exist there. But look at class or bin/build directory where all your output classes are set. I suspect you will need only resources/beans.xml path to use.

How can I require at least one checkbox be checked before a form can be submitted?

<ul>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>

<script type="text/javascript">
$(document).ready(function(){
    var checkboxes = $('.checkboxes');
    checkboxes.change(function(){
        if($('.checkboxes:checked').length>0) {
            checkboxes.removeAttr('required');
        } else {
            checkboxes.attr('required', 'required');
        }
    });
});
</script>

How to make System.out.println() shorter

package some.useful.methods;

public class B {

    public static void p(Object s){
        System.out.println(s);
    }
}
package first.java.lesson;

import static some.useful.methods.B.*;

public class A {

    public static void main(String[] args) {

        p("Hello!");

    }
}

JavaScript function to add X months to a date

As demonstrated by many of the complicated, ugly answers presented, Dates and Times can be a nightmare for programmers using any language. My approach is to convert dates and 'delta t' values into Epoch Time (in ms), perform any arithmetic, then convert back to "human time."

// Given a number of days, return a Date object
//   that many days in the future. 
function getFutureDate( days ) {

    // Convert 'days' to milliseconds
    var millies = 1000 * 60 * 60 * 24 * days;

    // Get the current date/time
    var todaysDate = new Date();

    // Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
    var futureMillies = todaysDate.getTime() + millies;

    // Use the Epoch time of the targeted future date to create
    //   a new Date object, and then return it.
    return new Date( futureMillies );
}

// Use case: get a Date that's 60 days from now.
var twoMonthsOut = getFutureDate( 60 );

This was written for a slightly different use case, but you should be able to easily adapt it for related tasks.

EDIT: Full source here!

How to dynamically set bootstrap-datepicker's date value?

On page load if you dont want to fire the changeDate event which I didnt

$('#calendarDatePicker').data("date", new Date());
$('#calendarDatePicker').datapicker();

Get week day name from a given month, day and year individually in SQL Server

You need to construct a date string. You're using / or - operators which do MATH/numeric operations on the numeric return values of DATEPART. Then DATENAME is taking that numeric value and interpreting it as a date.

You need to convert it to a string. For example:

SELECT (
  DATENAME(dw, 
  CAST(DATEPART(m, GETDATE()) AS VARCHAR) 
  + '/' 
  + CAST(DATEPART(d, myDateCol1) AS VARCHAR) 
  + '/' 
  + CAST(DATEPART(yy, getdate()) AS VARCHAR))
  )

MySQL Trigger: Delete From Table AFTER DELETE

I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
    WHERE patron_info.pid = old.id;
END

Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

Log4net does not write the log in the log file

There are a few ways to use log4net. I found it is useful while I was searching for a solution. The solution is described here: https://www.hemelix.com/log4net/

Java Refuses to Start - Could not reserve enough space for object heap

I am using SOA env, Decreased Xmx from 1024 to 768 in setSOADomainENV.cmd resolved the issue.

REM set DEFAULT_MEM_ARGS=-Xms512m -Xmx1024m
set DEFAULT_MEM_ARGS=-Xms512m -Xmx768m

How to execute Table valued function

You can execute it just as you select a table using SELECT clause. In addition you can provide parameters within parentheses.

Try with below syntax:

SELECT * FROM yourFunctionName(parameter1, parameter2)

How to remove stop words using nltk or python

using filter:

from nltk.corpus import stopwords
# ...  
filtered_words = list(filter(lambda word: word not in stopwords.words('english'), word_list))

How to design RESTful search/filtering?

If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.

What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.

Use URL or Query parameters instead of request body parameters, e.g.:

/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx 

In fact, the HTTP RFC 7231 says that:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

For more information take a look here.

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

How do I do a multi-line string in node.js?

If you use io.js, it has support for multi-line strings as they are in ECMAScript 6.

var a =
`this is
a multi-line
string`;

See "New String Methods" at http://davidwalsh.name/es6-io for details and "template strings" at http://kangax.github.io/compat-table/es6/ for tracking compatibility.

How do I execute external program within C code in linux with arguments?

How about like this:

char* cmd = "./foo 1 2 3";
system(cmd);

How to use terminal commands with Github?

git add myfile.h
git commit -m "your commit message"
git push -u origin master

if you don't remember all the files you need to update, use

git status

Detecting installed programs via registry

In addition to all the registry keys mentioned above, you may also have to look at HKEY_CURRENT_USER\Software\Microsoft\Installer\Products for programs installed just for the current user.

How do I analyze a program's core dump file with GDB when it has command-line parameters?

Simply type the command:

$ gdb <Binary> <codeDump>

Or

$ gdb <binary>

$ gdb) core <coreDump>

There isn't any need to provide any command line argument. The code dump generated due to an earlier exercise.

How to quickly drop a user with existing privileges

There is no REVOKE ALL PRIVILEGES ON ALL VIEWS, so I ended with:

do $$
DECLARE r record;
begin
  for r in select * from pg_views where schemaname = 'myschem'
  loop
    execute 'revoke all on ' || quote_ident(r.schemaname) ||'.'|| quote_ident(r.viewname) || ' from "XUSER"';
  end loop;
end $$;

and usual:

REVOKE ALL PRIVILEGES ON DATABASE mydb FROM "XUSER";
REVOKE ALL PRIVILEGES ON SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA myschem FROM "XUSER";

for the following to succeed:

drop role "XUSER";

ps command doesn't work in docker container

ps is not installed in the base wheezy image. Try this from within the container:

RUN apt-get update && apt-get install -y procps

How to get the current directory in a C program?

Note that getcwd(3) is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.

Must link with -loldnames (oldnames.lib, which is done automatically in most cases), or use _getcwd(). The unprefixed version is unavailable under Windows RT.

How to remove all of the data in a table using Django

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance1 = SomeModel.objects.get(id=id)
instance1.delete()

// don't use same name

Jenkins could not run git

For Jenkins 2.121.3 version, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe It works!

In Jenkins, give the http URL. SSH URL shows similar error.

How can I remove an element from a list?

You can also negatively index from a list using the extract function of the magrittr package to remove a list item.

a <- seq(1,5)
b <- seq(2,6)
c <- seq(3,7)
l <- list(a,b,c)

library(magrittr)

extract(l,-1) #simple one-function method
[[1]]
[1] 2 3 4 5 6

[[2]]
[1] 3 4 5 6 7

BULK INSERT with identity (auto-increment) column

You have to do bulk insert with format file:

   BULK INSERT Employee FROM 'path\tempFile.csv ' 
   WITH (FORMATFILE = 'path\tempFile.fmt');

where format file (tempFile.fmt) looks like this:

11.0
2
1 SQLCHAR 0 50 "\t"  2  Name   SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3  Address  SQL_Latin1_General_CP1_CI_AS

more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx

How to prevent long words from breaking my div?

Two fixes:

  1. overflow:scroll -- this makes sure your content can be seen at the cost of design (scrollbars are ugly)
  2. overflow:hidden -- just cuts off any overflow. It means people can't read the content though.

If (in the SO example) you want to stop it overlapping the padding, you'd probably have to create another div, inside the padding, to hold your content.

Edit: As the other answers state, there are a variety of methods for truncating the words, be that working out the render width on the client side (never attempt to do this server-side as it will never work reliably, cross platform) through JS and inserting break-characters, or using non-standard and/or wildly incompatible CSS tags (word-wrap: break-word doesn't appear to work in Firefox).

You will always need an overflow descriptor though. If your div contains another too-wide block-type piece of content (image, table, etc), you'll need overflow to make it not destroy the layout/design.

So by all means use another method (or a combination of them) but remember to add overflow too so you cover all browsers.

Edit 2 (to address your comment below):

Start off using the CSS overflow property isn't perfect but it stops designs breaking. Apply overflow:hidden first. Remember that overflow might not break on padding so either nest divs or use a border (whatever works best for you).

This will hide overflowing content and therefore you might lose meaning. You could use a scrollbar (using overflow:auto or overflow:scroll instead of overflow:hidden) but depending on the dimensions of the div, and your design, this might not look or work great.

To fix it, we can use JS to pull things back and do some form of automated truncation. I was half-way through writing out some pseudo code for you but it gets seriously complicated about half-way through. If you need to show as much as possible, give hyphenator a look in (as mentioned below).

Just be aware that this comes at the cost of user's CPUs. It could result in pages taking a long time to load and/or resize.

jackson deserialization json to java-objects

You have to change the line

product userFromJSON = mapper.readValue(userDataJSON, product.class);

to

product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);

since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

Edit: You can also go with Steven Schlansker's suggestion and use

List<product> userFromJSON =
        mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});

instead if you want to avoid arrays.

What resources are shared between threads?

From Wikipedia (I think that would make a really good answer for the interviewer :P)

Threads differ from traditional multitasking operating system processes in that:

  • processes are typically independent, while threads exist as subsets of a process
  • processes carry considerable state information, whereas multiple threads within a process share state as well as memory and other resources
  • processes have separate address spaces, whereas threads share their address space
  • processes interact only through system-provided inter-process communication mechanisms.
  • Context switching between threads in the same process is typically faster than context switching between processes.

SQL: How to properly check if a record exists

I would prefer not use Count function at all:

IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
     <do smth>

For example if you want to check if user exists before inserting it into the database the query can look like this:

IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
    INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse

Console.Write((int)response.StatusCode);

HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
{
    ...
    Moved = 301,
    OK = 200,
    Redirect = 302,
    ...
}

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

Best way to check that element is not present using Selenium WebDriver with java

Unable to comment to The Meteor Test Manual, since I have no rep, but I wanted to provide an example that took me quite awhile to figure out:

Assert.assertEquals(0, wd.findElements(By.locator("locator")).size());

This assertion verifies that there are no matching elements in the DOM and returns the value of Zero, so the assertion passes when the element is not present. Also it would fail if it was present.

Trusting all certificates with okHttp

Update OkHttp 3.0, the getAcceptedIssuers() function must return an empty array instead of null.

How to run Conda?

This is the easiest solution for me :

  1. go to the user folder (/home/liedji in my case):
  2. run the command: ./anaconda3/bin/conda init
  3. close and restart the terminal
  4. and finally run conda --version to test if everything works

Note: windows users should use ./anaconda3/Scripts/conda.exe init instead.

TypeScript error TS1005: ';' expected (II)

Just try to without changing anything npm install [email protected] X.X.X is your current version

Get month and year from a datetime in SQL Server 2005

Use:

select datepart(mm,getdate())  --to get month value
select datename(mm,getdate())  --to get name of month

PHP error: Notice: Undefined index:

undefined index means the array key is not set , do a var_dump($_POST);die(); before the line that throws the error and see that you're trying to get an array key that does not exist.

How to make Visual Studio copy a DLL file to the output directory?

The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.

I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line

now I added these two lines to copy the output dll into the two folders:

xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug

How to Populate a DataTable from a Stored Procedure

You don't need to add the columns manually. Just use a DataAdapter and it's simple as:

DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
   cmd.CommandType = CommandType.StoredProcedure;
   da.Fill(table);
}

Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter.

The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

Why cannot change checkbox color whatever I do?

Technically, it is possible to change the color of anything with CSS. As mentioned, you can't change the background-color or color but you can use CSS filters. For example:

input[type="checkbox"] { /* change "blue" browser chrome to yellow */
  filter: invert(100%) hue-rotate(18deg) brightness(1.7);
}

If you are really looking for design control over checkboxes though, your best bet is to do the "hidden" checkbox and style an adjacent element such as a div.

How do I detect what .NET Framework versions and service packs are installed?

Using the Signum.Utilities library from SignumFramework (which you can use stand-alone), you can get it nicely and without dealing with the registry by yourself:

AboutTools.FrameworkVersions().ToConsole();
//Writes in my machine:
//v2.0.50727 SP2
//v3.0 SP2
//v3.5 SP1

ECMAScript 6 class destructor

I just came across this question in a search about destructors and I thought there was an unanswered part of your question in your comments, so I thought I would address that.

thank you guys. But what would be a good convention if ECMAScript doesn't have destructors? Should I create a method called destructor and call it manually when I'm done with the object? Any other idea?

If you want to tell your object that you are now done with it and it should specifically release any event listeners it has, then you can just create an ordinary method for doing that. You can call the method something like release() or deregister() or unhook() or anything of that ilk. The idea is that you're telling the object to disconnect itself from anything else it is hooked up to (deregister event listeners, clear external object references, etc...). You will have to call it manually at the appropriate time.

If, at the same time you also make sure there are no other references to that object, then your object will become eligible for garbage collection at that point.

ES6 does have weakMap and weakSet which are ways of keeping track of a set of objects that are still alive without affecting when they can be garbage collected, but it does not provide any sort of notification when they are garbage collected. They just disappear from the weakMap or weakSet at some point (when they are GCed).


FYI, the issue with this type of destructor you ask for (and probably why there isn't much of a call for it) is that because of garbage collection, an item is not eligible for garbage collection when it has an open event handler against a live object so even if there was such a destructor, it would never get called in your circumstance until you actually removed the event listeners. And, once you've removed the event listeners, there's no need for the destructor for this purpose.

I suppose there's a possible weakListener() that would not prevent garbage collection, but such a thing does not exist either.


FYI, here's another relevant question Why is the object destructor paradigm in garbage collected languages pervasively absent?. This discussion covers finalizer, destructor and disposer design patterns. I found it useful to see the distinction between the three.


Edit in 2020 - proposal for object finalizer

There is a Stage 3 EMCAScript proposal to add a user-defined finalizer function after an object is garbage collected.

A canonical example of something that would benefit from a feature like this is an object that contains a handle to an open file. If the object is garbage collected (because no other code still has a reference to it), then this finalizer scheme allows one to at least put a message to the console that an external resource has just been leaked and code elsewhere should be fixed to prevent this leak.

If you read the proposal thoroughly, you will see that it's nothing like a full-blown destructor in a language like C++. This finalizer is called after the object has already been destroyed and you have to predetermine what part of the instance data needs to be passed to the finalizer for it to do its work. Further, this feature is not meant to be relied upon for normal operation, but rather as a debugging aid and as a backstop against certain types of bugs. You can read the full explanation for these limitations in the proposal.

SQL WHERE ID IN (id1, id2, ..., idn)

Try this

SELECT Position_ID , Position_Name
FROM 
position
WHERE Position_ID IN (6 ,7 ,8)
ORDER BY Position_Name

How to config routeProvider and locationProvider in angularJS?

AngularJS provides a simple and concise way to associate routes with controllers and templates using a $routeProvider object. While recently updating an application to the latest release (1.2 RC1 at the current time) I realized that $routeProvider isn’t available in the standard angular.js script any longer.

After reading through the change log I realized that routing is now a separate module (a great move I think) as well as animation and a few others. As a result, standard module definitions and config code like the following won’t work any longer if you’re moving to the 1.2 (or future) release:

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

app.config(function ($routeProvider) {

    $routeProvider.when('/', {
        controller: 'customersController',
        templateUrl: '/app/views/customers.html'
    });

});

How do you fix it?

Simply add angular-route.js in addition to angular.js to your page (grab a version of angular-route.js here – keep in mind it’s currently a release candidate version which will be updated) and change the module definition to look like the following:

var app = angular.module('customersApp', ['ngRoute']);

If you’re using animations you’ll need angular-animation.js and also need to reference the appropriate module:

 var app = angular.module('customersApp', ['ngRoute', 'ngAnimate']);

Your Code can be as follows:

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

    app.config(function($routeProvider) {

    $routeProvider
        .when('/controllerone', {
                controller: 'friendDetails',
                templateUrl: 'controller3.html'

            }, {
                controller: 'friendsName',
                templateUrl: 'controller3.html'

            }

    )
        .when('/controllerTwo', {
            controller: 'simpleControoller',
            templateUrl: 'views.html'
        })
        .when('/controllerThree', {
            controller: 'simpleControoller',
            templateUrl: 'view2.html'
        })
        .otherwise({
            redirectTo: '/'
        });

});

relative path to CSS file

if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"

View HTTP headers in Google Chrome?

To view the request or response HTTP headers in Google Chrome, take the following steps :

  1. In Chrome, visit a URL(such as https://www.google.com), right click, select Inspect to open the developer tools.
    enter image description here
  2. Select Network tab.
  3. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

enter image description here

HTML5 best practices; section/header/aside/article elements

„line 23. Is this div right? or must this be a section?“

Neither – there is a main tag for that purpose, which is only allowed once per page and should be used as a wrapper for the main content (in contrast to a sidebar or a site-wide header).

<main>
    <!-- The main content -->
</main>

http://www.w3.org/html/wg/drafts/html/master/grouping-content.html#the-main-element

Best way to determine user's locale within browser

You said your website has Flash, then, as another option, you can get operation system's language with flash.system.Capabilities.language— see How to determine OS language within browser to guess an operation system locale.

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

How do I force git pull to overwrite everything on every pull?

I'm not sure how to do it in one command but you could do something like:

git reset --hard
git pull

or even

git stash
git pull

C++ IDE for Linux?

SlickEdit. I have used and loved SlickEdit since 2005, both on Windows and on Linux. I also have experience working in Visual Studio (5, 6, 2003, 2005) and just with Emacs and command line. I use SlickEdit with external makefiles, some of my teammates use SlickEdit, others use Emacs/vi. I do not use the integrated debugger, integrated version control, integrated build system: I generally find too much integration to be real pain. SlickEdit is robust (very few bugs), fast and intuitive. It is like a German car, a driver's car.

The newest versions of SlickEdit seem to offer many features that do not interest me, I am a little worried that the product will become bloated and diluted in the future. For now (I use V13.0) it is great.

Set date input field's max date to today

it can be useful : If you want to do it with Symfony forms :

 $today = new DateTime('now');
 $formBuilder->add('startDate', DateType::class, array(
                   'widget' => 'single_text',
                   'data'   => new \DateTime(),
                   'attr'   => ['min' => $today->format('Y-m-d')]
                   ));

What is the maximum length of a String in PHP?

In a new upcoming php7 among many other features, they added a support for strings bigger than 2^31 bytes:

Support for strings with length >= 2^31 bytes in 64 bit builds.

Sadly they did not specify how much bigger can it be.

c++ Read from .csv file

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M

Try this

0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M


while(file.good())
{

    getline(file, ID, ',');
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero) ; \\ diff
    cout << "Sexo: " <<  genero;\\diff


}

Select all from table with Laravel and Eloquent

You simply call

Blog::all();

//example usage.
$posts = Blog::all();

$posts->each(function($post) // foreach($posts as $post) { }
{
    //do something
}

from anywhere in your application.

Reading the documentation will help a lot.

How to check 'undefined' value in jQuery

I know I am late to answer the function but jquery have a in build function to do this

if(jQuery.type(val) === "undefined"){
    //Some code goes here
}

Refer jquery API document of jquery.type https://api.jquery.com/jQuery.type/ for the same.

How can I get zoom functionality for images?

Something like below will do it.

@Override public boolean onTouch(View v,MotionEvent e)
{

    tap=tap2=drag=pinch=none;
    int mask=e.getActionMasked();
    posx=e.getX();posy=e.getY();

    float midx= img.getWidth()/2f;
    float midy=img.getHeight()/2f;
    int fingers=e.getPointerCount();

    switch(mask)
    {
        case MotionEvent.ACTION_POINTER_UP:
            tap2=1;break;

        case MotionEvent.ACTION_UP:
            tap=1;break;

        case MotionEvent.ACTION_MOVE:
            drag=1;
    }
    if(fingers==2){nowsp=Math.abs(e.getX(0)-e.getX(1));}
    if((fingers==2)&&(drag==0)){ tap2=1;tap=0;drag=0;}
    if((fingers==2)&&(drag==1)){ tap2=0;tap=0;drag=0;pinch=1;}

    if(pinch==1)

    {
        if(nowsp>oldsp)scale+=0.1;
        if(nowsp<oldsp)scale-=0.1;
        tap2=tap=drag=0;    
    }
    if(tap2==1)
        {
            scale-=0.1;
            tap=0;drag=0;
        }
    if(tap==1)
        {
            tap2=0;drag=0;
            scale+=0.1;
        }
    if(drag==1)
        {
            movx=posx-oldx;
            movy=posy-oldy;
            x+=movx;
            y+=movy;
            tap=0;tap2=0;
        }
    m.setTranslate(x,y);
    m.postScale(scale,scale,midx,midy);
    img.setImageMatrix(m);img.invalidate();
    tap=tap2=drag=none;
    oldx=posx;oldy=posy;
    oldsp=nowsp;
    return true;
}


public void onCreate(Bundle b)
{
        super.onCreate(b);

    img=new ImageView(this);
    img.setScaleType(ImageView.ScaleType.MATRIX);
    img.setOnTouchListener(this);

    path=Environment.getExternalStorageDirectory().getPath();   
    path=path+"/DCIM"+"/behala.jpg";
    byte[] bytes;
    bytes=null;
    try{
        FileInputStream fis;
        fis=new FileInputStream(path);
        BufferedInputStream bis;
        bis=new BufferedInputStream(fis);
        bytes=new byte[bis.available()];
        bis.read(bytes);
        if(bis!=null)bis.close();
        if(fis!=null)fis.close();

     }
    catch(Exception e)
        {
        ret="Nothing";
        }
    Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);

    img.setImageBitmap(bmp);

    setContentView(img);
}

For viewing complete program see here: Program to zoom image in android

PHP convert string to hex and hex to string

Using @bill-shirley answer with a little addition

function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}

Usage:

  $str = "Go placidly amidst the noise";
  $hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
  $strstr = hex_to_str($str);// Go placidly amidst the noise

Loop through a comma-separated shell variable

Try this one.

#/bin/bash   
testpid="abc,def,ghij" 
count=`echo $testpid | grep -o ',' | wc -l` # this is not a good way
count=`expr $count + 1` 
while [ $count -gt 0 ]  ; do
     echo $testpid | cut -d ',' -f $i
     count=`expr $count - 1 `
done

How to replace (or strip) an extension from a filename in Python?

As @jethro said, splitext is the neat way to do it. But in this case, it's pretty easy to split it yourself, since the extension must be the part of the filename coming after the final period:

filename = '/home/user/somefile.txt'
print( filename.rsplit( ".", 1 )[ 0 ] )
# '/home/user/somefile'

The rsplit tells Python to perform the string splits starting from the right of the string, and the 1 says to perform at most one split (so that e.g. 'foo.bar.baz' -> [ 'foo.bar', 'baz' ]). Since rsplit will always return a non-empty array, we may safely index 0 into it to get the filename minus the extension.

Force browser to clear cache

I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody

<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...

EDIT As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:

<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"

How to add an extra language input to Android?

I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

What is the best way to access redux store outside a react component?

It might be a bit late but i think the best way is to use axios.interceptors as below. Import urls might change based on your project setup.

index.js

import axios from 'axios';
import setupAxios from './redux/setupAxios';
import store from './redux/store';

// some other codes

setupAxios(axios, store);

setupAxios.js

export default function setupAxios(axios, store) {
    axios.interceptors.request.use(
        (config) => {
            const {
                auth: { tokens: { authorization_token } },
            } = store.getState();

            if (authorization_token) {
                config.headers.Authorization = `Bearer ${authorization_token}`;
            }

            return config;
        },
       (err) => Promise.reject(err)
    );
}

Which to use <div class="name"> or <div id="name">?

The object itself will not change. The main difference between these 2 keyword is the use:

  • The ID is usually single in the page
  • The class can have one or many occurences

In the CSS or Javascript files:

  • The ID will be accessed by the character #
  • The class will be accessed by the character .

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

How to prevent a background process from being stopped after closing SSH client in Linux

Personally, I like the 'batch' command.

$ batch
> mycommand -x arg1 -y arg2 -z arg3
> ^D

This stuffs it in to the background, and then mails the results to you. It's a part of cron.

Trying to load local JSON file to show data in a html page using JQuery

Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.

According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>        
<script type="text/javascript" language="javascript" src="priorities.json"></script> 

<script type="text/javascript">
   $(document).ready(function(e) {
         alert(jsonObject.start.count);
   });
</script>

Your priorities.json file:

var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js">    </script> 
     <script type="text/javascript">
           $(document).ready(function(e) {

           });

           function jsonCallback(jsonObject){
               alert(jsonObject.start.count);
           }
        </script>

 <script type="text/javascript" language="javascript" src="priorities.json"></script> 

Your priorities.json file:

jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.

With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

Convert a Unix timestamp to time in JavaScript

This works with PHP timestamps

_x000D_
_x000D_
var d = 1541415288860;
//var d =val.timestamp;

//NB: use + before variable name
var date = new Date(+d);

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
_x000D_
_x000D_
_x000D_

var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());

the methods above will generate this results

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM

There's a bunch of methods that work perfectly with timestamps. Cant list them all

npm - how to show the latest version of a package

You can use:

npm show {pkg} version

(so npm show express version will return now 3.0.0rc3).

Add Marker function with Google Maps API

<div id="map" style="width:100%;height:500px"></div>

<script>
function myMap() {
  var myCenter = new google.maps.LatLng(51.508742,-0.120850);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 5};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>

How to show google.com in an iframe?

This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.

<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">

web

I guess the better option is to just use Curl or similar.

Regex Last occurrence?

One that worked for me was:

.+(\\.+)$

Try it online!

Explanation:

.+     - any character except newline
(      - create a group
 \\.+   - match a backslash, and any characters after it
)      - end group
$      - this all has to happen at the end of the string

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Setting up connection string in ASP.NET to SQL SERVER

Connection in WebConfig

Add the your connection string to the <connectionStrings> element in the Web.config file.

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public static string ConnectionString{
get{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;}
set{}

Setting Oracle 11g Session Timeout

Does the DB know the connection has dropped, or is the session still listed in v$session? That would indicate, I think, that it's being dropped by the network. Do you know how long it can stay idle before encountering the problem, and if that bears any resemblance to the TCP idle values (net.ipv4.tcp_keepalive_time, tcp_keepalive_probes and tcp_keepalive_interval from sysctl if I recall correctly)? Can't remember whether sysctl changes persist by default, but that might be something that was modified and then reset by the reboot.

Also you might be able to reset your JDBC connections without bouncing the whole server; certainly can in WebLogic, which I realise doesn't help much, but I'm not familiar with the Tomcat equivalents.

jQuery.inArray(), how to use it right?

the shortest and simplest way is.

arrayHere = ['cat1', 'dog2', 'bat3']; 

if(arrayHere[any key want to search])   
   console.log("yes found in array");

How do I pass along variables with XMLHTTPRequest

Yes that's the correct method to do it with a GET request.

However, please remember that multiple query string parameters should be separated with &

eg. ?variable1=value1&variable2=value2

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

Difference between ProcessBuilder and Runtime.exec()

Yes there is a difference.

  • The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments.

  • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)

So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.

Checking for an empty file in C++

Perhaps something akin to:

bool is_empty(std::ifstream& pFile)
{
    return pFile.peek() == std::ifstream::traits_type::eof();
}

Short and sweet.


With concerns to your error, the other answers use C-style file access, where you get a FILE* with specific functions.

Contrarily, you and I are working with C++ streams, and as such cannot use those functions. The above code works in a simple manner: peek() will peek at the stream and return, without removing, the next character. If it reaches the end of file, it returns eof(). Ergo, we just peek() at the stream and see if it's eof(), since an empty file has nothing to peek at.

Note, this also returns true if the file never opened in the first place, which should work in your case. If you don't want that:

std::ifstream file("filename");

if (!file)
{
    // file is not open
}

if (is_empty(file))
{
    // file is empty
}

// file is open and not empty

How to create timer in angular2

import {Component, View, OnInit, OnDestroy} from "angular2/core";

import { Observable, Subscription } from 'rxjs/Rx';

@Component({

})
export class NewContactComponent implements OnInit, OnDestroy {

    ticks = 0;
    private timer;
    // Subscription object
    private sub: Subscription;


    ngOnInit() {
        this.timer = Observable.timer(2000,5000);
        // subscribing to a observable returns a subscription object
        this.sub = this.timer.subscribe(t => this.tickerFunc(t));
    }
    tickerFunc(tick){
        console.log(this);
        this.ticks = tick
    }

    ngOnDestroy(){
        console.log("Destroy timer");
        // unsubscribe here
        this.sub.unsubscribe();

    }


}

Joining Multiple Tables - Oracle

While former answer is absolutely correct, I prefer using the JOIN ON syntax to be sure that I know how do I join and on what fields. It would look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order         Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';

This syntax seperates completely the WHERE clause from the JOIN clause, making the statement more readable and easier for you to debug.

Access iframe elements in JavaScript

Make sure your iframe is already loaded. Old but reliable way without jQuery:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>

Where is the IIS Express configuration / metabase file found?

To come full circle and include all versions of Visual Studio, @Myster originally stated that;

Pre Visual Studio 2015 the paths to applicationhost.config were:

%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config

Visual Studio 2015/2017 path can be found at: (credit: @Talon)

$(solutionDir)\.vs\config\applicationhost.config

Visual Studio 2019 path can be found at: (credit: @Talon)

$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config

But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)

So, if you make a change in the applicationhost.config you also have to make sure your changes match here:

$(solutionDir)\ProjectName.sln

The two important settings should look like:

Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"

and

VWDPort = "Port#"

What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.

HTML5 textarea placeholder not appearing

This one has always been a gotcha for me and many others. In short, the opening and closing tags for the <textarea> element must be on the same line, otherwise a newline character occupies it. The placeholder will therefore not be displayed since the input area contains content (a newline character is, technically, valid content).

Good:

<textarea></textarea>

Bad:

<textarea>
</textarea>

Update (2020)

This is not true anymore, according to the HTML5 parsing spec:

If the next token is a U+000A LINE FEED (LF) character token, 
then ignore that token and move on to the next one. (Newlines 
at the start of textarea elements are ignored as an authoring 
convenience.)

You might still have trouble if you editor insists on ending lines with CRLF, though.

C# naming convention for constants?

The ALL_CAPS is taken from the C and C++ way of working I believe. This article here explains how the style differences came about.

In the new IDE's such as Visual Studio it is easy to identify the types, scope and if they are constant so it is not strictly necessary.

The FxCop and Microsoft StyleCop software will help give you guidelines and check your code so everyone works the same way.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

In Java or JavaScript:

driver.navigate().refresh();

This should refresh page.

jQuery if Element has an ID?

You can do this:

if ($(".parent a[Id]").length > 0) {

    /* then do something here */

}

Comments in Android Layout xml

From Federico Culloca's note:

Also you cannot use them inside tags

Means; you have to put the comment at the top or bottom of the file - all the places you really want to add comments are at least inside the top level layout tag

How do you serialize a model instance in Django?

Here's my solution for this, which allows you to easily customize the JSON as well as organize related records

Firstly implement a method on the model. I call is json but you can call it whatever you like, e.g.:

class Car(Model):
    ...
    def json(self):
        return {
            'manufacturer': self.manufacturer.name,
            'model': self.model,
            'colors': [color.json for color in self.colors.all()],
        }

Then in the view I do:

data = [car.json for car in Car.objects.all()]
return HttpResponse(json.dumps(data), content_type='application/json; charset=UTF-8', status=status)

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

Test iOS app on device without apple developer program or jailbreak

Follow these Steps:

1.Open the Xcode->Select the project->select targets->Tick an automatically manage signing->then add your apple developer account->clean the project->build the project->run,everything works fine.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

For anyone who is trying to convert JSON to dictionary just for retrieving some value out of it. There is a simple way using Newtonsoft.JSON

using Newtonsoft.Json.Linq
...

JObject o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");

string cpu = (string)o["CPU"];
// Intel

string firstDrive = (string)o["Drives"][0];
// DVD read/writer

IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive

Move textfield when keyboard appears swift

There are a couple of improvements to be made on the existing answers.

Firstly the UIKeyboardWillChangeFrameNotification is probably the best notification as it handles changes that aren't just show/hide but changes due to keyboard changes (language, using 3rd party keyboards etc.) and rotations too (but note comment below indicating the keyboard will hide should also be handled to support hardware keyboard connection).

Secondly the animation parameters can be pulled from the notification to ensure that animations are properly together.

There are probably options to clean up this code a bit more especially if you are comfortable with force unwrapping the dictionary code.

 class MyViewController: UIViewController {

   // This constraint ties an element at zero points from the bottom layout guide
   @IBOutlet var keyboardHeightLayoutConstraint: NSLayoutConstraint?
 
   override func viewDidLoad() {
     super.viewDidLoad()
     NotificationCenter.default.addObserver(self,
       selector: #selector(self.keyboardNotification(notification:)),
       name: UIResponder.keyboardWillChangeFrameNotification,
       object: nil)
   }
 
   deinit {
     NotificationCenter.default.removeObserver(self)
   }
 
   @objc func keyboardNotification(notification: NSNotification) {
     guard let userInfo = notification.userInfo else { return }

     let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
     let endFrameY = endFrame?.origin.y ?? 0
     let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
     let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
     let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
     let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)

     if endFrameY >= UIScreen.main.bounds.size.height {
       self.keyboardHeightLayoutConstraint?.constant = 0.0
     } else {
       self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0
     }

     UIView.animate(
       withDuration: duration,
       delay: TimeInterval(0),
       options: animationCurve,
       animations: { self.view.layoutIfNeeded() },
       completion: nil)
   }
}

How to connect to LocalDB in Visual Studio Server Explorer?

In Visual Studio 2012 all I had to do was enter:

(localdb)\v11.0

Visual Studio 2015 and Visual Studio 2017 changed to:

(localdb)\MSSQLLocalDB

as the server name when adding a Microsoft SQL Server Data source in:

View/Server Explorer/(Right click) Data Connections/Add Connection

and then the database names were populated. I didn't need to do all the other steps in the accepted answer, although it would be nice if the server name was available automatically in the server name combo box.

You can also browse the LocalDB database names available on your machine using:

View/SQL Server Object Explorer.

MySQL dump by query

If you want to export your last n amount of records into a file, you can run the following:

mysqldump -u user -p -h localhost --where "1=1 ORDER BY id DESC LIMIT 100" database table > export_file.sql

The above will save the last 100 records into export_file.sql, assuming the table you're exporting from has an auto-incremented id column.

You will need to alter the user, localhost, database and table values. You may optionally alter the id column and export file name.

Printing variables in Python 3.4

Version 3.6+: Use a formatted string literal, f-string for short

print(f"{i}. {key} appears {wordBank[key]} times.")

Background image jumps when address bar hides iOS/Android/Mobile Chrome

With the support of CSS custom properties (variables) in iOS, you can set these with JS and use them on iOS only.

const iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (iOS) {
  document.body.classList.add('ios');
  const vh = window.innerHeight / 100;
  document.documentElement.style
    .setProperty('--ios-10-vh', `${10 * vh}px`);
  document.documentElement.style
    .setProperty('--ios-50-vh', `${50 * vh}px`);
  document.documentElement.style
    .setProperty('--ios-100-vh', `${100 * vh}px`);
}
body.ios {
    .side-nav {
        top: var(--ios-50-vh);
    }
    section {
        min-height: var(--ios-100-vh);
        .container {
            position: relative;
            padding-top: var(--ios-10-vh);
            padding-bottom: var(--ios-10-vh);
        }
    }
}

Facebook Open Graph Error - Inferred Property

In my case an unexpected error notice in the source code stopped the facebook crawler from parsing the (correctly set) og-meta tags.

I was using the HTTP_ACCEPT_LANGUAGE header, which worked fine for regular browser requests but not for the crawler, as it obviously won't use/set it.

Therefore, it was crucial for me to use the facebook's debugger feature See exactly what our scraper sees for your URL, as the error notice only could only be seen there (but not through the regular 'view source code'-browser feature).

screenshot of the facebook debugger

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

The key parameter is: innodb_page_size

Support for 32k and 64k page sizes was added in MySQL 5.7. For both 32k and 64k page sizes, the maximum row length is approximately 16000 bytes.

The trick is that this parameter can be only changed during the INITIALIZATION of the mysql service instance, so it does not have any affect if you change this parameter after the instance is already initialized (the very first run of the instance).

innodb_page_size can only be configured prior to initializing the MySQL instance and cannot be changed afterward. If no value is specified, the instance is initialized using the default page size. See Section 14.6.1, “InnoDB Startup Configuration”.

So if you do not change this value in my.ini before initialization, the default value will be 16K, which will have row size limit of ~8K. Thats why the error comes up.

If you increase the innodb_page_size, the innodb_log_buffer_size must be also increased. Set it at least to 16M. Also if the ROW_FORMAT is set to COMPRESSED you cannot increase innodb_page_size to 32k, or 64K. It should be DYNAMIC (default in 5.7).

ROW_FORMAT=COMPRESSED is not supported when innodb_page_size is set to 32KB or 64KB. For innodb_page_size=32k, extent size is 2MB. For innodb_page_size=64k, extent size is 4MB. innodb_log_buffer_size should be set to at least 16M (the default) when using 32k or 64k page sizes.

Furthermore the innodb_buffer_pool_size should be increased from 128M to 512M at least, otherwise you will get an error on initialization of the instance (I do not have the exact error).

After this, the row size error gone.

The problem with this is that you have to create a new MySql instance, and migrate data to your new DataBase instance, from old one.

Parameters that I changed and works (after creating a new instance and initialized with the my.ini that is first modified with these settings):

innodb_page_size=64k
innodb_log_buffer_size=32M
innodb_buffer_pool_size=512M

All the settings and descriptions in which I found the solution can be found here:

https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html

Hope this helps!

Regards!

How to wrap text in LaTeX tables?

I like the simplicity of tabulary package:

\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
    \hline
    Short sentences      & \#  & Long sentences                                                 \\
    \hline
    This is short.       & 173 & This is much loooooooonger, because there are many more words.  \\
    This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
    \hline
\end{tabulary} 

In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.

Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

For identifying a windows machine uniquely. Make sure when you use wmic to have a strategy of alternative methods. Since "wmic bios get serialnumber" might not work on all machines, you might need to have additional methods:

# Get serial number from bios
wmic bios get serialnumber
# If previous fails, get UUID
wmic csproduct get UUID
# If previous fails, get diskdrive serialnumber
wmic DISKDRIVE get SerialNumber

Resources: The Best Way To Uniquely Identify A Windows Machine http://www.nextofwindows.com/the-best-way-to-uniquely-identify-a-windows-machine/

Why do you create a View in a database?

For security: Gives each user permission to access the database only through a small set of views that contain the specific data the user or group of users is authorized to see, restricting user access to other data.

Simplicity for queries and structure: A view can draw data from several tables and present a single table, simplifying the information and turning multi-table queries into single-table queries for a view and it give users a specific view of the database structure, presenting the database as a set of virtual tables specific to particular users or groups of users.

For create consistent database structure: Views present a consistent, unchanged image of the database structure, even if underlying source tables are changed.

How can I enable cURL for an installed Ubuntu LAMP stack?

First thing to do: Check for the PHP version your machine is running.

Command Line: php -version

This will show something like this (in my case):

PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS ) Copyright (c) 1997-2016 The PHP Group

If you are using PHP 5.x.x => run command: sudo apt-get install php5-curl

If PHP 7.x.x => run command (in my case): sudo apt-get install php7.0-curl

Enable this extension by running:

sudo gedit /etc/php/7.0/cli/php.ini

And in the file "php.ini" search for keyword "curl" to find this line below and change it from

;extension=php_curl.dll

To:

extension=php_curl.dll

Next, save your file "php.ini".

Finally, in your command line, restart your server by running: sudo service apache2 restart.

JavaScript file not updating no matter what I do

A little late to the party, but if you put this in your html, it will keep your website from updating the cache. It takes the website a little longer to load, but for debugging purposes i like it. Taken from this answer: How to programmatically empty browser cache?

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

How to remove part of a string before a ":" in javascript?

There is no need for jQuery here, regular JavaScript will do:

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

Or, the .split() and .pop() version:

var str = "Abc: Lorem ipsum sit amet";
str = str.split(":").pop();

Or, the regex version (several variants of this):

var str = "Abc: Lorem ipsum sit amet";
str = /:(.+)/.exec(str)[1];

batch file to check 64bit or 32bit OS

Seems to work if you do only these:

echo "%PROCESSOR_ARCHITECTURE%"

I've found these script which will do specific stuff depending of OS Architecture (x64 or x86):

@echo off
echo Detecting OS processor type

if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto 64BIT
echo 32-bit OS
\\savdaldpm01\ProtectionAgents\RA\3.0.7558.0\i386\DPMAgentInstaller_x86 /q
goto END
:64BIT
echo 64-bit OS
\\savdaldpm01\ProtectionAgents\RA\3.0.7558.0\amd64\DPMAgentInstaller_x64 /q
:END

"C:\Program Files\Microsoft Data Protection Manager\DPM\bin\setdpmserver.exe" -dpmservername sa

Try to find a way without GOTO please...

For people whom work with Unix systems, uname -m will do the trick.

Open File Dialog, One Filter for Multiple Excel Extensions?

Use a semicolon

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

datetime dtypes in pandas read_csv

I tried using the dtypes=[datetime, ...] option, but

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

I encountered the following error:

TypeError: data type not understood

The only change I had to make is to replace datetime with datetime.datetime

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime.datetime, datetime.datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I'm using bootstrap.
I used css parameters.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

and bootstrap grid system parameters, like this.

<th class="col-sm-2">Name</th>

<td class="col-sm-2">hoge</td>

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

With components containing Angular Material, a similar error came up with my unit tests. As per @Dan Stirling-Talbert's answer above, added this to my component .spec file and the error was cleared from my unit tests.

Import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'

Then add the schema in the generated beforeEach() statement:

beforeEach(asyn(() => {
    declarations: [ AboutComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
.compileComponents();
}));

My Karma error was: If 'mat-panel-title' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

How to print an exception in Python?

(I was going to leave this as a comment on @jldupont's answer, but I don't have enough reputation.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.

Sleep/Wait command in Batch

timeout 5

to delay

timeout 5 >nul

to delay without asking you to press any key to cancel

ipad safari: disable scrolling, and bounce effect?

Code to To remove ipad safari: disable scrolling, and bounce effect

   document.addEventListener("touchmove", function (e) {
        e.preventDefault();
    }, { passive: false });

If you have canvas tag inside document, sometime it will affect the usability of object inside Canvas(example: movement of object); so add below code to fix it.

    document.getElementById("canvasId").addEventListener("touchmove", function (e) {
        e.stopPropagation();
    }, { passive: false });

Using SVG as background image

Try placing it on your body

body {
    height: 100%;
    background-image: url(../img/bg.svg);
    background-size:100% 100%;
    -o-background-size: 100% 100%;
    -webkit-background-size: 100% 100%;
    background-size:cover;
}

Android: How can I get the current foreground activity (from a service)?

Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.

if (Build.VERSION.SDK_INT >= 21) {
    String currentApp = null;
    UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();
    List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
    if (applist != null && applist.size() > 0) {
        SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
        for (UsageStats usageStats : applist) {
            mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);

        }
        if (mySortedMap != null && !mySortedMap.isEmpty()) {
            currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
        }
    }

jquery - Click event not working for dynamically created button

You create buttons dynamically because of that you need to call them with .live() method if you use jquery 1.7

but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:

$(document).on('click', 'selector', function(){ 
     // Your Code
});

For Example

If your html is something like this

<div id="btn-list">
    <div class="btn12">MyButton</div>
</div>

You can write your jquery like this

$(document).on('click', '#btn-list .btn12', function(){ 
     // Your Code
});

TypeScript function overloading

What is function overloading in general?

Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations (Wikipedia)


What is function overloading in JS?

This feature is not possible in JS - the last defined function is taken in case of multiple declarations:

function foo(a1, a2) { return `${a1}, ${a2}` }
function foo(a1) { return `${a1}` } // replaces above `foo` declaration
foo(42, "foo") // "42"

... and in TS?

Overloads are a compile-time construct with no impact on the JS runtime:

function foo(s: string): string // overload #1 of foo
function foo(s: string, n: number): number // overload #2 of foo
function foo(s: string, n?: number): string | number {/* ... */} // foo implementation

A duplicate implementation error is triggered, if you use above code (safer than JS). TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad.


Method overloading in TS: a more complex example

Overloaded class method types can be used in a similar way to function overloading:

class LayerFactory {
    createFeatureLayer(a1: string, a2: number): string
    createFeatureLayer(a1: number, a2: boolean, a3: string): number
    createFeatureLayer(a1: string | number, a2: number | boolean, a3?: string)
        : number | string { /*... your implementation*/ }
}

const fact = new LayerFactory()
fact.createFeatureLayer("foo", 42) // string
fact.createFeatureLayer(3, true, "bar") // number

The vastly different overloads are possible, as the function implementation is compatible to all overload signatures - enforced by the compiler.

More infos:

iOS - Ensure execution on main thread

When you're using iOS >= 4

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

replace String with another in java

Another suggestion, Let's say you have two same words in the String

String s1 = "who is my brother, who is your brother"; // I don't mind the meaning of the sentence.

replace function will change every string is given in the first parameter to the second parameter

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

and you can use also replaceAll method for the same result

System.out.println(s1.replace("brother", "sister")); // who is my sister, who is your sister

if you want to change just the first string which is positioned earlier,

System.out.println(s1.replaceFirst("brother", "sister")); // whos is my sister, who is your brother.

How to execute a stored procedure inside a select query

As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.

Stored procedures are for executing by an outside program, or on a timed interval.

The answers here will explain it better than I can:

Function vs. Stored Procedure in SQL Server

jQuery ajax success callback function definition

I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess: i.e.

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

Unused arguments in R

I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with

library(magrittr)
do_func_ignore_things <- function(data, what){
    acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
    do.call(what, acceptable_args %>% as.list)
}

do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I googled a lot but did not find a definite answer to my problem. I used KeyPass to generate a strong password and could use it successfully on mysql workbench to connect but not from the command line. So I changed the psw to an easy one and it worked on the command line. I have managed to create a strong password that was able to connect from the terminal. So my advise is, try with an easy password first before trying all kind of things.

How to verify if $_GET exists?

Please try it:

if(isset($_GET['id']) && !empty($_GET['id'])){
   echo $_GET["id"];
 }

'xmlParseEntityRef: no name' warnings while loading xml into a php file

Try to clean the HTML first using this function:

$html = htmlspecialchars($html);

Special chars are usually represented differently in HTML and it might be confusing for the compiler. Like & becomes &amp;.

How can I determine if a date is between two dates in Java?

Between dates Including end points can be written as

public static boolean isDateInBetweenIncludingEndPoints(final Date min, final Date max, final Date date){
    return !(date.before(min) || date.after(max));
}

Adding space/padding to a UILabel

Swift 3, iOS10 solution:

open class UIInsetLabel: UILabel {

    open var insets : UIEdgeInsets = UIEdgeInsets() {
        didSet {
            super.invalidateIntrinsicContentSize()
        }
    }

    open override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        size.width += insets.left + insets.right
        size.height += insets.top + insets.bottom
        return size
    }

    override open func drawText(in rect: CGRect) {
        return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }
}

Is it possible to break a long line to multiple lines in Python?

There is more than one way to do it.

1). A long statement:

>>> def print_something():
         print 'This is a really long line,', \
               'but we can make it across multiple lines.'

2). Using parenthesis:

>>> def print_something():
        print ('Wow, this also works?',
               'I never knew!')

3). Using \ again:

>>> x = 10
>>> if x == 10 or x > 0 or \
       x < 100:
       print 'True'

Quoting PEP8:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I was struggling with this issue for several hours, i have read every relevant topic and found out that the error was caused because under the privacy settings of my device, the camera access to my app was blocked!!! I have never denied access to camera and i don't know how it was blocked but that was the problem!

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

What is tail recursion?

There are two basic kinds of recursions: head recursion and tail recursion.

In head recursion, a function makes its recursive call and then performs some more calculations, maybe using the result of the recursive call, for example.

In a tail recursive function, all calculations happen first and the recursive call is the last thing that happens.

Taken from this super awesome post. Please consider reading it.

Alter a SQL server function to accept new optional parameter

I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.

Volatile boolean vs AtomicBoolean

You can't do compareAndSet, getAndSet as atomic operation with volatile boolean (unless of course you synchronize it).

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Because an interface is just a contract. And a class is actually a container for data.

How to limit the number of selected checkboxes?

If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox

var queue = [];
function checking(id){
   queue.push(id)
   if (queue.length===3){
    queue[0].checked = false
    queue.shift()
   }
}

Access denied for user 'test'@'localhost' (using password: YES) except root user

Try this:

If you have already created your user, you might have created your user with the wrong password.

So drop that user and create another user by doing this. To see your current users.

SELECT Host,User FROM mysql.user;

To drop the user

DROP User '<your-username>'@'localhost';

After this you can create the user again with the correct password

CREATE USER '<your-username>'@'localhost' IDENTIFIED WITH mysql_native_password BY '<correct password>';

then

FLUSH PRIVILEGES;

You might still run into some more errors with getting access to the database, if you have that error run this.

GRANT ALL PRIVILEGES ON *.* to '<your-username>'@'localhost';

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

Show animated GIF

I came here searching for the same answer, but based on the top answers, I came up with an easier code. Hope this will help future searches.

Icon icon = new ImageIcon("src/path.gif");
            try {
                mainframe.setContentPane(new JLabel(icon));
            } catch (Exception e) {
            }

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

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

How to convert int to date in SQL Server 2008

You have to first convert it into datetime, then to date.

Try this, it might be helpful:

Select Convert(DATETIME, LEFT(20130101, 8))

then convert to date.

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

Adding custom HTTP headers using JavaScript

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

How to disable and then enable onclick event on <div> with javascript

You can disable the event by applying following code:

with .attr() API

$('#your_id').attr("disabled", "disabled");

or with .prop() API

$('#your_id').prop('disabled', true);

How can I enable CORS on Django REST Framework

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem

Adding Lombok plugin to IntelliJ project

There is a lot of really helpful info posted here, but there is one thing that all the posts seem to have wrong. I could not find any 'Settings' option under 'Files', and I hunted around for 10 minutes looking through all the menus until I found the settings under 'IntelliJ IDE' -> 'Preferences'.

I don't know if I am using a differing OS version or IntelliJ version from other posters, or if it is because I am a stupid Windows user that doesn't know that settings == preferences on a mac (Did I miss the memo?), but I hope this helps you if you aren't finding the paths that other posts are suggesting.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

Add play-services-safetynet library in android build.gradle:

implementation 'com.google.android.gms:play-services-safetynet:+'

and add this code to your MainApplication.java:

@Override
  public void onCreate() {
    super.onCreate();
    upgradeSecurityProvider();
    SoLoader.init(this, /* native exopackage */ false);
  }

  private void upgradeSecurityProvider() {
    ProviderInstaller.installIfNeededAsync(this, new ProviderInstallListener() {
      @Override
      public void onProviderInstalled() {

      }

      @Override
      public void onProviderInstallFailed(int errorCode, Intent recoveryIntent) {
//        GooglePlayServicesUtil.showErrorNotification(errorCode, MainApplication.this);
        GoogleApiAvailability.getInstance().showErrorNotification(MainApplication.this, errorCode);
      }
    });
  }

Could not reliably determine the server's fully qualified domain name

Yes, you should set ServerName:

http://wiki.apache.org/httpd/CouldNotDetermineServerName

http://httpd.apache.org/docs/current/mod/core.html#servername

You can find information on the layouts used by the various httpd distributions here:

http://wiki.apache.org/httpd/DistrosDefaultLayout

In your case the file to edit is /etc/httpd/conf/httpd.conf

How do I make the return type of a method generic?

You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.

    public static T values<T>()
    {
        Random random = new Random();
        int number = random.Next(1, 4);
        return (T)Convert.ChangeType(number, typeof(T));
    }

You need pass a type that is type casteable for the value you return through that method.

If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.

How do I comment out a block of tags in XML?

Actually, you can use the <!--...--> format with multi-lines or tags:

<!--
  ...
  ...
  ...
-->

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

Excel how to find values in 1 column exist in the range of values in another

Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A. Data > Filter and choose Filter by color.

Maven Out of Memory Build Failure

This happens in big projects on Windows when cygwin or other linux emulator is used(git bash). By some coincidence, both does not work on my project, what is an big open source project. In a sh script, a couple of mvn commands are called. The memory size grows to heap size bigger that specified in Xmx and most of the time in a case second windows process is started. This is making the memory consumption even higher.

The solution in this case is to use batch file and reduced Xmx size and then the maven operations are successful. If there is interest I can reveal more details.

display: inline-block extra margin

Can you post a link to the HTML in question?

Ultimately you should be able to do:

div {
    margin:0;
    padding: 0;
}

to remove the spacing. Is this just in one particular browser or all of them?

Counting repeated characters in a string in Python

If someone is looking for the simplest way without collections module. I guess this will be helpful:

>>> s = "asldaksldkalskdla"
>>> {i:s.count(i) for i in set(s)}
{'a': 4, 'd': 3, 'k': 3, 's': 3, 'l': 4}

or

>>> [(i,s.count(i)) for i in set(s)]
[('a', 4), ('k', 3), ('s', 3), ('l', 4), ('d', 3)]

Object Dump JavaScript

If you're on Chrome, Firefox or IE10 + why not extend the console and use

(function() {
    console.dump = function(object) {
        if (window.JSON && window.JSON.stringify)
            console.log(JSON.stringify(object));
        else
            console.log(object);
    };
})();

for a concise, cross-browser solution.

Cleanest way to write retry logic?

Implemented LBushkin's answer in the latest fashion:

    public static async Task Do(Func<Task> task, TimeSpan retryInterval, int maxAttemptCount = 3)
    {
        var exceptions = new List<Exception>();
        for (int attempted = 0; attempted < maxAttemptCount; attempted++)
        {
            try
            {
                if (attempted > 0)
                {
                    await Task.Delay(retryInterval);
                }

                await task();
                return;
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }
        throw new AggregateException(exceptions);
    }

    public static async Task<T> Do<T>(Func<Task<T>> task, TimeSpan retryInterval, int maxAttemptCount = 3)
    {
        var exceptions = new List<Exception>();
        for (int attempted = 0; attempted < maxAttemptCount; attempted++)
        {
            try
            {
                if (attempted > 0)
                {
                    await Task.Delay(retryInterval);
                }
                return await task();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }
        throw new AggregateException(exceptions);
    }  

and to use it:

await Retry.Do([TaskFunction], retryInterval, retryAttempts);

whereas the function [TaskFunction] can either be Task<T> or just Task.

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

CSS @media print issues with background-color;

Tested and Working over Chrome, Firefox, Opera and Edge by 2016/10. Should work on any browser and should always look as expected.

Ok, I did a little cross-browser experiment for printing background colors. Just copy, paste & enjoy!

Here it is a full printable HTML page for bootstrap:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">

    /* Both z-index are resolving recursive element containment */
    [background-color] {
        z-index: 0;
        position: relative;
        -webkit-print-color-adjust: exact !important;
    }

    [background-color] canvas {
        display: block;
        position:absolute;
        z-index: -1;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

</style>
</head>

<!-- CONTENT -->
<body>

    <!-- PRINT ROW BLOCK -->
    <div class="container">

    <div class="row">
        <div class="col-xs-6">
            <div background-color="#A400C1">
                <h4>
                Hey... this works !
                </h4>
                <div background-color="#0068C1">
                    <p>
                    Ohh... this works recursive too !!
                    <div background-color="green" style="width: 80px; height: 60px">
                        Any size !!
                    </div>
                    </p>
                </div>
            </div>
        </div>

        <div class="col-xs-6">
            <div background-color="#FFCB83" style="height: 200px">
                Some content...
            </div>
        </div>

    </div>


<script>
    var containers = document.querySelectorAll("[background-color]");

    for (i = 0; i < containers.length; i++)
    {
        // Element
        var container = containers[i];
        container.insertAdjacentHTML('beforeend', '<canvas id="canvas-' + i + '"></canvas>');

        // Color
        var color = container.getAttribute("background-color");
        container.style.backgroundColor = color;

        // Inner Canvas
        var canvas = document.getElementById("canvas-" + i);
        canvas.width = container.offsetWidth;
        canvas.height = container.offsetHeight;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }

    window.print();
</script>


</body>

</html>

How to enable scrolling of content inside a modal?

This answer actually has two parts, a UX warning, and an actual solution.

UX Warning

If your modal contains so much that it needs to scroll, ask yourself if you should be using a modal at all. The size of the bootstrap modal by default is a pretty good constraint on how much visual information should fit. Depending on what you're making, you may instead want to opt for a new page or a wizard.

Actual Solution

Is here: http://jsfiddle.net/ajkochanowicz/YDjsE/2/

This solution will also allow you to change the height of .modal and have the .modal-body take up the remaining space with a vertical scrollbar if necessary.

UPDATE

Note that in Bootstrap 3, the modal has been refactored to better handle overflowing content. You'll be able to scroll the modal itself up and down as it flows under the viewport.

How do you replace all the occurrences of a certain character in a string?

The problem is you're not doing anything with the result of replace. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.

line[8] = line[8].replace(letter, "")

Reset the Value of a Select Box

I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):

function clearForm(form) {
  // iterate over all of the inputs for the given form element
  $(':input', form).each(function() {
    var type = this.type;
    var tag = this.tagName.toLowerCase(); // normalize case
    // it's ok to reset the value attr of text inputs, 
    // password inputs, and textareas
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = "";
    // checkboxes and radios need to have their checked state cleared 
    // but should *not* have their 'value' changed
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    // select elements need to have their 'selectedIndex' property set to -1
    // (this works for both single and multiple select elements)
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

... or as a jQuery plugin...

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

Create PostgreSQL ROLE (user) if it doesn't exist

You can do it in your batch file by parsing the output of:

SELECT * FROM pg_user WHERE usename = 'my_user'

and then running psql.exe once again if the role does not exist.

Set Date in a single line

You could use new GregorianCalendar(theYear, theMonth, theDay).getTime():

public GregorianCalendar(int year, int month, int dayOfMonth)

Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

Loading custom functions in PowerShell

You have to dot source them:

. .\build_funtions.ps1
. .\build_builddefs.ps1

Note the extra .

This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

Determine if a cell (value) is used in any formula

On Excel 2010 try this:

  1. select the cell you want to check if is used somewhere in a formula;
  2. Formulas -> Trace Dependents (on Formula Auditing menu)

Playing a video in VideoView in Android

My guess is that your video is incompatible with Android. Try it with a different video. This one definitely works used to work with Android (but does not on newer devices, for some reason). If that video works, and yours does not, then your video is not compatible with Android.

As others have indicated, please test this on a device. Video playback on the emulator requires too much power.

UPDATE 2020-02-18: https://law.duke.edu/cspd/contest/videos/Framed-Contest_Documentaries-and-You.mp4 is an MP4 of the same content, but I have no idea if it is the same actual MP4 as I previously linked to.

How to decrypt an encrypted Apple iTunes iPhone backup?

Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.

http://www.elcomsoft.com/eppb.html

Saving an Excel sheet in a current directory with VBA

VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

How to round a number to n decimal places in Java

Keep in mind that String.format() and DecimalFormat produce string using default Locale. So they may write formatted number with dot or comma as a separator between integer and decimal parts. To make sure that rounded String is in the format you want use java.text.NumberFormat as so:

  Locale locale = Locale.ENGLISH;
  NumberFormat nf = NumberFormat.getNumberInstance(locale);
  // for trailing zeros:
  nf.setMinimumFractionDigits(2);
  // round to 2 digits:
  nf.setMaximumFractionDigits(2);

  System.out.println(nf.format(.99));
  System.out.println(nf.format(123.567));
  System.out.println(nf.format(123.0));

Will print in English locale (no matter what your locale is): 0.99 123.57 123.00

The example is taken from Farenda - how to convert double to String correctly.

Subtract days from a DateTime

That error usually occurs when you try to subtract an interval from DateTime.MinValue or you want to add something to DateTime.MaxValue (or you try to instantiate a date outside this min-max interval). Are you sure you're not assigning MinValue somewhere?

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

How to limit file upload type file size in PHP?

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

`upload_max_filesize = 2M` `post_max_size = 2M`

that will set the maximum upload limit to 2 MB

Actual meaning of 'shell=True' in subprocess

>>> import subprocess
>>> subprocess.call('echo $HOME')
Traceback (most recent call last):
...
OSError: [Errno 2] No such file or directory
>>>
>>> subprocess.call('echo $HOME', shell=True)
/user/khong
0

Setting the shell argument to a true value causes subprocess to spawn an intermediate shell process, and tell it to run the command. In other words, using an intermediate shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run. Here, in the example, $HOME was processed before the echo command. Actually, this is the case of command with shell expansion while the command ls -l considered as a simple command.

source: Subprocess Module

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

Thank you #DangerDave this solved my problem on Magento 2, and this is how I did

I am on a vps

root@myvps [~]# cd /var/lib/mysql/mydatabasename/

root@myvps [~]# ls

check for tables with no .frm fie (only .idb) and delete them,

rm customer_grid_flat.ibd

System will regenerate tables after running index:reindex command

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml from a file deployed at http://run.jsbin.com due to the same-origin policy.


As the source (aka origin) page and the target URL are at different domains (run.jsbin.com and www.ecb.europa.eu), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET.

In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.


Example:

A page at http://www.example.com/myPage.html can only directly request services that are at http://www.example.com, like http://www.example.com/api/myService. If the service is hosted at another domain (say http://www.ok.com/api/myService), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a (CORS) request* across different domains, your browser:

  • Will include an Origin header in the original request (with the page's domain as value) and perform it as usual; and then
  • Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).


* The above depicts the steps in a simple request, such as a regular GET with no fancy headers. If the request is not simple (like a POST with application/json as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS request to the target URL. Like above, it only will continue if the response to this OPTIONS request contains the CORS headers. This OPTIONS call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers header.


How to fix it?

Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com it will only make regular calls to www.example.com! Other URLs, such as api.example.com or even example.com or www.example.com:8080 are considered different domains by the browser! Yes, if the port is different, then it is a different domain!

Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses. (Each server/language has a way to do that - check some solutions here.)

Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.