# Programs & Examples On #Wcf encryption

### How to close the current fragment by using Button like the back button?

For those who need to figure out simple way

Try `getActivity().onBackPressed();`

# Examples

Given the string `foobarbarfoo`:

``````bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)
``````

You can also combine them:

``````(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)
``````

# Definitions

#### Look ahead positive `(?=)`

Find expression A where expression B follows:

``````A(?=B)
``````

#### Look ahead negative `(?!)`

Find expression A where expression B does not follow:

``````A(?!B)
``````

#### Look behind positive `(?<=)`

Find expression A where expression B precedes:

``````(?<=B)A
``````

#### Look behind negative `(?<!)`

Find expression A where expression B does not precede:

``````(?<!B)A
``````

#### Atomic groups `(?>)`

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

• `(?>foo|foot)s` applied to `foots` will match its 1st alternative `foo`, then fail as `s` does not immediately follow, and stop as backtracking is disabled

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

• `(foo|foot)s` applied to `foots` will:

1. match its 1st alternative `foo`, then fail as `s` does not immediately follow in `foots`, and backtrack to its 2nd alternative;
2. match its 2nd alternative `foot`, then succeed as `s` immediately follows in `foots`, and stop.

# Online testers

### Using logging in multiple modules

A simple way of using one instance of logging library in multiple modules for me was following solution:

#### base_logger.py

``````import logging

logger = logging
logger.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
``````

#### Other files

``````from base_logger import logger

if __name__ == '__main__':
logger.info("This is an info message")
``````

### PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

``````<?php
mysql_select_db("Database Name", \$con);
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
\$sth = mysql_query("SELECT * FROM chart");

while(\$r = mysql_fetch_assoc(\$sth)) {
\$arr2=array_keys(\$r);
\$arr1=array_values(\$r);

}

for(\$i=0;\$i<count(\$arr1);\$i++)
{
\$chart_array[\$i]=array((string)\$arr2[\$i],intval(\$arr1[\$i]));
}
echo "<pre>";
\$data=json_encode(\$chart_array);
?>

<html>
<script type="text/javascript">

// Load the Visualization API and the piechart package.

// Set a callback to run when the Google Visualization API is loaded.

function drawChart() {

// Create our data table out of JSON data loaded from server.

]);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
chart.draw(data, options);
}
</script>

<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
``````

### Does C have a string type?

In C, a string simply is an array of characters, ending with a null byte. So a `char*` is often pronounced "string", when you're reading C code.

### Code for Greatest Common Divisor in Python

``````def _grateest_common_devisor_euclid(p, q):
if q==0 :
return p
else:
reminder = p%q
return _grateest_common_devisor_euclid(q, reminder)

print(_grateest_common_devisor_euclid(8,3))
``````

### Read lines from a text file but skip the first two lines

``````Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir\$(sFileName)) = 0 Then
MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum

''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr

Do While Not EOF(iFileNum)
Line Input #iFileNum, Fields

MsgBox (Fields)
Loop
``````

### How to match a substring in a string, ignoring case

Try:

``````if haystackstr.lower().find(needlestr.lower()) != -1:
# True
``````

### src absolute path problem

I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.

### How do I find if a string starts with another string in Ruby?

``````puts 'abcdefg'.start_with?('abc')  #=> true
``````

 This is something I didn't know before this question: `start_with` takes multiple arguments.

``````'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
``````

### Finding sum of elements in Swift array

Swift 3

If you have an array of generic objects and you want to sum some object property then:

``````class A: NSObject {
var value = 0
init(value: Int) {
self.value = value
}
}

let array = [A(value: 2), A(value: 4)]
let sum = array.reduce(0, { \$0 + \$1.value })
//                           ^       ^
//                        \$0=result  \$1=next A object
print(sum) // 6
``````

Despite of the shorter form, many times you may prefer the classic for-cycle:

``````let array = [A(value: 2), A(value: 4)]
var sum = 0
array.forEach({ sum += \$0.value})
// or
for element in array {
sum += element.value
}
``````

### Python Accessing Nested JSON Data

Places is a list and not a dictionary. This line below should therefore not work:

``````print data['places']['latitude']
``````

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

``````print data['places'][0]['post code']
``````

### Error:attempt to apply non-function

You're missing `*`s in the last two terms of your expression, so R is interpreting (e.g.) `0.207 (log(DIAM93))^2` as an attempt to call a function named `0.207` ...

For example:

``````> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
``````

Error: attempt to apply non-function

``````censusdata_20\$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2  -
0.0281*(log(DIAM93))^3)
``````

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

### How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

I ran into a problem in the docker node:current-slim (running npm 7.0.9) where `npm install` appeared to ignore `--production`, `--only=prod` and `--only=production`. I found two work-arounds:

1. use ci instead (`RUN npm ci --only=production`) which requires an up-to-date package-lock.json
2. before `npm install`, brutally edit the package.json with:

`RUN node -e 'const fs = require("fs"); const pkg = JSON.parse(fs.readFileSync("./package.json", "utf-8")); delete pkg.devDependencies; fs.writeFileSync("./package.json", JSON.stringify(pkg), "utf-8");'`

This won't edit your working package.json, just the one copied to the docker container. Of course, this shouldn't be necessary, but if it is (as it was for me), there's your hack.

``````\$myArr = array();

function someFuntion(array \$myArr) {
\$myVal = //some processing here to determine value of \$myVal
\$myArr[] = \$myVal;

return \$myArr;
}

\$myArr = someFunction(\$myArr);
``````

### Failed to load resource under Chrome

I recently ran into this problem and discovered that it was caused by the "Adblock" extension (my best guess is that it's because I had the words "banner" and "ad" in the filename).

As a quick test to see if that's your problem, start Chrome in incognito mode with extensions disabled (ctrl+shift+n) and see if your page works now. Note that by default all extensions will be already disabled in incognito mode unless you've specifically set them to run (via `chrome://extensions`).

### Splitting dataframe into multiple dataframes

In addition to Gusev Slava's answer, you might want to use groupby's groups:

``````{key: df.loc[value] for key, value in df.groupby("name").groups.items()}
``````

This will yield a dictionary with the keys you have grouped by, pointing to the corresponding partitions. The advantage is that the keys are maintained and don't vanish in the list index.

### Type or namespace name does not exist

I had the same problem and tried all of the above without any success, then I found out what it was:

I'd created a folder called "System" in one of my projects and then created a class in it. The problem seems to stem from having a namespace called "System" when the .cs file is created, even if it is in a namespace of "MyProject.System".

Looking back I can understand why this would cause problems. It really stumped me at first as the error messages don't initially seem to relate to the problem.

# Concrete example

mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:

``````mosquitto_sub -h test.mosquitto.org -t "#" -v
``````

The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.

If your MQTT device publishes a topic of `irisys/V4D-19230005/` to the test MQTT broker , then you could filter the messages:

``````mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v
``````

Options:

• -h the hostname (default MQTT port = 1883)
• -t precedes the topic

### What does "Use of unassigned local variable" mean?

You don't assign values outside of the if statements ... and it is possible that credit might be something other than 0, 1, 2, or 3, as @iomaxx noted.

Try changing the separate if statements to a single if/else if/else if/else. Or assign default values up at the top.

### Difference between a User and a Login in SQL Server

The first important thing that needs to be understood about SQL Server security is that there are two security realms involved - the server and the database. The server realm encompasses multiple database realms. All work is done in the context of some database, but to get to do the work, one needs to first have access to the server and then to have access to the database.

But logins are not enough, because work is usually done in a database and databases are separate realms. Access to databases is granted via users.

Users are mapped to logins and the mapping is expressed by the SID property of logins and users. A login maps to a user in a database if their SID values are identical. Depending on the type of login, we can therefore have a categorization of users that mimics the above categorization for logins; so, we have SQL users and Windows users and the latter category consists of users mapped to Windows user logins and of users mapped to Windows group logins.

Let's take a step back for a quick overview: a login provides access to the server and to further get access to a database, a user mapped to the login must exist in the database.

that's the link to the full post.

### Renaming the current file in Vim

You can also do it using netrw

The explore command opens up netrw in the directory of the open file

``````:E
``````

Move the cursor over the file you want to rename:

``````R
``````

Type in the new name, press enter, press y.

### How to write a comment in a Razor view?

This comment syntax should work for you:

``````@* enter comments here *@
``````

### How to create jar file with package structure?

This is what I do inside .sh file, let's consider install.sh

``````#!/bin/sh
echo Installing
cd .../Your_Project_Directory/com/cdy/ws/
jar cfe X.jar Main *.class
cd .../Your_Project_Directory/
ln -s .../Your_Project_Directory/com/cdy/ws/X.jar X
echo Testing...
java -jar X
echo You are Good to Go...Use hapily
#etc.
``````

Creating Executable Jar file at the Class directory and creating a SymLink at anywhere you want.

Run it using,

``````\$ sh install.sh[ENTER]
\$ java -jar X[ENTER]
``````

### How does collections.defaultdict work?

My own 2¢: you can also subclass defaultdict:

``````class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
``````

This could come in handy for very complex cases.

### What are the alternatives now that the Google web search API has been deprecated?

You can create "everywhere" custom search engine right from the Google Custom Search homepage ( http://www.google.com/cse/ ). You should just click 'advanced', during adding new engine. There you can provide Schema.org site type. 'Thing' is most generic type, which covers all the web.

### Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

I managed to solve the problem by the following steps :
1. Disable windows updates(but check the option "let users install updates manually")
2. Reboot the PC
3. Manually install kb2999226 update from VS install folder (packages/Patch/x64/Windows6.1-KB299926-x64.msu)
4. Start the VS install
5. After install is finished turn back automatic updates

### What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

### Calling constructors in c++ without new

Quite simply, both lines create the object on the stack, rather than on the heap as 'new' does. The second line actually involves a second call to a copy constructor, so it should be avoided (it also needs to be corrected as indicated in the comments). You should use the stack for small objects as much as possible since it is faster, however if your objects are going to survive for longer than the stack frame, then it's clearly the wrong choice.

You should find all HTTP headers in the `\$_SERVER` global variable prefixed with `HTTP_` uppercased and with dashes (-) replaced by underscores (_).

For instance your `X-Requested-With` can be found in:

``````\$_SERVER['HTTP_X_REQUESTED_WITH']
``````

It might be convenient to create an associative array from the `\$_SERVER` variable. This can be done in several styles, but here's a function that outputs camelcased keys:

``````\$headers = array();
foreach (\$_SERVER as \$key => \$value) {
if (strpos(\$key, 'HTTP_') === 0) {
\$headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr(\$key, 5)))))] = \$value;
}
}
``````

Now just use `\$headers['XRequestedWith']` to retrieve the desired header.

PHP manual on `\$_SERVER`: http://php.net/manual/en/reserved.variables.server.php

### ASP.NET set hiddenfield a value in Javascript

• First you need to create the Hidden Field properly

`<asp:HiddenField ID="hdntxtbxTaksit" runat="server"></asp:HiddenField>`

• Then you need to set value to the hidden field

If you aren't using Jquery you should use it:

`document.getElementById("<%= hdntxtbxTaksit.ClientID %>").value = "test";`

If you are using Jquery, this is how it should be:

`\$("#<%= hdntxtbxTaksit.ClientID %>").val("test");`

### What is C# equivalent of <map> in C++?

Take a look at the Dictionary class in System::Collections::Generic.

``````Dictionary<myComplex, int> myMap = new Dictionary<myComplex, int>();
``````

### How to configure PostgreSQL to accept all incoming connections

Add this line to pg_hba.conf of postgres folder

``````host    all    all    all    trust
``````

"trust" allows all users to connect without any password.

### Equivalent of Super Keyword in C#

C# equivalent of your code is

``````  class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
{ }

// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
``````

### Removing all script tags from html with JS Regular Expression

This Regex should work too:

``````<script(?:(?!\/\/)(?!\/\*)[^'"]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\/.*(?:\n)|\/\*(?:(?:.|\s))*?\*\/)*?<\/script>
``````

It even allows to have "problematic" variable strings like these inside:

``````<script type="text/javascript">
var test1 = "</script>";
var test2 = '\'</script>';
var test1 = "\"</script>";
var test1 = "<script>\"";
var test2 = '<scr\'ipt>';
/* </script> */
// </script>
/* ' */
// var foo=" '
</script>
``````

It seams that jQuery and Prototype fail on these ones...

Edit July 31 '17: Added a) non-capturing groups for better performance (and no empty groups) and b) support for JavaScript comments.

### Python: import module from another directory at the same level in project hierarchy

I faced the same issues. To solve this, I used `export PYTHONPATH="\$PWD"`. However, in this case, you will need to modify imports in your `Scripts` dir depending on the below:

Case 1: If you are in the `user_management` dir, your `scripts` should use this style `from Modules import LDAPManager` to import module.

Case 2: If you are out of the `user_management` 1 level like `main`, your `scripts` should use this style `from user_management.Modules import LDAPManager` to import modules.

### Open new Terminal Tab from command line (Mac OS X)

With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).

### Resizing Images in VB.NET

``````    Dim x As Integer = 0
Dim y As Integer = 0
Dim k = 0
Dim l = 0
Dim bm As New Bitmap(p1.Image)
Dim om As New Bitmap(p1.Image.Width, p1.Image.Height)
Dim r, g, b As Byte
Do While x < bm.Width - 1
y = 0
l = 0
Do While y < bm.Height - 1
r = 255 - bm.GetPixel(x, y).R
g = 255 - bm.GetPixel(x, y).G
b = 255 - bm.GetPixel(x, y).B
om.SetPixel(k, l, Color.FromArgb(r, g, b))
y += 3
l += 1
Loop
x += 3
k += 1
Loop
p2.Image = om
``````

### Android: ProgressDialog.show() crashes with getApplicationContext

Having read the above answers i found that for my situation the following fixed the issue.

This threw the error

``````myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(getApplicationContext());
dialog.show();
}
});
``````

Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.

``````myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(v.getContext());
dialog.show();
}
});
``````

I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).

### Ignore duplicates when producing map using streams

This is possible using the `mergeFunction` parameter of `Collectors.toMap(keyMapper, valueMapper, mergeFunction)`:

``````Map<String, String> phoneBook =
people.stream()
.collect(Collectors.toMap(
Person::getName,
System.out.println("duplicate key found!");
}
));
``````

`mergeFunction` is a function that operates on two values associated with the same key. `adress1` corresponds to the first address that was encountered when collecting elements and `adress2` corresponds to the second address encountered: this lambda just tells to keep the first address and ignores the second.

### Updating .class file in jar

Do you want to do it automatically or manually? If manually, a JAR file is really just a ZIP file, so you should be able to open it with any ZIP reader. (You may need to change the extension first.) If you want to update the JAR file automatically via Eclipse, you may want to look into Ant support in Eclipse and look at the zip task.

### Difference between \b and \B in regex

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

• Before the first character in the string, if the first character is a word character.
• After the last character in the string, if the last character is a word character.
• Between two characters in the string, where one is a word character and the other is not a word character.

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters.

### Get element inside element by class and ID - JavaScript

THe easiest way to do so is:

``````function findChild(idOfElement, idOfChild){
let element = document.getElementById(idOfElement);
return element.querySelector('[id=' + idOfChild + ']');
}
``````

``````findChild = (idOfElement, idOfChild) => {
let element = document.getElementById(idOfElement);
return element.querySelector(`[id=\${idOfChild}]`);
}
``````

### How to install PHP mbstring on CentOS 6.2

do the following:

``````sudo nano /etc/yum.repos.d/CentOS-Base.repo
``````

under the section `updates`, comment out the mirrorlist line (put a `#` in front of the line), then on a new line write:

``````baseurl=http://centos.intergenia.de/\$releasever/updates/\$basearch/
``````

now try:

``````yum install php-mbstring
``````

(afterwards you'll probably want to uncomment the mirrorlist and comment out the baseurl)

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

### How do you get the contextPath from JavaScript, the right way?

Got it :D

``````function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
``````

Important note: Does only work for the "root" context path. Does not work with "subfolders", or if context path has a slash ("/") in it.

### How to yum install Node.JS on Amazon Linux

I usually use NVM to install node on server. It gives me option to install multiple version of nodejs. Commands are given below

then check if it's install properly

command -v nvm

nvm install node

or

nvm install 11

### JNZ & CMP Assembly Instructions

I will make a little bit wider answer here.

There are generally speaking two types of conditional jumps in x86:

1. Arithmetic jumps - like JZ (jump if zero), JC (jump if carry), JNC (jump if not carry), etc.

2. Comparison jumps - JE (jump if equal), JB (jump if below), JAE (jump if above or equal), etc.

So, use the first type only after arithmetic or logical instructions:

``````sub  eax, ebx
jnz  .result_is_not_zero

and  ecx, edx
jz   .the_bit_is_not_set
``````

Use the second group only after CMP instructions:

``````cmp  eax, ebx
jne  .eax_is_not_equal_to_ebx

cmp  ecx, edx
ja   .ecx_is_above_than_edx
``````

This way, the program becomes more readable and you will never be confused.

Note, that sometimes these instructions are actually synonyms. JZ == JE; JC == JB; JNC == JAE and so on. The full table is following. As you can see, there are only 16 conditional jump instructions, but 30 mnemonics - they are provided to allow creation of more readable source code:

``````Mnemonic        Condition tested  Description

jo              OF = 1            overflow
jno             OF = 0            not overflow
jc, jb, jnae    CF = 1            carry / below / not above nor equal
jnc, jae, jnb   CF = 0            not carry / above or equal / not below
je, jz          ZF = 1            equal / zero
jne, jnz        ZF = 0            not equal / not zero
jbe, jna        CF or ZF = 1      below or equal / not above
ja, jnbe        CF and ZF = 0      above / not below or equal
js              SF = 1            sign
jns             SF = 0            not sign
jp, jpe         PF = 1            parity / parity even
jnp, jpo        PF = 0            not parity / parity odd
jl, jnge        SF xor OF = 1     less / not greater nor equal
jge, jnl        SF xor OF = 0     greater or equal / not less
jle, jng    (SF xor OF) or ZF = 1 less or equal / not greater
jg, jnle    (SF xor OF) or ZF = 0 greater / not less nor equal
``````

### What is the difference between Serializable and Externalizable in Java?

The Externalizable interface was not actually provided to optimize the serialization process performance! but to provide means of implementing your own custom processing and offer complete control over the format and contents of the stream for an object and its super types!

Examples of this is the implementation of AMF (ActionScript Message Format) remoting to transfer native action script objects over the network.

### Javascript set img src

Your src property is an object because you are setting the src element to be the entire image you created in JavaScript.

Try

``````document["pic1"].src = searchPic.src;
``````

### Create a SQL query to retrieve most recent records

another way, this will scan the table only once instead of twice if you use a subquery

only sql server 2005 and up

``````select Date, User, Status, Notes
from (
select m.*, row_number() over (partition by user order by Date desc) as rn
from [SOMETABLE] m
) m2
where m2.rn = 1;
``````

### Convert integer to hexadecimal and back again

Use:

``````int myInt = 2934;
string myHex = myInt.ToString("X");  // Gives you hexadecimal
int myNewInt = Convert.ToInt32(myHex, 16);  // Back to int again.
``````

See How to: Convert Between Hexadecimal Strings and Numeric Types (C# Programming Guide) for more information and examples.

### Getting path of captured image in Android using camera intent

There is a solution to create file (on external cache dir or anywhere else) and put this file's uri as output extra to camera intent - this will define path where taken picture will be stored.

Here is an example:

``````File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;

private void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = new File(getActivity().getExternalCacheDir(),
String.valueOf(System.currentTimeMillis()) + ".jpg");
fileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {

//do whatever you need with taken photo using file or fileUri

}
}
}
``````

Then if you don't need the file anymore, you can delete it using `file.delete();`

By the way, files from cache dir will be removed when user clears app's cache from apps settings.

### How to display data from database into textbox, and update it

The answer is `.IsPostBack` as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load

``````private void PopulateFields()
{
using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
{
DataTable dt = new DataTable();
con1.Open();
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);

{
}
con1.Close();
}//end using
}
``````

``````protected void Page_Load(object sender, EventArgs e)
{

if(!Page.IsPostBack)
{
PopulateFields();
}
}
``````

### UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

According to @Shovalt's answer, but in short:

Alternatively you could use the following lines of code

``````    from sklearn.metrics import f1_score
metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))
``````

This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.

### Android - Activity vs FragmentActivity?

If you use the Eclipse "New Android Project" wizard in a recent ADT bundle, you'll automatically get tabs implemented as a Fragments. This makes the conversion of your application to the tablet format much easier in the future.

For simple single screen layouts you may still use `Activity`.

### Generating combinations in c++

A simple way using `std::next_permutation`:

``````#include <iostream>
#include <algorithm>
#include <vector>

int main() {
int n, r;
std::cin >> n;
std::cin >> r;

std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);

do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
``````

or a slight variation that outputs the results in an easier to follow order:

``````#include <iostream>
#include <algorithm>
#include <vector>

int main() {
int n, r;
std::cin >> n;
std::cin >> r;

std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);

do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
``````

A bit of explanation:

It works by creating a "selection array" (`v`), where we place `r` selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of `v`.

You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

``````#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
typedef vector<int> combination_t;

// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}

// true while there are more solutions
bool completed;

// count how many generated
int generated;

// get current and compute next combination
combination_t next()
{
combination_t ret = curr;

// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}

return ret;
}

private:

int N, R;
combination_t curr;
};

int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
``````

test output:

``````1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
``````

### Custom Listview Adapter with filter Android

I hope it will be helpful for others.

``````// put below code (method) in Adapter class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
myList.clear();
if (charText.length() == 0) {
}
else
{
for (MyBean wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
}
}
}
notifyDataSetChanged();
}
``````

declare below code in adapter class

``````private ArrayList<MyBean> myList;  // for loading main list
``````

``````this.arraylist = new ArrayList<MyBean>();
``````

and below code in your activity class

``````final EditText searchET = (EditText)findViewById(R.id.search_et);
// Capture Text in EditText

@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = searchET.getText().toString().toLowerCase(Locale.getDefault());
}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}

@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
``````

### Editable 'Select' element

Similar to answer above but without the absolute positioning:

``````<select style="width: 200px; float: left;" onchange="this.nextElementSibling.value=this.value">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input style="width: 185px; margin-left: -199px; margin-top: 1px; border: none; float: left;"/>
``````

So create a input box and put it over the top of the combobox

### alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

### How to check for empty array in vba macro

To check whether a Byte array is empty, the simplest way is to use the VBA function `StrPtr()`.

If the Byte array is empty, `StrPtr()` returns `0`; otherwise, it returns a non-zero value (however, it's not the address to the first element).

``````Dim ar() As Byte
Debug.Assert StrPtr(ar) = 0

ReDim ar(0 to 3) As Byte
Debug.Assert StrPtr(ar) <> 0
``````

However, it only works with Byte array.

### How to create a inner border for a box in html?

``````<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.box{ width:500px; height:200px; background:#000; border:2px solid #ccc;}
.inner-border {
border: 20px solid black;
box-shadow: inset 0px 0px 0px 10px red;
box-sizing: border-box; /* Include padding and border in element's width and height */
}
/* CSS3 solution only for rectangular shape */
.inner-outline {
outline: 10px solid red;
outline-offset: -30px;
}
</style>

<body>
<div class="box inner-border inner-outline"></div>
</body>
</html>
``````

### Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

### Are the days of passing const std::string & as a parameter over?

• If you won't modify the string (treat is as read-only), pass it as `const ref&`.
(the `const ref&` obviously needs to stay within scope while the function that uses it executes)
• If you plan to modify it or you know it will get out of scope (threads), pass it as a `value`, don't copy the `const ref&` inside your function body.

There was a post on cpp-next.com called "Want speed, pass by value!". The TL;DR:

Guideline: Don’t copy your function arguments. Instead, pass them by value and let the compiler do the copying.

TRANSLATION of ^

Don’t copy your function arguments --- means: if you plan to modify the argument value by copying it to an internal variable, just use a value argument instead.

So, don't do this:

``````std::string function(const std::string& aString){
auto vString(aString);
vString.clear();
return vString;
}
``````

do this:

``````std::string function(std::string aString){
aString.clear();
return aString;
}
``````

When you need to modify the argument value in your function body.

You just need to be aware how you plan to use the argument in the function body. Read-only or NOT... and if it sticks within scope.

### Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

I've found the answer regarding how to do this myself. Inside the model code, just put:

For Rails <= 2:

``````include ActionController::UrlWriter
``````

For Rails 3:

``````include Rails.application.routes.url_helpers
``````

This magically makes `thing_path(self)` return the URL for the current thing, or `other_model_path(self.association_to_other_model)` return some other URL.

### Google Maps API warning: NoApiKeys

I had the same problem and I found out that if you add the URL param `?v=3` you won't get the warning message anymore:

``````<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
``````

Reproduction online

As pointed out in the comments by @Zia Ul Rehman Mughal

Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version

# Update 07-Jun-2016

This solution doesn't work anymore.

### How is Docker different from a virtual machine?

The docker documentation (and self-explanation) makes a distinction between "virtual machines" vs. "containers". They have the tendency to interpret and use things in a little bit uncommon ways. They can do that because it is up to them, what do they write in their documentation, and because the terminology for virtualization is not yet really exact.

Fact is what the Docker documentation understands on "containers", is paravirtualization (sometimes "OS-Level virtualization") in the reality, contrarily the hardware virtualization, which is docker not.

Docker is a low quality paravirtualisation solution. The container vs. VM distinction is invented by the docker development, to explain the serious disadvantages of their product.

The reason, why it became so popular, is that they "gave the fire to the ordinary people", i.e. it made possible the simple usage of typically server ( = Linux) environments / software products on Win10 workstations. This is also a reason for us to tolerate their little "nuance". But it does not mean that we should also believe it.

The situation is made yet more cloudy by the fact that docker on Windows hosts used an embedded Linux in HyperV, and its containers have run in that. Thus, docker on Windows uses a combined hardware and paravirtualization solution.

In short, Docker containers are low-quality (para)virtual machines with a huge advantage and a lot of disadvantages.

### show and hide divs based on radio button click

With `\$("div.desc").hide();` you are essentially trying to hide a div with a class name of `desc`. Which doesn't exist. With `\$("#"+test).show();` you are trying to show either a div with an id of `#2` or `#3`. Those are illegal id's in HTML (can't start with a number), though they will work in many browsers. However, they don't exist.

I'd rename the two divs to `carDiv2` and `carDiv3` and then use different logic to hide or show.

``````if((test) == 2) { ... }
``````

Also, use a class for your checkboxes so your binding becomes something like

``````\$('.carCheckboxes').click(function ...
``````

### How do I create a batch file timer to execute / call another batch throughout the day

I would use the scheduler (control panel) rather than a cmd line or other application.

If your system has `systemctl`

``````sudo systemctl reload nginx
``````

If your system supports `service` (using debian/ubuntu) try this

``````sudo service nginx reload
``````

If not (using centos/fedora/etc) you can try the init script

``````sudo /etc/init.d/nginx reload
``````

### How do you stretch an image to fill a <div> while keeping the image's aspect-ratio?

HTML:

``````<style>
#foo, #bar{
width: 50px; /* use any width or height */
height: 50px;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
</style>

<div id="foo" style="background-image: url('path/to/image1.png');">
<div id="bar" style="background-image: url('path/to/image2.png');">
``````

JSFiddle

...And if you want to set or change the image (using #foo as an example):

jQuery:

``````\$("#foo").css("background-image", "url('path/to/image.png')");
``````

JavaScript:

``````document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";
``````

### How do you make a deep copy of an object?

1)

``````public static Object deepClone(Object object) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}

2)

// (1) create a MyPerson object named Al
MyPerson al = new MyPerson("Al", "Arun", address);

// (2) make a deep clone of Al
MyPerson neighbor = (MyPerson)deepClone(al);
``````

### Get java.nio.file.Path object from java.io.File

From the documentation:

Paths associated with the default `provider` are generally interoperable with the `java.io.File` class. Paths created by other providers are unlikely to be interoperable with the abstract path names represented by `java.io.File`. The `toPath` method may be used to obtain a Path from the abstract path name represented by a java.io.File object. The resulting Path can be used to operate on the same file as the `java.io.File` object. In addition, the `toFile` method is useful to construct a `File` from the `String` representation of a `Path`.

(emphasis mine)

So, for `toFile`:

Returns a `File` object representing this path.

And `toPath`:

Returns a `java.nio.file.Path` object constructed from the this abstract path.

### Function that creates a timestamp in c#

You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)

### Spring Boot Multiple Datasource

Use multiple datasource or realizing the separation of reading & writing. you must have a knowledge of Class `AbstractRoutingDataSource` which support dynamic datasource choose.

Here is my `datasource.yaml` and I figure out how to resolve this case. You can refer to this project spring-boot + quartz. Hope this will help you.

``````dbServer:
default: localhost:3306
write: localhost:3306
datasource:
default:
type: com.zaxxer.hikari.HikariDataSource
pool-name: default
continue-on-error: false
jdbc-url: jdbc:mysql://\${dbServer.default}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
type: com.zaxxer.hikari.HikariDataSource
continue-on-error: false
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
write:
type: com.zaxxer.hikari.HikariDataSource
pool-name: write
continue-on-error: false
jdbc-url: jdbc:mysql://\${dbServer.write}/schedule_job?useSSL=true&verifyServerCertificate=false&useUnicode=true&characterEncoding=utf8
connection-timeout: 30000
connection-test-query: SELECT 1
maximum-pool-size: 5
minimum-idle: 2
idle-timeout: 600000
destroy-method: shutdown
auto-commit: false
``````

### Using HTML5/Canvas/JavaScript to take in-browser screenshots

Heres an example using: getDisplayMedia

``````document.body.innerHTML = '<video style="width: 100%; height: 100%; border: 1px black solid;"/>';

.then( mediaStream => {
const video = document.querySelector('video');
video.srcObject = mediaStream;
video.play();
video.pause();
};
})
.catch( err => console.log(`\${err.name}: \${err.message}`));
``````

Also worth checking out is the Screen Capture API docs.

### How can I concatenate two arrays in Java?

This is probably the only generic and type-safe way:

``````public class ArrayConcatenator<T> {
private final IntFunction<T[]> generator;

private ArrayConcatenator(IntFunction<T[]> generator) {
this.generator = generator;
}

public static <T> ArrayConcatenator<T> concat(IntFunction<T[]> generator) {
return new ArrayConcatenator<>(generator);
}

public T[] apply(T[] array1, T[] array2) {
T[] array = generator.apply(array1.length + array2.length);
System.arraycopy(array1, 0, array, 0, array1.length);
System.arraycopy(array2, 0, array, array1.length, array2.length);
return array;
}
}
``````

And the usage is quite concise:

``````Integer[] array1 = { 1, 2, 3 };
Double[] array2 = { 4.0, 5.0, 6.0 };
Number[] array = concat(Number[]::new).apply(array1, array2);
``````

(requires static import)

Invalid array types are rejected:

``````concat(String[]::new).apply(array1, array2); // error
concat(Integer[]::new).apply(array1, array2); // error
``````

### How do you clear the console screen in C?

Since you mention `cls`, it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:

``````cls( GetStdHandle( STD_OUTPUT_HANDLE ));
``````

### Configuring diff tool with .gitconfig

Git offers a range of difftools pre-configured "out-of-the-box" (kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse, opendiff, p4merge and araxis), and also allows you to specify your own. To use one of the pre-configured difftools (for example, "vimdiff"), you add the following lines to your `~/.gitconfig`:

``````[diff]
tool = vimdiff
``````

Now, you will be able to run "git difftool" and use your tool of choice.

Specifying your own difftool, on the other hand, takes a little bit more work, see How do I view 'git diff' output with my preferred diff tool/ viewer?

### Removing duplicates from a String in Java

Code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra array is not:

``````import java.util.*;
public class Main{
public static char[] removeDupes(char[] arr){
if (arr == null || arr.length < 2)
return arr;
int len = arr.length;
int tail = 1;
for(int x = 1; x < len; x++){
int y;
for(y = 0; y < tail; y++){
if (arr[x] == arr[y]) break;
}
if (y == tail){
arr[tail] = arr[x];
tail++;
}
}
return Arrays.copyOfRange(arr, 0, tail);
}

public static char[] bigArr(int len){
char[] arr = new char[len];
Random r = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#\$%^&*()-=_+[]{}|;:',.<>/?`~";

for(int x = 0; x < len; x++){
arr[x] = alphabet.charAt(r.nextInt(alphabet.length()));
}

return arr;
}
public static void main(String args[]){

String result = new String(removeDupes(new char[]{'a', 'b', 'c', 'd', 'a'}));
assert "abcd".equals(result) : "abcda should return abcd but it returns: " + result;

result = new String(removeDupes(new char[]{'a', 'a', 'a', 'a'}));
assert "a".equals(result) : "aaaa should return a but it returns: " + result;

result = new String(removeDupes(new char[]{'a', 'b', 'c', 'a'}));
assert "abc".equals(result) : "abca should return abc but it returns: " + result;

result = new String(removeDupes(new char[]{'a', 'a', 'b', 'b'}));
assert "ab".equals(result) : "aabb should return ab but it returns: " + result;

result = new String(removeDupes(new char[]{'a'}));
assert "a".equals(result) : "a should return a but it returns: " + result;

result = new String(removeDupes(new char[]{'a', 'b', 'b', 'a'}));
assert "ab".equals(result) : "abba should return ab but it returns: " + result;

char[] arr = bigArr(5000000);
long startTime = System.nanoTime();
System.out.println("2: " + new String(removeDupes(arr)));
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Program took: " + duration + " nanoseconds");
System.out.println("Program took: " + duration/1000000000 + " seconds");

}
}
``````

1. The method called removeDupes takes an array of primitive char called arr.
2. arr is returned as an array of primitive characters "by value". The arr passed in is garbage collected at the end of Main's member method removeDupes.
3. The runtime complexity of this algorithm is O(n) or more specifically O(n+(small constant)) the constant being the unique characters in the entire array of primitive chars.
4. The copyOfRange does not increase runtime complexity significantly since it only copies a small constant number of items. The char array called arr is not stepped all the way through.
5. If you pass null into removeDupes, the method returns null.
6. If you pass an empty array of primitive chars or an array containing one value, that unmodified array is returned.
7. Method removeDupes goes about as fast as physically possible, fully utilizing the L1 and L2 cache, so Branch redirects are kept to a minimum.
8. A 2015 standard issue unburdened computer should be able to complete this method with an primitive char array containing 500 million characters between 15 and 25 seconds.

Explain how this code works:

The first part of the array passed in is used as the repository for the unique characters that are ultimately returned. At the beginning of the function the answer is: "the characters between 0 and 1" as between 0 and tail.

We define the variable y outside of the loop because we want to find the first location where the array index that we are looking at has been duplicated in our repository. When a duplicate is found, it breaks out and quits, the y==tail returns false and the repository is not contributed to.

when the index x that we are peeking at is not represented in our repository, then we pull that one and add it to the end of our repository at index tail and increment tail.

At the end, we return the array between the points 0 and tail, which should be smaller or equal to in length to the original array.

Talking points exercise for coder interviews:

Will the program behave differently if you change the y++ to ++y? Why or why not.

Does the array copy at the end represent another 'N' pass through the entire array making runtime complexity O(n*n) instead of O(n) ? Why or why not.

Can you replace the double equals comparing primitive characters with a .equals? Why or why not?

Can this method be changed in order to do the replacements "by reference" instead of as it is now, "by value"? Why or why not?

Can you increase the efficiency of this algorithm by sorting the repository of unique values at the beginning of 'arr'? Under which circumstances would it be more efficient?

### Removing NA observations with dplyr::filter()

If someone is here in 2020, after making all the pipes, if u pipe `%>% na.exclude` will take away all the NAs in the pipe!

### How to change default language for SQL Server?

``````DECLARE @Today DATETIME;
SET @Today = '12/5/2007';

SET LANGUAGE Italian;
SELECT DATENAME(month, @Today) AS 'Month Name';

SET LANGUAGE us_english;
SELECT DATENAME(month, @Today) AS 'Month Name' ;
GO
``````

Reference:

https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql

### Iterating through a JSON object

This question has been out here a long time, but I wanted to contribute how I usually iterate through a JSON object. In the example below, I've shown a hard-coded string that contains the JSON, but the JSON string could just as easily have come from a web service or a file.

``````import json

def main():

# create a simple JSON array
jsonString = '{"key1":"value1","key2":"value2","key3":"value3"}'

# change the JSON string into a JSON object

# print the keys and values
for key in jsonObject:
value = jsonObject[key]
print("The key and value are ({}) = ({})".format(key, value))

pass

if __name__ == '__main__':
main()
``````

### Why is Spring's ApplicationContext.getBean considered bad?

One of the reasons is testability. Say you have this class:

``````interface HttpLoader {
}
interface StringOutput {
void print(String txt);
}
@Component
class MyBean {
@Autowired
}
}
``````

How can you test this bean? E.g. like this:

``````class MyBeanTest {
public void creatingMyBean_writesStackoverflowPageToOutput() {
// setup
String stackOverflowHtml = "dummy";
StringBuilder result = new StringBuilder();

// execution
new MyBean(Collections.singletonMap("https://stackoverflow.com", stackOverflowHtml)::get, result::append);

// evaluation
assertEquals(result.toString(), stackOverflowHtml);
}
}
``````

Easy, right?

While you still depend on Spring (due to the annotations) you can remove you dependency on spring without changing any code (only the annotation definitions) and the test developer does not need to know anything about how spring works (maybe he should anyway, but it allows to review and test the code separately from what spring does).

It is still possible to do the same when using the ApplicationContext. However then you need to mock `ApplicationContext` which is a huge interface. You either need a dummy implementation or you can use a mocking framework such as Mockito:

``````@Component
class MyBean {
@Autowired
MyBean(ApplicationContext context) {
StringOutput out = context.getBean(StringOutput.class);

}
}
class MyBeanTest {
public void creatingMyBean_writesStackoverflowPageToOutput() {
// setup
String stackOverflowHtml = "dummy";
StringBuilder result = new StringBuilder();
ApplicationContext context = Mockito.mock(ApplicationContext.class);
.thenReturn(Collections.singletonMap("https://stackoverflow.com", stackOverflowHtml)::get);
Mockito.when(context.getBean(StringOutput.class)).thenReturn(result::append);

// execution
new MyBean(context);

// evaluation
assertEquals(result.toString(), stackOverflowHtml);
}
}
``````

This is quite a possibility, but I think most people would agree that the first option is more elegant and makes the test simpler.

The only option that is really a problem is this one:

``````@Component
class MyBean {
@Autowired
MyBean(StringOutput out) {
}
}
``````

Testing this requires huge efforts or your bean is going to attempt to connect to stackoverflow on each test. And as soon as you have a network failure (or the admins at stackoverflow block you due to excessive access rate) you will have randomly failing tests.

So as a conclusion I would not say that using the `ApplicationContext` directly is automatically wrong and should be avoided at all costs. However if there are better options (and there are in most cases), then use the better options.

### Edit a specific Line of a Text File in C#

the easiest way is :

``````static void lineChanger(string newText, string fileName, int line_to_edit)
{
arrLine[line_to_edit - 1] = newText;
File.WriteAllLines(fileName, arrLine);
}
``````

usage :

``````lineChanger("new content for this line" , "sample.text" , 34);
``````

### history.replaceState() example?

The second argument Title does not mean Title of the page - It is more of a definition/information for the state of that page

But we can still change the title using onpopstate event, and passing the title name not from the second argument, but as an attribute from the first parameter passed as object

### nvarchar(max) vs NText

`VARCHAR(MAX)` is big enough to accommodate `TEXT` field. `TEXT`, `NTEXT` and `IMAGE` data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are `VARCHAR(MAX)`, `NVARCHAR(MAX)` and `VARBINARY(MAX)`.

### How do I mock a REST template exchange?

This is an example with the non deprecated ArgumentMatchers class

``````when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<String>>any()))
.thenReturn(responseEntity);
``````

### Removing numbers from string

Not sure if your teacher allows you to use filters but...

``````filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")
``````

returns-

``````'aaasdffgh'
``````

Much more efficient than looping...

Example:

``````for i in range(10):
a.replace(str(i),'')
``````

### How to clear mysql screen console in windows?

just type `\system cls`

took me a couple hours to get it jejej

### Loop code for each file in a directory

Check out the DirectoryIterator class.

From one of the comments on that page:

``````// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as \$fileInfo) {
if(\$fileInfo->isDot()) continue;
echo \$fileInfo->getFilename() . "<br>\n";
}
``````

The recursive version is RecursiveDirectoryIterator.

### Jasmine.js comparing arrays

Just did the test and it works with `toEqual`

http://jsfiddle.net/7q9N7/3/

``````describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
``````

Just for information:

toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.

### What is the default Jenkins password?

Before installing jenkins, create a user named jenkins and set password there. Then after installing jenkins you can use the password you created.

### Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

``````adb shell am force-stop <PACKAGE>
``````

The following command is WORKING:

``````adb shell pm disable <PACKAGE>
``````

If you want to restart the app,you must run command below first:

``````adb shell pm enable <PACKAGE>
``````

### how to set select element as readonly ('disabled' doesnt pass select value on server)

without disabling the selected value on submitting..

``````\$('#selectID option:not(:selected)').prop('disabled', true);

If you use Jquery version lesser than 1.7
\$('#selectID option:not(:selected)').attr('disabled', true);
``````

It works for me..

### Most concise way to convert a Set<T> to a List<T>

not really sure what you're doing exactly via the context of your code but...

why make the `listOfTopicAuthors` variable at all?

``````List<String> list = Arrays.asList((....).toArray( new String[0] ) );
``````

the "...." represents however your set came into play, whether it's new or came from another location.

### Show/Hide Multiple Divs with Jquery

Check This Example

Html:

``````<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>

<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
``````

Javascript:

``````\$('#showall').click(function(){
\$('div').show();
});

\$('#showdiv1').click(function(){
\$('div[id^=div]').hide();
\$('#div1').show();
});
\$('#showdiv2').click(function(){
\$('div[id^=div]').hide();
\$('#div2').show();
});

\$('#showdiv3').click(function(){
\$('div[id^=div]').hide();
\$('#div3').show();
});

\$('#showdiv4').click(function(){
\$('div[id^=div]').hide();
\$('#div4').show();

});
``````

### Changing the Git remote 'push to' default

You can use `git push -u <remote_name> <local_branch_name>` to set the default upstream. See the documentation for git push for more details.

### Updating a JSON object using Javascript

``````    var jsonObj = [{'Id':'1','Quantity':'2','Done':'0','state':'todo',
'product_id':[315,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
{'Id':'2','Quantity':'2','Done':'0','state':'todo',
'product_id':[314,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],
{'Id':'3','Quantity':'2','Done':'0','state':'todo',
'product_id':[316,"[LBI-W-SL-3-AG-TA004-C650-36] LAURA BONELLI-WOMEN'S-SANDAL"],

for (var i = 0; i < jsonObj.length; ++i) {
if (jsonObj[i]['product_id'][0] === 314) {

jsonObj[i]['Done'] = ""+this.quantity_done+"";

if(jsonObj[i]['Quantity'] === jsonObj[i]['Done']){
console.log('both are equal');
jsonObj[i]['state'] = 'packed';
}else{
console.log('not equal');
jsonObj[i]['state'] = 'todo';
}

console.log('quantiy',jsonObj[i]['Quantity']);
console.log('done',jsonObj[i]['Done']);

}
}

console.log('final',jsonObj);
}

quantity_done: any = 0;

this.quantity_done += 1;
console.log(this.quantity_done + 1);
}
``````

### Python convert csv to xlsx

Here's an example using xlsxwriter:

``````import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
with open(csvfile, 'rt', encoding='utf8') as f:
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
``````

FYI, there is also a package called openpyxl, that can read/write Excel 2007 xlsx/xlsm files.

Hope that helps.

### How can I get phone serial number (IMEI)

Here is the code:-

``````telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

deviceId = telephonyManager.getDeviceId();
Log.d(TAG, "getDeviceId() " + deviceId);

phoneType = telephonyManager.getPhoneType();
Log.d(TAG, "getPhoneType () " + phoneType);
``````

### Converting char[] to byte[]

You could make a method:

``````public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
}
``````

Hope this helps

### TypeError: Cannot read property "0" from undefined

Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.

### Github Push Error: RPC failed; result=22, HTTP code = 413

Was facing the same issue however it got resolved by cleaning up the git repository (Clean untracked files using "git clean").

### NPM global install "cannot find module"

I got the "optimist" module error and I just did "npm install" to resolve it. went past that error.

https://github.com/mbloch/mapshaper/issues/12

### 400 vs 422 response to POST of data

400 Bad Request would now seem to be the best HTTP/1.1 status code for your use case.

At the time of your question (and my original answer), RFC 7231 was not a thing; at which point I objected to `400 Bad Request` because RFC 2616 said (with emphasis mine):

The request could not be understood by the server due to malformed syntax.

and the request you describe is syntactically valid JSON encased in syntactically valid HTTP, and thus the server has no issues with the syntax of the request.

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

However, prior to that re-wording (or if you want to quibble about RFC 7231 only being a proposed standard right now), `422 Unprocessable Entity` does not seem an incorrect HTTP status code for your use case, because as the introduction to RFC 4918 says:

While the status codes provided by HTTP/1.1 are sufficient to describe most error conditions encountered by WebDAV methods, there are some errors that do not fall neatly into the existing categories. This specification defines extra status codes developed for WebDAV methods (Section 11)

And the description of `422` says:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.

(Note the reference to syntax; I suspect 7231 partly obsoletes 4918 too)

This sounds exactly like your situation, but just in case there was any doubt, it goes on to say:

For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

(Replace "XML" with "JSON" and I think we can agree that's your situation)

Now, some will object that RFC 4918 is about "HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)" and that you (presumably) are doing nothing involving WebDAV so shouldn't use things from it.

Given the choice between using an error code in the original standard that explicitly doesn't cover the situation, and one from an extension that describes the situation exactly, I would choose the latter.

Furthermore, RFC 4918 Section 21.4 refers to the IANA Hypertext Transfer Protocol (HTTP) Status Code Registry, where 422 can be found.

I propose that it is totally reasonable for an HTTP client or server to use any status code from that registry, so long as they do so correctly.

But as of HTTP/1.1, RFC 7231 has traction, so just use `400 Bad Request`!

### How to display a list of images in a ListView in Android?

Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.

In main.xml

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

<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
``````

create listview_layout.xml and paste this code

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

<ImageView
android:id="@+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello"

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="TextView1" />

<TextView
android:id="@+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:text="TextView2" />
</LinearLayout>
``````

``````package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class SimpleListImageActivity extends Activity {

// Array of strings storing country names
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};

// Array of integers points to images stored in /res/drawable-hdpi/

//here you have to give image name which you already pasted it in /res/drawable-hdpi/

int[] flags = new int[]{
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
};

// Array of strings to store currencies
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
"Renminbi",
"Nepalese Rupee",
"Afghani",
"North Korean Won",
"South Korean Won",
"Japanese Yen"
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
}

// Keys used in Hashmap
String[] from = { "flag","txt","cur" };

// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};

// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item

// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);

// Setting the adapter to the listView
}
}
``````

This is the full code.you can make changes to your need... Comments are welcome

### Using Python to execute a command on every file in a folder

I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.

It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD

I also add a small interface, hope someone else find it useful!

I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/

### How do I set a checkbox in razor view?

you set AllowRating property to true from your controller or model

``````      @Html.CheckBoxFor(m => m.AllowRating, new { @checked =Model.AllowRating })
``````

### How to add a title to a html select tag

``````<select name="city">
<option value ="0">What is your city</option>
<option value ="1">Sydney</option>
<option value ="2">Melbourne</option>
<option value ="3">Cromwell</option>
<option value ="4">Queenstown</option>
</select>
``````

You can use the unique id for the value instead

### Getting JSONObject from JSONArray

start from

``````JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
``````

you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each `deletedtrs_array` member

Iterating

``````for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());

// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);

// String company_id = obj.getString("companyid");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
``````

Own object type

``````class DeletedTrsWrapper {

public String company_id;
public String date;
public int report_id;

public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
``````

### How to add a line break within echo in PHP?

You have to use br when using echo , like this :

``````echo "Thanks for your email" ."<br>". "Your orders details are below:"
``````

and it will work properly

### How to change font-size of a tag using inline css?

You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a `style` attribute. Apparently, it has to be one using the `!important` specifier, which generally indicates poor logic and structure in styling.

Primarily, modify the style.css file so that it does not use `!important`. Failing this, add `!important` to the rule in `style` attribute. But you should aim at reducing the use of `!important`, not increasing it.

### Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

### Paste multiple columns together

As a variant on baptiste's answer, with `data` defined as you have and the columns that you want to put together defined in `cols`

``````cols <- c("b", "c", "d")
``````

You can add the new column to `data` and delete the old ones with

``````data\$x <- do.call(paste, c(data[cols], sep="-"))
for (co in cols) data[co] <- NULL
``````

which gives

``````> data
a     x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i
``````

### What is 'Context' on Android?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.

For more information, look in Introduction to Android development with Android Studio - Tutorial.

### Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

``````import java.lang.*;
import java.io.*;
public class rupee
{
public static void main(String[] args)throws  IOException
{

int len=0,revnum=0,i,dup=0,j=0,k=0;
int gvalue;
String[] ones={"one","Two","Three","Four","Five","Six","Seven","Eight","Nine","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",""};
String[] twos={"Ten","Twenty","Thirty","Fourty","fifty","Sixty","Seventy","eighty","Ninety",""};
System.out.println("\n Enter value");
if(gvalue==10)

System.out.println("Ten");

else if(gvalue==100)

System.out.println("Hundred");

else if(gvalue==1000)
System.out.println("Thousand");

dup=gvalue;
for(i=0;dup>0;i++)
{
revnum=revnum*10+dup%10;
len++;
dup=dup/10;
}
while(j<len)
{
if(gvalue<10)
{
System.out.println(ones[gvalue-1]);
}
else if(gvalue>10&&gvalue<=19)
{
System.out.println(ones[gvalue-2]);
break;
}
else if(gvalue>19&&gvalue<100)
{
k=gvalue/10;
gvalue=gvalue%10;
System.out.println(twos[k-1]);
}
else if(gvalue>100&&gvalue<1000)
{
k=gvalue/100;
gvalue=gvalue%100;
System.out.println(ones[k-1] +"Hundred");
}
else if(gvalue>=1000&&gvalue<9999)
{
k=gvalue/1000;
gvalue=gvalue%1000;
System.out.println(ones[k-1]+"Thousand");
}
else if(gvalue>=11000&&gvalue<=19000)
{
k=gvalue/1000;
gvalue=gvalue%1000;
System.out.println(twos[k-2]+"Thousand");
}
else if(gvalue>=12000&&gvalue<100000)
{
k=gvalue/10000;
gvalue=gvalue%10000;
System.out.println(ones[gvalue-1]);
}
else
{
System.out.println("");
}
j++;
}
}
}
``````

### Where is SQL Profiler in my SQL Server 2008?

Also ensure that "client tools" are selected in the install options. However if SQL Managment Studio 2008 exists then it is likely that you installed the express edition.

### Turn a number into star rating display using jQuery and CSS

Try this jquery helper function/file

jquery.Rating.js

``````//ES5
\$.fn.stars = function() {
return \$(this).each(function() {
var rating = \$(this).data("rating");
var fullStar = new Array(Math.floor(rating + 1)).join('<i class="fas fa-star"></i>');
var halfStar = ((rating%1) !== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
var noStar = new Array(Math.floor(\$(this).data("numStars") + 1 - rating)).join('<i class="far fa-star"></i>');
\$(this).html(fullStar + halfStar + noStar);
});
}

//ES6
\$.fn.stars = function() {
return \$(this).each(function() {
const rating = \$(this).data("rating");
const numStars = \$(this).data("numStars");
const fullStar = '<i class="fas fa-star"></i>'.repeat(Math.floor(rating));
const halfStar = (rating%1!== 0) ? '<i class="fas fa-star-half-alt"></i>': '';
const noStar = '<i class="far fa-star"></i>'.repeat(Math.floor(numStars-rating));
\$(this).html(`\${fullStar}\${halfStar}\${noStar}`);
});
}
``````

index.html

``````   <!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Star Rating</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="js/jquery.Rating.js"></script>
<script>
\$(function(){
\$('.stars').stars();
});
</script>
<body>

<span class="stars" data-rating="3.5" data-num-stars="5" ></span>

</body>
</html>
``````

### How can you search Google Programmatically Java API

In light of those TOS alterations last year we built an API that gives access to Google's search. It was for our own use only but after some requests we decided to open it up. We're planning to add additional search engines in the future!

Should anyone be looking for an easy way to implement / acquire search results you are free to sign up and give the REST API a try: https://searchapi.io

It returns JSON results and should be easy enough to implement with the detailed docs.

It's a shame that Bing and Yahoo are miles ahead on Google in this regard. Their APIs aren't cheap, but at least available.

### Deserializing a JSON into a JavaScript object

The whole point of JSON is that JSON strings can be converted to native objects without doing anything. Check this link

You can use either `eval(string)` or `JSON.parse(string)`.

However, `eval` is risky. From json.org:

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

### SecurityError: Blocked a frame with origin from accessing a cross-origin frame

#### Same-origin policy

You can't access an `<iframe>` with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

`protocol://hostname:port/...`

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

#### Examples

Here's what would happen trying to access the following URLs from `http://www.example.com/home/index.html`

``````URL                                             RESULT
http://www.example.com/home/other.html       -> Success
http://www.example.com/dir/inner/another.php -> Success
http://www.example.com:80                    -> Success (default port for HTTP)
http://www.example.com:2251                  -> Failure: different port
http://data.example.com/dir/other.html       -> Failure: different hostname
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname
``````

#### Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using `window.postMessage` and its relative `message` event to send messages between the two pages, like this:

``````const frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
``````

The second argument to `postMessage()` can be `'*'` to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

• In your `<iframe>` (contained in the main page):

``````window.addEventListener('message', event => {
// IMPORTANT: check the origin of the data!
if (event.origin.startsWith('http://your-first-site.com')) {
// The data was sent from your site.
// Data sent with postMessage is stored in event.data:
console.log(event.data);
} else {
// The data was NOT sent from your site!
// Be careful! Do not use it. This else branch is
// here just for clarity, you usually shouldn't need it.
return;
}
});
``````

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using `window.open()`) as well, without any difference.

### Add new line in text file with Windows batch file

You can use:

``````type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt
``````

or something like this:

``````echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt
``````

### Initializing a dictionary in python with a key value and no corresponding values

Comprehension could be also convenient in this case:

``````# from a list
keys = ["k1", "k2"]
d = {k:None for k in keys}

# or from another dict
d1 = {"k1" : 1, "k2" : 2}
d2 = {k:None for k in d1.keys()}

d2
# {'k1': None, 'k2': None}
``````

### Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

For me it was "Prefer 32bit": clearing the checkbox allowed CLR to load Crystal Reports 64bit runtime (the only one installed).

### How to manage startActivityForResult on Android?

#### startActivityForResult : Deprecated in androidx

For New way we have `registerForActivityResult`

In Java :

`````` // You need to create lanucher variable inside onAttach or onCreate or global, i.e, before the activity is displayed
ActivityResultLauncher<Intent> launchSomeActivity = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
}
}
});

public void openYourActivity() {
Intent intent = new Intent(this, SomeActivity.class);
launchSomeActivity.launch(intent);
}
``````

In Kotlin :

``````var resultLauncher = registerForActivityResult(StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
}
}

fun openYourActivity() {
val intent = Intent(this, SomeActivity::class.java)
resultLauncher.launch(intent)
}
``````

New way is reduce complexity which we faced when we call activity from fragment or from another activity

### Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

There are some good answers here already. But it's worthwhile to drive home the difference in parallelism offered:

• `success()` returns the original promise
• `then()` returns a new promise

The difference is `then()` drives sequential operations, since each call returns a new promise.

``````\$http.get(/*...*/).
then(function seqFunc1(response){/*...*/}).
then(function seqFunc2(response){/*...*/})
``````
1. `\$http.get()`
2. `seqFunc1()`
3. `seqFunc2()`

`success()` drives parallel operations, since handlers are chained on the same promise.

``````\$http(/*...*/).
success(function parFunc1(data){/*...*/}).
success(function parFunc2(data){/*...*/})
``````
1. `\$http.get()`
2. `parFunc1()`, `parFunc2()` in parallel

### How to configure postgresql for the first time?

If you're running macOS like I am, you may not have the postgres user.

When trying to run `sudo -u postgres psql` I was getting the error `sudo: unknown user: postgres`

Luckily there are executables that postgres provides.

``````createuser -D /var/postgres/var-10-local --superuser --username=nick
createdb --owner=nick
``````

Then I was able to access `psql` without issues.

``````psql
psql (10.2)
Type "help" for help.

nick=#
``````

If you're creating a new postgres instance from scratch, here are the steps I took. I used a non-default port so I could run two instances.

``````mkdir /var/postgres/var-10-local
pg_ctl init -D /var/postgres/var-10-local
``````

Then I edited `/var/postgres/var-10-local/postgresql.conf` with my preferred port, 5433.

``````/Applications/Postgres.app/Contents/Versions/10/bin/postgres -D /Users/nick/Library/Application\ Support/Postgres/var-10-local -p 5433

createuser -D /var/postgres/var-10-local --superuser --username=nick --port=5433
createdb --owner=nick --port=5433
``````

Done!

### JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".

That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.

JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

### How do you deploy Angular apps?

With the Angular CLI it's easy. An example for Heroku:

1. Create a Heroku account and install the CLI

2. Move the `angular-cli` dep to the `dependencies` in `package.json` (so that it gets installed when you push to Heroku.

3. Add a `postinstall` script that will run `ng build` when the code gets pushed to Heroku. Also add a start command for a Node server that will be created in the following step. This will place the static files for the app in a `dist` directory on the server and start the app afterward.

``````"scripts": {
// ...
"start": "node server.js",
"postinstall": "ng build --aot -prod"
}
``````
1. Create an Express server to serve the app.
``````// server.js
const express = require('express');
const app = express();
// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));
// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 8080);
``````
1. Create a Heroku remote and push to depoy the app.
``````heroku create
git commit -m "first deploy"
git push heroku master
``````

Here's a quick writeup I did that has more detail, including how to force requests to use HTTPS and how to handle `PathLocationStrategy` :)

### How do I know which version of Javascript I'm using?

Rather than finding which version you are using you can rephrase your question to "which version of ECMA script does my browser's JavaScript/JSscript engine conform to".

For IE :

``````alert(@_jscript_version);      //IE
``````

Refer Squeegy's answer for non-IE versions :)

### Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\

`mysqli_select_db()` should have 2 parameters, the connection link and the database name -

``````mysqli_select_db(\$con, 'phpcadet') or die(mysqli_error(\$con));
``````

Using `mysqli_error` in the die statement will tell you exactly what is wrong as opposed to a generic error message.

### How to clear the Entry widget after a button is pressed in Tkinter?

if none of the above is working you can use this->

idAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)

for e.g. ->

id assigned is = en then

en.delete(first =0, last =100)

### How is __eq__ handled in Python and in what order?

The `a == b` expression invokes `A.__eq__`, since it exists. Its code includes `self.value == other`. Since int's don't know how to compare themselves to B's, Python tries invoking `B.__eq__` to see if it knows how to compare itself to an int.

If you amend your code to show what values are being compared:

``````class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other

a = A()
a.value = 3
b = B()
b.value = 4
a == b
``````

it will print:

``````A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
``````

### How to set conditional breakpoints in Visual Studio?

Visual Studio provides lots of options for conditional breakpoints:

To set any of these you

1. Set a breakpoint.
2. Right-Click over the breakpoint, and in the popup menu you select an option that suites you.

These options are as follows:

• You can set a condition, based on a code expression that you supply (select Condition from the popup menu). For instance, you can specify that `foo == 8` or some other expression.
• You can make breakpoints trigger after they have been hit a certain number of times. (select Hit Count from the popup menu). This is a fun option to play with as you actually aren't limited to breaking on a certain hit count, but you have options for a few other scenarios as well. I'll leave it to you to explore the possibilities.
• You can Set filters on the Process ID, thread ID, and machine name (select Filter from the popup menu)

### What is the (best) way to manage permissions for Docker shared volumes?

UPDATE 2016-03-02: As of Docker 1.9.0, Docker has named volumes which replace data-only containers. The answer below, as well as my linked blog post, still has value in the sense of how to think about data inside docker but consider using named volumes to implement the pattern described below rather than data containers.

I believe the canonical way to solve this is by using data-only containers. With this approach, all access to the volume data is via containers that use `-volumes-from` the data container, so the host uid/gid doesn't matter.

For example, one use case given in the documentation is backing up a data volume. To do this another container is used to do the backup via `tar`, and it too uses `-volumes-from` in order to mount the volume. So I think the key point to grok is: rather than thinking about how to get access to the data on the host with the proper permissions, think about how to do whatever you need -- backups, browsing, etc. -- via another container. The containers themselves need to use consistent uid/gids, but they don't need to map to anything on the host, thereby remaining portable.

This is relatively new for me as well but if you have a particular use case feel free to comment and I'll try to expand on the answer.

UPDATE: For the given use case in the comments, you might have an image `some/graphite` to run graphite, and an image `some/graphitedata` as the data container. So, ignoring ports and such, the `Dockerfile` of image `some/graphitedata` is something like:

``````FROM debian:jessie
# add our user and group first to make sure their IDs get assigned consistently, regardless of other deps added later
&& useradd -r -g graphite graphite
RUN mkdir -p /data/graphite \
&& chown -R graphite:graphite /data/graphite
VOLUME /data/graphite
USER graphite
CMD ["echo", "Data container for graphite"]
``````

Build and create the data container:

``````docker build -t some/graphitedata Dockerfile
docker run --name graphitedata some/graphitedata
``````

The `some/graphite` Dockerfile should also get the same uid/gids, therefore it might look something like this:

``````FROM debian:jessie
# add our user and group first to make sure their IDs get assigned consistently, regardless of other deps added later
&& useradd -r -g graphite graphite
# ... graphite installation ...
VOLUME /data/graphite
USER graphite
CMD ["/bin/graphite"]
``````

And it would be run as follows:

``````docker run --volumes-from=graphitedata some/graphite
``````

Ok, now that gives us our graphite container and associated data-only container with the correct user/group (note you could re-use the `some/graphite` container for the data container as well, overriding the entrypoing/cmd when running it, but having them as separate images IMO is clearer).

Now, lets say you want to edit something in the data folder. So rather than bind mounting the volume to the host and editing it there, create a new container to do that job. Lets call it `some/graphitetools`. Lets also create the appropriate user/group, just like the `some/graphite` image.

``````FROM debian:jessie
# add our user and group first to make sure their IDs get assigned consistently, regardless of other deps added later
&& useradd -r -g graphite graphite
VOLUME /data/graphite
USER graphite
CMD ["/bin/bash"]
``````

You could make this DRY by inheriting from `some/graphite` or `some/graphitedata` in the Dockerfile, or instead of creating a new image just re-use one of the existing ones (overriding entrypoint/cmd as necessary).

Now, you simply run:

``````docker run -ti --rm --volumes-from=graphitedata some/graphitetools
``````

and then `vi /data/graphite/whatever.txt`. This works perfectly because all the containers have the same graphite user with matching uid/gid.

Since you never mount `/data/graphite` from the host, you don't care how the host uid/gid maps to the uid/gid defined inside the `graphite` and `graphitetools` containers. Those containers can now be deployed to any host, and they will continue to work perfectly.

The neat thing about this is that `graphitetools` could have all sorts of useful utilities and scripts, that you can now also deploy in a portable manner.

UPDATE 3: I corrected this answer and added more specifics. It previously contained some incorrect assumptions about ownership and perms -- the ownership is usually assigned at volume creation time i.e. in the data container, because that is when the volume is created. See this blog. This is not a requirement though -- you can just use the data container as a "reference/handle" and set the ownership/perms in another container via chown in an entrypoint, which ends with gosu to run the command as the correct user. If anyone is interested in this approach, please comment and I can provide links to a sample using this approach.

### What file uses .md extension and how should I edit them?

The .md stands for Markdown Text. Basically, its just another type of text file, like .txt

### Completely cancel a rebase

If you are "Rebasing", "Already started rebase" which you want to cancel, just comment `(#)` all commits listed in rebase editor.

As a result you will get a command line message

``````Nothing to do
``````

### Javascript equivalent of php's strtotime()?

I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.

``````// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
``````

Go back and forth using the `subtract()` and `add()` with the `endOf()` and `startOf()`:

``````// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
``````

### Permanently add a directory to PYTHONPATH?

You could add the path via your pythonrc file, which defaults to ~/.pythonrc on linux. ie.

``````import sys
sys.path.append('/path/to/dir')
``````

You could also set the `PYTHONPATH` environment variable, in a global rc file, such `~/.profile` on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment Variables on windows.

### Is there a bash command which counts files?

Here is my one liner for this.

`````` file_count=\$( shopt -s nullglob ; set -- \$directory_to_search_inside/* ; echo \$#)
``````

### How can I change image source on click with jQuery?

You need to use `preventDefault()` to make it so the link does not go through when u click on it:

``````\$(function() {
e.preventDefault();
\$("#bg").attr('src',"img/picture1.jpg");
});
});
``````

### How to create JNDI context in Spring Boot with Embedded Tomcat Container

``````public TomcatEmbeddedServletContainerFactory tomcatFactory()
``````

I had to use the following method signature

``````public EmbeddedServletContainerFactory embeddedServletContainerFactory()
``````

### Converting string format to datetime in mm/dd/yyyy

You can change the format too by doing this

``````string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
``````

// this change the `"/"` for the `"-"`

### Loaded nib but the 'view' outlet was not set

The View Identity - Class Identity was not set. After setting it to the appropriate class, the issue was resolved.

### How do I make Git use the editor of my choice for commits?

#### For users of TextWrangler from the Mac app store:

``````git config --global core.editor "open -n -W -a TextWrangler"
``````

Also, make sure your "TextWrangler > Preferences > Application > When TextWrangler becomes active:" setting is set to "Do nothing"

This works for me on OS X 10.11.4 with TextWrangler 5.0.2 from the Mac app store.

Explanation:

The -n means open in a new instance.

The -W means to wait until the application exits before using the contents of the edited file as the commit message.

The -a TextWrangler means use the TextWrangler application to open the file.

See `man open` in your Mac Terminal app for more details.

### Jquery \$(this) Child Selector

In the click event "this" is the a tag that was clicked

``````jQuery('.class1 a').click( function() {
var divToSlide = \$(this).parent().find(".class2");
if (divToSlide.is(":hidden")) {
divToSlide.slideDown("slow");
} else {
divToSlide.slideUp();
}
});
``````

There's multiple ways to get to the div though you could also use .siblings, .next etc

### PowerShell and the -contains operator

The `-Contains` operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

From the documentation you linked to:

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

In the example you provided you're working with a collection containing just one string item.

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

Examples:

``````PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match
``````

I think what you want is the `-Match` operator:

``````"12-18" -Match "-"
``````

Which returns `True`.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the `-Match` operator uses regular expressions to perform text matching.

### Serializing to JSON in jQuery

Works on IE8+

No need for jQuery, use:

``````JSON.stringify(countries);
``````

### How to show form input fields based on select value?

``````<!DOCTYPE html>
<html>

<script>
function myfun(){

\$("#select").click(
function(){
var data=\$("#select").val();
\$("#disp").val(data);
});
});
}
</script>
<body>

<p>id <input type="text" name="user" id="disp"></p>

<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>

</body>
</html>
``````

### How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Using Firebase Console you can send message to all users based on application package.But with CURL or PHP API its not possible.

Through API You can send notification to specific device ID or subscribed users to selected topic or subscribed topic users.

``````Get a view on following link. It will help you.
``````

### How can I get a list of all classes within current module in Python?

I was able to get all I needed from the `dir` built in plus `getattr`.

``````# Works on pretty much everything, but be mindful that
# you get lists of strings back

print dir(myproject)
print dir(myproject.mymodule)
print dir(myproject.mymodule.myfile)
print dir(myproject.mymodule.myfile.myclass)

# But, the string names can be resolved with getattr, (as seen below)
``````

Though, it does come out looking like a hairball:

``````def list_supported_platforms():
"""
List supported platforms (to match sys.platform)

@Retirms:
list str: platform names
"""
return list(itertools.chain(
*list(
# Get the class's constant
getattr(
# Get the module's first class, which we wrote
getattr(
# Get the module
getattr(platforms, item),
dir(
getattr(platforms, item)
)[0]
),
'SYS_PLATFORMS'
)
# For each include in platforms/__init__.py
for item in dir(platforms)
# Ignore magic, ourselves (index.py) and a base class.
if not item.startswith('__') and item not in ['index', 'base']
)
))
``````

### Angularjs \$http.get().then and binding to a list

Promise returned from `\$http` can not be binded directly (I dont exactly know why). I'm using wrapping service that works perfectly for me:

``````.factory('DocumentsList', function(\$http, \$q){
var d = \$q.defer();
\$http.get('/DocumentsList').success(function(data){
d.resolve(data);
});
return d.promise;
});
``````

and bind to it in controller:

``````function Ctrl(\$scope, DocumentsList) {
\$scope.Documents = DocumentsList;
...
}
``````

UPDATE!:

In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises

### How do I change the data type for a column in MySQL?

If you want to change all columns of a certain type to another type, you can generate queries using a query like this:

``````select distinct concat('alter table ',
table_name,
' modify ',
column_name,
' <new datatype> ',
if(is_nullable = 'NO', ' NOT ', ''),
' NULL;')
from information_schema.columns
and column_type = '<old datatype>';
``````

For instance, if you want to change columns from `tinyint(4)` to `bit(1)`, run it like this:

``````select distinct concat('alter table ',
table_name,
' modify ',
column_name,
' bit(1) ',
if(is_nullable = 'NO', ' NOT ', ''),
' NULL;')
from information_schema.columns
where table_schema = 'MyDatabase'
and column_type = 'tinyint(4)';
``````

and get an output like this:

``````alter table table1 modify finished bit(1)  NOT  NULL;
alter table table2 modify canItBeTrue bit(1)  NOT  NULL;
alter table table3 modify canBeNull bit(1)  NULL;
``````

!! Does not keep unique constraints, but should be easily fixed with another `if`-parameter to `concat`. I'll leave it up to the reader to implement that if needed..

### How to check if a string contains text from an array of substrings in JavaScript?

Javascript function to search an array of tags or keywords using a search string or an array of search strings. (Uses ES5 some array method and ES6 arrow functions)

``````// returns true for 1 or more matches, where 'a' is an array and 'b' is a search string or an array of multiple search strings
function contains(a, b) {
// array matches
if (Array.isArray(b)) {
return b.some(x => a.indexOf(x) > -1);
}
// string match
return a.indexOf(b) > -1;
}
``````

Example usage:

``````var a = ["a","b","c","d","e"];
var b = ["a","b"];
if ( contains(a, b) ) {
// 1 or more matches found
}
``````

### How the single threaded non blocking IO model works in Node.js

Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.

That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.

So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.

Clear? :-)

I don’t know Node. But where does the c.query come from?

### Transfer data from one database to another database

1. You can backup and restore the database using Management Studio.
2. Again from Management Studio you can use "copy database".
3. you can even do it manually if there is a reason to do so. I mean manually create the target db and manually copying data by sql statements...

can you clarify why you ask this? Is it that you dont have expierience in doing it or something else?

### Using CSS :before and :after pseudo-elements with inline CSS?

you can use

``````parent.style.setProperty("--padding-top", (height*100/width).toFixed(2)+"%");
``````

in css

``````el:after{
....
}
``````

### Encrypt & Decrypt using PyCrypto AES 256

For the benefit of others, here is my decryption implementation which I got to by combining the answers of @Cyril and @Marcus. This assumes that this coming in via HTTP Request with the encryptedText quoted and base64 encoded.

``````import base64
import urllib2
from Crypto.Cipher import AES

def decrypt(quotedEncodedEncrypted):
key = 'SecretKey'

encodedEncrypted = urllib2.unquote(quotedEncodedEncrypted)

cipher = AES.new(key)
decrypted = cipher.decrypt(base64.b64decode(encodedEncrypted))[:16]

for i in range(1, len(base64.b64decode(encodedEncrypted))/16):
cipher = AES.new(key, AES.MODE_CBC, base64.b64decode(encodedEncrypted)[(i-1)*16:i*16])
decrypted += cipher.decrypt(base64.b64decode(encodedEncrypted)[i*16:])[:16]

return decrypted.strip()
``````

### How to convert ZonedDateTime to Date?

If you are using the ThreeTen backport for Android and can't use the newer `Date.from(Instant instant)` (which requires minimum of API 26) you can use:

``````ZonedDateTime zdt = ZonedDateTime.now();
Date date = new Date(zdt.toInstant().toEpochMilli());
``````

or:

``````Date date = DateTimeUtils.toDate(zdt.toInstant());
``````

### How to subtract X days from a date using Java calendar?

Taken from the docs here:

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:

``````Calendar calendar = Calendar.getInstance(); // this would default to now
``````

### What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

``````<table border="1px">

<tr>
<th>Student Name</th>
<th>Email</th>
</tr>

<?php

If(mysql_num_rows(\$result)>0)
{
while(\$rows=mysql_fetch_array(\$result))
{

?>
<?php echo "<tr>";?>
<td><?php echo \$rows['email'];?></td>

<?php echo "</tr>";?>
<?php
}
}

?>
</table>
<?php
}
?>
``````

### Fetch frame count with ffmpeg

You can use `ffprobe` to get frame number with the following commands

1. first method

`ffprobe.exe -i video_name -print_format json -loglevel fatal -show_streams -count_frames -select_streams v`

which tell to print data in `json` format

`select_streams v` will tell `ffprobe` to just give us `video` stream data and if you remove it, it will give you `audio` information as well

and the output will be like

``````{
"streams": [
{
"index": 0,
"codec_name": "mpeg4",
"codec_long_name": "MPEG-4 part 2",
"profile": "Simple Profile",
"codec_type": "video",
"codec_time_base": "1/25",
"codec_tag_string": "mp4v",
"codec_tag": "0x7634706d",
"width": 640,
"height": 480,
"coded_width": 640,
"coded_height": 480,
"has_b_frames": 1,
"sample_aspect_ratio": "1:1",
"display_aspect_ratio": "4:3",
"pix_fmt": "yuv420p",
"level": 1,
"chroma_location": "left",
"refs": 1,
"quarter_sample": "0",
"divx_packed": "0",
"r_frame_rate": "10/1",
"avg_frame_rate": "10/1",
"time_base": "1/3000",
"start_pts": 0,
"start_time": "0:00:00.000000",
"duration_ts": 256500,
"duration": "0:01:25.500000",
"bit_rate": "261.816000 Kbit/s",
"nb_frames": "855",
"disposition": {
"default": 1,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0
},
"tags": {
"creation_time": "2005-10-17 22:54:33",
"language": "eng",
"handler_name": "Apple Video Media Handler",
"encoder": "3ivx D4 4.5.1"
}
}
]
}
``````

2. you can use

``````ffprobe -v error -show_format -show_streams video_name
``````

which will give you stream data, if you want selected information like frame rate, use the following command

``````ffprobe -v error -select_streams v:0 -show_entries stream=avg_frame_rate -of default=noprint_wrappers=1:nokey=1 video_name
``````

which give a number base on your video information, the problem is when you use this method, its possible you get a `N/A` as output.

### JFrame: How to disable window resizing?

it's easy to use:

``````frame.setResizable(false);
``````

In XML Drawable File:

``````<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
android:endColor="#9b0493"
android:startColor="#38068f"
android:type="linear" />
</shape>
</item>
</selector>
``````

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

</LinearLayout>
``````

### SMTP connect() failed PHPmailer - PHP

`````` \$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
``````

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

• .py - Regular script
• .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
• .pyc - compiled script (Bytecode)
• .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
• .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
• .pyx - Cython src to be converted to C/C++
• .pyd - Python script made as a Windows DLL
• .pxd - Cython script which is equivalent to a C/C++ header
• .pxi - MyPy stub
• .pyi - Stub file (PEP 484)
• .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
• .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
• .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
• .pth - a path configuration file; its contents are additional items (one per line) to be added to `sys.path`. See `site` module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

### E: Unable to locate package mongodb-org

All steps are correct just change the Step 4 as below

• Step 4: Install the last stable MongoDB version and all the necessary packages on our system

Command: `sudo apt-get install mongodb`

It has worked for me.

### What is the difference between loose coupling and tight coupling in the object oriented paradigm?

There are certain tools that provide dependency injection through their library, for example in .net we have ninject Library .

If you are going further in java then spring provides this capabilities.

Loosly coupled objects can be made by introducing Interfaces in your code, thats what these sources do.

Say in your code you are writing

``````Myclass m = new Myclass();
``````

now this statement in your method says that you are dependent on `myclass` this is called a tightly coupled. Now you provide some constructor injection , or property injection and instantiating object then it will become loosly coupled.

### Convert string to date in bash

date only work with GNU date (usually comes with Linux)

for OS X, two choices:

1. change command (verified)

``````#!/bin/sh
#DATE=20090801204150
#date -jf "%Y%m%d%H%M%S" \$DATE "+date \"%A,%_d %B %Y %H:%M:%S\""
date "Saturday, 1 August 2009 20:41:50"
``````

http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html

### hidden field in php

Yes, you can access it through `GET` and `POST` (trying this simple task would have made you aware of that).

Yes, there are other ways, one of the other "preferred" ways is using sessions. When you would want to use hidden over session is kind of touchy, but any GET / POST data is easily manipulated by the end user. A session is a bit more secure given it is saved to a file on the server and it is much harder for the end user to manipulate without access through the program.

### How to add an image in Tkinter?

This code works for me, also you should consider if you have any other button or labels in that window and you not use `.place()` it will not work properly.

``````from Tkinter import*
from PIL import Image, ImageTk

img  = Image.open("path/x.png")
photo=ImageTk.PhotoImage(img)
lab=Label(image=photo).place(x=50,y=50)
``````

### SELECT INTO a table variable in T-SQL

The purpose of `SELECT INTO` is (per the docs, my emphasis)

To create a new table from values in another table

But you already have a target table! So what you want is

The `INSERT` statement adds one or more new rows to a table

You can specify the data values in the following ways:

...

By using a `SELECT` subquery to specify the data values for one or more rows, such as:

``````  INSERT INTO MyTable
(PriKey, Description)
SELECT ForeignKey, Description
FROM SomeView
``````

And in this syntax, it's allowed for `MyTable` to be a table variable.

### InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

I faced the same issue. Tried adding the `US_export_policy.jar` and `local_policy.jar` in the java security folder first but the issue persisted. Then added the below in `java_opts` inside tomcat `setenv.sh`file and it worked.

``````-Djdk.tls.ephemeralDHKeySize=2048
``````

### How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

Network debugging requires Xcode 9.0 or later running on macOS 10.12.4 or later, and on the device, requires iOS 11.0 or later, or tvOS 11.0 or later.

iPhone

iOS 11 won't be available for 32bit devices, i.e. iPhone 5 and iPhone 5c and below. The first 64bit iPhone is 5s.

iPad mini 2 will be the oldest iPad with iOS 11 support.

iPod

iPod needs to be an iPod 6 to be able to run iOS.

If you use your devices not only for developing but also for production, be warned that a beta OS is not for the faint hearted ;-)

### Can't install any packages in Node.js using "npm install"

I found the there is a certificate expired issue with:

``````npm set registry https://registry.npmjs.org/
``````

So I made it http, not https :-

``````npm set registry http://registry.npmjs.org/
``````

And have no problems so far.

### How to convert an Object {} to an Array [] of key-value pairs in JavaScript

This is my simple barebone implementation:

``````let obj = {
"1": 5,
"2": 7,
"3": 0,
"4": 0,
"5": 0,
"6": 0,
"7": 0,
"8": 0,
"9": 0,
"10": 0,
"11": 0,
"12": 0
};

const objectToArray = obj => {
let sol = [];
for (key in obj) {
sol.push([key, obj[key]]);
}
return sol;
};

objectToArray(obj)
``````

### how to setup ssh keys for jenkins to publish via ssh

For Windows:

1. Install the necessary plugins for the repository (ex: GitHub install GitHub and GitHub Authentication plugins) in Jenkins.
2. You can generate a key with Putty key generator, or by running the following command in git bash: `\$ ssh-keygen -t rsa -b 4096 -C [email protected]`
3. Private key must be OpenSSH. You can convert your private key to OpenSSH in putty key generator
4. SSH keys come in pairs, public and private. Public keys are inserted in the repository to be cloned. Private keys are saved as credentials in Jenkins
5. You need to copy the SSH URL not the HTTPS to work with ssh keys.

### Codeigniter - multiple database connections

While looking at your code, the only thing I see wrong, is when you try to load the second database:

``````\$DB2=\$this->load->database(\$config);
``````

When you want to retrieve the database object, you have to pass TRUE in the second argument.

From the Codeigniter User Guide:

By setting the second parameter to TRUE (boolean) the function will return the database object.

``````\$DB2=\$this->load->database(\$config, TRUE);
``````

That will make it work.

### if-else statement inside jsx: ReactJS

Just Tried that:

``````return(
<>
{
main-condition-1 &&
main-condition-2 &&
(sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
}
</>
)
``````

Let me know what you guys think!!!

### Position DIV relative to another DIV?

First set `position` of the parent DIV to `relative` (specifying the offset, i.e. `left`, `top` etc. is not necessary) and then apply `position: absolute` to the child DIV with the offset you want.
It's simple and should do the trick well.

### How can I disable an <option> in a <select> based on its value in JavaScript?

#### Pure Javascript

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

``````// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
``````

Without enabling non-targeted elements:

``````// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
``````

#### jQuery

With jQuery you can do this with a single line:

``````\$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
``````

Without enabling non-targeted elements:

``````\$("option[value='stackoverflow']").attr("disabled", "disabled");
``````

? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

``````\$("option").each(function(){
if (\$(this).val().toLowerCase() == "stackoverflow") {
\$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
``````

Without enabling non-targeted elements:

``````\$("option").each(function(){
if (\$(this).val().toLowerCase() == "stackoverflow") {
\$(this).attr("disabled", "disabled");
}
});
``````

### How to do a less than or equal to filter in Django queryset?

Less than or equal:

``````User.objects.filter(userprofile__level__lte=0)
``````

Greater than or equal:

``````User.objects.filter(userprofile__level__gte=0)
``````

Likewise, `lt` for less than and `gt` for greater than. You can find them all in the documentation.

### select from one table, insert into another table oracle sql query

From the oracle documentation, the below query explains it better

``````INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
``````

Your query would be as follows

``````//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
``````

Note: Make sure the columns in insert and select are in right position as per your requirement

Hope this helps!

### get unique machine id

Check out this article. It is very exhaustive and you will find how to extract various hardware information.

Quote from the article:

To get hardware information, you need to create an object of ManagementObjectSearcher class.

``````using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
foreach (ManagementObject share in searcher.Get()) {
// Some Codes ...
}
``````

The Key on the code above, is a variable that is replaced with appropriate data. For example, to get the information of the CPU, you have to replace the Key with Win32_Processor.

### Is it possible to decompile a compiled .pyc file into a .py file?

Yes, it is possible.

There is a perfect open-source Python (.PYC) decompiler, called Decompyle++ https://github.com/zrax/pycdc/

Decompyle++ aims to translate compiled Python byte-code back into valid and human-readable Python source code. While other projects have achieved this with varied success, Decompyle++ is unique in that it seeks to support byte-code from any version of Python.

### Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

Do just simple thing:

1. Open git-hub (Shell) and navigate to the directory file belongs to (cd /a/b/c/...)
2. Execute dos2unix (sometime dos2unix.exe)
3. Try commit now. If you get same error again. Perform all above steps except instead of dos2unix, do unix2dox (unix2dos.exe sometime)

### com.apple.WebKit.WebContent drops 113 error: Could not find specified service

Mine was different again. I was setting the user-agent like so:

``````    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
``````

This was causing something on the web page to freak out and leak memory. Not sure why but removing this sorted the issue for me.

### Python, compute list difference

Adding an answer to take care of the case where we want a strict difference with repetitions, i.e., there are repetitions in the first list that we want to keep in the result. e.g. to get,

``````[1, 1, 1, 2] - [1, 1] --> [1, 2]
``````

We could use an additional counter to have an elegant difference function.

``````from collections import Counter

def diff(first, second):
secondCntr = Counter(second)
second = set(second)
res = []
for i in first:
if i not in second:
res.append(i)
elif i in secondCntr:
if secondCntr[i] > 0:
secondCntr[i] -= 1
else:
res.append(i)
return res
``````

### JavaFX and OpenJDK

Where can I get pre-built JavaFX libraries for OpenJDK (Windows)

On Linux its not really a problem, but on Windows its not that easy, especially if you want to distribute the JRE.

You can actually use OpenJFX with OpenJDK 8 on windows, you just have to assemble it yourself:

copy all the files from the OpenFX zip on top of the JDK, voila, you have an OpenJDK with JavaFX.

Update:

### java.net.SocketException: Software caused connection abort: recv failed

This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.

### Hex colors: Numeric representation for "transparent"?

Very simple: no color, no opacity:

``````rgba(0, 0, 0, 0);
``````

### SQL - Rounding off to 2 decimal places

What ever you use in denomination should be in decimal, for example `1548/100` will give `15.00`

If we replace `100` with `100.0` in our example the we will get `15.48`

``````select 1548/100
15.00000

select 1548/100.0
15.4800

0
``````

### org.hibernate.MappingException: Could not determine type for: java.util.Set

Adding the `@ElementCollection` to the List field solved this issue:

``````@Column
@ElementCollection(targetClass=Integer.class)
private List<Integer> countries;
``````

### ASP.NET MVC: What is the purpose of @section?

`@section` is for defining a content are override from a shared view. Basically, it is a way for you to adjust your shared view (similar to a Master Page in Web Forms).

You might find Scott Gu's write up on this very interesting.

Edit: Based on additional question clarification

The `@RenderSection` syntax goes into the Shared View, such as:

``````<div id="sidebar">
@RenderSection("Sidebar", required: false)
</div>
``````

This would then be placed in your view with `@Section` syntax:

``````@section Sidebar{
<!-- Content Here -->
}
``````

In MVC3+ you can either define the Layout file to be used for the view directly or you can have a default view for all views.

Common view settings can be set in _ViewStart.cshtml which defines the default layout view similar to this:

``````@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
``````

You can also set the Shared View to use directly in the file, such as index.cshtml directly as shown in this snippet.

``````@{
ViewBag.Title = "Corporate Homepage";
ViewBag.BodyID = "page-home";
Layout = "~/Views/Shared/_Layout2.cshtml";
}
``````

There are a variety of ways you can adjust this setting with a few more mentioned in this SO answer.

### javascript compare strings without being case sensitive

You can also use string.match().

``````var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}
``````

### Iterate over elements of List and Map using JSTL <c:forEach> tag

Suppose `\${list}` points to a `List<Object>`, then the following

``````<c:forEach items="\${list}" var="item">
\${item}<br>
</c:forEach>
``````

does basically the same as as following in "normal Java":

``````for (Object item : list) {
System.out.println(item);
}
``````

If you have a `List<Map<K, V>>` instead, then the following

``````<c:forEach items="\${list}" var="map">
<c:forEach items="\${map}" var="entry">
\${entry.key}<br>
\${entry.value}<br>
</c:forEach>
</c:forEach>
``````

does basically the same as as following in "normal Java":

``````for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
``````

The `key` and `value` are here not special methods or so. They are actually getter methods of `Map.Entry` object (click at the blue `Map.Entry` link to see the API doc). In EL (Expression Language) you can use the `.` dot operator to access getter methods using "property name" (the getter method name without the `get` prefix), all just according the Javabean specification.

### How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that the best solution currently for springBoot 2.0 is using profiles

``````@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
public class ExcludeAutoConfigIntegrationTest {
// ...
}
``````

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

anyway in the following link give 6 different alternatives to solve this.

### Reset textbox value in javascript

Try using this:

``````\$('#searchField').val('');
``````