Programs & Examples On #Alpha transparency

The alpha transparency of an image defines how transparent the pixels of this image are. Typically, each pixel has an alpha value between 0 (fully transparent) and 255 (fully opaque).

Set transparent background using ImageMagick and commandline prompt

I had the same problem. In which i have to remove white background from jpg/png image format using ImageMagick.

What worked for me was:

1) Convert image format to png: convert input.jpg input.png

2) convert input.png -fuzz 2% -transparent white output.png

Replace transparency in PNG images with white background

Welp it looks like my decision to install "graphics magick" over "image magick" has some rough edges - when I reinstall genuine crufty old "image magick", then the above command works perfectly well.

edit, a long time later — One of these days I'll check to see if "graphics magick" has fixed this issue.

Adding elements to object

Adding new key/pair elements into the original object:

const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }

Object.entries(add).forEach(([key,value]) => { obj[key] = value })

obj new value:

{a: 1, b: 2, c: 3, d: 4, e: ["x", "y", "z"] }

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I ran into this problem too when I copied some text from the Internet. My solution is to trim the text/remove formatting before doing any further processing.

Delete files in subfolder using batch script

I had to complete the same task and I used a "for" loop and a "del" command as follows:

@ECHO OFF

set dir=%cd%

FOR /d /r %dir% %%x in (archive\) do (
    if exist "%%x" del %%x\*.txt /f /q
)

You can set the dir variable with any start directory you want or used the current directory (%cd%) variable.

These are the options for "for" command:

  • /d For directories
  • /r For recursive

These are the options for "del" command:

  • /f Force deletes read-only files
  • /q Quiet mode; suppresses prompts for delete confirmations.

OpenCV Python rotate image by X degrees around specific point

Quick tweak to @alex-rodrigues answer... deals with shape including the number of channels.

import cv2
import numpy as np

def rotateImage(image, angle):
    center=tuple(np.array(image.shape[0:2])/2)
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
    return cv2.warpAffine(image, rot_mat, image.shape[0:2],flags=cv2.INTER_LINEAR)

MySQL Like multiple values

Don't forget to use parenthesis if you use this function after an AND parameter

Like this:

WHERE id=123 and(interests LIKE '%sports%' OR interests LIKE '%pub%')

MS Excel showing the formula in a cell instead of the resulting value

Try this if the above solution aren't working, worked for me

Cut the whole contents in the worksheet using "Ctrl + A" followed by "Ctrl + X" and paste it to a new sheet. Your reference to formulas will remain intact when you cut paste.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

AsyncTask<CognitoCachingCredentialsProvider, Integer, Void> task = new 
AsyncTask<CognitoCachingCredentialsProvider, Integer, Void>() {

@Override
protected Void doInBackground(CognitoCachingCredentialsProvider... params) {
    AWSSessionCredentials creds = credentialsProvider.getCredentials();
    String id = credentialsProvider.getCachedIdentityId();
    credentialsProvider.refresh();
    Log.d("wooohoo", String.format("id=%s, token=%s", id, creds.getSessionToken()));
    return null;
    }
};

task.execute(credentialsProvider);

Check Answer Key 2018

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Get the last three chars from any string - Java

You can use a substring

String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);

Redirect to a page/URL after alert button is pressed

<head>
<script>
    function myFunction() {
        var x;
        var r = confirm("Do you want to clear data?");
        if (r == true) {
            x = "Your Data is Cleared";
            window.location.href = "firstpage.php";
        }
        else {
            x = "You pressed Cancel!";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>

<p id="demo"></p>
</body>
</html>

This will redirect to new php page.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

What does %>% mean in R

The infix operator %>% is not part of base R, but is in fact defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).

It works like a pipe, hence the reference to Magritte's famous painting The Treachery of Images.

What the function does is to pass the left hand side of the operator to the first argument of the right hand side of the operator. In the following example, the data frame iris gets passed to head():

library(magrittr)
iris %>% head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Thus, iris %>% head() is equivalent to head(iris).

Often, %>% is called multiple times to "chain" functions together, which accomplishes the same result as nesting. For example in the chain below, iris is passed to head(), then the result of that is passed to summary().

iris %>% head() %>% summary()

Thus iris %>% head() %>% summary() is equivalent to summary(head(iris)). Some people prefer chaining to nesting because the functions applied can be read from left to right rather than from inside out.

Declare a variable as Decimal

You can't declare a variable as Decimal - you have to use Variant (you can use CDec to populate it with a Decimal type though).

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

when you do UNIQUE as a table level constraint as you have done then what your defining is a bit like a composite primary key see ddl constraints, here is an extract

"This specifies that the *combination* of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique."

this means that either field could possibly have a non unique value provided the combination is unique and this does not match your foreign key constraint.

most likely you want the constraint to be at column level. so rather then define them as table level constraints, 'append' UNIQUE to the end of the column definition like name VARCHAR(60) NOT NULL UNIQUE or specify indivdual table level constraints for each field.

Code not running in IE 11, works fine in Chrome

If this is happening in Angular 2+ application, you can just uncomment string polyfills in polyfills.ts:

import 'core-js/es6/string';

How do I concatenate strings with variables in PowerShell?

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name

How to do an array of hashmaps?

What gives? It works. Just ignore it:

@SuppressWarnings("unchecked")

No, you cannot parameterize it. I'd however rather use a List<Map<K, V>> instead.

List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();

To learn more about collections and maps, have a look at this tutorial.

Exception from HRESULT: 0x800A03EC Error

Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". This problem occurs if you are using an older version of excel file (.xls) instead of .xlsx. The older version does not allow more than 65k rows in the excel sheet.

Once you have saved as .xslx, try executing your code again.

edit ----

Looking more into your problem, it seems that the problem might be locale specific. Does the code work on another machine? What value does the cell have? Is it datetime format? Have a look here:

http://support.microsoft.com/kb/320369

http://blogs.msdn.com/b/eric_carter/archive/2005/06/15/429515.aspx

Python: Adding element to list while iterating

Alternate solution :

reduce(lambda x,newObj : x +[newObj] if somecond else x,myarr,myarr)

Add leading zeroes to number in Java?

Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.

Populate dropdown select with array using jQuery

The array declaration has incorrect syntax. Try the following, instead:

var numbers = [ 1, 2, 3, 4, 5]

The loop part seems right

$.each(numbers, function(val, text) {
            $('#items').append( $('<option></option>').val(val).html(text) )
            }); // there was also a ) missing here

As @Reigel did seems to add a bit more performance (it is not noticeable on such small arrays)

What does it mean to write to stdout in C?

@K Scott Piel wrote a great answer here, but I want to add one important point.

Note that the stdout stream is usually line-buffered, so to ensure the output is actually printed and not just left sitting in the buffer waiting to be written you must flush the buffer by either ending your printf statement with a \n

Ex:

printf("hello world\n");

or

printf("hello world"); 
printf("\n");

or similar, OR you must call fflush(stdout); after your printf call.

Ex:

printf("hello world"); 
fflush(stdout);

Read more here: Why does printf not flush after the call unless a newline is in the format string?

Testing web application on Mac/Safari when I don't own a Mac

A) Install VirtualBox and download free MacOS High Sierra image

See tutorial here: https://www.wikigain.com/install-macos-high-sierra-virtualbox-windows/

You will get the latest Safari.

You don't need to pay for those online services!!!

Use these vbox settings to increase resolution and memory, but it is still very laggy and slow:

cd "C:\Program Files\Oracle\VirtualBox\"
VBoxManage setextradata "macOS" VBoxInternal2/EfiGraphicsResolution 1920x1080
VBoxManage modifyvm "macOS" --vram 256

B) Alternatively try VMware

which seems to be much faster: youtube.com/watch?v=K7E_UqgCFbQ (video taken down) - use google ( you need VMware + MacOs ISO image)

@edit: It is significantly faster!!!

Create a string of variable length, filled with a repeated character

A great ES6 option would be to padStart an empty string. Like this:

var str = ''.padStart(10, "#");

Note: this won't work in IE (without a polyfill).

Why does Git say my master branch is "already up to date" even though it is not?

I think your basic issue here is that you're misinterpreting and/or misunderstanding what git does and why it does it.

When you clone some other repository, git makes a copy of whatever is "over there". It also takes "their" branch labels, such as master, and makes a copy of that label whose "full name" in your git tree is (normally) remotes/origin/master (but in your case, remotes/upstream/master). Most of the time you get to omit the remotes/ part too, so you can refer to that original copy as upstream/master.

If you now make and commit some change(s) to some file(s), you're the only one with those changes. Meanwhile other people may use the original repository (from which you made your clone) to make other clones and change those clones. They are the only ones with their changes, of course. Eventually though, someone may have changes they send back to the original owner (via "push" or patches or whatever).

The git pull command is mostly just shorthand for git fetch followed by git merge. This is important because it means you need to understand what those two operations actually do.

The git fetch command says to go back to wherever you cloned from (or have otherwise set up as a place to fetch from) and find "new stuff someone else added or changed or removed". Those changes are copied over and applied to your copy of what you got from them earlier. They are not applied to your own work, only to theirs.

The git merge command is more complicated and is where you are going awry. What it does, oversimplified a bit, is compare "what you changed in your copy" to "changes you fetched from someone-else and thus got added to your-copy-of-the-someone-else's-work". If your changes and their changes don't seem to conflict, the merge operation mushes them together and gives you a "merge commit" that ties your development and their development together (though there is a very common "easy" case in which you have no changes and you get a "fast forward").

The situation you're encountering now is one in which you have made changes and committed them—nine times, in fact, hence the "ahead 9"—and they have made no changes. So, fetch dutifully fetches nothing, and then merge takes their lack-of-changes and also does nothing.

What you want is to look at, or maybe even "reset" to, "their" version of the code.

If you merely want to look at it, you can simply check out that version:

git checkout upstream/master

That tells git that you want to move the current directory to the branch whose full name is actually remotes/upstream/master. You'll see their code as of the last time you ran git fetch and got their latest code.

If you want to abandon all your own changes, what you need to do is change git's idea of which revision your label, master, should name. Currently it names your most recent commit. If you get back onto that branch:

git checkout master

then the git reset command will allow you to "move the label", as it were. The only remaining problem (assuming you're really ready to abandon everything you've don) is finding where the label should point.

git log will let you find the numeric names—those things like 7cfcb29—which are permanent (never changing) names, and there are a ridiculous number of other ways to name them, but in this case you just want the name upstream/master.

To move the label, wiping out your own changes (any that you have committed are actually recoverable for quite a while but it's a lot harder after this so be very sure):

git reset --hard upstream/master

The --hard tells git to wipe out what you have been doing, move the current branch label, and then check out the given commit.

It's not super-common to really want to git reset --hard and wipe out a bunch of work. A safer method (making it a lot easier to recover that work if you decide some of it was worthwhile after all) is to rename your existing branch:

git branch -m master bunchofhacks

and then make a new local branch named master that "tracks" (I don't really like this term as I think it confuses people but that's the git term :-) ) the origin (or upstream) master:

git branch -t master upstream/master

which you can then get yourself on with:

git checkout master

What the last three commands do (there's shortcuts to make it just two commands) is to change the name pasted on the existing label, then make a new label, then switch to it:

before doing anything:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "master"

after git branch -m:

C0 -    "remotes/upstream/master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

after git branch -t master upstream/master:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 --- C8 --- C9    "bunchofhacks"

Here C0 is the latest commit (a complete source tree) that you got when you first did your git clone. C1 through C9 are your commits.

Note that if you were to git checkout bunchofhacks and then git reset --hard HEAD^^, this would change the last picture to:

C0 -    "remotes/upstream/master", "master"
    \
     \- C1 --- C2 --- C3 --- C4 --- C5 --- C6 --- C7 -    "bunchofhacks"
                                                      \
                                                       \- C8 --- C9

The reason is that HEAD^^ names the revision two up from the head of the current branch (which just before the reset would be bunchofhacks), and reset --hard then moves the label. Commits C8 and C9 are now mostly invisible (you can use things like the reflog and git fsck to find them but it's no longer trivial). Your labels are yours to move however you like. The fetch command takes care of the ones that start with remotes/. It's conventional to match "yours" with "theirs" (so if they have a remotes/origin/mauve you'd name yours mauve too), but you can type in "theirs" whenever you want to name/see commits you got "from them". (Remember that "one commit" is an entire source tree. You can pick out one specific file from one commit, with git show for instance, if and when you want that.)

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);

Python: How to remove empty lists from a list?

A few options:

filter(lambda x: len(x) > 0, list1)  # Doesn't work with number types
filter(None, list1)  # Filters out int(0)
filter(lambda x: x==0 or x, list1) # Retains int(0)

sample session:

Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [[], [], [], [], [], 'text', 'text2', [], 'moreText']
>>> filter(lambda x: len(x) > 0, list1)
['text', 'text2', 'moreText']
>>> list2 = [[], [], [], [], [], 'text', 'text2', [], 'moreText', 0.5, 1, -1, 0]
>>> filter(lambda x: x==0 or x, list2)
['text', 'text2', 'moreText', 0.5, 1, -1, 0]
>>> filter(None, list2)
['text', 'text2', 'moreText', 0.5, 1, -1]
>>>

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you're recompiling a disassembled APK with APK tool:

Just Set Memory Allocation a little bigger

set switch -Xmx1024mto -Xmx2048m

java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"

you're good to go.. :)

Regular expression for letters, numbers and - _

This is the pattern you are looking for

/^[\w-_.]*$/

What this means:

  • ^ Start of string
  • [...] Match characters inside
  • \w Any word character so 0-9 a-z A-Z
  • -_. Match - and _ and .
  • * Zero or more of pattern or unlimited
  • $ End of string

If you want to limit the amount of characters:

/^[\w-_.]{0,5}$/

{0,5} Means 0-5 characters

How to disable the parent form when a child form is active?

@Melodia

Sorry for this is not C# code but this is what you would want, besides translating this should be easy.

FORM1

Private Sub Form1_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
    Me.Focus()
    Me.Enabled = True
    Form2.Enabled = False
End Sub

Private Sub Form1_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
    Form2.Enabled = True
    Form2.Focus()
End Sub

FORM2

Private Sub Form2_MouseEnter(sender As Object, e As EventArgs) Handles MyBase.MouseEnter
    Me.Focus()
    Me.Enabled = True
    Form1.Enabled = False
End Sub

Private Sub Form2_MouseLeave(sender As Object, e As EventArgs) Handles MyBase.MouseLeave
    Form1.Enabled = True
    Form1.Focus()
End Sub

Hope this helps

JavaScript array to CSV

The following code were written in ES6 and it will work in most of the browsers without an issue.

_x000D_
_x000D_
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
_x000D_
_x000D_

Why do people hate SQL cursors so much?

Cursors make people overly apply a procedural mindset to a set-based environment.

And they are SLOW!!!

From SQLTeam:

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.

Detect merged cells in VBA Excel with MergeArea

While working with selected cells as shown by @tbur can be useful, it's also not the only option available.

You can use Range() like so:

If Worksheets("Sheet1").Range("A1").MergeCells Then
  Do something
Else
  Do something else
End If

Or:

If Worksheets("Sheet1").Range("A1:C1").MergeCells Then
  Do something
Else
  Do something else
End If

Alternately, you can use Cells():

If Worksheets("Sheet1").Cells(1, 1).MergeCells Then
  Do something
Else
  Do something else
End If

What's the u prefix in a Python string?

My guess is that it indicates "Unicode", is it correct?

Yes.

If so, since when is it available?

Python 2.x.

In Python 3.x the strings use Unicode by default and there's no need for the u prefix. Note: in Python 3.0-3.2, the u is a syntax error. In Python 3.3+ it's legal again to make it easier to write 2/3 compatible apps.

jQuery load more data on scroll

You question specifically is about loading data when a div falls into view, and not when the user reaches the end of the page.

Here's the best answer to your question: https://stackoverflow.com/a/33979503/3024226

How can I convert a date to GMT?

[Update]

Matt Johnsons answer is much better than this one was.

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

https://stackoverflow.com/a/26454317/334274

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way

1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"

password was also updated successfully.

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

Add space between <li> elements

#access a {
    border-bottom: 2px solid #fff;
    color: #eee;
    display: block;
    line-height: 3.333em;
    padding: 0 10px 0 20px;
    text-decoration: none;
}

I see that you had used line-height but you gave it to <a> tag instead of <ul> Try this:

#access ul {line-height:3.333em;}

You wouldn't need to play with margins then.

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:

The buffer size. The algorithm you basically have is

  • copy from disk to buffer
  • copy from buffer to disk

My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.

Don't perform java benchmarks that read and write to the same disk.

If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.

Don't use a buffer if you don't need to.

Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.

Like other have said, use FileChannel.transferTo() or FileChannel.transferFrom(). The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.

The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:

Use production data and environments

Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.

My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.

What are you running on? It matters.

Examples of GoF Design Patterns in Java's core libraries

Even though I'm sort of a broken clock with this one, Java XML API uses Factory a lot. I mean just look at this:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
String title = XPathFactory.newInstance().newXPath().evaluate("//title", doc);

...and so on and so forth.

Additionally various Buffers (StringBuffer, ByteBuffer, StringBuilder) use Builder.

How does "make" app know default target to build if no target is specified?

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

Determine if map contains a value for a key?

If you want to determine whether a key is there in map or not, you can use the find() or count() member function of map. The find function which is used here in example returns the iterator to element or map::end otherwise. In case of count the count returns 1 if found, else it returns zero(or otherwise).

if(phone.count(key))
{ //key found
}
else
{//key not found
}

for(int i=0;i<v.size();i++){
    phoneMap::iterator itr=phone.find(v[i]);//I have used a vector in this example to check through map you cal receive a value using at() e.g: map.at(key);
    if(itr!=phone.end())
        cout<<v[i]<<"="<<itr->second<<endl;
    else
        cout<<"Not found"<<endl;
}

Loop Through Each HTML Table Column and Get the Data using jQuery

You can try with textContent.

var productId = val[key].textContent;

How to correctly link php-fpm and Nginx Docker containers?

As previous answers have solved for, but should be stated very explicitly: the php code needs to live in the php-fpm container, while the static files need to live in the nginx container. For simplicity, most people have just attached all the code to both, as I have also done below. If the future, I will likely separate out these different parts of the code in my own projects as to minimize which containers have access to which parts.

Updated my example files below with this latest revelation (thank you @alkaline )

This seems to be the minimum setup for docker 2.0 forward (because things got a lot easier in docker 2.0)

docker-compose.yml:

version: '2'
services:
  php:
    container_name: test-php
    image: php:fpm
    volumes:
      - ./code:/var/www/html/site
  nginx:
    container_name: test-nginx
    image: nginx:latest
    volumes:
      - ./code:/var/www/html/site
      - ./site.conf:/etc/nginx/conf.d/site.conf:ro
    ports:
      - 80:80

(UPDATED the docker-compose.yml above: For sites that have css, javascript, static files, etc, you will need those files accessible to the nginx container. While still having all the php code accessible to the fpm container. Again, because my base code is a messy mix of css, js, and php, this example just attaches all the code to both containers)

In the same folder:

site.conf:

server
{
    listen   80;
    server_name site.local.[YOUR URL].com;

    root /var/www/html/site;
    index index.php;

    location /
    {
        try_files $uri =404;
    }

    location ~ \.php$ {
        fastcgi_pass   test-php:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

In folder code:

./code/index.php:

<?php
phpinfo();

and don't forget to update your hosts file:

127.0.0.1 site.local.[YOUR URL].com

and run your docker-compose up

$docker-compose up -d

and try the URL from your favorite browser

site.local.[YOUR URL].com/index.php

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

This is how I implemented it with map. It should run in O(n) time and should kinda be easy to gasp.

_x000D_
_x000D_
    var first_array=[1,1,2,3,4,4,5,6];_x000D_
    var find_dup=new Map;_x000D_
_x000D_
    for (const iterator of first_array) {_x000D_
            // if present value++_x000D_
            if(find_dup.has(iterator)){ _x000D_
                find_dup.set(iterator,find_dup.get(iterator)+1); _x000D_
            }else{_x000D_
            // else add it_x000D_
                find_dup.set(iterator,1);_x000D_
            }_x000D_
        }_x000D_
    console.log(find_dup.get(2));
_x000D_
_x000D_
_x000D_

Then you can find_dup.get(key) to find if it has duplicates (it should give > 1).

Promise.all().then() resolve?

But that doesn't seem like the proper way to do it..

That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("First handler", data);_x000D_
    return data.map(entry => entry * 10);_x000D_
  })_x000D_
  .then(data => {_x000D_
    console.log("Second handler", data);_x000D_
  });
_x000D_
_x000D_
_x000D_

(catch handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)

The output we see from that is:

First handler [1,2]
Second handler [10,20]

...because the first handler gets the resolution of the two promises (1 and 2) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.

If the additional work you're doing is synchronous, you can also put it in the first handler:

Example:

_x000D_
_x000D_
const promises = [_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
  new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
  .then(data => {_x000D_
    console.log("Initial data", data);_x000D_
    data = data.map(entry => entry * 10);_x000D_
    console.log("Updated data", data);_x000D_
    return data;_x000D_
  });
_x000D_
_x000D_
_x000D_

...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.

Expression must be a modifiable lvalue

In C, you will also experience the same error if you declare a:

char array[size];

and than try to assign a value without specifying an index position:

array = '\0'; 

By doing:

array[index] = '0\';

You're specifying the accessible/modifiable address previously declared.

MySQL "incorrect string value" error when save unicode string in Django

I had the same problem and resolved it by changing the character set of the column. Even though your database has a default character set of utf-8 I think it's possible for database columns to have a different character set in MySQL. Here's the SQL QUERY I used:

    ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
    CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

How do I set proxy for chrome in python webdriver?

For people out there asking how to setup proxy server in chrome which needs authentication should follow these steps.

  1. Create a proxy.py file in your project, use this code and call proxy_chrome from
    proxy.py everytime you need it. You need to pass parameters like proxy server, port and username password for authentication.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

I know this is an old thread but what solved the issue for me was adding the following to my build.gradle files. As already stated above there is a compatibility issue with mockito-all

Possibly useful post:

testCompile ('junit:junit:4.12') {
    exclude group: 'org.hamcrest'
}
testCompile ('org.mockito:mockito-core:1.10.19') {
    exclude group: 'org.hamcrest'
}
testCompile 'org.hamcrest:hamcrest-core:1.3'

Difference between number and integer datatype in oracle dictionary views

Integer is only there for the sql standard ie deprecated by Oracle.

You should use Number instead.

Integers get stored as Number anyway by Oracle behind the scenes.

Most commonly when ints are stored for IDs and such they are defined with no params - so in theory you could look at the scale and precision columns of the metadata views to see of no decimal values can be stored - however 99% of the time this will not help.

As was commented above you could look for number(38,0) columns or similar (ie columns with no decimal points allowed) but this will only tell you which columns cannot take decimals, and not what columns were defined so that INTS can be stored.

Suggestion: do a data profile on the number columns. Something like this:

 select max( case when trunc(column_name,0)=column_name then 0 else 1 end ) as has_dec_vals
 from table_name

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

How many times a substring occurs

You can count the frequency using two ways:

  1. Using the count() in str:

    a.count(b)

  2. Or, you can use:

    len(a.split(b))-1

Where a is the string and b is the substring whose frequency is to be calculated.

What's the best way to get the current URL in Spring MVC?

in jsp file:

request.getAttribute("javax.servlet.forward.request_uri")

How to get length of a string using strlen function

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()

{
    char str[80];

    int i;

    cout<<"\n enter string:";

    cin.getline(str,80);

    int n=strlen(str);

    cout<<"\n lenght is:"<<n;

    getch();

    return 0;

}

This is the program if you want to use strlen . Hope this helps!

Return outside function error in Python

You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

Download file from an ASP.NET Web API method using AngularJS

Send your file as a base64 string.

 var element = angular.element('<a/>');
                         element.attr({
                             href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
                             target: '_blank',
                             download: fname
                         })[0].click();

If attr method not working in Firefox You can also use javaScript setAttribute method

What is the maximum length of data I can put in a BLOB column in MySQL?

May or may not be accurate, but according to this site: http://www.htmlite.com/mysql003.php.

BLOB A string with a maximum length of 65535 characters.

The MySQL manual says:

The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers

I think the first site gets their answers from interpreting the MySQL manual, per http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

Subset of rows containing NA (missing) values in a chosen column of a data frame

new_data <- data %>% filter_all(any_vars(is.na(.))) 

This should create a new data frame (new_data) with only the missing values in it.

Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).

How to check existence of user-define table type in SQL Server 2008?

You can look in sys.types or use TYPE_ID:

IF TYPE_ID(N'MyType') IS NULL ...

Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

If you use tostring you lose information on both shape and data type:

>>> import numpy as np
>>> a = np.arange(12).reshape(3, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> s = a.tostring()
>>> aa = np.fromstring(a)
>>> aa
array([  0.00000000e+000,   4.94065646e-324,   9.88131292e-324,
         1.48219694e-323,   1.97626258e-323,   2.47032823e-323,
         2.96439388e-323,   3.45845952e-323,   3.95252517e-323,
         4.44659081e-323,   4.94065646e-323,   5.43472210e-323])
>>> aa = np.fromstring(a, dtype=int)
>>> aa
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> aa = np.fromstring(a, dtype=int).reshape(3, 4)
>>> aa
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

This means you have to send the metadata along with the data to the recipient. To exchange auto-consistent objects, try cPickle:

>>> import cPickle
>>> s = cPickle.dumps(a)
>>> cPickle.loads(s)
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

How to align iframe always in the center

First remove position:absolute of div#iframe-wrapper iframe, Remove position:fixed and all other css from div#iframe-wrapper

Then apply this css,

div#iframe-wrapper {
  width: 200px;
  height: 400px;
  margin: 0 auto;
}

FIDDLE DEMO

./configure : /bin/sh^M : bad interpreter

Looks like you have a dos line ending file. The clue is the ^M.

You need to re-save the file using Unix line endings.

You might have a dos2unix command line utility that will also do this for you.

How to get row data by clicking a button in a row in an ASP.NET gridview

            <asp:Button  ID="btnEdit" Text="Edit" runat="server"  OnClick="btnEdit_Click" CssClass="CoolButtons"/>


protected void btnEdit_Click(object sender, EventArgs e)
{
       Button btnEdit = (Button)sender;
       GridViewRow Grow = (GridViewRow)btnEdit.NamingContainer;
      TextBox txtledName = (TextBox)Grow.FindControl("txtAccountName");
      HyperLink HplnkDr = (HyperLink)Grow.FindControl("HplnkDr");
      TextBox txtnarration = (TextBox)Grow.FindControl("txtnarration");
     //Get the gridview Row Details
}

And Same As for Delete button

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

A simple solution is

UUID.randomUUID().toString().replace("-", "")

(Like the existing solutions, only that it avoids the String#replaceAll call. Regular expression replacement is not required here, so String#replace feels more natural, though technically it still is implemented with regular expressions. Given that the generation of the UUID is more costly than the replacement, there should not be a significant difference in runtime.)

Using the UUID class is probably fast enough for most scenarios, though I would expect that some specialized hand-written variant, which does not need the postprocessing, to be faster. Anyway, the bottleneck of the overall computation will normally be the random number generator. In case of the UUID class, it uses SecureRandom.

Which random number generator to use is also a trade-off that depends on the application. If it is security-sensitive, SecureRandom is, in general, the recommendation. Otherwise, ThreadLocalRandom is an alternative (faster than SecureRandom or the old Random, but not cryptographically secure).

How to get the current time as datetime

You can get from Dateformatter

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

In Visual Studio: Properties -> Advanced -> Entry Point -> write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

jQuery hyperlinks - href value?

Add return false to the end of your click handler, this prevents the browser default handler occurring which attempts to redirect the page:

$('a').click(function() {
// do stuff
return false;
});

How do I display a wordpress page content?

Page content can be displayed easily and perfectly this way:

<?php if(have_posts()) : ?>
    <?php while(have_posts())  : the_post(); ?>
      <h2><?php the_title(); ?></h2>                        
      <?php the_content(); ?>          
      <?php comments_template( '', true ); ?> 
    <?php endwhile; ?>                   
      <?php else : ?>                       
        <h3><?php _e('404 Error&#58; Not Found'); ?></h3>
<?php endif; ?>         

Note:

In terms of displaying content - i) comments_template() function is an optional use if you need to enable commenting with different functionality.

ii) _e() function is also optional but more meaningful & effective than just showing text through <p>. while preferred stylized 404.php can be created to be redirected.

Correct set of dependencies for using Jackson mapper

The package names in Jackson 2.x got changed to com.fasterxml1 from org.codehaus2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.

Creating a simple login form

<html>
<head>
<meta charset="utf-8">
<title>Best Login Page design in html and css</title>
<style type="text/css">
body {
background-color: #f4f4f4;
color: #5a5656;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
font-size: 16px;
line-height: 1.5em;
}
a { text-decoration: none; }
h1 { font-size: 1em; }
h1, p {
margin-bottom: 10px;
}
strong {
font-weight: bold;
}
.uppercase { text-transform: uppercase; }

/* ---------- LOGIN ---------- */
#login {
margin: 50px auto;
width: 300px;
}
form fieldset input[type="text"], input[type="password"] {
background-color: #e5e5e5;
border: none;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: #5a5656;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
font-size: 14px;
height: 50px;
outline: none;
padding: 0px 10px;
width: 280px;
-webkit-appearance:none;
}
form fieldset input[type="submit"] {
background-color: #008dde;
border: none;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
color: #f4f4f4;
cursor: pointer;
font-family: 'Open Sans', Arial, Helvetica, sans-serif;
height: 50px;
text-transform: uppercase;
width: 300px;
-webkit-appearance:none;
}
form fieldset a {
color: #5a5656;
font-size: 10px;
}
form fieldset a:hover { text-decoration: underline; }
.btn-round {
background-color: #5a5656;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
color: #f4f4f4;
display: block;
font-size: 12px;
height: 50px;
line-height: 50px;
margin: 30px 125px;
text-align: center;
text-transform: uppercase;
width: 50px;
}
.facebook-before {
background-color: #0064ab;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
color: #f4f4f4;
display: block;
float: left;
height: 50px;
line-height: 50px;
text-align: center;
width: 50px;
}
.facebook {
background-color: #0079ce;
border: none;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
color: #f4f4f4;
cursor: pointer;
height: 50px;
text-transform: uppercase;
width: 250px;
}
.twitter-before {
background-color: #189bcb;
border-radius: 3px 0px 0px 3px;
-moz-border-radius: 3px 0px 0px 3px;
-webkit-border-radius: 3px 0px 0px 3px;
color: #f4f4f4;
display: block;
float: left;
height: 50px;
line-height: 50px;
text-align: center;
width: 50px;
}
.twitter {
background-color: #1bb2e9;
border: none;
border-radius: 0px 3px 3px 0px;
-moz-border-radius: 0px 3px 3px 0px;
-webkit-border-radius: 0px 3px 3px 0px;
color: #f4f4f4;
cursor: pointer;
height: 50px;
text-transform: uppercase;
width: 250px;
}
</style>
</head>
<body>
<div id="login">
<h1><strong>Welcome.</strong> Please login.</h1>
<form action="javascript:void(0);" method="get">
<fieldset>
<p><input type="text" required value="Username" onBlur="if(this.value=='')this.value='Username'" onFocus="if(this.value=='Username')this.value='' "></p>
<p><input type="password" required value="Password" onBlur="if(this.value=='')this.value='Password'" onFocus="if(this.value=='Password')this.value='' "></p>
<p><a href="#">Forgot Password?</a></p>
<p><input type="submit" value="Login"></p>
</fieldset>
</form>
<p><span class="btn-round">or</span></p>
<p>
<a class="facebook-before"></a>
<button class="facebook">Login Using Facbook</button>
</p>
<p>
<a class="twitter-before"></a>
<button class="twitter">Login Using Twitter</button>
</p>
</div> <!-- end login -->
</body>
</html>

Start thread with member function

Since you are using C++11, lambda-expression is a nice&clean solution.

class blub {
    void test() {}
  public:
    std::thread spawn() {
      return std::thread( [this] { this->test(); } );
    }
};

since this-> can be omitted, it could be shorten to:

std::thread( [this] { test(); } )

or just (deprecated)

std::thread( [=] { test(); } )

How can jQuery deferred be used?

You can also integrate it with any 3rd-party libraries which makes use of JQuery.

One such library is Backbone, which is actually going to support Deferred in their next version.

PHP memcached Fatal error: Class 'Memcache' not found

The right is php_memcache.dll. In my case i was using lib compiled with vc9 instead of vc6 compiler. In apatche error logs i got something like:

PHP Startup: sqlanywhere: Unable to initialize module Module compiled with build ID=API20090626, TS,VC9 PHP compiled with build ID=API20090626, TS,VC6 These options need to match

Check if you have same log and try downloading different dll that are compiled with different compiler.

Correct way to pause a Python program

It Seems fine to me (or raw_input() in Python 2.X). Alternatively, you could use time.sleep() if you want to pause for a certain number of seconds.

import time
print("something")
time.sleep(5.5)    # Pause 5.5 seconds
print("something")

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

Because I hate repeating complex logic, here's a generic version of Slauma's solution.

Here's my update method. Note that in a detached scenario, sometimes your code will read data and then update it, so it's not always detached.

public async Task UpdateAsync(TempOrder order)
{
    order.CheckNotNull(nameof(order));
    order.OrderId.CheckNotNull(nameof(order.OrderId));

    order.DateModified = _dateService.UtcNow;

    if (_context.Entry(order).State == EntityState.Modified)
    {
        await _context.SaveChangesAsync().ConfigureAwait(false);
    }
    else // Detached.
    {
        var existing = await SelectAsync(order.OrderId!.Value).ConfigureAwait(false);
        if (existing != null)
        {
            order.DateModified = _dateService.UtcNow;
            _context.TrackChildChanges(order.Products, existing.Products, (a, b) => a.OrderProductId == b.OrderProductId);
            await _context.SaveChangesAsync(order, existing).ConfigureAwait(false);
        }
    }
}

CheckNotNull is defined here.

Create these extension methods.

/// <summary>
/// Tracks changes on childs models by comparing with latest database state.
/// </summary>
/// <typeparam name="T">The type of model to track.</typeparam>
/// <param name="context">The database context tracking changes.</param>
/// <param name="childs">The childs to update, detached from the context.</param>
/// <param name="existingChilds">The latest existing data, attached to the context.</param>
/// <param name="match">A function to match models by their primary key(s).</param>
public static void TrackChildChanges<T>(this DbContext context, IList<T> childs, IList<T> existingChilds, Func<T, T, bool> match)
    where T : class
{
    context.CheckNotNull(nameof(context));
    childs.CheckNotNull(nameof(childs));
    existingChilds.CheckNotNull(nameof(existingChilds));

    // Delete childs.
    foreach (var existing in existingChilds.ToList())
    {
        if (!childs.Any(c => match(c, existing)))
        {
            existingChilds.Remove(existing);
        }
    }

    // Update and Insert childs.
    var existingChildsCopy = existingChilds.ToList();
    foreach (var item in childs.ToList())
    {
        var existing = existingChildsCopy
            .Where(c => match(c, item))
            .SingleOrDefault();

        if (existing != null)
        {
            // Update child.
            context.Entry(existing).CurrentValues.SetValues(item);
        }
        else
        {
            // Insert child.
            existingChilds.Add(item);
            // context.Entry(item).State = EntityState.Added;
        }
    }
}

/// <summary>
/// Saves changes to a detached model by comparing it with the latest data.
/// </summary>
/// <typeparam name="T">The type of model to save.</typeparam>
/// <param name="context">The database context tracking changes.</param>
/// <param name="model">The model object to save.</param>
/// <param name="existing">The latest model data.</param>
public static void SaveChanges<T>(this DbContext context, T model, T existing)
    where T : class
{
    context.CheckNotNull(nameof(context));
    model.CheckNotNull(nameof(context));

    context.Entry(existing).CurrentValues.SetValues(model);
    context.SaveChanges();
}

/// <summary>
/// Saves changes to a detached model by comparing it with the latest data.
/// </summary>
/// <typeparam name="T">The type of model to save.</typeparam>
/// <param name="context">The database context tracking changes.</param>
/// <param name="model">The model object to save.</param>
/// <param name="existing">The latest model data.</param>
/// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
/// <returns></returns>
public static async Task SaveChangesAsync<T>(this DbContext context, T model, T existing, CancellationToken cancellationToken = default)
    where T : class
{
    context.CheckNotNull(nameof(context));
    model.CheckNotNull(nameof(context));

    context.Entry(existing).CurrentValues.SetValues(model);
    await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}

How to use OUTPUT parameter in Stored Procedure

You need to define the output parameter as an output parameter in the code with the ParameterDirection.Output enumeration. There are numerous examples of this out there, but here's one on MSDN.

Convert UTC datetime string to local datetime

See the datetime documentation on tzinfo objects. You have to implement the timezones you want to support yourself. The are examples at the bottom of the documentation.

Here's a simple example:

from datetime import datetime,tzinfo,timedelta

class Zone(tzinfo):
    def __init__(self,offset,isdst,name):
        self.offset = offset
        self.isdst = isdst
        self.name = name
    def utcoffset(self, dt):
        return timedelta(hours=self.offset) + self.dst(dt)
    def dst(self, dt):
            return timedelta(hours=1) if self.isdst else timedelta(0)
    def tzname(self,dt):
         return self.name

GMT = Zone(0,False,'GMT')
EST = Zone(-5,False,'EST')

print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(GMT).strftime('%m/%d/%Y %H:%M:%S %Z')
print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z')

t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S')
t = t.replace(tzinfo=GMT)
print t
print t.astimezone(EST)

Output

01/22/2011 21:52:09 
01/22/2011 21:52:09 GMT
01/22/2011 16:52:09 EST
2011-01-21 02:37:21+00:00
2011-01-20 21:37:21-05:00a

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Lombok is not generating getter and setter

In mac os lombok will not be able to find eclipse location. please click on specify location and go to the eclipse installed folder you can find the eclipse.ini file select that

enter image description here

How to Apply global font to whole HTML document

You should never use * + !important. What if you want to change font in some parts your HTML document? You should always use body without important. Use !important only if there is no other option.

How to implement linear interpolation?

Instead of extrapolating off the ends, you could return the extents of the y_list. Most of the time your application is well behaved, and the Interpolate[x] will be in the x_list. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.

  • Returning a non-linear result (bounded by the contents of x_list and y_list) your program's behavior may alert you to an issue for values greatly outside x_list. (Linear behavior goes bananas when given non-linear inputs!)

  • Returning the extents of the y_list for Interpolate[x] outside of x_list also means you know the range of your output value. If you extrapolate based on x much, much less than x_list[0] or x much, much greater than x_list[-1], your return result could be outside of the range of values you expected.

    def __getitem__(self, x):
        if x <= self.x_list[0]:
            return self.y_list[0]
        elif x >= self.x_list[-1]:
            return self.y_list[-1]
        else:
            i = bisect_left(self.x_list, x) - 1
            return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
    

Calculating sum of repeated elements in AngularJS ng-repeat

here is my solution to this problem:

<td>Total: {{ calculateTotal() }}</td>

script

$scope.calculateVAT = function () {
    return $scope.cart.products.reduce((accumulator, currentValue) => accumulator + (currentValue.price * currentValue.quantity), 0);
};

reduce will execute for each product in products array. Accumulator is the total accumulated amount, currentValue is the current element of the array and the 0 in the last is the initial value

Integer ASCII value to character in BASH using printf

For capital letters:

i=67
letters=({A..Z})
echo "${letters[$i-65]}"

Output:

C

Regular Expression for alphanumeric and underscores

To check the entire string and not allow empty strings, try

^[A-Za-z0-9_]+$

Trying to start a service on boot on Android

note that at the beginning of the question, there is a typo mistake:

<action android:name="android.intent.action._BOOT_COMPLETED"/>

instead of :

<action android:name="android.intent.action.BOOT_COMPLETED"/>

one small "_" and all this trouble :)

Extract Data from PDF and Add to Worksheet

Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext.

Pseudocode to extract the text would include:

  1. Using SHELL VBA statement to extract the text from PDF to a temporary file using XPDF
  2. Using sequential file read statements to read the temporary file contents into a string
  3. Pasting the string into Excel

Simplified example below:

    Sub ReadIntoExcel(PDFName As String)
        'Convert PDF to text
        Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"

        'Read in the text file and write to Excel
        Dim TextLine as String
        Dim RowNumber as Integer
        Dim F1 as Integer
        RowNumber = 1
        F1 = Freefile()
        Open "tempfile.txt" for Input as #F1
            While Not EOF(#F1)
                Line Input #F1, TextLine
                ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
                RowNumber = RowNumber + 1
            Wend
        Close #F1
    End Sub

What is the significance of #pragma marks? Why do we need #pragma marks?

In simple word we can say that #pragma mark - is used for categorizing methods, so you can find your methods easily. It is very useful for long projects.

oracle.jdbc.driver.OracleDriver ClassNotFoundException

In Eclipse , rightclick on your application

Run As -> Run configurations -> select your server from type filter text box

Then in Classpath under Bootstrap Entries add your classes12.jar File and Click on Apply.
Now, run the file...... This worked for me !!

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

Replacing all non-alphanumeric characters with empty strings

return value.replaceAll("[^A-Za-z0-9 ]", "");

This will leave spaces intact. I assume that's what you want. Otherwise, remove the space from the regex.

LINQ - Full Outer Join

I've written this extensions class for an app perhaps 6 years ago, and have been using it ever since in many solutions without issues. Hope it helps.

edit: I noticed some might not know how to use an extension class.

To use this extension class, just reference its namespace in your class by adding the following line using joinext;

^ this should allow you to to see the intellisense of extension functions on any IEnumerable object collection you happen to use.

Hope this helps. Let me know if it's still not clear, and I'll hopefully write a sample example on how to use it.

Now here is the class:

namespace joinext
{    
public static class JoinExtensions
    {
        public static IEnumerable<TResult> FullOuterJoin<TOuter, TInner, TKey, TResult>(
            this IEnumerable<TOuter> outer,
            IEnumerable<TInner> inner,
            Func<TOuter, TKey> outerKeySelector,
            Func<TInner, TKey> innerKeySelector,
            Func<TOuter, TInner, TResult> resultSelector)
            where TInner : class
            where TOuter : class
        {
            var innerLookup = inner.ToLookup(innerKeySelector);
            var outerLookup = outer.ToLookup(outerKeySelector);

            var innerJoinItems = inner
                .Where(innerItem => !outerLookup.Contains(innerKeySelector(innerItem)))
                .Select(innerItem => resultSelector(null, innerItem));

            return outer
                .SelectMany(outerItem =>
                {
                    var innerItems = innerLookup[outerKeySelector(outerItem)];

                    return innerItems.Any() ? innerItems : new TInner[] { null };
                }, resultSelector)
                .Concat(innerJoinItems);
        }


        public static IEnumerable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
            this IEnumerable<TOuter> outer,
            IEnumerable<TInner> inner,
            Func<TOuter, TKey> outerKeySelector,
            Func<TInner, TKey> innerKeySelector,
            Func<TOuter, TInner, TResult> resultSelector)
        {
            return outer.GroupJoin(
                inner,
                outerKeySelector,
                innerKeySelector,
                (o, i) =>
                    new { o = o, i = i.DefaultIfEmpty() })
                    .SelectMany(m => m.i.Select(inn =>
                        resultSelector(m.o, inn)
                        ));

        }



        public static IEnumerable<TResult> RightJoin<TOuter, TInner, TKey, TResult>(
            this IEnumerable<TOuter> outer,
            IEnumerable<TInner> inner,
            Func<TOuter, TKey> outerKeySelector,
            Func<TInner, TKey> innerKeySelector,
            Func<TOuter, TInner, TResult> resultSelector)
        {
            return inner.GroupJoin(
                outer,
                innerKeySelector,
                outerKeySelector,
                (i, o) =>
                    new { i = i, o = o.DefaultIfEmpty() })
                    .SelectMany(m => m.o.Select(outt =>
                        resultSelector(outt, m.i)
                        ));

        }

    }
}

How does database indexing work?

Simple Description!

The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.

Example: We have a database table called User with three columns – Name, Age and Address. Assume that the User table has thousands of rows.

Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:

SELECT * FROM User 
WHERE Name = 'John'

The database software would literally have to look at every single row in the User table to see if the Name for that row is ‘John’. This will take a long time.

This is where index helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.

How to create an index:

CREATE INDEX name_index
ON User (Name)

An index consists of column values(Eg: John) from one table, and those values are stored in a data structure.

So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!

Removing carriage return and new-line from the end of a string in c#

String temp = s.Replace("\r\n","").Trim();

s being the original string. (Note capitals)

Upload folder with subfolders using S3 and the AWS console

You don't need Enhanced Uploader (which I believe is not exists anymore) or any third party software (that is always got risk that someone will steal your private data or access keys from S3 bucket or even from all AWS resources).

Since the new AWS S3 Web Upload manager supports drag'n'drop for files and folders, just login to https://console.aws.amazon.com/s3/home and start uploading process as usual, then just drag folder from your desktop directly to S3 page.

Can't get Python to import from a different folder

import user

u=user.User() #error on this line

Because of the lack of __init__ mentioned above, you would expect an ImportError which would make the problem clearer.

You don't get one because 'user' is also an existing module in the standard library. Your import statement grabs that one and tries to find the User class inside it; that doesn't exist and only then do you get the error.

It is generally a good idea to make your import absolute:

import Server.Models.user

to avoid this kind of ambiguity. Indeed from Python 2.7 'import user' won't look relative to the current module at all.

If you really want relative imports, you can have them explicitly in Python 2.5 and up using the somewhat ugly syntax:

from .user import User

How can I set focus on an element in an HTML form using JavaScript?

Do this.

If your element is something like this..

<input type="text" id="mytext"/>

Your script would be

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>

Explanation of the UML arrows

The accepted answer being said, It is missing some explanations. For example, what is the difference between a uni-directional and a bi-directional association? In the provided example, both do exist. ( Both '5's in the arrows)

If looking for a more complete answer and have more time, here is a thorough explanation.

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

mysql_config not found when installing mysqldb python interface

I think, following lines can be executed on terminal

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

This mysql_config directory is for zend server on MacOSx. You can do it for linux like following lines

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

This is default linux mysql directory.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

One risk of using the keyboard shortcut is that it requires using a non-ASCII encoding. That might be fine, but if your source is loaded by different editors in different locales, you might hit trouble somewhere along the line.

It might be safer to use either &#8217; or &rsquo; (which are equivalent) as both are ASCII.

Java: Reading a file into an array

You should be able to use forward slashes in Java to refer to file locations.

The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.

Toolkit's use of BufferedReader is probably what you need.

Turn a number into star rating display using jQuery and CSS

If you only have to support modern browsers, you can get away with:

  • No images;
  • Mostly static css;
  • Nearly no jQuery or Javascript;

You only need to convert the number to a class, e.g. class='stars-score-50'.

First a demo of "rendered" markup:

_x000D_
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
Within block level elements:_x000D_
_x000D_
<div><span class="stars-container stars-0">?????</span></div>_x000D_
<div><span class="stars-container stars-10">?????</span></div>_x000D_
<div><span class="stars-container stars-20">?????</span></div>_x000D_
<div><span class="stars-container stars-30">?????</span></div>_x000D_
<div><span class="stars-container stars-40">?????</span></div>_x000D_
<div><span class="stars-container stars-50">?????</span></div>_x000D_
<div><span class="stars-container stars-60">?????</span></div>_x000D_
<div><span class="stars-container stars-70">?????</span></div>_x000D_
<div><span class="stars-container stars-80">?????</span></div>_x000D_
<div><span class="stars-container stars-90">?????</span></div>_x000D_
<div><span class="stars-container stars-100">?????</span></div>_x000D_
_x000D_
<p>Or use it in a sentence: <span class="stars-container stars-70">?????</span> (cool, huh?).</p>
_x000D_
_x000D_
_x000D_

Then a demo that uses a wee bit of code:

_x000D_
_x000D_
$(function() {_x000D_
  function addScore(score, $domElement) {_x000D_
    $("<span class='stars-container'>")_x000D_
      .addClass("stars-" + score.toString())_x000D_
      .text("?????")_x000D_
      .appendTo($domElement);_x000D_
  }_x000D_
_x000D_
  addScore(70, $("#fixture"));_x000D_
});
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  content: '?????';_x000D_
  color: gold;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Generated: <div id="fixture"></div>
_x000D_
_x000D_
_x000D_

The biggest downsides of this solution are:

  1. You need the stars inside the element to generate correct width;
  2. There's no semantic markup, e.g. you'd prefer the score as text inside the element;
  3. It only allows for as many scores as you'll have classes (because we can't use Javascript to set a precise width on a pseudo-element).

To fix this the solution above can be easily tweaked. The :before and :after bits need to become actual elements in the DOM (so we need some JS for that).

The latter is left as an excercise for the reader.

List supported SSL/TLS versions for a specific OpenSSL build

It's clumsy, but you can get this from the usage messages for s_client or s_server, which are #ifed at compile time to match the supported protocol versions. Use something like

 openssl s_client -help 2>&1 | awk '/-ssl[0-9]|-tls[0-9]/{print $1}' 
 # in older releases any unknown -option will work; in 1.1.0 must be exactly -help

How do I clear the dropdownlist values on button click event using jQuery?

A shorter alternative to the first solution given by Russ Cam would be:

$('#mySelect').val('');

This assumes you want to retain the list, but make it so that no option is selected.

If you wish to select a particular default value, just pass that value instead of an empty string.

$('#mySelect').val('someDefaultValue');

or to do it by the index of the option, you could do:

$('#mySelect option:eq(0)').attr('selected','selected'); // Select first option

How to use bootstrap datepicker

man you can use the basic Bootstrap Datepicker this way:

<!DOCTYPE html>
<head runat="server">
<title>Test Zone</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="Css/datepicker.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../Js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#pickyDate').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

and inside body:

<body>
<div id="testDIV">
    <div class="container">
        <div class="hero-unit">
            <input  type="text" placeholder="click to show datepicker"  id="pickyDate"/>
        </div>
    </div>
</div>

datepicker.css and bootstrap-datepicker.js you can download from here on the Download button below "About" on the left side. Hope this help someone, greetings.

How to change the value of attribute in appSettings section with Web.config transformation

I do not like transformations to have any more info than needed. So instead of restating the keys, I simply state the condition and intention. It is much easier to see the intention when done like this, at least IMO. Also, I try and put all the xdt attributes first to indicate to the reader, these are transformations and not new things being defined.

<appSettings>
  <add xdt:Locator="Condition(@key='developmentModeUserId')" xdt:Transform="Remove" />
  <add xdt:Locator="Condition(@key='developmentMode')" xdt:Transform="SetAttributes"
       value="false"/>
</appSettings>

In the above it is much easier to see that the first one is removing the element. The 2nd one is setting attributes. It will set/replace any attributes you define here. In this case it will simply set value to false.

How to use if statements in underscore.js templates?

You can try _.isUndefined

<% if (!_.isUndefined(date)) { %><span class="date"><%= date %></span><% } %>

Making an image act like a button

You could implement a JavaScript block which contains a function with your needs.

<div style="position: absolute; left: 10px; top: 40px;"> 
    <img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>

Reflection: How to Invoke Method with parameters

I'am posting this answer because many visitors enter here from google for this problem.


string result = this.GetType().GetMethod("Print").Invoke(this, new object[]{"firstParam", 157, "third_Parammmm" } );

when external .dll -instead of this.GetType(), you might use typeof(YourClass).

SQL Query for Student mark functionality

You just have to partition the problem into some bite-sized steps and solve each one by one

First, get the maximum score in each subject:

select SubjectID, max(MarkRate)
from Mark
group by SubjectID;

Then query who are those that has SubjectID with max MarkRate:

select SubjectID, MarkRate, StudentID
from Mark
where (SubjectID,MarkRate)
in
  (
  select SubjectID, max(MarkRate)
  from Mark
  group by SubjectID
  )
order by SubjectID, StudentID;

Then obtain the Student's name, instead of displaying just the StudentID:

select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)
where (SubjectID,MarkRate)
in
  (
  select SubjectID, max(MarkRate)
  from Mark
  group by SubjectID
  )
order by SubjectName, StudentName

Database vendors' artificial differences aside with regards to joining and correlating results, the basic step is the same; first, partition the problem in a bite-sized parts, and then integrate them as you solved each one of them, so it won't be as confusing.


Sample data:

CREATE TABLE Student
    (StudentID int, StudentName varchar(6), Details varchar(1));    
INSERT INTO Student
    (StudentID, StudentName, Details)
VALUES
    (1, 'John', 'X'),
    (2, 'Paul', 'X'),
    (3, 'George', 'X'),
    (4, 'Paul', 'X');

CREATE TABLE Subject
    (SubjectID varchar(1), SubjectName varchar(7));    
INSERT INTO Subject
    (SubjectID, SubjectName)
VALUES
    ('M', 'Math'),
    ('E', 'English'),
    ('H', 'History');

CREATE TABLE Mark
    (StudentID int, SubjectID varchar(1), MarkRate int);    
INSERT INTO Mark
    (StudentID, SubjectID, MarkRate)
VALUES
    (1, 'M', 90),
    (1, 'E', 100),
    (2, 'M', 95),
    (2, 'E', 70),
    (3, 'E', 95),
    (3, 'H', 98),
    (4, 'H', 90),
    (4, 'E', 100);

Live test here: http://www.sqlfiddle.com/#!1/08728/3


IN tuple test is still a join by any other name:

Convert this..

select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)

where (SubjectID,MarkRate)
in
  (
  select SubjectID, max(MarkRate)
  from Mark
  group by SubjectID
  )

order by SubjectName, StudentName

..to JOIN:

select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)

join
  (
  select SubjectID, max(MarkRate) as MarkRate
  from Mark
  group by SubjectID
  ) as x using(SubjectID,MarkRate)

order by SubjectName, StudentName

Contrast this code with the code immediate it. See how JOIN on independent query look like an IN construct? They almost look the same, and IN was just replaced with JOIN keyword; and the replaced IN keyword with JOIN is in fact longer, you need to alias the independent query's column result(max(MarkRate) AS MarkRate) and also the subquery itself (as x). Anyway, this are just matter of style, I prefer IN clause, as the intent is clearer. Using JOINs merely to reflect the data relationship.

Anyway, here's the query that works on all databases that doesn't support tuple test(IN):

select sb.SubjectName, m.MarkRate, st.StudentName
from Mark as m
join Student as st on st.StudentID = m.StudentID
join Subject as sb on sb.SubjectID = m.SubjectID

join
  (
  select SubjectID, max(MarkRate) as MaxMarkRate
  from Mark
  group by SubjectID
  ) as x on m.SubjectID = x.SubjectID AND m.MarkRate = x.MaxMarkRate

order by sb.SubjectName, st.StudentName

Live test: http://www.sqlfiddle.com/#!1/08728/4

Split List into Sublists with LINQ

This is an old question but this is what I ended up with; it enumerates the enumerable only once, but does create lists for each of the partitions. It doesn't suffer from unexpected behavior when ToArray() is called as some of the implementations do:

    public static IEnumerable<IEnumerable<T>> Partition<T>(IEnumerable<T> source, int chunkSize)
    {
        if (source == null)
        {
            throw new ArgumentNullException("source");
        }

        if (chunkSize < 1)
        {
            throw new ArgumentException("Invalid chunkSize: " + chunkSize);
        }

        using (IEnumerator<T> sourceEnumerator = source.GetEnumerator())
        {
            IList<T> currentChunk = new List<T>();
            while (sourceEnumerator.MoveNext())
            {
                currentChunk.Add(sourceEnumerator.Current);
                if (currentChunk.Count == chunkSize)
                {
                    yield return currentChunk;
                    currentChunk = new List<T>();
                }
            }

            if (currentChunk.Any())
            {
                yield return currentChunk;
            }
        }
    }

Clean out Eclipse workspace metadata

There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.

Your best bet is to optimize the re-import, where I would like to point out the following:

  • When creating a new workspace, you can already choose to have some settings being copied from the current to the new workspace.
  • You can export the preferences of the current workspace (using the Export menu) and re-import them in the new workspace.
  • There are lots of recommendations on the Internet to just copy the ${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)
  • You may want to consider using more project specific settings than workspace preferences in the future. So for instance all the Java compiler settings can either be set on the workspace level or on the project level. If set on the project level, you can put them under version control and are independent of the workspace.

How to export datagridview to excel using vb.net?

The following code works fine for me :)

Protected Sub ExportToExcel(sender As Object, e As EventArgs) Handles ExportExcel.Click
        Try
            Response.Clear()
            Response.Buffer = True
            Response.AddHeader("content-disposition", "attachment;filename=ExportEthias.xls")
            Response.Charset = ""
            Response.ContentType = "application/vnd.ms-excel"
            Using sw As New StringWriter()
                Dim hw As New HtmlTextWriter(sw)
                GvActifs.RenderControl(hw)
                'Le format de base est le texte pour éviter les problèmes d'arrondis des nombres
                Dim style As String = "<style> .textmode { } </style>"
                Response.Write(Style)
                Response.Output.Write(sw.ToString())
                Response.Flush()
                Response.End()
            End Using
        Catch ex As Exception
            lblMessage.Text = "Erreur export Excel : " & ex.Message
        End Try
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        ' Verifies that the control is rendered
    End Sub

Hopes this help you.

How to find row number of a value in R code

I would be tempted to use grepl, which should give all the lines with matches and can be generalised for arbitrary strings.

mydata_2 <- read.table(textConnection("
sex age height_seca1 height_chad1 height_DL weight_alog1
1 F 19 1800 1797 180 70.0
2 F 19 1682 1670 167 69.0
3 F 21 1765 1765 178 80.0
4 F 21 1829 1833 181 74.0
5 F 21 1706 1705 170 103.0
6 F 18 1607 1606 160 76.0
7 F 19 1578 1576 156 50.0
8 F 19 1577 1575 156 61.0
9 F 21 1666 1665 166 52.0
10 F 17 1710 1716 172 65.0
11 F 28 1616 1619 161 65.5
12 F 22 1648 1644 165 57.5
13 F 19 1569 1570 155 55.0
14 F 19 1779 1777 177 55.0
15 M 18 1773 1772 179 70.0
16 M 18 1816 1809 181 81.0
17 M 19 1766 1765 178 77.0
18 M 19 1745 1741 174 76.0
19 M 18 1716 1714 170 71.0
20 M 21 1785 1783 179 64.0
21 M 19 1850 1854 185 71.0
22 M 31 1875 1880 188 95.0
23 M 26 1877 1877 186 105.5
24 M 19 1836 1837 185 100.0
25 M 18 1825 1823 182 85.0
26 M 19 1755 1754 174 79.0
27 M 26 1658 1658 165 69.0
28 M 20 1816 1818 183 84.0
29 M 18 1755 1755 175 67.0"),
                       sep = " ", header = TRUE)

which(grepl(1578, mydata_2$height_seca1))

The output is:

> which(grepl(1578, mydata_2$height_seca1))
[1] 7
> 

[Edit] However, as pointed out in the comments, this will capture much more than the string 1578 (e.g. it also matches for 21578 etc) and thus should be used only if you are certain that you the length of the values you are searching will not be larger than the four characters or digits shown here.

And subsetting as per the other answer also works fine:

mydata_2[mydata_2$height_seca1 == 1578, ]
  sex age height_seca1 height_chad1 height_DL weight_alog1
7   F  19         1578         1576       156           50
> 

If you're looking for several different values, you could put them in a vector and then use the %in% operator:

look.for <- c(1578, 1658, 1616)
> mydata_2[mydata_2$height_seca1 %in% look.for, ]
   sex age height_seca1 height_chad1 height_DL weight_alog1
7    F  19         1578         1576       156         50.0
11   F  28         1616         1619       161         65.5
27   M  26         1658         1658       165         69.0
> 

What is __gxx_personality_v0 for?

A quick grep of the libstd++ code base revealed the following two usages of __gx_personality_v0:

In libsupc++/unwind-cxx.h

// GNU C++ personality routine, Version 0.                                      
extern "C" _Unwind_Reason_Code __gxx_personality_v0
     (int, _Unwind_Action, _Unwind_Exception_Class,
      struct _Unwind_Exception *, struct _Unwind_Context *);

In libsupc++/eh_personality.cc

#define PERSONALITY_FUNCTION    __gxx_personality_v0
extern "C" _Unwind_Reason_Code
PERSONALITY_FUNCTION (int version,
                      _Unwind_Action actions,
                      _Unwind_Exception_Class exception_class,
                      struct _Unwind_Exception *ue_header,
                      struct _Unwind_Context *context)
{
  // ... code to handle exceptions and stuff ...
}

(Note: it's actually a little more complicated than that; there's some conditional compilation that can change some details).

So, as long as your code isn't actually using exception handling, defining the symbol as void* won't affect anything, but as soon as it does, you're going to crash - __gxx_personality_v0 is a function, not some global object, so trying to call the function is going to jump to address 0 and cause a segfault.

Getting distance between two points based on latitude/longitude

You can use Uber's H3,point_dist() function to compute the spherical distance between two (lat, lng) points. We can set return unit ('km', 'm', or 'rads'). The default unit is Km.

Example :

import H3

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
distance = h3.point_dist(coords_1,coords_2) #278.4584889328128

Hope this will usefull!

Why fragments, and when to use fragments instead of activities?

Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entry in the Dev Guide, consider reading it for details.

In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.

Retrieve data from website in android app

You can do the HTML parsing but it is not at all recommended instead ask the website owners to provide web services then you can parse that information.

Getting last day of the month in a given string date

Works fine for me with this

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone());
    cal.set(Calendar.MONTH, month-1);  
    cal.set(Calendar.YEAR, year);  
    cal.add(Calendar.DATE, -1);  
    cal.set(Calendar.DAY_OF_MONTH, 
    cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTimeInMillis();

How do you create a read-only user in PostgreSQL?

Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer):

$ sudo -upostgres psql postgres
postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE';
postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run:

$ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf
$ sudo service postgresql reload

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

How to detect the end of loading of UITableView

Using private API:

@objc func tableViewDidFinishReload(_ tableView: UITableView) {
    print(#function)
    cellsAreLoaded = true
}

Using public API:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // cancel the perform request if there is another section
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];

    // create a perform request to call the didLoadRows method on the next event loop.
    [self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];

    return [self.myDataSource numberOfRowsInSection:section];
}

// called after the rows in the last section is loaded
-(void)tableViewDidLoadRows:(UITableView*)tableView{
    self.cellsAreLoaded = YES;
}

A possible better design is to add the visible cells to a set, then when you need to check if the table is loaded you can instead do a for loop around this set, e.g.

var visibleCells = Set<UITableViewCell>()

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.insert(cell)
}

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.remove(cell)
}

// example property you want to show on a cell that you only want to update the cell after the table is loaded. cellForRow also calls configure too for the initial state.
var count = 5 {
    didSet {
        for cell in visibleCells {
            configureCell(cell)
        }
    }
}

Equivalent of LIMIT for DB2

@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:

select * from (
    select * from (
        select * from MYLIB.MYTABLE
        order by MYID asc 
        fetch first {last} rows only 
        ) I 
    order by MYID desc
    fetch first {length} rows only
    ) II
order by MYID asc

where {last} should be replaced with row number of the last record I need and {length} should be replaced with the number of rows I need, calculated as last row - first row + 1.

E.g. if I want rows from 10 to 25 (totally 16 rows), {last} will be 25 and {length} will be 25-10+1=16.

MS Access VBA: Sending an email through Outlook

Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.

Public Function SendEmail2()

Dim varName As Variant          
Dim varCC As Variant            
Dim varSubject As Variant      
Dim varBody As Variant          

varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','

varSubject = "Hello"
'Email subject

varBody = "Let's get ice cream this week"

'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File

End Function

Regular expression search replace in Sublime Text 2

Important: Use the ( ) parentheses in your search string

While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( ) parentheses, otherwise these matched segments won't be accessible to defined variables such as $1, $2 or \1, \2 etc.

For example we want to replace 'em' with 'px' but preserve the digit values:

    margin: 10em;  /* Expected: margin: 10px */
    margin: 2em;   /* Expected: margin: 2px */
  • Replacement string: margin: $1px or margin: \1px
  • Search string (CORRECT): margin: ([0-9]*)em // with parentheses
  • Search string (INCORRECT): margin: [0-9]*em

CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em search string (with parentheses). Enclose the desired matched segment (e.g. $1 or \1) by ( ) parentheses as following:

  • Find: margin: ([0-9]*)em (with parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: 10px;
    margin: 2px;

INCORRECT CASE EXAMPLE: Using margin: [0-9]*em search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1 or \1:

  • Find: margin: [0-9]*em (without parentheses)
  • Replace to: margin: $1px or margin: \1px
  • Result:
    margin: px; /* `$1` is undefined */
    margin: px; /* `$1` is undefined */

Adding a y-axis label to secondary y-axis in matplotlib

For everyone stumbling upon this post because pandas gets mentioned, you now have the very elegant and straighforward option of directly accessing the secondary_y axis in pandas with ax.right_ax

So paraphrasing the example initially posted, you would write:

table = sql.read_frame(query,connection)

ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.set_ylabel('$')
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')

(this is already mentioned in these posts as well: 1 2)

IPhone/IPad: How to get screen width programmatically?

As of iOS 9.0 there's no way to get the orientation reliably. This is the code I used for an app I design for only portrait mode, so if the app is opened in landscape mode it will still be accurate:

screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
    float tempHeight = screenWidth;
    screenWidth = screenHeight;
    screenHeight = tempHeight;
}

How to add leading zeros for for-loop in shell?

Just a note: I have experienced different behaviours on different versions of bash:

  • version 3.1.17(1)-release-(x86_64-suse-linux) and
  • Version 4.1.17(9)-release (x86_64-unknown-cygwin))

for the former (3.1) for nn in (00..99) ; do ... works but for nn in (000..999) ; do ... does not work both will work on version 4.1 ; haven't tested printf behaviour (bash --version gave the version info)

Cheers, Jan

Setting a width and height on an A tag

You can also use display: inline-block. The advantage of this is that it will set the height and width like a block element but also set it inline so that you can have another a tag sitting right next to it, permitting the parent space.

You can find out more about display properties here

Replace Div Content onclick

EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.


Here is an example of how it could work:

Working jsFiddle Demo

HTML:

<div id="someDiv">
    Once upon a midnight dreary
    <br>While I pondered weak and weary
    <br>Over many a quaint and curious
    <br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />

<input type="hidden" id="vault" />

javascript/jQuery:

//Declare persistent vars outside function
var savText, newText, myState = 0;

$('#mybutt').click(function(){
    if (myState==0){
        savText = $('#someDiv').html(); //save poem data from DIV
        newText = $('#replacementtext').val(); //save data from input field
        $('#replacementtext').val(''); //clear input field
        $('#someDiv').html( newText ); //replace poem with insert field data
        myState = 1; //remember swap has been done once
    } else {
        $('#someDiv').html(savText);
        $('#replacementtext').val(newText); //replace contents
        myState = 0;
    }
});

How to make java delay for a few seconds?

As per java documentation definition of Thread.sleep is :

Thread.sleep(t);
where t => time in millisecons to sleep

If you want to sleep for 1 second you should have :

Thread.sleep(1000);

Process with an ID #### is not running in visual studio professional 2013 update 3

The following steps fix the problem for Visual Studio 2015 and Visual Studio 2017:

  • Close VS.
  • Navigate to the folder of the solution and delete the hidden .vs folder.
  • Restart VS.
  • Hit F5 and IIS Express should load as normal, allowing you to debug.

Note: Based on my experience and others in the comments, this problem seems to be caused by moving a project between workstations, environments, or versions of Visual Studio. There must be some environment specific information contained in the .vs folder.

Creating a Custom Event

Declare the class containing the event:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        OnEvent();
    }

    private void OnEvent() {
        if (MyEvent != null) {
            MyEvent(this, EventArgs.Empty);
        }
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

Angular 2: import external js file into component

For .js files that expose more than one variable (unlike drawGauge), a better solution would be to set the Typescript compiler to process .js files.

In your tsconfig.json, set allowJs option to true:

"compilerOptions": {
     ...
    "allowJs": true,
     ...
}

Otherwise, you'll have to declare each and every variable in either your component.ts or d.ts.

Mailto links do nothing in Chrome but work in Firefox?

Another solution is to implement your own custom popup/form/user control that will be universally interpreted across all browsers.

Granted this will not leverage the "mailto" out of the box capabilities. It all depends on what availability adherence you are working against. Unfortunately for myself - the mailto needed to be available to everyone by default without "inconveniencing the client".

Your decision ultimately.

Xcode stuck on Indexing

Faced this recently on XCode 7.3.1 - for me, I noticed RAM usage going to 100% on to CleanMyMac3. The problem magically fixed itself after I restarted my machine. In all fairness however, I'd already gone ahead and tried the accepted-answer, so you'll want to do the same before you restart just in case :-)

CSS opacity only to background color, not the text on it?

The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
#block {_x000D_
  background: #CCC;_x000D_
  filter: alpha(opacity=60);_x000D_
  /* IE */_x000D_
  -moz-opacity: 0.6;_x000D_
  /* Mozilla */_x000D_
  opacity: 0.6;_x000D_
  /* CSS3 */_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="block"></div>_x000D_
  <div id="text">Test</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adding text to a cell in Excel using VBA

You need to use Range and Value functions.
Range would be the cell where you want the text you want
Value would be the text that you want in that Cell

Range("A1").Value="whatever text"

How can I render a list select box (dropdown) with bootstrap?

Another option is to make the Bootstrap dropdown behave like a select using jQuery...

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});

http://www.bootply.com/b4NKREUPkN

How do I right align div elements?

I know this is an old post but couldn't you just use <div id=xyz align="right"> for right.

You can just replace right with left, center and justify.

Worked on my site:)

openCV video saving in python

As @????? ????????? said: the sizes of Writer have to match with the frame from the camera or files.

You can use such code to check if your camera is (640, 480) or not:

print(int(cap.get(3)), int(cap.get(4)))

For myself, I found my camera is (1280, 720) and replaced (640, 480) with (1280, 720). Then it can save videos.

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

Kotlin:

var list=ArrayList<Your class name>()
val listresult: Array<YOUR CLASS NAME> = Gson().fromJson(
                YOUR JSON RESPONSE IN STRING,
                Array<Your class name>:: class.java)

list.addAll(listresult)

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

How do I convert strings between uppercase and lowercase in Java?

Yes. There are methods on the String itself for this.

Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.

break out of if and foreach

For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.

<?php

for ($i=0; $i < 100; $i++) { 
    if (i%2 == 0) {
        include(do_this_for_even.php);
    }
    else {
        include(do_this_for_odd.php);
    }
}

?>

If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here

Select a date from date picker using Selenium webdriver

There is an argument for keeping it simple and stupid if the date picker comes from a simple html5 input and the goal is to test whatever events were added to the test. Consider for example:

<input type=date name=mydate /> 

and one wants to set a test where 'mydate' is hardcoded to 02/22/2017, a solution with python is to use the following code, which is simple enough to debug to observe what it does:

def setdate(elem_name, date_str):
    elem = driver.find_element_by_name('mydate')
    elem.click()
    elem.send_keys(Keys.ARROW_LEFT)
    elem.send_keys(Keys.ARROW_LEFT)
    elem.send_keys(date_str)

setdate('mydate'', '02222017')

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

Recommended SQL database design for tags or tagging

I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.

Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.

Escaping single quote in PHP when inserting into MySQL

You have a couple of things fighting in your strings.

  • lack of correct MySQL quoting (mysql_real_escape_string())
  • potential automatic 'magic quote' -- check your gpc_magic_quotes setting
  • embedded string variables, which means you have to know how PHP correctly finds variables

It's also possible that the single-quoted value is not present in the parameters to the first query. Your example is a proper name, after all, and only the second query seems to be dealing with names.

Where is web.xml in Eclipse Dynamic Web Project

If you don't see the web.xml file in WEB-INF folder,

enter image description here

- Select Deployment Descriptor and right click on it.
- Then select the Generate Deployment Descriptor Stub

enter image description here

Finally you get web.xml file.

enter image description here

Get Value of Row in Datatable c#

Dont use a foreach then. Use a 'for loop'. Your code is a bit messed up but you could do something like...

for (Int32 i = 0; i < dt_pattern.Rows.Count; i++)
{
    double yATmax = ToDouble(dt_pattern.Rows[i+1]["Ampl"].ToString()) + AT;
}

Note you would have to take into account during the last row there will be no 'i+1' so you will have to use an if statement to catch that.

Why use pointers?

Let me try and answer this too.

Pointers are similar to references. In other words, they're not copies, but rather a way to refer to the original value.

Before anything else, one place where you will typically have to use pointers a lot is when you're dealing with embedded hardware. Maybe you need to toggle the state of a digital IO pin. Maybe you're processing an interrupt and need to store a value at a specific location. You get the picture. However, if you're not dealing with hardware directly and are just wondering about which types to use, read on.

Why use pointers as opposed to normal variables? The answer becomes clearer when you're dealing with complex types, like classes, structures and arrays. If you were to use a normal variable, you might end up making a copy (compilers are smart enough to prevent this in some situations and C++11 helps too, but we'll stay away from that discussion for now).

Now what happens if you want to modify the original value? You could use something like this:

MyType a; //let's ignore what MyType actually is right now.
a = modify(a); 

That will work just fine and if you don't know exactly why you're using pointers, you shouldn't use them. Beware of the "they're probably faster" reason. Run your own tests and if they actually are faster, then use them.

However, let's say you're solving a problem where you need to allocate memory. When you allocate memory, you need to deallocate it. The memory allocation may or may not be successful. This is where pointers come in useful - they allow you to test for the existence of the object you've allocated and they allow you to access the object the memory was allocated for by de-referencing the pointer.

MyType *p = NULL; //empty pointer
if(p)
{
    //we never reach here, because the pointer points to nothing
}
//now, let's allocate some memory
p = new MyType[50000];
if(p) //if the memory was allocated, this test will pass
{
    //we can do something with our allocated array
    for(size_t i=0; i!=50000; i++)
    {
        MyType &v = *(p+i); //get a reference to the ith object
        //do something with it
        //...
    }
    delete[] p; //we're done. de-allocate the memory
}

This is the key to why you would use pointers - references assume the element you're referencing exists already. A pointer does not.

The other reason why you would use pointers (or at least end up having to deal with them) is because they're a data type that existed before references. Therefore, if you end up using libraries to do the things that you know they're better at, you will find that a lot of these libraries use pointers all over the place, simply because of how long they've been around (a lot of them were written before C++).

If you didn't use any libraries, you could design your code in such a way that you could stay away from pointers, but given that pointers are one of the basic types of the language, the faster you get comfortable using them, the more portable your C++ skills would be.

From a maintainability point of view, I should also mention that when you do use pointers, you either have to test for their validity and handle the case when they're not valid, or, just assume they are valid and accept the fact that your program will crash or worse WHEN that assumption is broken. Put another way, your choice with pointers is to either introduce code complexity or more maintenance effort when something breaks and you're trying to track down a bug that belongs to a whole class of errors that pointers introduce, like memory corruption.

So if you control all of your code, stay away from pointers and instead use references, keeping them const when you can. This will force you to think about the life times of your objects and will end up keeping your code easier to understand.

Just remember this difference: A reference is essentially a valid pointer. A pointer is not always valid.

So am I saying that its impossible to create an invalid reference? No. Its totally possible, because C++ lets you do almost anything. It's just harder to do unintentionally and you will be amazed at how many bugs are unintentional :)

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

how to completely clear localstorage

localStorage.clear();

how to completely clear sessionstorage

sessionStorage.clear();

[...] Cookies ?

var cookies = document.cookie;

for (var i = 0; i < cookies.split(";").length; ++i)
{
    var myCookie = cookies[i];
    var pos = myCookie.indexOf("=");
    var name = pos > -1 ? myCookie.substr(0, pos) : myCookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

is there any way to get the value back after clear these ?

No, there isn't. But you shouldn't rely on this if this is related to a security question.

Determine Whether Integer Is Between Two Other Integers?

Your operator is incorrect. Should be if number >= 10000 and number <= 30000:. Additionally, Python has a shorthand for this sort of thing, if 10000 <= number <= 30000:.

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

What is the use of hashCode in Java?

One of the uses of hashCode() is building a Catching mechanism. Look at this example:

        class Point
    {
      public int x, y;

      public Point(int x, int y)
      {
        this.x = x;
        this.y = y;
      }

      @Override
      public boolean equals(Object o)
      {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Point point = (Point) o;

        if (x != point.x) return false;
        return y == point.y;
      }

      @Override
      public int hashCode()
      {
        int result = x;
        result = 31 * result + y;
        return result;
      }

class Line
{
  public Point start, end;

  public Line(Point start, Point end)
  {
    this.start = start;
    this.end = end;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Line line = (Line) o;

    if (!start.equals(line.start)) return false;
    return end.equals(line.end);
  }

  @Override
  public int hashCode()
  {
    int result = start.hashCode();
    result = 31 * result + end.hashCode();
    return result;
  }
}
class LineToPointAdapter implements Iterable<Point>
{
  private static int count = 0;
  private static Map<Integer, List<Point>> cache = new HashMap<>();
  private int hash;

  public LineToPointAdapter(Line line)
  {
    hash = line.hashCode();
    if (cache.get(hash) != null) return; // we already have it

    System.out.println(
      String.format("%d: Generating points for line [%d,%d]-[%d,%d] (no caching)",
        ++count, line.start.x, line.start.y, line.end.x, line.end.y));
}

Two values from one input in python?

Two inputs separated by space:

x,y=input().split()

How can I open a website in my web browser using Python?

Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")

Selecting text in an element (akin to highlighting with your mouse)

I was searching for the same thing, my solution was this:

$('#el-id').focus().select();

Get generic type of class at runtime

To complete some of the answers here, I had to get the ParametrizedType of MyGenericClass, no matter how high is the hierarchy, with the help of recursion:

private Class<T> getGenericTypeClass() {
        return (Class<T>) (getParametrizedType(getClass())).getActualTypeArguments()[0];
}

private static ParameterizedType getParametrizedType(Class clazz){
    if(clazz.getSuperclass().equals(MyGenericClass.class)){ // check that we are at the top of the hierarchy
        return (ParameterizedType) clazz.getGenericSuperclass();
    } else {
        return getParametrizedType(clazz.getSuperclass());
    }
}

How can I go back/route-back on vue-router?

Another solution is using vue-router-back-mixin

import BackMixin from `vue-router-back-mixin`

export default {
  ...
  mixins: [BackMixin],
  methods() {
    goBack() {
      this.backMixin_handleBack()
    }
  }
  ...
}

Detecting which UIButton was pressed in a UITableView

How about sending the information like NSIndexPath in the UIButton using runtime injection.

1) You need runtime on the import

2) add static constant

3) add NSIndexPath to your button on runtime using:

(void)setMetaData:(id)target withObject:(id)newObj

4) on button press get metadata using:

(id)metaData:(id)target

Enjoy

    #import <objc/runtime.h>
    static char const * const kMetaDic = "kMetaDic";


    #pragma mark - Getters / Setters

- (id)metaData:(id)target {
    return objc_getAssociatedObject(target, kMetaDic);
}

- (void)setMetaData:(id)target withObject:(id)newObj {
    objc_setAssociatedObject(target, kMetaDic, newObj, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}



    #On the cell constructor
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
    ....
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    ....
    [btnSocial addTarget:self
                                   action:@selector(openComments:)
                         forControlEvents:UIControlEventTouchUpInside];

    #add the indexpath here or another object
    [self setMetaData:btnSocial withObject:indexPath];

    ....
    }



    #The action after button been press:

    - (IBAction)openComments:(UIButton*)sender{

        NSIndexPath *indexPath = [self metaData:sender];
        NSLog(@"indexPath: %d", indexPath.row);

        //Reuse your indexpath Now
    }

Javascript - Get Image height

My preferred solution for this would be to do the resizing server-side, so you are transmitting less unnecessary data.

If you have to do it client-side though, and need to keep the image ratio, you could use the below:

var image_from_ajax = new Image();
image_from_ajax.src = fetch_image_from_ajax(); // Downloaded via ajax call?

image_from_ajax = rescaleImage(image_from_ajax);

// Rescale the given image to a max of max_height and max_width
function rescaleImage(image_name)
{
    var max_height = 100;
    var max_width = 100;

    var height = image_name.height;
    var width = image_name.width;
    var ratio = height/width;

    // If height or width are too large, they need to be scaled down
    // Multiply height and width by the same value to keep ratio constant
    if(height > max_height)
    {
        ratio = max_height / height;
        height = height * ratio;
        width = width * ratio;
    }

    if(width > max_width)
    {
        ratio = max_width / width;
        height = height * ratio;
        width = width * ratio;
    }

    image_name.width = width;
    image_name.height = height;
    return image_name;
}

INSERT SELECT statement in Oracle 11G

Get rid of the values keyword and the parens. You can see an example here.

This is basic INSERT syntax:

INSERT INTO "table_name" ("column1", "column2", ...)
VALUES ("value1", "value2", ...);

This is the INSERT SELECT syntax:

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2";

Making Python loggers output all messages to stdout in addition to log file

You could create two handlers for file and stdout and then create one logger with handlers argument to basicConfig. It could be useful if you have the same log_level and format output for both handlers:

import logging
import sys

file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG, 
    format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
    handlers=handlers
)

logger = logging.getLogger('LOGGER_NAME')

Receive result from DialogFragment

Well its too late may be to answer but here is what i did to get results back from the DialogFragment. very similar to @brandon's answer. Here i am calling DialogFragment from a fragment, just place this code where you are calling your dialog.

FragmentManager fragmentManager = getFragmentManager();
            categoryDialog.setTargetFragment(this,1);
            categoryDialog.show(fragmentManager, "dialog");

where categoryDialog is my DialogFragment which i want to call and after this in your implementation of dialogfragment place this code where you are setting your data in intent. The value of resultCode is 1 you can set it or use system Defined.

            Intent intent = new Intent();
            intent.putExtra("listdata", stringData);
            getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
            getDialog().dismiss();

now its time to get back to to the calling fragment and implement this method. check for data validity or result success if you want with resultCode and requestCode in if condition.

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);        
        //do what ever you want here, and get the result from intent like below
        String myData = data.getStringExtra("listdata");
Toast.makeText(getActivity(),data.getStringExtra("listdata"),Toast.LENGTH_SHORT).show();
    }

Drop shadow for PNG image in CSS

img {
  -webkit-filter: drop-shadow(5px 5px 5px #222222);
  filter: drop-shadow(5px 5px 5px #222222);
}

That worked great for me. One thing to note tho in IE you need the full color (#222222) three characters don't work.

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

How do I change select2 box height

Just add in select2.css

/* Make Select2 boxes match Bootstrap3 as well as Bootstrap4 heights: */
.select2-selection__rendered {
line-height: 32px !important;
}

.select2-selection {
height: 34px !important;
}

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No, see this question which I asked - Upcasting in .NET using generics

The best way is to make a default constructor on the class, construct and then call an Initialise method

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

Problem in running .net framework 4.0 website on iis 7.0

Step 1: Open IIS and click the server name Step 2. Double click “ISAPI and CGI Restrictions” Step 3. Right click ASP.NET v4.0.30319 and select “allow”

After Stopping and Starting the World Wide Web Publishing Service

1.Go to Start > All Programs > Administrative Tools > Services. 2.In the services list, right-click World Wide Web Publishing Service, and then click Stop (to stop the service), Start (to start it after it has been stopped), or Restart (to restart the service when it is running).

Pramesh

How to get the first word in the string

Don't need a regex. string[: string.find(' ')]

Get records with max value for each group of grouped SQL results

axiac's solution is what worked best for me in the end. I had an additional complexity however: a calculated "max value", derived from two columns.

Let's use the same example: I would like the oldest person in each group. If there are people that are equally old, take the tallest person.

I had to perform the left join two times to get this behavior:

SELECT o1.* WHERE
    (SELECT o.*
    FROM `Persons` o
    LEFT JOIN `Persons` b
    ON o.Group = b.Group AND o.Age < b.Age
    WHERE b.Age is NULL) o1
LEFT JOIN
    (SELECT o.*
    FROM `Persons` o
    LEFT JOIN `Persons` b
    ON o.Group = b.Group AND o.Age < b.Age
    WHERE b.Age is NULL) o2
ON o1.Group = o2.Group AND o1.Height < o2.Height 
WHERE o2.Height is NULL;

Hope this helps! I guess there should be better way to do this though...

Loop in react-native

 render() {
    var myloop = [];

    for (let i = 0; i < 10; i++) {
      myloop.push(
        <View key={i}>
        <Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
        </View>
      );
    }

     return (

            <View >
              <Text >Welcome to React Native!</Text>
               {myloop}
            </View>


        );
      }

Output 1 2 3 4 5 6 7 8 9

What's the difference between event.stopPropagation and event.preventDefault?

This is the quote from here

Event.preventDefault

The preventDefault method prevents an event from carrying out its default functionality. For example, you would use preventDefault on an A element to stop clicking that element from leaving the current page:

//clicking the link will *not* allow the user to leave the page 
myChildElement.onclick = function(e) { 
    e.preventDefault(); 
    console.log('brick me!'); 
};

//clicking the parent node will run the following console statement because event propagation occurs
logo.parentNode.onclick = function(e) { 
    console.log('you bricked my child!'); 
};

While the element's default functionality is bricked, the event continues to bubble up the DOM.

Event.stopPropagation

The second method, stopPropagation, allows the event's default functionality to happen but prevents the event from propagating:

//clicking the element will allow the default action to occur but propagation will be stopped...
myChildElement.onclick = function(e) { 
    e.stopPropagation();
    console.log('prop stop! no bubbles!'); 
};

//since propagation was stopped by the child element's onClick, this message will never be seen!
myChildElement.parentNode.onclick = function(e) { 
    console.log('you will never see this message!'); 
};

stopPropagation effectively stops parent elements from knowing about a given event on its child.

While a simple stop method allows us to quickly handle events, it's important to think about what exactly you want to happen with bubbling. I'd bet that all a developer really wants is preventDefault 90% of the time! Incorrectly "stopping" an event could cause you numerous troubles down the line; your plugins may not work and your third party plugins could be bricked. Or worse yet -- your code breaks other functionality on a site.

How to remove \xa0 from string in Python?

try this:

string.replace('\\xa0', ' ')

Content is not allowed in Prolog SAXParserException

This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client. In one of my xsd it was defined as below

<xs:import schemaLocation="" namespace="http://MultiChoice.PaymentService/DataContracts" />

Where the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.

<xs:import schemaLocation="multichoice.paymentservice.DataContracts.xsd" namespace="http://MultiChoice.PaymentService/DataContracts" />

Map with Key as String and Value as List in Groovy

def map = [:]
map["stringKey"] = [1, 2, 3, 4]
map["anotherKey"] = [55, 66, 77]

assert map["anotherKey"] == [55, 66, 77] 

Properties file in python (similar to Java Properties)

if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:

File t.properties:

a=b
c=d
e=f

Python code:

with open("t.properties") as f:
    l = [line.split("=") for line in f.readlines()]
    d = {key.strip(): value.strip() for key, value in l}

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

First of all, you should check bundle id, provision profile and certificate with private key (.p12).

If it doesn't help. Be sure that the Code Signing Entitlements has correct value or remove it at all.

enter image description here

Remove duplicate values from JS array

The simplest way to remove a duplicate is to do a for loop and compare the elements that are not the same and push them into the new array

 var array = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

 var removeDublicate = function(arr){
 var result = []
 var sort_arr = arr.sort() //=> optional
 for (var i = 0; i < arr.length; i++) {
        if(arr[ i + 1] !== arr[i] ){
            result.push(arr[i])
        }
 };
  return result
}  
console.log(removeDublicate(array))
==>  ["Adam", "Carl", "Jenny", "Matt", "Mike", "Nancy"]

Error parsing yaml file: mapping values are not allowed here

I've seen this error in a similar situation to mentioned in Joe's answer:

description: Too high 5xx responses rate: {{ .Value }} > 0.05

We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:

description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'

NameError: global name is not defined

That's How Python works. Try this :

from sqlitedbx import SqliteDBzz

Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc

Cannot call getSupportFragmentManager() from activity

get current activity from parent, then using this code

getActivity().getSupportFragmentManager()

Best Way to Refresh Adapter/ListView on Android

adapter.notifyDataSetChanged();

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

How to add new activity to existing project in Android Studio?

In Android Studio 2, just right click on app and select New > Activity > ... to create desired activity type.

enter image description here

How permission can be checked at runtime without throwing SecurityException?

Check Permissions In KOTLIN (RunTime)

In Manifest: (android.permission.WRITE_EXTERNAL_STORAGE)

    fun checkPermissions(){

      var permission_array=arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
      if((ContextCompat.checkSelfPermission(this,permission_array[0]))==PackageManager.PERMI   SSION_DENIED){
        requestPermissions(permission_array,0)
      }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

          if(requestCode==0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

       //Do Your Operations Here

        ---------->
         //


          }
    }

Hide/Show Action Bar Option Menu Item for different fragments

This will work for sure I guess...

// Declare
Menu menu;
MenuItem menuDoneItem;

// Then in your onCreateOptionMenu() method write the following...
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        this.menu=menu;
        inflater.inflate(R.menu.secutity, menu);
            }

// In your onOptionItemSelected() method write the following...
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.done_item:
                this.menuDoneItem=item;
                someOperation();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

// Now Making invisible any menu item...
public void menuInvisible(){
setHasOptionsMenu(true);// Take part in populating the action bar menu
            menuDoneItem=(MenuItem)menu.findItem(R.id.done_item);
                menuRefresh.setVisible(false); // make true to make the menu item visible.
}

//Use the above method whenever you need to make your menu item visible or invisiable

You can also refer this link for more details, it is a very useful one.