Programs & Examples On #Ezpublish

eZ Publish is a PHP based CMF/CMS for publishing, especially editorial content.

How to delete object?

From any class you can't set its value to null. This is not allowed and doesn't make sense also -

public void Delete()
{
    this = null; <-- NOT ALLOWED
}

You need an instance of class to call Delete() method so why not set that instance to null itself once you are done with it.

Car car = new Car();
// Use car objects and once done set back to null
car = null;

Anyhow what you are trying to achieve is not possible in C#. I suspect from your question that you want this because there are memory leaks present in your current design which doesn't let the Car instance to go away. I would suggest you better profile your application and identify the areas which is stopping GC to collect car instance and work on improving that area.

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

#1292 - Incorrect date value: '0000-00-00'

After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.

It's incorrect to use zeros in date or in datetime, just put null instead of zeros.

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

Linq style "For Each"

There is no Linq ForEach extension. However, the List class has a ForEach method on it, if you're willing to use the List directly.

For what it's worth, the standard foreach syntax will give you the results you want and it's probably easier to read:

foreach (var x in someValues)
{
    list.Add(x + 1);
}

If you're adamant you want an Linq style extension. it's trivial to implement this yourself.

public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
{
   foreach (var x in @this)
      action(x);
}

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.

From the Oracle 10g SQL Reference:

Notes on Updatable Views

An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.

To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:

  • Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.
  • The view must not contain any of the following constructs:
    • A set operator
    • a DISTINCT operator
    • An aggregate or analytic function
    • A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause
    • A collection expression in a SELECT list
    • A subquery in a SELECT list
    • A subquery designated WITH READ ONLY
    • Joins, with some exceptions, as documented in Oracle Database Administrator's Guide

In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following conditions must be true:

  • The DML statement must affect only one table underlying the join.
  • For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.
  • For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.
  • For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.

Keep placeholder text in UITextField on input in IOS

Instead of using the placeholder text, you'll want to set the actual text property of the field to MM/YYYY, set the delegate of the text field and listen for this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     // update the text of the label } 

Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.

CSS to select/style first word

Sadly even with the likes of CSS 3 we still do not have the likes of :first-word :last-word etc using pure CSS. Thankfully there's almost a JavaScript nowadays for everything which brings me to my recommendation. Using nthEverything and jQuery you can expand from the traditional Pseudo elements.

Currently the valid Pseudos are:

  • :first-child
  • :first-of-type
  • :only-child
  • :last-child
  • :last-of-type
  • :only-of-type
  • :nth-child
  • :nth-of-type
  • :nth-last-child
  • :nth-last-of-type

And using nth Everything we can expand this to:

  • ::first-letter
  • ::first-line
  • ::first-word
  • ::last-letter
  • ::last-line
  • ::last-word
  • ::nth-letter
  • ::nth-line
  • ::nth-word
  • ::nth-last-letter
  • ::nth-last-line
  • ::nth-last-word

CSS last-child selector: select last-element of specific class, not last child inside of parent?

What about this solution?

div.commentList > article.comment:not(:last-child):last-of-type
{
    color:red; /*or whatever...*/
}

Rails 3.1 and Image Assets

when referencing images in CSS or in an IMG tag, use image-name.jpg

while the image is really located under ./assets/images/image-name.jpg

Change limit for "Mysql Row size too large"

The question has been asked on serverfault too.

You may want to take a look at this article which explains a lot about MySQL row sizes. It's important to note that even if you use TEXT or BLOB fields, your row size could still be over 8K (limit for InnoDB) because it stores the first 768 bytes for each field inline in the page.

The simplest way to fix this is to use the Barracuda file format with InnoDB. This basically gets rid of the problem altogether by only storing the 20 byte pointer to the text data instead of storing the first 768 bytes.


The method that worked for the OP there was:

  1. Add the following to the my.cnf file under [mysqld] section.

    innodb_file_per_table=1
    innodb_file_format = Barracuda
    
  2. ALTER the table to use ROW_FORMAT=COMPRESSED.

    ALTER TABLE nombre_tabla
        ENGINE=InnoDB
        ROW_FORMAT=COMPRESSED 
        KEY_BLOCK_SIZE=8;
    

There is a possibility that the above still does not resolve your issues. It is a known (and verified) bug with the InnoDB engine, and a temporary fix for now is to fallback to MyISAM engine as temporary storage. So, in your my.cnf file:

internal_tmp_disk_storage_engine=MyISAM

fatal: could not read Username for 'https://github.com': No such file or directory

This error can also happen when trying to clone an invalid HTTP URL. For example, this is the error I got when trying to clone a GitHub URL that was a few characters off:

$ git clone -v http://github.com/username/repo-name.git
Cloning into 'repo-name'...
Username for 'https://github.com': 
Password for 'https://github.com': 
remote: Repository not found.
fatal: Authentication failed for 'https://github.com/username/repo-name.git/'

It actually happened inside Emacs, though, so the error in Emacs looked like this:

fatal: could not read Username for ’https://github.com’: No such device or address

So instead of a helpful error saying that there was no such repo at that URL, it gave me that, sending me on a wild goose chase until I finally realized that the URL was incorrect.

This is with git version 2.7.4.

I'm posting this here because it happened to me a month ago and again just now, sending me on the same wild goose chase again. >:(

How to change a Git remote on Heroku

Assuming your current remote is named origin then:

Delete the current remote reference with

git remote rm origin

Add the new remote

git remote add origin <URL to new heroku app>

push to new domain

git push -u origin master

The -u will set this up as tracked.

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

I want to delete all bin and obj folders to force all projects to rebuild everything

For the solution in batch. I am using the following command:

FOR /D /R %%G in (obj,bin) DO @IF EXIST %%G IF %%~aG geq d RMDIR /S /Q "%%G"


The reason not using DIR /S /AD /B xxx
1. DIR /S /AD /B obj will return empty list (at least on my Windows10) enter image description here
2. DIR /S /AD /B *obj will contain the result which is not expected (tobj folder) enter image description here

setting global sql_mode in mysql

Copy to Config File: /etc/mysql/my.cnf OR /bin/mysql/my.ini

[mysqld]
port = 3306
sql-mode=""

MySQL restart.

Or you can also do

[mysqld]
port = 3306
SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";

MySQL restart.

Getting list of tables, and fields in each, in a database

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

Set value to currency in <input type="number" />

The browser only allows numerical inputs when the type is set to "number". Details here.

You can use the type="text" and filter out any other than numerical input using JavaScript like descripted here

Simple GUI Java calculator

assuming that string1 is your whole operation

use mdas

double result;
string recurAndCheck(string operation){
  if(operation.indexOf("/")){
     String leftSide = recurAndCheck(operation.split("/")[0]);
     string rightSide = recurAndCheck(operation.split("/")[1]);
     result = Double.parseDouble(leftSide)/Double.parseDouble(rightSide);

  } else if (..continue w/ *...) {
    //same as above but change / with *
  } else if (..continue w/ -) { 
    //change as above but change with -
  } else if (..continuew with +) {
    //change with add
  } else {
    return;
  }
}

Amazon AWS Filezilla transfer permission denied

for me below worked:

chown -R ftpusername /var/app/current

Order data frame rows according to vector with specific order

If you don't want to use any libraries and you have reoccurrences in your data, you can use which with sapply as well.

new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df        <- df[new_order,]

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

How to decide when to use Node.js?

Another great thing that I think no one has mentioned about Node.js is the amazing community, the package management system (npm) and the amount of modules that exist that you can include by simply including them in your package.json file.

Scroll RecyclerView to show selected item on top

what i did to restore the scroll position after refreshing the RecyclerView on button clicked:

if (linearLayoutManager != null) {

    index = linearLayoutManager.findFirstVisibleItemPosition();
    View v = linearLayoutManager.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
    Log.d("TAG", "visible position " + " " + index);
}

else{
    index = 0;
}

linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.scrollToPositionWithOffset(index, top);

getting the offset of the first visible item from the top before creating the linearLayoutManager object and after instantiating it the scrollToPositionWithOffset of the LinearLayoutManager object was called.

error: ‘NULL’ was not declared in this scope

To complete the other answers: If you are using C++11, use nullptr, which is a keyword that means a void pointer pointing to null. (instead of NULL, which is not a pointer type)

Equivalent of SQL ISNULL in LINQ?

You can use the ?? operator to set the default value but first you must set the Nullable property to true in your dbml file in the required field (xx.Online)

var hht = from x in db.HandheldAssets
        join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
        from aa in DevInfo.DefaultIfEmpty()
        select new
        {
        AssetID = x.AssetID,
        Status = xx.Online ?? false
        };

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

In my case it happens when i want add view by parent to other view

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(lyt);  // ->  crash

you must add parent view like this

View root = inflater.inflate(R.layout.single, null);
LinearLayout lyt = root.findViewById(R.id.lytRoot);
lytAll.addView(root);

SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

You can use ALTER to update a view, but this is different than the Oracle command since it only works if the view already exists. Probably better off with DaveK's answer since that will always work.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.

The error message indirectly tells you what character set Python was trying to use:

  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

This means the charset is cp850.

You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).

It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)

But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:

>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

So, how do you print a string that won't print on your console?

You can replace every print function with something like this:

>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

… but that's going to get pretty tedious pretty fast.

The simple thing to do is to just set the error handler on sys.stdout:

>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:

with open('path', 'w', encoding='cp850') as f:

Do this:

with open('path', 'w', encoding='cp850', errors='replace') as f:

… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:

with open('path', 'w', encoding='utf-8') as f:

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Here is how I encountered this error in Django and fixed it:

Code with error

urlpatterns = [path('home/', views.home, 'home'),]

Correction

urlpatterns = [path('home/', views.home, name='home'),]

What is Options +FollowSymLinks?

You might try searching the internet for ".htaccess Options not allowed here".

A suggestion I found (using google) is:

Check to make sure that your httpd.conf file has AllowOverride All.

A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):

# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html

# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>

# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.

Argument list too long error for rm, cp, mv commands

A bit safer version than using xargs, also not recursive: ls -p | grep -v '/$' | grep '\.pdf$' | while read file; do rm "$file"; done

Filtering our directories here is a bit unnecessary as 'rm' won't delete it anyway, and it can be removed for simplicity, but why run something that will definitely return error?

How do I specify the platform for MSBuild?

In MSBuild or Teamcity use command line

MSBuild yourproject.sln /property:Configuration=Release /property:Platform=x64

or use shorter form:

MSBuild yourproject.sln /p:Configuration=Release /p:Platform=x64

However you need to set up platform in your project anyway, see the answer by Julien Hoarau.

Can't specify the 'async' modifier on the 'Main' method of a console app

For asynchronously calling task from Main, use

  1. Task.Run() for .NET 4.5

  2. Task.Factory.StartNew() for .NET 4.0 (May require Microsoft.Bcl.Async library for async and await keywords)

Details: http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx

Why do I get a "permission denied" error while installing a gem?

After setting the gems directory to the user directory that runs the gem install, using export GEM_HOME=/home/<user>/gems, the issue has been solved.

Reporting Services Remove Time from DateTime in Expression

In the format property of any textbox field you can use format strings:

e.g. D/M/Y, D, etc.

Defining a `required` field in Bootstrap

Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator" to your form element.

<form role="form" data-toggle="validator">
   ...
</form>

Or activate validation via JavaScript:

$('#myForm').validator()

and you need to use required flag in input field

For more details Click Here

Verilog generate/genvar in an always block

You don't need a generate bock if you want all the bits of temp assigned in the same always block.

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
    for (integer c=0; c<ROWBITS; c=c+1) begin: test
        temp[c] <= 1'b0;
    end
end

Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
        temp <= '0; // fill with 0
    end
end

Range of values in C Int and Long 32 - 64 bits

Take a look at limits.h. You can find the specific values for your compiler. INT_MIN and INT_MAX will be of interest.

phpmyadmin "no data received to import" error, how to fix?

Open your php.ini file use CNTRL+F to search for the following settings which may be the culprit:

  • file_uploads
  • upload_max_filesize
  • post_max_size
  • memory_limit
  • max_input_time
  • max_execution_time

Make sure to save a copy of the php.ini prior to making changes. You will want to adjust the settings to accommodate your file size, and increase input and/or execution time.

Remember to restart your services after making changes.

Warning! There may be some unforeseen drawbacks if you adjust these settings too liberally. I am not expert enough to know this for sure.

Source: http://forum.wampserver.com/read.php?2,20757,20935

How to force Selenium WebDriver to click on element which is not currently visible?

You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.

If this error happens, check if:

  • element is visible in your viewport, try to maximize the current window that webdriver is using (e.g. maximize() in node.js, maximize_window() in Python),
  • your element is not appearing twice (under the same selector), and you're selecting the wrong one,
  • if your element is hidden, then consider making it visible,
  • if you'd like to access/change value of hidden element despite of the limitation, then use Javascript for that (e.g. executeScript() in node.js, execute_script() in Python).

How to call a button click event from another method

You can call the button_click event by simply passing the arguments to it:

private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}

private void ChildNode_Click(object sender, RoutedEventArgs args)
{
   SubGraphButton_Click(sender, args);
}

Singleton: How should it be used

I use Singletons as an interview test.

When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.

Return value in a Bash function

Although bash has a return statement, the only thing you can specify with it is the function's own exit status (a value between 0 and 255, 0 meaning "success"). So return is not what you want.

You might want to convert your return statement to an echo statement - that way your function output could be captured using $() braces, which seems to be exactly what you want.

Here is an example:

function fun1(){
  echo 34
}

function fun2(){
  local res=$(fun1)
  echo $res
}

Another way to get the return value (if you just want to return an integer 0-255) is $?.

function fun1(){
  return 34
}

function fun2(){
  fun1
  local res=$?
  echo $res
}

Also, note that you can use the return value to use boolean logic like fun1 || fun2 will only run fun2 if fun1 returns a non-0 value. The default return value is the exit value of the last statement executed within the function.

How to get just numeric part of CSS property with jQuery?

Id go for:

Math.abs(parseFloat($(this).css("property")));

How to play only the audio of a Youtube video using HTML 5?

I agree with Tom van der Woerdt. You could use CSS to hide the video (visibility:hidden or overflow:hidden in a div wrapper constrained by height), but that may violate Youtube's policies. Additionally, how could you control the audio (pause, stop, volume, etc.)?

You could instead turn to resources such as http://www.houndbite.com/ to manage audio.

Showing which files have changed between two revisions

For people who are looking for a GUI solution, Git Cola has a very nice "Branch Diff Viewer (Diff -> Branches..).

How do I create a MessageBox in C#?

It is a static function on the MessageBox class, the simple way to do this is using

MessageBox.Show("my message");

in the System.Windows.Forms class. You can find more on the msdn page for this here . Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message"); or confirm("my question"); functions.

SyntaxError: multiple statements found while compiling a single statement

A (partial) practical work-around is to put things into a throw-away function.

Pasting

x = 1
x += 1
print(x)

results in

>>> x = 1
x += 1
print(x)
  File "<stdin>", line 1
    x += 1
print(x)

    ^
SyntaxError: multiple statements found while compiling a single statement
>>>

However, pasting

def abc():
  x = 1
  x += 1
  print(x)

works:

>>> def abc():
  x = 1
  x += 1
  print(x)
>>> abc()
2
>>>

Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython / jupyter qtconsole is probably the next simplest option.

How to compare two JSON objects with the same elements in a different order equal?

If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True

How to make a dropdown readonly using jquery?

I had the same problem, my solution was to disable all options not selected. Very easy with jQuery:

$('option:not(:selected)').attr('disabled', true);

Edit => If you have multiple dropdowns on same page, disable all not selected options on select-ID as below.

$('#select_field_id option:not(:selected)').attr('disabled', true);

Insert if not exists Oracle

Coming late to the party, but...

With oracle 11.2.0.1 there is a semantic hint that can do this: IGNORE_ROW_ON_DUPKEY_INDEX

Example:

insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(customer_orders,pk_customer_orders) */
  into customer_orders
       (order_id, customer, product)
values (    1234,     9876,  'K598')
     ;

UPDATE: Although this hint works (if you spell it correctly), there are better approaches which don't require Oracle 11R2:

First approach—direct translation of above semantic hint:

begin
  insert into customer_orders
         (order_id, customer, product)
  values (    1234,     9876,  'K698')
  ;
  commit;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

Second aproach—a lot faster than both above hints when there's a lot of contention:

begin
    select count (*)
    into   l_is_matching_row
    from   customer_orders
    where  order_id = 1234
    ;

    if (l_is_matching_row = 0)
    then
      insert into customer_orders
             (order_id, customer, product)
      values (    1234,     9876,  'K698')
      ;
      commit;
    end if;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

Amazing, there are dozens of answers here with javascript and viewports, and only one other mentions text-size-adjust which is what I believe is the best solution.

You can just set this to none.

Add the following CSS:

* {
 -webkit-text-size-adjust: none;
  text-size-adjust: none;
}

Best way to format integer as string with leading zeros?

For Python 3 and beyond: str.zfill() is still the most readable option

But it is a good idea to look into the new and powerful str.format(), what if you want to pad something that is not 0?

    # if we want to pad 22 with zeros in front, to be 5 digits in length:
    str_output = '{:0>5}'.format(22)
    print(str_output)
    # >>> 00022
    # {:0>5} meaning: ":0" means: pad with 0, ">" means move 22 to right most, "5" means the total length is 5

    # another example for comparision
    str_output = '{:#<4}'.format(11)
    print(str_output)
    # >>> 11##

    # to put it in a less hard-coded format:
    int_inputArg = 22
    int_desiredLength = 5
    str_output = '{str_0:0>{str_1}}'.format(str_0=int_inputArg, str_1=int_desiredLength)
    print(str_output)
    # >>> 00022

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

How to use the CancellationToken property?

You can implement your work method as follows:

private static void Work(CancellationToken cancelToken)
{
    while (true)
    {
        if(cancelToken.IsCancellationRequested)
        {
            return;
        }
        Console.Write("345");
    }
}

That's it. You always need to handle cancellation by yourself - exit from method when it is appropriate time to exit (so that your work and data is in consistent state)

UPDATE: I prefer not writing while (!cancelToken.IsCancellationRequested) because often there are few exit points where you can stop executing safely across loop body, and loop usually have some logical condition to exit (iterate over all items in collection etc.). So I believe it's better not to mix that conditions as they have different intention.

Cautionary note about avoiding CancellationToken.ThrowIfCancellationRequested():

Comment in question by Eamon Nerbonne:

... replacing ThrowIfCancellationRequested with a bunch of checks for IsCancellationRequested exits gracefully, as this answer says. But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, but in RanToCompletion. And that can affect not just explicit state checks, but also, more subtly, task chaining with e.g. ContinueWith, depending on the TaskContinuationOptions used. I'd say that avoiding ThrowIfCancellationRequested is dangerous advice.

Sorting options elements alphabetically using jQuery

I know this topic is old but I think my answer can be useful for a lot of people.

Here is jQuery plugin made from Pointy's answer using ES6:

/**
 * Sort values alphabetically in select
 * source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
 */
$.fn.extend({
    sortSelect() {
        let options = this.find("option"),
            arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();

        arr.sort((o1, o2) => { // sort select
            let t1 = o1.t.toLowerCase(), 
                t2 = o2.t.toLowerCase();
            return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
        });

        options.each((i, o) => {
            o.value = arr[i].v;
            $(o).text(arr[i].t);
        });
    }
});

Use is very easy

$("select").sortSelect();

Check if checkbox is NOT checked on click - jQuery

The answer already posted will work. If you want to use the jQuery :not you can do this:

if ($(this).is(':not(:checked)'))

or

if ($(this).attr('checked') == false)

Hidden Columns in jqGrid

I just want to expand on queen3's suggestion, applying the following does the trick:

editoptions: { 
              dataInit: function(element) { 
                          $(element).attr("readonly", "readonly"); 
                        } 
             }

Scenario #1:

  • Field must be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
        {  name:'providerUserId',
               index:'providerUserId', 
               width:100,editable:true, 
               editrules:{required:true}, 
               editoptions:{ 
                            dataInit: function(element) { 
                                  jq(element).attr("readonly", "readonly"); 
                             } 
                           }
            },
],

The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents.


Scenario #2:

  • Field must not be visible in the grid
  • Field must be visible in the form
  • Field must be read-only

Solution:

colModel:[
           {name:'providerUserId',
            index:'providerUserId', 
            width:100,editable:true, 
            editrules:{
                         required:true, 
                         edithidden:true
                      },
            hidden:true, 
            editoptions:{ 
                  dataInit: function(element) {                     
                             jq(element).attr("readonly", "readonly"); 
                          } 
                     }
         },
        ]

Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:

<script type="text/javascript">
    var jq = jQuery.noConflict();
</script>

How to convert an array to object in PHP?

Best Method in the WORLD :)

function arrayToObject($conArray)
{
    if(is_array($conArray)){
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return (object) array_map(__FUNCTION__, $conArray);
    }else{
        // Return object
        return $conArray;
    }
}

if you use different methods you will have problems. This is the best method. You have ever seen.

Powershell: A positional parameter cannot be found that accepts argument "xxx"

In my case there was a corrupted character in one of the named params ("-StorageAccountName" for cmdlet "Get-AzureStorageKey") which showed as perfectly normal in my editor (SublimeText) but Windows Powershell couldn't parse it.

To get to the bottom of it, I moved the offending lines from the error message into another .ps1 file, ran that, and the error now showed a botched character at the beginning of my "-StorageAccountName" parameter.

Deleting the character (again which looks normal in the actual editor) and re-typing it fixes this issue.

alternative to "!is.null()" in R

You may be better off working out what value type your function or code accepts, and asking for that:

if (is.integer(aVariable))
{
  do whatever
}

This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.

Alternatively, just make the function you want:

is.defined = function(x)!is.null(x)

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

What is difference between cacerts and keystore?

Cacerts are details of trusted signing authorities who can issue certs. This what most of the browsers have due to which certs determined to be authentic. Keystone has your service related certs to authenticate clients.

Warning message: In `...` : invalid factor level, NA generated

Here is a flexible approach, it can be used in all cases, in particular:

  1. to affect only one column, or
  2. the dataframe has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).

First, un-factorize a string using the as.character function, and, then, re-factorize with the as.factor (or simply factor) function:

fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))

# Un-factorize (as.numeric can be use for numeric values)
#              (as.vector  can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)

# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)

AsyncTask Android example

Move these two lines:

TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed");

out of your AsyncTask's doInBackground method and put them in the onPostExecute method. Your AsyncTask should look something like this:

private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            Thread.sleep(5000); // no need for a loop
        } catch (InterruptedException e) {
            Log.e("LongOperation", "Interrupted", e);
            return "Interrupted";
        }
        return "Executed";
    }      

    @Override
    protected void onPostExecute(String result) {               
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(result);
    }
}

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

When should I use double or single quotes in JavaScript?

The difference is purely stylistic. I used to be a double-quote Nazi. Now I use single quotes in nearly all cases. There's no practical difference beyond how your editor highlights the syntax.

presentViewController and displaying navigation bar

Swift version : This presents a ViewController which is embedded in a Navigation Controller.

    override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    //  Identify the bundle by means of a class in that bundle.
    let storyboard = UIStoryboard(name: "Storyboard", bundle: NSBundle(forClass: SettingsViewController.self))

    // Instance of ViewController that is in the storyboard.
    let settingViewController = storyboard.instantiateViewControllerWithIdentifier("SettingsVC")

    let navController = UINavigationController(rootViewController: settingViewController)

    presentViewController(navController, animated: true, completion: nil)

}

How to set IE11 Document mode to edge as default?

The rendering mode in Internet Explorer 11 can appear stuck if the site is added to your local Compatibility View list. When this happens, the rendering mode inside the developer tools and out will default to the specified compatibility settings.

While this may not be the only way a site can get on this list, Microsoft does document the steps for how to manually add a site to this list.

From Fix site display problems with Compatibility View:

To add a site to the Compatibility View list

  1. Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.

  2. Tap or click the Tools button, and then tap or click Compatibility View settings.

  3. Under Add this website, enter the URL of the site you want to add to the list, and then tap or click Add.

Site Compatibility View Removal Instructions:

To remove a site from this list, follow these instructions.

  1. Go to Tools > Compatibility View settings.
  2. In the resulting dialog, click on the site you want to remove from the list.
  3. Click the Remove button.

Screenshots:

Tools - Compatibility View settings

Compatibility View settings dialog

What is offsetHeight, clientHeight, scrollHeight?

To know the difference you have to understand the box model, but basically:

clientHeight:

returns the inner height of an element in pixels, including padding but not the horizontal scrollbar height, border, or margin

offsetHeight:

is a measurement which includes the element borders, the element vertical padding, the element horizontal scrollbar (if present, if rendered) and the element CSS height.

scrollHeight:

is a measurement of the height of an element's content including content not visible on the screen due to overflow


I will make it easier:

Consider:

<element>                                     
    <!-- *content*: child nodes: -->        | content
    A child node as text node               | of
    <div id="another_child_node"></div>     | the
    ... and I am the 4th child node         | element
</element>                                    

scrollHeight: ENTIRE content & padding (visible or not)
Height of all content + paddings, despite of height of the element.

clientHeight: VISIBLE content & padding
Only visible height: content portion limited by explicitly defined height of the element.

offsetHeight: VISIBLE content & padding + border + scrollbar
Height occupied by the element on document.

scrollHeight clientHeight and offsetHeight

How to scroll the window using JQuery $.scrollTo() function

$('html, body').animate({scrollTop: $("#page").offset().top}, 2000);

in_array() and multidimensional array

I used this method works for any number of nested and not require hacking

<?php
    $blogCategories = [
        'programing' => [
            'golang',
            'php',
            'ruby',
            'functional' => [
                'Erlang',
                'Haskell'
            ]
        ],
        'bd' => [
            'mysql',
            'sqlite'
        ]
    ];
    $it = new RecursiveArrayIterator($blogCategories);
    foreach (new RecursiveIteratorIterator($it) as $t) {
        $found = $t == 'Haskell';
        if ($found) {
           break;
        }
    }

How to remove specific session in asp.net?

HttpContext.Current.Session.Remove("sessionname");

it works for me

how to find my angular version in my project?

you can use ng --version for angular version 7

How can I round a number in JavaScript? .toFixed() returns a string?

For others like me that happen upon this very old question, a modern solution:

const roundValue = (num, decimals = 2) => {
    let scaling = 10 ** decimals;
    return Math.round((num + Number.EPSILON) * scaling) / scaling;
}

ref: https://stackoverflow.com/a/11832950

How do I set up Vim autoindentation properly for editing Python files?

I use this on my macbook:

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler                           " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

(edited to only show stuff related to indent / tabs)

How can I copy data from one column to another in the same table?

UPDATE table_name SET
    destination_column_name=orig_column_name
WHERE condition_if_necessary

Receive result from DialogFragment

Or share ViewModel like showed here:

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }

    public LiveData<Item> getSelected() {
        return selected;
    }
}


public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, { item ->
           // Update the UI.
        });
    }
}

https://developer.android.com/topic/libraries/architecture/viewmodel#sharing_data_between_fragments

Unsupported major.minor version 52.0 in my app

I had two versions of java jdk installed. Once I pointed to right version of java jdk in File->Project Structure -> SDK Location to the latest version which I had in JAVA_HOME environment variable, the issue went away.

Remove redundant paths from $PATH variable

Assuming your shell is Bash, you can set the path with

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

but like Levon said in another answer, as soon as you terminate the shell the changes will be gone. You probably want to set up your PATH in ~/.bash_profile or ~/.bashrc.

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Border Height on CSS

table {
 border-spacing: 10px 0px;
}

.rightborder {
border-right: 1px solid #fff;
}

Then with your code you can:

<td class="rightborder">whatever</td>

Hope that helps!

How to upload multiple files using PHP, jQuery and AJAX

HTML

<form enctype="multipart/form-data" action="upload.php" method="post">
    <input name="file[]" type="file" />
    <button class="add_more">Add More Files</button>
    <input type="button" value="Upload File" id="upload"/>
</form>

Javascript

 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(this).before("<input name='file[]' type='file'/>");
    });
});

for ajax upload

$('#upload').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;

    for (; i < len; i++) {
        file = filedata.files[i];

        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {

            },       
            error: function(res) {

             }       
             });
            }
        });

PHP

for($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

    if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo "The file has been uploaded successfully <br />";
    } else{
        echo "There was an error uploading the file, please try again! <br />";
    }
}

/** 
    Edit: $target_path variable need to be reinitialized and should 
    be inside for loop to avoid appending previous file name to new one. 
*/

Please use the script above script for ajax upload. It will work

GridLayout (not GridView) how to stretch all children evenly

Starting in API 21 without v7 support library with ScrollView:

enter image description here

XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:columnCount="2"
            >

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile1" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimaryDark"
            android:text="Tile2" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimary"
            android:text="Tile3" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile4" />

    </GridLayout>
</ScrollView>

Run a php app using tomcat?

A tad late, but here goes.

How about http://wiki.apache.org/tomcat/UsingPhp if you just want to run the real php on tomcat.

Concerning running tomcat on port 80 there's always jsvc, just google jsvc + tomcat.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

$(document).ready(function() {
    $(document).on("click", ".question", function(e) {
       var checked = $(this).find("input:checkbox").is(":checked");
       if (checked) {
           $('.answer').show(300);
       } else {
           $('.answer').hide(300);
       }
    });
});

PHP Redirect to another page after form submit

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"

database attached is read only

Make sure the files are writeable (not read-only), and that your user has write permissions on them.

Also, on most recent systems, the Program Files directory is read-only. Try to place the files in another directory.

Is there an arraylist in Javascript?

Arrays are pretty flexible in JS, you can do:

var myArray = new Array();
myArray.push("string 1");
myArray.push("string 2");

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

How do I open a URL from C++?

I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>


For those of you that are using Windows, as I am, you can use the following:

std::string op = std::string("start ").append(url);
system(op.c_str());

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

how to set textbox value in jquery

try

subtotal.value= 5 // some value

_x000D_
_x000D_
proc = async function(x,y) {_x000D_
  let url = "https://server.test-cors.org/server?id=346169&enable=true&status=200&credentials=false&methods=GET&" // some url working in snippet_x000D_
  _x000D_
  let r= await(await fetch(url+'&prodid=' + x + '&qbuys=' + y)).json(); // return json-object_x000D_
  console.log(r);_x000D_
  _x000D_
  subtotal.value= r.length; // example value from json_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form name="yoh" method="get"> _x000D_
Product id: <input type="text" id="pid"  value=""><br/>_x000D_
_x000D_
Quantity to buy:<input type="text" id="qtytobuy"  value="" onkeyup="proc(pid.value, this.value);"></br>_x000D_
_x000D_
Subtotal:<input type="text" name="subtotal" id="subtotal"  value=""></br>_x000D_
<div id="compz"></div>_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_

Is there an opposite of include? for Ruby Arrays?

Try something like this:

@players.include?(p.name) ? false : true

How to make an app's background image repeat

Ok, here's what I've got in my app. It includes a hack to prevent ListViews from going black while scrolling.

drawable/app_background.xml:

<?xml version="1.0" encoding="utf-8"?>
    <bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/actual_pattern_image"
        android:tileMode="repeat" />

values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <style name="app_theme" parent="android:Theme">
    <item name="android:windowBackground">@drawable/app_background</item>
    <item name="android:listViewStyle">@style/TransparentListView</item>
    <item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
  </style>

  <style name="TransparentListView" parent="@android:style/Widget.ListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

  <style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

</resources>

AndroidManifest.xml:

//
<application android:theme="@style/app_theme">
//

c# .net change label text

Have you tried running the code in the Page_Load() method?

protected void Page_Load(object sender, EventArgs e) 
{

         Label1.Text = "test";
        if (Request.QueryString["ID"] != null)
        {

            string test = Request.QueryString["ID"];
            Label1.Text = "Du har nu lånat filmen:" + test;
        }
}

Convert Float to Int in Swift

You can get an integer representation of your float by passing the float into the Integer initializer method.

Example:

Int(myFloat)

Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

Min/Max of dates in an array?

Something like:

var min = dates.reduce(function (a, b) { return a < b ? a : b; }); 
var max = dates.reduce(function (a, b) { return a > b ? a : b; });

Tested on Chrome 15.0.854.0 dev

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

I can offer you some general algorithms...

  • O(1): Accessing an element in an array (i.e. int i = a[9])
  • O(n log n): quick or mergesort (On average)
  • O(log n): Binary search

These would be the gut responses as this sounds like homework/interview kind of question. If you are looking for something more concrete it's a little harder as the public in general would have no idea of the underlying implementation (Sparing open source of course) of a popular application, nor does the concept in general apply to an "application"

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

Using the solution of Slauma, I created some generic functions to help update child objects and collections of child objects.

All my persistent objects implement this interface

/// <summary>
/// Base interface for all persisted entries
/// </summary>
public interface IBase
{
    /// <summary>
    /// The Id
    /// </summary>
    int Id { get; set; }
}

With this I implemented these two functions in my Repository

    /// <summary>
    /// Check if orgEntry is set update it's values, otherwise add it
    /// </summary>
    /// <param name="set">The collection</param>
    /// <param name="entry">The entry</param>
    /// <param name="orgEntry">The original entry found in the database (can be <code>null</code> is this is a new entry)</param>
    /// <returns>The added or updated entry</returns>
    public T AddOrUpdateEntry<T>(DbSet<T> set, T entry, T orgEntry) where T : class, IBase
    {
        if (entry.Id == 0 || orgEntry == null)
        {
            entry.Id = 0;
            return set.Add(entry);
        }
        else
        {
            Context.Entry(orgEntry).CurrentValues.SetValues(entry);
            return orgEntry;
        }
    }

    /// <summary>
    /// check if each entry of the new list was in the orginal list, if found, update it, if not found add it
    /// all entries found in the orignal list that are not in the new list are removed
    /// </summary>
    /// <typeparam name="T">The type of entry</typeparam>
    /// <param name="set">The database set</param>
    /// <param name="newList">The new list</param>
    /// <param name="orgList">The original list</param>
    public void AddOrUpdateCollection<T>(DbSet<T> set, ICollection<T> newList, ICollection<T> orgList) where T : class, IBase
    {
        // attach or update all entries in the new list
        foreach (T entry in newList)
        {
            // Find out if we had the entry already in the list
            var orgEntry = orgList.SingleOrDefault(e => e.Id != 0 && e.Id == entry.Id);

            AddOrUpdateEntry(set, entry, orgEntry);
        }

        // Remove all entries from the original list that are no longer in the new list
        foreach (T orgEntry in orgList.Where(e => e.Id != 0).ToList())
        {
            if (!newList.Any(e => e.Id == orgEntry.Id))
            {
                set.Remove(orgEntry);
            }
        }
    }

To use it i do the following:

var originalParent = _dbContext.ParentItems
    .Where(p => p.Id == parent.Id)
    .Include(p => p.ChildItems)
    .Include(p => p.ChildItems2)
    .SingleOrDefault();

// Add the parent (including collections) to the context or update it's values (except the collections)
originalParent = AddOrUpdateEntry(_dbContext.ParentItems, parent, originalParent);

// Update each collection
AddOrUpdateCollection(_dbContext.ChildItems, parent.ChildItems, orgiginalParent.ChildItems);
AddOrUpdateCollection(_dbContext.ChildItems2, parent.ChildItems2, orgiginalParent.ChildItems2);

Hope this helps


EXTRA: You could also make a seperate DbContextExtentions (or your own context inferface) class:

public static void DbContextExtentions {
    /// <summary>
    /// Check if orgEntry is set update it's values, otherwise add it
    /// </summary>
    /// <param name="_dbContext">The context object</param>
    /// <param name="set">The collection</param>
    /// <param name="entry">The entry</param>
    /// <param name="orgEntry">The original entry found in the database (can be <code>null</code> is this is a new entry)</param>
    /// <returns>The added or updated entry</returns>
    public static T AddOrUpdateEntry<T>(this DbContext _dbContext, DbSet<T> set, T entry, T orgEntry) where T : class, IBase
    {
        if (entry.IsNew || orgEntry == null) // New or not found in context
        {
            entry.Id = 0;
            return set.Add(entry);
        }
        else
        {
            _dbContext.Entry(orgEntry).CurrentValues.SetValues(entry);
            return orgEntry;
        }
    }

    /// <summary>
    /// check if each entry of the new list was in the orginal list, if found, update it, if not found add it
    /// all entries found in the orignal list that are not in the new list are removed
    /// </summary>
    /// <typeparam name="T">The type of entry</typeparam>
    /// <param name="_dbContext">The context object</param>
    /// <param name="set">The database set</param>
    /// <param name="newList">The new list</param>
    /// <param name="orgList">The original list</param>
    public static void AddOrUpdateCollection<T>(this DbContext _dbContext, DbSet<T> set, ICollection<T> newList, ICollection<T> orgList) where T : class, IBase
    {
        // attach or update all entries in the new list
        foreach (T entry in newList)
        {
            // Find out if we had the entry already in the list
            var orgEntry = orgList.SingleOrDefault(e => e.Id != 0 && e.Id == entry.Id);

            AddOrUpdateEntry(_dbContext, set, entry, orgEntry);
        }

        // Remove all entries from the original list that are no longer in the new list
        foreach (T orgEntry in orgList.Where(e => e.Id != 0).ToList())
        {
            if (!newList.Any(e => e.Id == orgEntry.Id))
            {
                set.Remove(orgEntry);
            }
        }
    }
}

and use it like:

var originalParent = _dbContext.ParentItems
    .Where(p => p.Id == parent.Id)
    .Include(p => p.ChildItems)
    .Include(p => p.ChildItems2)
    .SingleOrDefault();

// Add the parent (including collections) to the context or update it's values (except the collections)
originalParent = _dbContext.AddOrUpdateEntry(_dbContext.ParentItems, parent, originalParent);

// Update each collection
_dbContext.AddOrUpdateCollection(_dbContext.ChildItems, parent.ChildItems, orgiginalParent.ChildItems);
_dbContext.AddOrUpdateCollection(_dbContext.ChildItems2, parent.ChildItems2, orgiginalParent.ChildItems2);

How can I pass a parameter in Action?

You're looking for Action<T>, which takes a parameter.

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

How can I convert String[] to ArrayList<String>

Like this :

String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));

or

List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);

Getting values from query string in an url using AngularJS $location

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

Counting the Number of keywords in a dictionary in python

len(yourdict.keys())

or just

len(yourdict)

If you like to count unique words in the file, you could just use set and do like

len(set(open(yourdictfile).read().split()))

How to use multiprocessing queue in Python?

A multi-producers and multi-consumers example, verified. It should be easy to modify it to cover other cases, single/multi producers, single/multi consumers.

from multiprocessing import Process, JoinableQueue
import time
import os

q = JoinableQueue()

def producer():
    for item in range(30):
        time.sleep(2)
        q.put(item)
    pid = os.getpid()
    print(f'producer {pid} done')


def worker():
    while True:
        item = q.get()
        pid = os.getpid()
        print(f'pid {pid} Working on {item}')
        print(f'pid {pid} Finished {item}')
        q.task_done()

for i in range(5):
    p = Process(target=worker, daemon=True).start()

# send thirty task requests to the worker
producers = []
for i in range(2):
    p = Process(target=producer)
    producers.append(p)
    p.start()

# make sure producers done
for p in producers:
    p.join()

# block until all workers are done
q.join()
print('All work completed')

Explanation:

  1. Two producers and five consumers in this example.
  2. JoinableQueue is used to make sure all elements stored in queue will be processed. 'task_done' is for worker to notify an element is done. 'q.join()' will wait for all elements marked as done.
  3. With #2, there is no need to join wait for every worker.
  4. But it is important to join wait for every producer to store element into queue. Otherwise, program exit immediately.

Run Jquery function on window events: load, resize, and scroll?

just call your function inside the events.

load:

$(document).ready(function(){  // or  $(window).load(function(){
    topInViewport($(mydivname));
});

resize:

$(window).resize(function () {
    topInViewport($(mydivname));
});

scroll:

$(window).scroll(function () {
    topInViewport($(mydivname));
});

or bind all event in one function

$(window).on("load scroll resize",function(e){

Is there a stopwatch in Java?

Try this:

/*
 * calculates elapsed time in the form hrs:mins:secs
 */
public class StopWatch
{ 
    private Date startTime;

    public void startTiming()
    {
        startTime = new Date();
    }

    public String stopTiming()
    {
        Date stopTime = new Date();
        long timediff = (stopTime.getTime() - startTime.getTime())/1000L;
        return(DateUtils.formatElapsedTime(timediff));
    }

}

Use:

StopWatch sw = new StopWatch();
...
sw.startTiming();
...
String interval = sw.stopTiming();

disable viewport zooming iOS 10+ safari?

Check for scale factor in touchove event then prevent touch event.

document.addEventListener('touchmove', function(event) {
    event = event.originalEvent || event;
    if(event.scale > 1) {
        event.preventDefault();
    }
}, false);

Dart SDK is not configured

Just go to File > Settings > Languages & Frameworks > Dart

Click on check box Enable Dart Support for project 'projectName' Paste the Dart SDK path.

This is how you get Dart SDK path, follow the given steps copy the Dart SDK Path, which is in Flutter SDK, Go to location where your Flutter SDK Situated, then,

Flutter/bin/cache/dart-sdk , till dart-sdk, copy the path and paste it.

How do I select an element that has a certain class?

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

How to remove element from an array in JavaScript?

For a more flexible solution, use the splice() function. It allows you to remove any item in an Array based on Index Value:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

Spring Security exclude url patterns in security annotation configurartion

Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

The following is working for me.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()
        .antMatchers("/static/**").permitAll()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
                .usernameParameter("username").passwordParameter("password")
        .and()
            .logout().logoutSuccessUrl("/login?logout")
        .and()
            .exceptionHandling().accessDeniedPage("/403")
        .and()
            .csrf();

}

NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()

Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")

Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

How can I avoid Java code in JSP files, using JSP 2?

Nothing of that is used anymore, my friend. My advice is to decouple the view (CSS, HTML, JavaScript, etc.) from the server.

In my case, I do my systems handling the view with Angular and any data needed is brought from the server using REST services.

Believe me, this will change the way you design.

How to import a module given its name as string?

Similar as @monkut 's solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:

import os
import imp

def importFromURI(uri, absl):
    mod = None
    if not absl:
        uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
    path, fname = os.path.split(uri)
    mname, ext = os.path.splitext(fname)

    if os.path.exists(os.path.join(path,mname)+'.pyc'):
        try:
            return imp.load_compiled(mname, uri)
        except:
            pass
    if os.path.exists(os.path.join(path,mname)+'.py'):
        try:
            return imp.load_source(mname, uri)
        except:
            pass

    return mod

What are some reasons for jquery .focus() not working?

The problem in my case was that I entered a value IN THE LAST NOT DISABLED ELEMENT of the site and used tab to raise the onChange-Event. After that there is no next element to get the focus, so the "browser"-Focus switches to the browser-functionality (tabs, menu, and so on) and is not any longer inside the html-content.

To understand that, place a displayed, not disabled dummy-textbox at the end of your html-code. In that you can "park" the focus for later replacing. Should work. In my case. All other tries didnt work, also the setTimeout-Version.

Checked this out for about an hour, because it made me insane :)

Mätes

SQL Server Case Statement when IS NULL

Take a look at the ISNULL function. It helps you replace NULL values for other values. http://msdn.microsoft.com/en-us/library/ms184325.aspx

Is there an easy way to check the .NET Framework version?

This class allows your application to throw out a graceful notification message rather than crash and burn if it couldn't find the proper .NET version. All you need to do is this in your main code:

[STAThread]
static void Main(string[] args)
{
    if (!DotNetUtils.IsCompatible())
        return;
   . . .
}

By default it takes 4.5.2, but you can tweak it to your liking, the class (feel free to replace MessageBox with Console):

Updated for 4.8:

public class DotNetUtils
{
    public enum DotNetRelease
    {
        NOTFOUND,
        NET45,
        NET451,
        NET452,
        NET46,
        NET461,
        NET462,
        NET47,
        NET471,
        NET472,
        NET48,
    }

    public static bool IsCompatible(DotNetRelease req = DotNetRelease.NET452)
    {
        DotNetRelease r = GetRelease();
        if (r < req)
        {
            MessageBox.Show(String.Format("This this application requires {0} or greater.", req.ToString()));
            return false;
        }
        return true;
    }

    public static DotNetRelease GetRelease(int release = default(int))
    {
        int r = release != default(int) ? release : GetVersion();
        if (r >= 528040) return DotNetRelease.NET48;
        if (r >= 461808) return DotNetRelease.NET472;
        if (r >= 461308) return DotNetRelease.NET471;
        if (r >= 460798) return DotNetRelease.NET47;
        if (r >= 394802) return DotNetRelease.NET462;
        if (r >= 394254) return DotNetRelease.NET461;
        if (r >= 393295) return DotNetRelease.NET46;
        if (r >= 379893) return DotNetRelease.NET452;
        if (r >= 378675) return DotNetRelease.NET451;
        if (r >= 378389) return DotNetRelease.NET45;
        return DotNetRelease.NOTFOUND;
    }

    public static int GetVersion()
    {
        int release = 0;
        using (RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)
                                            .OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
        {
            release = Convert.ToInt32(key.GetValue("Release"));
        }
        return release;
    }
}

Easily extendable when they add a new version later on. I didn't bother with anything before 4.5 but you get the idea.

How can I concatenate strings in VBA?

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

How to overwrite the output directory in spark

This overloaded version of the save function works for me:

yourDF.save(outputPath, org.apache.spark.sql.SaveMode.valueOf("Overwrite"))

The example above would overwrite an existing folder. The savemode can take these parameters as well (https://spark.apache.org/docs/1.4.0/api/java/org/apache/spark/sql/SaveMode.html):

Append: Append mode means that when saving a DataFrame to a data source, if data/table already exists, contents of the DataFrame are expected to be appended to existing data.

ErrorIfExists: ErrorIfExists mode means that when saving a DataFrame to a data source, if data already exists, an exception is expected to be thrown.

Ignore: Ignore mode means that when saving a DataFrame to a data source, if data already exists, the save operation is expected to not save the contents of the DataFrame and to not change the existing data.

How do I use a Boolean in Python?

checker = None 

if some_decision:
    checker = True

if checker:
    # some stuff

[Edit]

For more information: http://docs.python.org/library/functions.html#bool

Your code works too, since 1 is converted to True when necessary. Actually Python didn't have a boolean type for a long time (as in old C), and some programmers still use integers instead of booleans.

Field 'browser' doesn't contain a valid alias configuration

Turned out to be an issue with Webpack just not resolving an import - talk about horrible horrible error messages :(

// Had to change
import DoISuportIt from 'components/DoISuportIt';

// To (notice the missing `./`)
import DoISuportIt from './components/DoISuportIt';

Node.js client for a socket.io server

Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

Difference between add(), replace(), and addToBackStack()

Although it is an old question already answered, maybe those next examples can complement the accepted answer and they can be useful for some new programmers in Android as I am.

Option 1 - "addToBackStack()" is never used

Case 1A - adding, removing, and clicking Back button

Activity :      onCreate() - onStart() - onResume()                             Activity is visible
add Fragment A :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment A is visible
add Fragment B :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment B is visible
add Fragment C :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment C is visible
remove Fragment C :     onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Fragment B is visible
(Back button clicked)
Activity :      onPause() - onStop() - onDestroy()
Fragment A :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()
Fragment B :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               App is closed, nothing is visible

Case 1B - adding, replacing, and clicking Back button

Activity :      onCreate() - onStart() - onResume()                             Activity is visible
add Fragment A :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment A is visible
add Fragment B :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment B is visible
(replace Fragment C)    
Fragment B :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               
Fragment A :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()
Fragment C :        onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment C is visible
(Back button clicked)
Activity :      onPause() - onStop() - onDestroy()
Fragment C :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               App is closed, nothing is visible

Option 2 - "addToBackStack()" is always used

Case 2A - adding, removing, and clicking Back button

Activity :      onCreate() - onStart() - onResume()                             Activity is visible
add Fragment A :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment A is visible
add Fragment B :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment B is visible
add Fragment C :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment C is visible
remove Fragment C :     onPause() - onStop() - onDestroyView()                              Fragment B is visible
(Back button clicked)
Fragment C :        onCreateView() - onActivityCreated() - onStart() - onResume()                   Fragment C is visible
(Back button clicked)
Fragment C :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Fragment B is visible
(Back button clicked)
Fragment B :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Fragment A is visible
(Back button clicked)
Fragment A :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Activity is visible
(Back button clicked)
Activity :      onPause() - onStop() - onDestroy()                              App is closed, nothing is visible

Case 2B - adding, replacing, removing, and clicking Back button

Activity :      onCreate() - onStart() - onResume()                             Activity is visible
add Fragment A :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment A is visible
add Fragment B :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment B is visible
(replace Fragment C)    
Fragment B :        onPause() - onStop() - onDestroyView()  
Fragment A :        onPause() - onStop() - onDestroyView() 
Fragment C :        onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment C is visible
remove Fragment C :     onPause() - onStop() - onDestroyView()                              Activity is visible
(Back button clicked)
Fragment C :        onCreateView() - onActivityCreated() - onStart() - onResume()                   Fragment C is visible
(Back button clicked)
Fragment C :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               
Fragment A :        onCreateView() - onActivityCreated() - onStart() - onResume()   
Fragment B :        onCreateView() - onActivityCreated() - onStart() - onResume()                   Fragment B is visible
(Back button clicked)
Fragment B :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Fragment A is visible
(Back button clicked)
Fragment A :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Activity is visible
(Back button clicked)
Activity :      onPause() - onStop() - onDestroy()                              App is closed, nothing is visible

Option 3 - "addToBackStack()" is not used always (in the below examples, w/o indicates that it is not used)

Case 3A - adding, removing, and clicking Back button

Activity :      onCreate() - onStart() - onResume()                             Activity is visible
add Fragment A :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment A is visible
add Fragment B w/o:     onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment B is visible
add Fragment C w/o:     onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment C is visible
remove Fragment C :     onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Fragment B is visible
(Back button clicked)
Fragment B :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               
Fragment A :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Activity is visible
(Back button clicked)
Activity :      onPause() - onStop() - onDestroy()                              App is closed, nothing is visible

Case 3B - adding, replacing, removing, and clicking Back button

Activity :      onCreate() - onStart() - onResume()                             Activity is visible
add Fragment A :    onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment A is visible
add Fragment B w/o:     onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment B is visible
(replace Fragment C)    
Fragment B :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()   
Fragment A :        onPause() - onStop() - onDestroyView() 
Fragment C :        onAttach() - onCreate() - onCreateView() - onActivityCreated() - onStart() - onResume()     Fragment C is visible
remove Fragment C :     onPause() - onStop() - onDestroyView()                              Activity is visible
(Back button clicked)
Fragment C :        onCreateView() - onActivityCreated() - onStart() - onResume()                   Fragment C is visible
(Back button clicked)
Fragment C :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               
Fragment A :        onCreateView() - onActivityCreated() - onStart() - onResume()                   Fragment A is visible
(Back button clicked)
Fragment A :        onPause() - onStop() - onDestroyView() - onDestroy() - onDetach()               Activity is visible
(Back button clicked)
Activity :      onPause() - onStop() - onDestroy()                              App is closed, nothing is visible

Difference between VARCHAR2(10 CHAR) and NVARCHAR2(10)

  • The NVARCHAR2 stores variable-length character data. When you create a table with the NVARCHAR2 column, the maximum size is always in character length semantics, which is also the default and only length semantics for the NVARCHAR2 data type.

    The NVARCHAR2data type uses AL16UTF16character set which encodes Unicode data in the UTF-16 encoding. The AL16UTF16 use 2 bytes to store a character. In addition, the maximum byte length of an NVARCHAR2 depends on the configured national character set.

  • VARCHAR2 The maximum size of VARCHAR2 can be in either bytes or characters. Its column only can store characters in the default character set while the NVARCHAR2 can store virtually any characters. A single character may require up to 4 bytes.

By defining the field as:

  • VARCHAR2(10 CHAR) you tell Oracle it can use enough space to store 10 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes.
  • NVARCHAR2(10) you tell Oracle it can store 10 characters with 2 bytes per character

In Summary:

  • VARCHAR2(10 CHAR) can store maximum of 10 characters and maximum of 40 bytes (depends on the configured national character set).

  • NVARCHAR2(10) can store maximum of 10 characters and maximum of 20 bytes (depends on the configured national character set).

Note: Character set can be UTF-8, UTF-16,....

Please have a look at this tutorial for more detail.

Have a good day!

OpenCV - Saving images to a particular folder of choice

FOR MAC USERS if you are working with open cv

import cv2

cv2.imwrite('path_to_folder/image.jpg',image)

What's the difference between unit, functional, acceptance, and integration tests?

This is very simple.

  1. Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..

  2. Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.

  3. Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.

  4. Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.

How to increase request timeout in IIS?

To Increase request time out add this to web.config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

and for a specific page add this

<location path="somefile.aspx">
    <system.web>
        <httpRuntime executionTimeout="180"/>
    </system.web>
</location>

The default is 90 seconds for .NET 1.x.

The default 110 seconds for .NET 2.0 and later.

HTML 'td' width and height

The width attribute of <td> is deprecated in HTML 5.

Use CSS. e.g.

 <td style="width:100px">

in detail, like this:

<table >
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td style="width:70%">January</td>
    <td style="width:30%">$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

iptables v1.4.14: can't initialize iptables table `nat': Table does not exist (do you need to insmod?)

Finaly, my service provider answered :

This is a limitation of the virtualization system we use (OpenVZ), basic iptables rules are possible but not those who use the nat table.

If this really is a problem, we can offer you to migrate to a other system virtualization (KVM) as we begin to offer our customers.

SO I had to migrate my server to the new system...

Basic calculator in Java

import java.util.Scanner;
public class JavaApplication1 {


    public static void main(String[] args) {

         int x,
         int y;

         Scanner input=new Scanner(System.in);
         System.out.println("Enter Number 1");
         x=input.nextInt();
         System.out.println("Enter Number 2");
         y=input.nextInt();

         System.out.println("Please enter operation + - / or *");
         Scanner op=new Scanner(System.in);
         String operation = op.next();

         if (operation.equals("+")){
             System.out.println("Your Answer: " + (x+y));
         }
         if (operation.equals("-")){
             System.out.println("Your Answer: "+ (x-y));
         }
         if (operation.equals("/")){
             System.out.println("Your Answer: "+ (x/y));
         }
         if (operation.equals("*")){
            System.out.println("Your Answer: "+ (x*y));
         }
    }

}

Unable to set data attribute using jQuery Data() API

Happened the same to me. It turns out that

var data = $("#myObject").data();

gives you a non-writable object. I solved it using:

var data = $.extend({}, $("#myObject").data());

And from then on, data was a standard, writable JS object.

Change icons of checked and unchecked for Checkbox for Android

One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.

Java: how to use UrlConnection to post request with authorization?

A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection, instead.

Below is the code to do that,

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestProperty ("Authorization", encodedCredentials);

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

    writer.write(data);
    writer.flush();
    String line;
    BufferedReader reader = new BufferedReader(new 
                                     InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    writer.close();
    reader.close();

Change URLConnection to HttpURLConnection, to make it POST request.

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

Suggestion (...in comments):

You might need to set these properties too,

conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

Using Apache httpclient for https

According to the documentation you need to specify the key store:

Protocol authhttps = new Protocol("https",  
      new AuthSSLProtocolSocketFactory(
          new URL("file:my.keystore"), "mypassword",
          new URL("file:my.truststore"), "mypassword"), 443); 

 HttpClient client = new HttpClient();
 client.getHostConfiguration().setHost("localhost", 443, authhttps);

What are the ways to sum matrix elements in MATLAB?

You are trying to sum up all the elements of 2-D Array

In Matlab use

Array_Sum = sum(sum(Array_Name));

Is there a performance difference between a for loop and a for-each loop?

Even with something like an ArrayList or Vector, where "get" is a simple array lookup, the second loop still has additional overhead that the first one doesn't. I would expect it to be a tiny bit slower than the first.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Open Your .edmx file in XML editor and then remove tag from Tag and also change store:Schema="dbo" to Schema="dbo" and rebuild the solution now error will resolve and you will be able to save the data.

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

Force IE10 to run in IE10 Compatibility View?

You should try the IE 5 quirks compatibility mod (is the default IE10 compatibility view)

<meta http-equiv="X-UA-Compatible" content="IE=5">

important: set in the top of your iframe structure (if you use iframe structure)

more info 1, 2

Can't type in React input text field

For me the following simple change worked perfectly

<input type="text" 
        value={props.letter} 
        onChange={event => setTxtLetter(event.target.value)} /> {/* does not work */}

change... value={myPropVal} to... defaultValue={myPropVal}

<input type="text" 
        defaultValue={props.letter} 
        onChange={event => setTxtLetter(event.target.value)} /> {/* Works!! */}

In C#, why is String a reference type that behaves like a value type?

Actually strings have very few resemblances to value types. For starters, not all value types are immutable, you can change the value of an Int32 all you want and it it would still be the same address on the stack.

Strings are immutable for a very good reason, it has nothing to do with it being a reference type, but has a lot to do with memory management. It's just more efficient to create a new object when string size changes than to shift things around on the managed heap. I think you're mixing together value/reference types and immutable objects concepts.

As far as "==": Like you said "==" is an operator overload, and again it was implemented for a very good reason to make framework more useful when working with strings.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Read the message:

Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element.

Move the configSections element to the top - just above where system.data is currently.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

You can configure property inclusion, and numerous other settings, via application.properties:

spring.jackson.default-property-inclusion=non_null

There's a table in the documentation that lists all of the properties that can be used.

If you want more control, you can also customize Spring Boot's configuration programatically using a Jackson2ObjectMapperBuilderCustomizer bean, as described in the documentation:

The context’s Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.

Lastly, if you don't want any of Boot's configuration and want to take complete control over how the ObjectMapper is configured, declare your own Jackson2ObjectMapperBuilder bean:

@Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    // Configure the builder to suit your needs
    return builder;
}

Create Excel file in Java

I've created an API to create an Excel file more easier.

Create Excel - Creating Excel from Template

Just set the required values upon instantiation then invoke execute(), it will be created based on your desired output directory.

But before you use this, you must have an Excel Template which will be use as a template of the newly created Excel file.

Also, you need Apache POI in your project's class path.

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Why do I get "warning longer object length is not a multiple of shorter object length"?

You don't give a reproducible example but your warning message tells you exactly what the problem is.

memb only has a length of 10. I'm guessing the length of dih_y2$MemberID isn't a multiple of 10. When using ==, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. == does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID are also in the vector memb. To do this you would want to use the %in% operator.

dih_col <- which(dih_y2$MemeberID %in% memb)

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

simple HTTP server in Java using only Java SE API

I can strongly recommend looking into Simple, especially if you don't need Servlet capabilities but simply access to the request/reponse objects. If you need REST you can put Jersey on top of it, if you need to output HTML or similar there's Freemarker. I really love what you can do with this combination, and there is relatively little API to learn.

How to access the elements of a 2D array?

Seems to work here:

>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1

Modal width (increase)

The following solution will work for Bootstrap 4.

.modal .modal-dialog {
  max-width: 850px;
}

Angular ng-click with call to a controller function not working

Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here

Just take note of the Controller, it has an alias of homeCtrl.

module MongoAngular {
    var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);

    app.config([
        '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
            $routeProvider
                .when('/Home', {
                    templateUrl: '/PartialViews/Home/home.html',
                    controller: 'HomeController as homeCtrl'
                })
                .otherwise({ redirectTo: '/Home' });
        }])
        .config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
        restangularProvider.setBaseUrl('/api');
    }]);
} 

And here's the way to use it...

ng-click="homeCtrl.addCustomer(customer)"

Try it.. It might work for you as it worked for me... ;)

Find all stored procedures that reference a specific column in some table

If you want to get stored procedures using specific column only, you can use try this query:

SELECT DISTINCT Name
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%CreatedDate%';

If you want to get stored procedures using specific column of table, you can use below query :

SELECT DISTINCT Name 
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%tbl_name%'
AND OBJECT_DEFINITION(OBJECT_ID) LIKE '%CreatedDate%';

Detect application heap size in Android

There are two ways to think about your phrase "application heap size available":

  1. How much heap can my app use before a hard error is triggered? And

  2. How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?

There is a different method for determining each of the above.

For item 1 above: maxMemory()

which can be invoked (e.g., in your main activity's onCreate() method) as follows:

Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));

This method tells you how many total bytes of heap your app is allowed to use.

For item 2 above: getMemoryClass()

which can be invoked as follows:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));

This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop() / onResume() cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.

This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.

For a stock version of Android, maxMemory() will typically return about the same number of megabytes as are indicated in getMemoryClass() (i.e., approximately a million times the latter value).

The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".

NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.

Here are my test results showing the values returned by maxMemory() and getMemoryClass() for four different devices running CyanogenMod, using two different (manually-set) heap values for each:

  • G1:
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 16
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 16
  • Moto Droid:
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 24
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 24
  • Nexus One:
    • With VM Heap size set to 32MB:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 32
  • Viewsonic GTab:
    • With VM Heap Size set to 32:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap Size set to 64:
      • maxMemory: 67108864
      • getMemoryClass: 32

In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.

For that device, here are the results:

  • Novo7
    • maxMemory: 62914560
    • getMemoryClass: 60

Also (per Kishore in a comment below):

  • HTC One X
    • maxMemory: 67108864
    • getMemoryClass: 64

And (per akauppi's comment):

  • Samsung Galaxy Core Plus
    • maxMemory: (Not specified in comment)
    • getMemoryClass: 48
    • largeMemoryClass: 128

Per a comment from cmcromance:

  • Galaxy S3 (Jelly Bean) large heap
    • maxMemory: 268435456
    • getMemoryClass: 64

And (per tencent's comments):

  • LG Nexus 5 (4.4.3) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • LG Nexus 5 (4.4.3) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192
  • Galaxy Nexus (4.3) normal
    • maxMemory: 100663296
    • getMemoryClass: 96
  • Galaxy Nexus (4.3) large heap
    • maxMemory: 268435456
    • getMemoryClass: 96
  • Galaxy S4 Play Store Edition (4.4.2) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • Galaxy S4 Play Store Edition (4.4.2) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192

Other Devices

  • Huawei Nexus 6P (6.0.1) normal
    • maxMemory: 201326592
    • getMemoryClass: 192

I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.

My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory() while leaving getMemoryClass() alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."

If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).

Note that the memory class apparently need not be a multiple of 8MB.

We can see from the above that the getMemoryClass() result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.

My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.

So, you cannot go over the amount of memory specified by maxMemory(). And, you should try to stay within the limits specified by getMemoryClass(). One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.

Finally, if you do plan to go over the number of megabytes specified in getMemoryClass(), my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop() / onResume() cycle occurs.

In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.

But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory() is telling you that you can go much higher than the 16MB that getMemoryClass() is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop() / onResume() works seamlessly.

getMemoryClass(), as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.

By contrast, maxMemory(), according to the documentation, is available all the way back to API level 1. maxMemory(), on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory() value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory() indicates is allowed.

Asynchronously load images with jQuery

$(<img />).attr('src','http://somedomain.com/image.jpg');

Should be better than ajax because if its a gallery and you are looping through a list of pics, if the image is already in cache, it wont send another request to server. It will request in the case of jQuery/ajax and return a HTTP 304 (Not modified) and then use original image from cache if its already there. The above method reduces an empty request to server after the first loop of images in the gallery.

javascript filter array of objects

You may use jQuery.grep():

var found_names = $.grep(names, function(v) {
    return v.name === "Joe" && v.age < 30;
});

DEMO: http://jsfiddle.net/ejPV4/

Getting value from JQUERY datepicker

$('div#someID').datepicker({
   onSelect: function(dateText, inst) { alert(dateText); }
});

you must bind it to input element only

Calling a function when ng-repeat has finished

var module = angular.module('testApp', [])
    .directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});

Notice that I didn't use .ready() but rather wrapped it in a $timeout. $timeout makes sure it's executed when the ng-repeated elements have REALLY finished rendering (because the $timeout will execute at the end of the current digest cycle -- and it will also call $apply internally, unlike setTimeout). So after the ng-repeat has finished, we use $emit to emit an event to outer scopes (sibling and parent scopes).

And then in your controller, you can catch it with $on:

$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
    //you also get the actual event object
    //do stuff, execute functions -- whatever...
});

With html that looks something like this:

<div ng-repeat="item in items" on-finish-render="ngRepeatFinished">
    <div>{{item.name}}}<div>
</div>

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

Laravel 5 Clear Views Cache

in Ubuntu system try to run below command:

sudo php artisan cache:clear

sudo php artisan view:clear

sudo php artisan config:cache

.htaccess 301 redirect of single page

RedirectMatch uses a regular expression that is matched against the URL path. And your regular expression /contact.php just means any URL path that contains /contact.php but not just any URL path that is exactly /contact.php. So use the anchors for the start and end of the string (^ and $):

RedirectMatch 301 ^/contact\.php$ /contact-us.php

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

What is the shortcut to Auto import all in Android Studio?

Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:

Select Insert imports on paste value to All

Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*

Getting reference to child component in parent component

You may actually go with ViewChild API...

parent.ts

<button (click)="clicked()">click</button>

export class App {
  @ViewChild(Child) vc:Child;
  constructor() {
    this.name = 'Angular2'
  }

  func(e) {
    console.log(e)

  }
  clicked(){
   this.vc.getName();
  }
}

child.ts

export class Child implements OnInit{

  onInitialized = new EventEmitter<Child>();
  ...  
  ...
  getName()
  {
     console.log('called by vc')
     console.log(this.name);
  }
}

"Find next" in Vim

As discussed, there are several ways to search:

/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)

plus, navigating prev/next with N and n.

You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.

Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:

hi Search ctermfg=yellow ctermbg=red guifg=...

But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:

nmap <leader>z :noh<CR>

I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Clear icon inside input text

If you want it like Google, then you should know that the "X" isn't actually inside the <input> -- they're next to each other with the outer container styled to appear like the text box.

HTML:

<form>
    <span class="x-input">
        <input type="text" class="x-input-text" />
        <input type="reset" />
    </span>
</form>

CSS:

.x-input {
    border: 1px solid #ccc;
}

.x-input input.x-input-text {
    border: 0;
    outline: 0;
}

Example: http://jsfiddle.net/VTvNX/

Call Python function from JavaScript code

Communicating through processes

Example:

Python: This python code block should return random temperatures.

# sensor.py

import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float
    temperatures.push(parseFloat(data));
    console.log(temperatures);
});

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

How to dynamically change a web page's title?

I use a seperate header and include it using php, in the header i use:

<?php
if (!isset($title)){
    $title = "Your Title";
  }
  else {
    $title = $title;
  }
 ?>
<head>
<title><?php echo $title; ?></title>

Then in each page I use:

<?php
  $title = "Your Title - Page";
  include( "./header.php" );
?>

How can I control the width of a label tag?

label {
  width:200px;
  display: inline-block;
}

OR 

label {
  width:200px;
  display: inline-flex;
}

OR 

label {
  width:200px;
  display: inline-table;
}

Numbering rows within groups in a data frame

Using the rowid() function in data.table:

> set.seed(100)  
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]  
> df$num <- data.table::rowid(df$cat)
> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

How do I update a GitHub forked repository?

A lot of answers end up moving your fork one commit ahead of the parent repository. This answer summarizes the steps found here which will move your fork to the same commit as the parent.

  1. Change directory to your local repository.

    • Switch to master branch if you are not git checkout master
  2. Add the parent as a remote repository, git remote add upstream <repo-location>

  3. Issue git fetch upstream
  4. Issue git rebase upstream/master

    • At this stage you check that commits what will be merged by typing git status
  5. Issue git push origin master

For more information about these commands, refer to step 3.

Writing Python lists to columns in csv

import csv
dic = {firstcol,secondcol} #dictionary
csv = open('result.csv', "w") 
for key in dic.keys():
    row ="\n"+ str(key) + "," + str(dic[key]) 
    csv.write(row)

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

If there is a good chance that the list will contain as much elements as it contains when clearing it, and if you're not in need for free memory, clearing the list is a better option. But my guess is that it probably doesn't matter. Don't try to optimize until you have detected a performance problem, and identified where it comes from.

How to undo a successful "git cherry-pick"?

Faced with this same problem, I discovered if you have committed and/or pushed to remote since your successful cherry-pick, and you want to remove it, you can find the cherry-pick's SHA by running:

git log --graph --decorate --oneline

Then, (after using :wq to exit the log) you can remove the cherry-pick using

git rebase -p --onto YOUR_SHA_HERE^ YOUR_SHA_HERE

where YOUR_SHA_HERE equals the cherry-picked commit's 40- or abbreviated 7-character SHA.

At first, you won't be able to push your changes because your remote repo and your local repo will have different commit histories. You can force your local commits to replace what's on your remote by using

git push --force origin YOUR_REPO_NAME

(I adapted this solution from Seth Robertson: See "Removing an entire commit.")

RESTful API methods; HEAD & OPTIONS

OPTIONS method returns info about API (methods/content type)

HEAD method returns info about resource (version/length/type)

Server response

OPTIONS

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
  • OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?
  • HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource
  • HEAD Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval
  • HEAD, OPTIONS Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application

Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.

How to install Jdk in centos

There are JDK versions available from the base CentOS repositories. Depending on your version of CentOS, and the JDK you want to install, the following as root should give you what you want:

OpenJDK Runtime Environment (Java SE 6)

yum install java-1.6.0-openjdk

OpenJDK Runtime Environment (Java SE 7)

yum install java-1.7.0-openjdk

OpenJDK Development Environment (Java SE 7)

yum install java-1.7.0-openjdk-devel

OpenJDK Development Environment (Java SE 6)

yum install java-1.6.0-openjdk-devel

Update for Java 8

In CentOS 6.6 or later, Java 8 is available. Similar to 6 and 7 above, the packages are as follows:

OpenJDK Runtime Environment (Java SE 8)

yum install java-1.8.0-openjdk

OpenJDK Development Environment (Java SE 8)

yum install java-1.8.0-openjdk-devel

There's also a 'headless' JRE package that is the same as the above JRE, except it doesn't contain audio/video support. This can be used for a slightly more minimal installation:

OpenJDK Runtime Environment - Headless (Java SE 8)

yum install java-1.8.0-openjdk-headless

What is the difference between declarations, providers, and import in NgModule?

Adding a quick cheat sheet that may help after the long break with Angular:


DECLARATIONS

Example:

declarations: [AppComponent]

What can we inject here? Components, pipes, directives


IMPORTS

Example:

imports: [BrowserModule, AppRoutingModule]

What can we inject here? other modules


PROVIDERS

Example:

providers: [UserService]

What can we inject here? services


BOOTSTRAP

Example:

bootstrap: [AppComponent]

What can we inject here? the main component that will be generated by this module (top parent node for a component tree)


ENTRY COMPONENTS

Example:

entryComponents: [PopupComponent]

What can we inject here? dynamically generated components (for instance by using ViewContainerRef.createComponent())


EXPORT

Example:

export: [TextDirective, PopupComponent, BrowserModule]

What can we inject here? components, directives, modules or pipes that we would like to have access to them in another module (after importing this module)

How do I extract data from JSON with PHP?

You can use json_decode() to convert a json string to a PHP object/array.

Eg.

Input:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

Output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Few Points to remember:

  • json_decode requires the string to be a valid json else it will return NULL.
  • In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.
  • Make sure you pass in utf8 content, or json_decode may error out and just return a NULL value.

Java Date cut off time information

For timestamps:

timestamp -= timestamp % (24 * 60 * 60 * 1000)

Convert Python ElementTree to string

Non-Latin Answer Extension

Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.

Input

xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???")  # Read Note about Python 2

NOTE: In Python 2, when calling the toString(...) code, assigning xml with ElementTree.Element("Person", Name="???")will raise an error...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)

Output

ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="&#53356;&#47532;&#49828;" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />


ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" />             <-------- Python 3
# Python 3 (John): <Person Name="John" />

# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'

# Python 2 (???): <Person Name="???" />             <-------- Python 2
# Python 2 (John): <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 3 (John): <Person Name="John" />

# Python 2 (???): <Person Name="&#53356;&#47532;&#49828;" />
# Python 2 (John): <Person Name="John" />

What's the difference between echo, print, and print_r in PHP?

they both are language constructs. echo returns void and print returns 1. echo is considered slightly faster than print.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

FormsModule should be added at imports array not declarations array.

  • imports array is for importing modules such as BrowserModule, FormsModule, HttpModule
  • declarations array is for your Components, Pipes, Directives

refer below change:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})