text:
Q: Prove that a continuous function on open sets is continuous on their union. I have a function between two metric spaces $f: (X,d_1) \to (Y,d_2)$ such that if $$X=\bigcup_{i=1}^n U_i$$ for $U_i$ open sets in $X$, $f$ is continuous on each $U_i$.
Prove $f$ is continuous on $X$.
My approach, take a family of open sets $V_i \in Y$ then since $f$ is continuous on each $U_n$ then $$f^{-1} (V_i)$$ is open in $U_i$ for each $i \in \{1,...n\}$.
So $$f^{-1} \left( \bigcup_{i=1}^n V_i \right) = \bigcup_{i=1}^n f^{-1} ( V_i)$$
Since all $f^{-1} (V_i)$ are open then their union is also open.
Is this proof correct?
What troubles me is the fact that I didn't use the fact that $U_i$ are open, so this argument could also prove the result even if $U_i$ were not open. So I think I made a mistake somewhere.


text:
Q: What kind of encoding is this (sha256 variant)? I have some config files from the program ELOG where I want to change the password manually, using something like echo -n "newpassword" | sha256sum but the value is not the expected hexa. Here's an extract from one such files:
<password encoding="SHA256">vyk1C6u3pcdfTIlvEFSdjvHBiymJBxUuvcZj3BR5Ol/</password>

What command can I use to generate a correct hash? This is not in the correct format:
$ echo -n "newpassword" | sha256sum
089542505d659cecbb988bb5ccff5bccf85be2dfa8c221359079aee2531298bb  -

The password toto gives the hash bfvea3iDok9C0ptb022ndR2uWZUq0BIOH.cVQvSOMUA

A: It's raw SHA256 encoded with something base64-ish. The length matches base64 of 32 bytes without padding.
SHA256 produces a string of 32 bytes. This string is usually represented in the hexadecimal format (as 64 characters [0-9a-f]), but it's not a requirement. One may choose to use a different encoding to make the produced string shorter.
Base64 can encode any string of 8-bit bytes into a string that can be represented with ASCII characters with just 33% of length overhead (compared to 100% of overhead for hexadecimal).
Base64 is quite straightforward: it first converts the string of 8-bit bytes into bits, then splits this string into 6-bit bytes. These 6-bit bytes are then represented using a fixed alphabet consisting of, in this order:

*

*uppercase letters A-Z (26 values 000000..011001)

*lowercase letters a-z (26 values 011010..110011)

*digits 0-9 (10 values 110100..111101)

*characters + and / (111110, 111111)

for a total of 64 characters to represent all possible values of a 6-bit byte. The resulting string is padded with one or two = characters so that string length is a multiple of 4. Many implementations don't require the padding for decoding because it doesn't carry any information.
Your example hashes are 43 characters long. That length matches the length of non-padded base64 of a 32-byte string.

But it's not so simple with ELOG! By looking at the source code you'll find that it uses a different base64 alphabet:

*

*characters . and /

*digits 0-9

*uppercase letters A-Z

*lowercase letters a-z
This difference could be easily worked around by using tr to map these alphabets. But even then results don't match yet. In your example, the string toto produces the hash bfvea3iDok9C0ptb022ndR2uWZUq0BIOH.cVQvSOMUA. Note the two consecutive identical characters:
bfvea3iDok9C0ptb022ndR2uWZUq0BIOH.cVQvSOMUA
                 ^^

The string toto encoded with the 'regular' SHA256+base64 doesn't have these:
$ echo -n toto | sha256 | base64
MfemXjFVhqwZi9eYtmKc5JA9CJlHbVdBqfMuLlIbamY=
                 ^^

A simple translation preserves similarity, so there must be something else at play here.
@KamilMaciorowski suggested in comments that some salt may be involved. A cryptographic salt is a randomized per-user string stored in plaintext that's appended to password before hashing so that identical passwords used by different users produce different hashes.
You can dive deeper into the code to figure out if the salt is used and how.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Group downloads by originating domain Can I automatically group downloads by domain (e.g. place it in corresponding folders inside Downloads directory)? I'm using Google Chrome and looks like it must be done by some sort of download manager.

*

*If this can be achieved with Chrome alone, how to do it?

*If not, what the best program for this task?

A: If you switch to Firefox, you can use DownThemAll, but they have no plans of porting to Chrome :(


text:
Q: Is there good way to get title tag of some other domain page using Javascript? Like this :
If I'm using jQuery:
    $.ajax({
        url:'https://www.google.com',
        //some other domain like 'https://facebook.com', Not of my domain that I can control.
        type:'get',
        dataType:'html',
        cache:false,
        success:function (data) {
            var headline = data;
            alert(data);
            $('#div_test').html(data.get_title_tag)
        }
    });

Let me say target url : http://example.com
I googled for a day, and found these.

*

*Iframe

Is it possible, if http://example.com does not allow Iframe access?
As I searched, It's impossible when http://example.com does not allows Iframe access.

*Server control

I post http://example.com url data to my server on my url_post_page, and server will do url request stuff, and return data to my url_post_page.
Question :
But I want to get <title>title</title> value of http://example.com just on client using Javascript or jQuery.
Is there any good way of this things?


text:
Q: How to split a string in two substrings of same length using bash? I would like to split a string into two halves and print them sequentially. For example:
abcdef

into
abc
def

Is there a simple way to do it, or it needs some string processing?

A: Using split, here strings and command substitution:
var=abcdef
printf '%s\n' "$(split -n1/2 <<<$var)" "$(split -n2/2 <<<$var)"

A: Another awk script can be:
echo abcdef | awk '{print substr($0,1,length/2); print substr($0,length/2+1)}'

A: Using parameter expansion and shell arithmetic:
The first half of the variable will be:
${var:0:${#var}/2}

The second half of the variable will be:
${var:${#var}/2}

so you could use:
printf '%s\n' "${var:0:${#var}/2}" "${var:${#var}/2}"

You could also use the following awk command:
awk 'BEGIN{FS=""}{for(i=1;i<=NF/2;i++)printf $i}{printf "\n"}{for(i=NF/2+1;i<=NF;i++){printf $i}{printf "\n"}}'

$ echo abcdef | awk 'BEGIN{FS=""}{for(i=1;i<=NF/2;i++)printf $i}{printf "\n"}{for(i=NF/2+1;i<=NF;i++){printf $i}{printf "\n"}}'
abc
def

A: Python 3
s = input()  # Take one line of input from stdin.
x = len(s) // 2  # Get middle of string. "//" is floor division
print(s[:x], s[x:], sep="\n")  # Print "s" up to "x", then "s" past "x", joined on newlines.

For example,
$ echo abcdef | python3 -c 's = input(); x = len(s) // 2; print(s[:x], s[x:], sep="\n")'
abc
def

If the string length is not an even number, the second line will be longer. E.g.
$ echo abcdefg | python3 -c 's = input(); x= len(s) // 2; print(s[:x], s[x:], sep="\n")'
abc
defg


text:
Q: How do I log failed MediaWiki login attempts? I cannot find a MediaWiki hook event for a failed login attempt. Does one exist? If not, does anyone know of a strategy for determining failed attempts?
In case there is another way - I am trying to log failed logins.
EDIT
Here is the pertinent bit of my code, the globals are set to the name of the wiki (I also tried the code offered in the comments):
$wgHooks['AuthManagerLoginAuthenticateAudit'][] = 'logAuth';
function logAuth($response, $user, $username)
{
    // grab the MediaWiki global vars
    global $fail2banfile;
    global $fail2banid;

    //set vars to log
    $time = date("Y-m-d H:i:s T");
    $ip = $_SERVER['REMOTE_ADDR'];

    //successful login
    if ($response->status == "PASS") {
        error_log("$time Successful login by $username from $ip on   $fail2banid\n", 3, $fail2banfile);
        return true; //continue to next hook
    } else {
        error_log("$time Authentication error by $username from $ip on $fail2banid\n", 3, $fail2banfile);
        return true; //continue to next hook
    }

The above logs successful logins, and failed logins by registered users. Login attempts by unregistered usernames are not logged. I am using the logs with Fail2Ban.

A: Use the AuthManagerLoginAuthenticateAudit hook. E.g.
use MediaWiki\Auth\AuthManager;
use MediaWiki\Auth\AuthenticationResponse;

$wgHooks['AuthManagerLoginAuthenticateAudit'][] = function ( $response, $user, $username ) {
    if ( $response->status === AuthenticationResponse::FAIL ) {
        log( "Failed login for user $username" );
    }
};

To catch some cases which the above hook wouldn't, you can create a logging provider:
use MediaWiki\Auth\AbstractPreAuthenticationProvider;
use MediaWiki\Auth\AuthenticationResponse;

class LoggingAuthenticationProvider extends AbstractPreAuthenticationProvider {
    public function postAuthentication( $user, AuthenticationResponse $response ) {
        if ( $response->status === AuthenticationResponse::FAIL && $user ) {
            log( 'Failed login for user ' . $user->getName() );
        }
    }
}

$wgAuthManagerAutoConfig['preauth'][LoggingAuthenticationProvider::class] = [
    'class' => LoggingAuthenticationProvider::class,
];


text:
Q: d3 Undefined Error When Using R2D3 in IE8 I am attempting to use R2D3 to support SVG elements in IE8.  I know, tell people not to use IE8 but in this case it's out of my control (i.e., corporate).  So, I've included d3 as follows in my Head:
<!DOCTYPE html>
<?php include("getUsers.php");?>
<!--[if lt IE 7]>
<html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>
<html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>
<html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>DRED</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->

<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->

<script src="js/vendor/modernizr-2.6.2.min.js"></script>

<script src="sizzle/src/sizzle.js"></script>

<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script src="js/bootstrap.min.js"></script>

<!-- Bootstrap -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/jquery-ui.css"/>
<link href="style.css" rel="stylesheet">

<!--[if lte IE 8]>
<script src="r2d3/inst/_js/r2d3.js" charset="utf-8"></script>
<![endif]-->

<!--[if gte IE 9]>
<script charset="utf-8" src="r2d3/inst/_js/d3.v2.min.js"></script>
<![endif]-->

<script src="js/script.js"></script>

This is with the version of d3 provided with R2D3 but I have also tried with the regular d3 version with no change in results.
As soon as my javascript (js/script.js) hits the following line it throws an error in IE8: 'd3' is undefined
div = d3.select("body").append("div")
    .attr("class","tooltip")
    .style("opacity",0);

Any advice would be very much appreciated.


text:
Q: Is it possibly for JEST mocks to be overwritten by each other? I have two tests that look something like:
import someThing from '../someThing';
jest.mock('../someThing');

describe('group', () => {
    it('test #1', async () => {
        someThing.someFunction.mockImplementation(() => 123);
    });
    it('test #2', async () => {
        someThing.someFunction.mockImplementation(() => 456);
    });
});

I'm seeing an issue where it appears the mockImplementation from the first test is being called in the second test. If I disable test #1 test# 2 works as expected. (My actual code is more complicated than this).
The reason I need a separate mock for both is that one is supposed to return a failure result and one is supposed to return a success one given the same input.
From what I understand, JEST runs all test in parallel so I'm assuming what's happening is that the mockImplementation is being modified by both tests at the same time as it's the same import.

A: It's virtually never desired for tests to affect each other.
As a rule of thumb, Jest spies need to be restored to original state between tests:
beforeEach(() => {
  jest.restoreAllMocks();
  jest.clearAllMocks();
});

Or preferably applied to all tests unconditionally with Jest restoreMocks and clearMocks configuration options.
Not doing this results in test cross-contamination.
A workaround is to use *Once methods, as another answer describes. When used together with *restore*, they are only needed for sequential mocks within a single test.

From what I understand, JEST runs all test in parallel

Jest runs test files in parallel. As for single tests, this isn't the case, unless concurrent tests are in use.

A: From the Mock Implementations docs:

The mockImplementation method is useful when you need to define the default implementation of a mock function that is created from another module

When you need to recreate a complex behavior of a mock function such that multiple function calls produce different results, use the mockImplementationOnce method

For your case:
import someThing from '../someThing';
jest.mock('../someThing');

describe('group', () => {
    it('test #1', async () => {
        someThing.someFunction.mockImplementationOnce(() => 123);
    });
    it('test #2', async () => {
        someThing.someFunction.mockImplementationOnce(() => 456);
    });
});


text: Q: EJB 2.0 myql connector jar is not bundled in the final jar In my EJB 2.0 project, when I try to invoke a method(with code to make jdbc connection) from client, the ClassNotFoundException is encountered for mysql driver even I have added mysqlconnector jar.


text:
Q: Git Pull command in shell script without having to enter password manually? I need a way off avoiding entering my password manually when a git pull command is executed in a build script I have.
I have tried the ssh keygen method and the git credentials caching method but both of them do not work for me.
So is there any way of somehow storing the password in the shell script somewhere, so the password prompt just uses the stored password, instead of waiting for me to enter the password explicitly and hitting enter.
Thanks guys.

A: I really think that you should fix the process git ssh keys, but if you really want to automate something, you can always use expect:
/usr/bin/expect <<EOD
spawn git pull
expect "password:"
send "this_is_my_password_unsafely_stored_in_a_bash_script\r"
interact
EOD

A: git config --global credential.helper "cache --timeout=2400"

You can change timeout value according to your need.
Also see: Is there a way to skip password typing when using https:// on GitHub?


text:
Q: How can I create multiple Git repo in Openshift I am trying to use OpenShift to deploy my application.
But it's split up into multiple maven projects and I was looking to get repos corresponding to them. Is it possible to do?


text:
Q: Uniformly continuous derivative Let $f:[a,b)\to\mathbb{R}$ be a differentiable function such that $f$ and $f'$ are uniformly continuous in $(a,b)$. Is it true then that $f'$ is continuous at a?
Note: By $f'(a)$ I mean $\lim_{h\to0^{+}}\frac{f(a+h)-f(a)}{h}$.

A: Hints:
(1)    Show that $f'(x_n)$ is a Cauchy sequence when $x_n \to a+$. Show $\lim_{x \to a+} f'(x) = L $ exists uniquely.
(2) Use the mean value theorem
$$ \frac{f(x+h) - f(x)}{h} = f'(\xi)$$


text:
Q: Google Admin SDK - add group to another group using Java client API I can add a member to a Google Group like this:
directory.members().insert(<groupKey>, <member>).execute()

If I want to add a group to the group instead of a member, how do I do it? I can retrieve a Group reference like this:
Group myGroup = directory.groups().get(myGroupKey).execute();

... so how do I add it to a specified group?


text:
Q: Создать запрос в nginx Можно ли в nginx создать запрос?
Имеются два модуля nginx: один работает с веб-сокетами, а второй с базой данных постгрес.
Чтобы отправить сообщение в веб-сокет - надо выполнить запрос на определённый location (первого модуля)
Второй же модуль может получать от базы асинхронные уведомления (listen/notify)
И теперь надо как-то при получении асинхронного уведомления во втором модуле как-то создать запрос, который вызовет location первого модуля, чтобы тот отправил данные в веб-сокет
Можно ли это как-то сделать? В какую сторону копать?


text:
Q: How to handle this situatiuon in Perl I am having a configuration INI file to store all configuration required for my script to run. I have a Logger.PM which uses Log4Perl, and ConfigReader.PM which reads the INI file and stores the value in global variable. My Start.PL is the entry point where i call the methods from Logger and configreader.
What I do currently

*

*In Start.PL I hardcoded the INI file path

*In Logger.Pm I harcoded the directory name where log files should be stored

What I want

*

*I want the INI file path as configurable

*I want the log folder path to be taken from the INI file

I could do this by following

*

*Pass the INI file path as a parameter to the start.pl

*Read the INI file and get the folder path from INI file

What I could face is that

*

*I cannot use the Logger.PM in ConfigReader (partially) since the
folder name required for logger is part of INI file

I want to log every step of my script (for logging/debugging purpose in case of failure. )
I can use print but this will write to console and to capture i need to use >>log.txt. Then i will be forced to maintain 2 logs for my application which is not what I wanted
Anyone have a good solution for this scenario?

A: You can pass INI file path in command line using Getopt::Long, and command line switches for istance:
Start.pl --ini=/path/to/INI_file

Here is a code sample to show what changes are needed in Start.pl, in order to have switches:
#!/usr/bin/env perl

use v5.12;
use strict;

use Getopt::Long;

# That little tiny 's' after 'ini=' is for string
GetOptions ( 'ini=s' => \my $ini_file );

say $ini_file;

After this change, you can read all options from your INI file, including log folder path ( are you already using a module to manage INI files like Config::IniFiles? ).
There is something still unclear in your question about print: although one of my master said that print with a pair of square brackets is the best debugger in the world, why use print when you have set up Log::Log4perl?
When you say that Logger.PL can't be used in ConfigReader, are you referring to the log object?


text:
Q: I want disable Log-in time button. I want to disable Login time button. When again click on Logout time button that time i want enable the lo-gin button. If page refresh i won't enable login time button(when he already print login time). how can do this through jquery ajax. or Server side. I tried through java script but when i refresh the page again it's going to work.
function submitForm(form) {
    alert("submitted");
}

$('#logintime').click(function(e) {
    this.disabled = true;
});

$('#form').submit(function(e) {
    submitForm(this);
});

But i need when i click on log Out time then only i want enable the login time button.

A: $('#logintime').click(function(e) {
  $(this).attr('disabled','disabled');
});


text:
Q: Python coverage.py exclude_lines Background
I have a couple Django projects that I use coverage.py with and have been trying to add some additional expressions to the exclude_lines portion of my .coveragerc configuration file. The problem is that even with proper regex that works at picking up the line in a tester such as http://www.pythonregex.com or http://www.regexr.com it doesn't result in the lines being ignored in the report.
I've reviewed the docs and poked around the repository but haven't been able to dig up any reasoning to why the config I have might not be working. From the docs it appears I have the config exactly as they describe it should be.
I've also attempted to use django-nose version 1.2, the last PyPI release, which would allow exception injection but to no avail, it appears to have some issues with figuring out the coverage of Django views and Django REST Framework API endpoints at least in version 1.7.
What I've Tried
My configuration is as follows:
[run]
branch = True
omit =
    */tests*
    */migrations/*
    *__init__.py*
    */settings/*
    *wsgi.py*
    *admin.py*

[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    pragma: no cover
    def __repr__
    if self.debug:
    raise AssertionError
    raise NotImplementedError
    (.*)except Exception as e:(.*)
    if 0:
    if __name__ == .__main__.:

I've also tried the following combinations for the exception handling in the report section of the config:
(.*)except Exception as e:
except Exception as e:
except Exception as e:(.*)

An example of a function with the portion of code I expect to be ignored is below:
def my_func():
    try:
        # Some logic
        return True
    except Exception as e:
        return defensive_exception(my_func.__name__, e, False)

In the above example, based on the documentation, I would expect everything under the except Exception as e: to be ignored or at least the except Exception as e line itself. However this doesn't appear to be the case. If anyone has some insight into what is wrong with my configuration or what I need to do differently I would greatly appreciate the help.

A: What I always do is use pragma: no cover for this which you already have in your exclude_lines.
def my_func():
    try:
        # Some logic
        return True
    except Exception as e:  # pragma: no cover
        return defensive_exception(my_func.__name__, e, False)

A: You do not need to match the entire line, so there is no need for the dot-stars at the end.  This should work:
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    pragma: no cover
    def __repr__
    if self.debug:
    raise AssertionError
    raise NotImplementedError
    except Exception as e:

THAT SAID: this style of coding concerns me a great deal.  Catching blanket exceptions as you are doing is bad style and can hide problems.  Then you seem to not care if that code is tested!
If you need to perform strong exception handling across a large number of functions like this, perhaps you want to write a function decorator to wrap the function call.  That will reduce the number of lines of code, and centralize your logic.  Then you can deal with the coverage issues in one place also.


text:
Q: wkhtmltopdf in Rails3 works on Mac, but failed on Ubuntu Error message:
command failed: /home/ubuntu/Circle/vendor/bin/wkhtmltopdf --encoding UTF-8 --print-media-type --page-size A4 --margin-top 0.8in --margin-right 0.5in --margin-bottom 0.8in --margin-left 0.5in --footer-font-size 10 --header-line --header-spacing 5 --footer-spacing 5 --header-right Powered\ by\ ctquan.com --footer-center \[page\] --header-center Elite\ English\ Circle --quiet - -

It works on Mac OSX, but fails on Linux of both development and production environment.

A: I solved the problem myself with a tricky method.
Edit config/initializers/pdfkit.rb like this:
PDFKit.configure do |config|
  config.wkhtmltopdf = `which wkhtmltopdf`.gsub!(/\s/, '')
end

Anyway, it depends on a binary wkhtmltopdf, so add gem 'wkhtmltopdf-binary' in Gemfile. In this way, we will have a binary wkhtmltopdf in rvm. And bundle install will solve the problem of the dependency. There's no need to install an independent wkhtmltopdf instance.
So that Rails server can find wkhtmltopdf with the absolute path now, and everything works.


text:
Q: How to get product links I am trying to fetch the product links for a product, but all return as null or zero. Even though, the product links are shown on the admin UI.
1: Use ProductLinkRepositoryInterface
    $prdRepo = $this->objectManager->create('Magento\Catalog\Api\ProductLinkRepositoryInterface');
    if ($prdRepo) {
        $links = $prdRepo->getList($product);
        //This output as 0
        echo 'links='; echo count($links); echo PHP_EOL;
    }

2: Use ProductInterface, getProductLinks() method
$productLinks = $product->getProductLinks();

These two ways return 0.
I am not sure if it is the correct way to fetch the product links.


text:
Q: Python Pandas - Strip Out Non-Numeric Characters and Spaces If I have a pandas dataframe with column header "Name" and three rows (as below), how do I write a function to change the entries of "Name" such that all non-numeric characters, spaces and 0's at the front of numbers are stripped out to produce a new "Name" column as below?
Name (Before)
'John5'
'Tom  08'
'Ron 722'

Name (After)
'5'
'8'
'722'


text:
Q: $S$-matrix element for real photon production In this book (Thermal field theory by Bellac) on page 109 the $S$-matrix element for the transition from an initial state to a final state plus photon $(i)\to(f,\gamma)$ is given:
$$S_{fi}^{(\lambda)}(Q)=-ie\int d^4x e^{i Q\cdot x} \epsilon^{(\lambda)}_{\mu}(Q)<f|j^{\mu}(x)|i>$$
where $Q$ is the photon four momentum, $\epsilon^{(\lambda)}_{\mu} $ is its polarization four vector and $j_{\mu}$ is the electromagnetic current.
How can I derive this?

A: Well, I do not know how to derive this, but I can convince you why this holds I think. The S-matrix element for the interaction $(i)\rightarrow(f,\gamma)$ would be written (according to your notation I think) as
$$<f,\gamma|S|i>$$
Given that $S=e^{i\int d^4x\mathcal{L}_I}$, where $\mathcal{L}_I$ is the interaction QED Lagrangian, $\mathcal{L}_I=-eA_{\mu}(x)j^{\mu}(x)$, where $j^{\mu}(x)$ is simply the matter current, and given that what we are looking there is just the first order in perturbation theory scattering amplitude, one can write the amplitude above as
$$<f,\gamma|S|i>=-ie\int d^4x<f|A_{\mu}(x)j^{\mu}(x)|i>$$
Now, one can expand the electromagnetic field according to
$$A_{\mu}(x)=A_{\mu}^{+}(x)+A_{\mu}^-(x)$$
where $A_{\mu}^{+}$ creates a photon at point $x$ in the final state and $A_{\mu}^{-}$ destroys a photon at point $x$ in the final state. So, if there is no other photon in the final state, the latter will not survive and the former will be written as a Fourier expansion containing the exponential factor $e^{iQ\cdot x}$, the operator that will create a photon in the final state and the polarization vector. Also, there is going to be an integral over the photon's momentum. From that point, one can define the S-matrix element in the momentum space to be everything but that last integral over the photon's momentum. There you have your expression ...
I hope that helps.


text:
Q: Is it possible to have temp tables in a function? Apparently, I can't use them. I'm getting an error message like:

Invalid use of a side-effecting operator 'SELECT' within a function

If I want to do something like this:
select bleh
  into #temp
  from Blah

... inside a function.

A: No, per this thread where the same question was asked, you cannot, but you can use a table variable
DECLARE @MyTempTableVariable TABLE (SCHEMA)

INSERT INTO @MyTempTableVariable
SELECT bleh
FROM bleh

A: You can also do it with a CTE.  See the template browser in SSMS.  IntelliSense confuses the issue and will show an error until you complete the CTE and the following insert/select, but it will work.


text:
Q: How can I change the colour of PHP functions? I'm using VS Code to edit PHP files. This setting lets me change the colour of the functions that I define myself:
"editor.tokenColorCustomizations": {
    "functions": "#000000"
},

But it doesn't affect the colour of the functions that come with PHP and that are called in my code. They're still in some brown. That's too close to the grey I chose for my comments and I want to change it to plain black.
How can I change that colour?

A: Execute from command palette Developer: Inspect TM Scopes. Find needed scope for function. Apply like this(no idea if this selector works for php):
"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "scope": [
                "support.function",
                "entity.name.function",
                "meta.function-call support.function",
                "meta.function-call entity.name.function",
            ],
            "settings": {
                "foreground": "#40b18c",
            }
        },
    ]
}


text:
Q: How to delete all lines in a text file that do not contain the specified words It is necessary to implement a function in which an array containing several words (the number is unknown) will be passed as a parameter.
There is a source file, output.txt, it contains a large number of lines, it is necessary for the function to delete all the lines entirely if the line does not contain at least one word from the array of words
This is what I have at the moment, but this function only removes one word at a time, but it needs several
import re
with open('output.txt') as f:
    lines = f.readlines()
str = "bmw" # Keyword
pattern = re.compile(re.escape(str))
with open('output.txt', 'w') as f:
    for line in lines:
        result = pattern.search(line)
        if result is not None:
            f.write(line)


text:
Q: Runtime 9 error after workbook opens CSV successfully I have a VBA macro that opens IBM cognos to run a report and save it out as a CSV file. The macro then opens the file and copy pastes it into my excel workbook.
On
Workbooks.Open Filename:= _
        "S:\Supply Chain\Scheduling\NBVI\buf.csv"

I get Runtime Error 9: subscript out of range after the workbook opens.
This same code works in other workbooks and I'm at a loss.


text:
Q: Has the Chrome console's autocomplete feature gotten more aggressive? It seems like lately I have been having been getting hung up on the auto-completion drop down when using the console in Chrome DevTools. It seems like it has suddenly gotten more aggressive. I have never had a problem with the feature until the other day when I was trying to enter commands into the console quickly in order to test things. I wasn't sure why it wasn't working right. when I'd hit Enter auto-completion kept popping up and not executing what I typed. At first it seems as if auto-completion was activating whenever I would hit Enter to execute my code. However, it began to look like it was only popping up when I would end a statement with ;.
For example, typing the following statement into the console and pressing Enter would not cause the autocomplete drop down to activate:
console.log('did it')

However, if I add a semicolon then as soon as I press ; a number of milliseconds later the autocompletion feature immediately pops up:
console.log('did it');

At this point if I press Enter it will simply select the first entry, $, and add it as the next statement so we get:
console.log('did it');$

I know this is not really a big deal, after all, the only reason you would need the semicolon is for entering in multiple statements. However, I feel like in the past I've always added a semicolon ; to the end of simple single test statements such as the console.log shown above not activated the auto-completion, being able to execute it by just hitting Enter.
I definitely feel like my console's auto-completion is being activated more aggressive than it used to.
Has anyone else felt like the auto-completion in the console is activating too often all of the sudden? I am wondering whether or not this could have actually been changed in Chrome or if somehow I have made my console start acting this way with a setting or something?
While writing this I noticed that it seems not to only be after ; that auto-completion seems to pop up when it hadn't before. If you refer to Chrome DevTools - Using the Console you'll see that auto-completion is only referred to once:

The Console attempts to evaluate any JavaScript expression you enter at the shell prompt, upon pressing the Return or Enter key. The Console provides auto-completion and tab-completion. As you type expressions, property names are automatically suggested. If there are multiple properties with the same prefix, pressing the Tab key cycles through them. Pressing the right arrow key accepts the current suggestion. The current suggestion is also accepted by pressing the Tab key if there is only one matched property.

After this it goes on to say that we can use Shift+Enter in order to enter a multi-line expression and it gives the following example:

(source: google.com)
This is something I know for sure I have done plenty of times in the past with no problems from auto-completion. When I try to type the code in the above image I get as far as:
var add = function (val1, val2) {

Then when I press Shift+Enter instead of going to a new line like I am positive it did before (for me at least). Apparently anytime a new statement is started it will pop up. Has anyone else started getting highly annoyed at this feature as of very recently? Does anyone know if there's a way I could have caused this behavior?

A: Whoever answered my question before deleted their answer. I would like to close the question as it has been answered. This is indeed a bug as stated in the comments above and on the deleted answer. Anyone else that is here because they are experiencing problems as well will have to wait for the release to make it down to their version of Chrome, with Canary getting it first of course. You could presumably install an earlier version of Chrome to get around this as well. I know this is not directly about coding, but I see no reason to close it now when others may find the information useful.
Link to the Chrome Issue referencing this problem: https://code.google.com/p/chromium/issues/detail?id=263925


text:
Q: Passing a list from a view to a controller? I'm a relatively new Rails developer with a heavy Java/C# background and I'm trying to pass multiple time ranges from my view to my controller. For instance, the user could select the time range 9:00am to 11:00am as well as 2:00pm to 4:00pm. The first thing to came to mind was a list of times or a list of key value pairs so that I know when a time range starts and ends. I'm having trouble figuring out how to pass this information to my Rails controller though.
Is there an ideal Rails way of passing a list to a controller?

A: You pass information from a view to a controller via http query string ('get') or form data ('post').
I would consider multi-select dropdown for this case.

A: From Rails Guide http://guides.rubyonrails.org/action_controller_overview.html
request
GET /mytime?t[]=1&t[]=2&t[]=3
in view
<form method="GET" action="mytime">
<select multiple name="t[]">
<option value="1">1:00pm</option>
<option value="2">2:00pm</option>
<option value="3">3:00pm</option>
</select>
</form>

or
<form method="GET" action="mytime">
<input type="text" name="t[]">
<input type="hidden" name="t[]" value="11">
</form>

#in mytime_controller.rb
def index
  params[:t] # return Array of values
end

A: Instead of dropdown i suggest you should create a cool for using some jquery plugin that will improve your application's user experience and yes create a rails form and submit it then you can have information in your controller.
Now is you are saving these selected time, that i think you should do then create a model if you haven't already and use form_for else your can use form_tag for your rails application.
Visit Here and find some time picker that suits you need.


text:
Q: How to Clone OS from HDD to SSD with different sector sizes I have an Asus laptop with a 1TB HDD and I bought an NVMe type SSD recently. I'm using Windows 10 and I want to clone my OS from the HDD to SSD and I'm getting different sector size error for both cloning and image restoring. Even the PC do not list down the SSD to install fesh OS. But using minitool I could create a partition on SSD.
Here are the sector details.
HDD:
C:\Windows\system32>fsutil fsinfo ntfsinfo c:
NTFS Volume Serial Number :        0x44bc75efbc75dbbc
NTFS Version      :                3.1
LFS Version       :                2.0
Total Sectors     :                722,824,590  (344.7 GB)
Total Clusters    :                 90,353,073  (344.7 GB)
Free Clusters     :                 54,879,625  (209.3 GB)
Total Reserved Clusters :            1,796,984  (  6.9 GB)
Reserved For Storage Reserve :       1,784,892  (  6.8 GB)
Bytes Per Sector  :                512
Bytes Per Physical Sector :        4096
Bytes Per Cluster :                4096
Bytes Per FileRecord Segment    :  1024
Clusters Per FileRecord Segment :  0
Mft Valid Data Length :            1.25 GB
Mft Start Lcn  :                   0x00000000000c0000
Mft2 Start Lcn :                   0x0000000000000002
Mft Zone Start :                   0x0000000001791b60
Mft Zone End   :                   0x000000000179e380
MFT Zone Size  :                   200.13 MB
Max Device Trim Extent Count :     512
Max Device Trim Byte Count :       0xffffffff
Max Volume Trim Extent Count :     62
Max Volume Trim Byte Count :       0x40000000
Resource Manager Identifier :      9CBF94F9-6118-11EA-AAFC-00909E9AAD84

SSD:
C:\Windows\system32>fsutil fsinfo ntfsinfo d:
NTFS Volume Serial Number :        0x01d72955ab807340
NTFS Version      :                3.1
LFS Version       :                2.0
Total Sectors     :                123,993,599  (473.0 GB)
Total Clusters    :                123,993,599  (473.0 GB)
Free Clusters     :                123,965,910  (472.9 GB)
Total Reserved Clusters :              156,573  (611.6 MB)
Reserved For Storage Reserve :               0  (  0.0 KB)
Bytes Per Sector  :                4096
Bytes Per Physical Sector :        4096
Bytes Per Cluster :                4096
Bytes Per FileRecord Segment    :  4096
Clusters Per FileRecord Segment :  1
Mft Valid Data Length :            1.00 MB
Mft Start Lcn  :                   0x00000000000012c7
Mft2 Start Lcn :                   0x0000000000000026
Mft Zone Start :                   0x0000000000005320
Mft Zone End   :                   0x0000000000011b40
MFT Zone Size  :                   200.13 MB
Max Device Trim Extent Count :     4294967295
Max Device Trim Byte Count :       0xffffffff
Max Volume Trim Extent Count :     62
Max Volume Trim Byte Count :       0xffffffff
Resource Manager Identifier :      AAC332FB-9541-11EB-BB85-BEC52B07437F

I spent many hours searching for a solution. Hope someone will help me.

A: After struggling with this for days and trying numerous apps and methods,  thanks to this post by ArtPog from several years ago I finally found an app that can do this: Casper, by Future Systems. It has a 30 day trial that you can use to perform the clone if you don't already own it. I'm impressed with it though because it seems to be the only app in existence — or at least the only one I've found after a wide search — that can make a bootable clone of a Windows partition without doing a sector-by-sector copy.
For the record, here are a list of apps that I tried and didn't work, in the hopes that it'll help save someone some time: AOMEI Partition Assistant, Clonezilla, Macrium Reflect, EaseUS Partition Master, dd / ddrescue, HDClone

A: I've had the most luck using Aomei Partition Assistant cloning NVMe drives.
Download:
https://www.diskpart.com/free-partition-manager.html
Make Bootable Media:
https://www.diskpart.com/help/make-bootable-cd-wizard.html


text:
Q: Calling static Java methods in the ScriptEngine's environment/context I can write scripts which run in a closed-source Java app. The scripts have acces to the application's static API.
The following script asks the Static API where the mouse is positioned on the Java App window:
public class JavaScript extends Script {
    public void run() {
        System.out.println(General.getMousePos());
    }
}

However this does not work (API crashes with NullPointerException):
public class JavaScript extends Script {
    public void run() {
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine rubyEngine = m.getEngineByName("jruby");
        rubyEngine.eval("puts General.getRealMousePos()");
    }
}

Because of General.respond_to? "getRealMousePos" == true I think that the Ruby code is talking with a different instance of the API that is not initialised by the application.
Is it possible to pass objects from Java to Ruby or call methods from the environment/context where the ScriptEngine object is running? I only found strings (setContext/setAttrib)

A: It's possible that your application is doing something very crazy, but I threw together a quick test that seems to show that the scripting container uses the same static data:
com/test/Static.java
package com.test;

public class Static {
    private static long init;

    static {
        init = System.currentTimeMillis();
        try {
            // If this is run a second time, make sure it's different.
            Thread.sleep(1000);
        } catch (Exception e) {
            // LOL
        }
    }

    public static long getInitTime() {
        return init;
    }
}

Main.java
import javax.script.*;

public class Main {
    public static void main(String args[]) throws Exception {
        ScriptEngineManager m = new ScriptEngineManager();
        ScriptEngine rubyEngine = m.getEngineByName("jruby");

        System.out.println("Java time: " + com.test.Static.getInitTime());
        rubyEngine.eval("puts \"Ruby time: #{com.test.Static.init_time}\"");
    }
}

Run as
javac -cp . *java com/test/*java
jar -cf static.jar com/
java -cp jruby.jar:. Main

Output
Java time: 1388707668166
Ruby time: 1388707668166


text:
Q: jQuery Ajax: FormData is returning 403 error for base64 data I am trying to upload a base64 image data through FormData using jQuery ajax.
But it failed with 403 error. But If I remove base64 data from input then it works perfectly fine.
That's strange.
Even If I enter just this value in input "data:image/jpeg;base64" then it will fail with 403 error.
So is it really possible to upload base64 string ( image ) using FormData() ? if yes then why did not this work?
My code:
<script>
var formData = new FormData($('#form')[0]);
formData.append('base64Img', base64);
var url  = "http://www.example.com";
var type  = "POST";
$.ajax({data:formData, type:type, url:url, processData:false, cache:false, contentType:false});
</script>

A: I got solution.
Actually everything is fine in my code.
Issue was with my hosting. Hosting company resolved my issue.
Thanks


text:
Q: Solrnet : modify default Operator I use solrnet and I would add an "advanced search" on my website. For this, i need to change default operator ("OR" or "AND")
I try this with
this.solr.Query(new LocalParams {{"q.op", "OR"}} + q, options);

However, the query generated is between quote and it's for exact query (I query solr with "SolrQueryByField").
So, is it possible to query solr and change the default operator or remove quote at request.
Thanks.

A: Use SolrQuery instead of SolrQueryByField. SolrQuery is pass-through, anything you give it is passed as-is to Solr (modulo URL encoding of course)


text:
Q: Resolve IP address given in hexadecimal format using getnameinfo() I have a simple program in C, which resolves IP addresses into hostnames.
#include <stdio.h>          /* stderr, stdout */
#include <netinet/in.h>     /* in_addr structure */
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char **argv) {

if ( argc == 2) {

  struct sockaddr_in sa;
  sa.sin_family = AF_INET;
  inet_pton(AF_INET, argv[1], &sa.sin_addr);

  char node[NI_MAXHOST];
  int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
  if (res)
  {
    printf("%s\n", gai_strerror(res));
    return 1;
  }
  printf("%s\n", node);

  return 0;
 }
}

It works fine (i.e. ./a.out 10.1.1.2) but I need to modify it so that it accepts IP addresses in HEX format.
Is there some function to convert hex IP addresses to decimal?

A: I haven't tested this but should work.
#include <stdio.h>          /* stderr, stdout */
#include <netinet/in.h>     /* in_addr structure */
#include <strings.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char **argv) {

if ( argc == 2) {

  struct sockaddr_in sa;
  char a[2048] = {'\0'}; // placeholder    not to overflow and initialised.
  if( NULL == strchr(argv[1],'.') )
  {
      unsigned int unit0, uint1, uint2, uint3;
      sscanf(argv[1], "%2x%2x%2x%2x", &uint0, &uint1, &uint2, &uint3);
      sprintf(a,"%u.%u.%u.%u",uint0, uint1, uint2, uint3);
  }
  else
      strcpy(a.argv[1]);
  sa.sin_family = AF_INET;
  inet_pton(AF_INET, a, &sa.sin_addr);

  char node[NI_MAXHOST];
  int res = getnameinfo((struct sockaddr*)&sa, sizeof(sa), node, sizeof(node), NULL, 0, 0);
  if (res)
  {
    printf("%s\n", gai_strerror(res));
    return 1;
  }
  printf("%s\n", node);

  return 0;
 }
}

Thanks


text:
Q: TEdgeBrowser Navigate fails with error "File not found" My first attempt to try the new TEdgeBrowser fails with 'The system can't find the file'
procedure TFrmTEdgeBrowser.BtnNavigateClick(Sender: TObject);
var lErrCode: Integer;
begin
  if not EdgeBrowser.Navigate('https://www.google.com') then
  begin
     lErrCode := EdgeBrowser.LastErrorCode;
     ShowMessage(IntToStr(lErrCode) + ': ' + SysErrorMessage(lErrCode));
  end;
end;

Error code -2147024894 = $80070002 is indeed ERROR_FILE_NOT_FOUND
Sequence (e.g as per https://www.delphipraxis.net/204266-new-vcl-tedgebrowser-component-coming-rad-studio-10-4-a.html or http://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_TEdgeBrowser_Component_and_Changes_to_the_TWebBrowser_Component):

*

*New Win10 VM, start Edge, win installer runs and install Edge correctly

*Download and install Edgeview2 SDK through GetIt

*Copy c:\Program Files (x86)\Embarcadero\Studio\21.0\Redist\win32\WebView2Loader.dll to app dir

Config: Delphi 10.4.3 Sydney, running a 32 bit app in a Win10 VM, Edge  84.0.522.52 installed
Attempts: no https: in front, reboot, tried to get more info from a TApplicationEvents.OnException
I then tried to run the demo c:\Users\Public\Documents\Embarcadero\Studio\21.0\Samples\Object Pascal\VCL\WebBrowser\Edge\EdgeBrowser.dproj (with the dll copied into that directory as well) but this gives the initialization error from the end of its:
procedure TfrmMain.EdgeBrowserCreateWebViewCompleted(Sender: TCustomEdgeBrowser; AResult: HResult);
begin
{$IFDEF DEBUG}
  OutputDebugString('EdgeBrowser OnCreateWebViewCompleted');
{$ENDIF}
  if Succeeded(AResult) then
  begin
    tbCancel.Enabled := True;
    tbReload.Enabled := True;
    tbGo.Enabled := True;
    edtAddress.Enabled := True;
    Sender.AddWebResourceRequestedFilter('*', COREWEBVIEW2_WEB_RESOURCE_CONTEXT_IMAGE);
  end
  else
  begin
    if AResult = HResultFromWin32(ERROR_FILE_NOT_FOUND) then
      Application.MessageBox('Could not find Edge installation. ' +
        'Do you have a version installed that''s compatible with this WebView2 SDK version?',
        'Edge initialisation error', MB_OK or MB_ICONERROR)
    else
      Application.MessageBox('Failed to initialise Edge browser control',
        'Edge initialisation error', MB_OK or MB_ICONERROR)
  end;
end;

But now AResult is -2147467259 = $80004005
which seems to be data/ODBC related.
Updating to a later version 0.9.579 (20 jul 2020) of Microsoft.Web.Webview2 did not help.

A: I downloaded the Beta Version of Edge and that fixed it for me.
I was using version 84.0.522.59 (Official build) (64-bit), and had the same problem as you.
The version I downloaded was 85.0.564.30 (Official build) beta (64-bit).
Also, I looked back over the documentation and it says to get the canary channel version. So while I downloaded the beta version, I'm assuming the canary version is what you are supposed to download, and will also fix the problem.
http://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_TEdgeBrowser_Component_and_Changes_to_the_TWebBrowser_Component

The Microsoft Edge Chromium-based browser currently available from
https://www.microsoftedgeinsider.com/download (Canary channel
version whilst the WebView2 SDK is in pre-release, currently the
minimum required version is 82.0.430.0).


text:
Q: fluxcd not applying anything with err="running kubectl: error: unable to recognize \"STDIN\": ..." I recently installed FluxCD 1.19.0 on an Azure AKS k8s cluster using fluxctl install. We use a private git (self hosted bitbucket) which Flux is able to reach and check out.
Now Flux is not applying anything with the error message:
ts=2020-06-10T09:07:42.7589883Z caller=loop.go:133 component=sync-loop event=refreshed url=ssh://git@bitbucket.some-private-server.com:7999/infra/k8s-gitops.git branch=master HEAD=7bb83d1753a814c510b1583da6867408a5f7e21b
ts=2020-06-10T09:09:00.631764Z caller=sync.go:73 component=daemon info="trying to sync git changes to the cluster" old=7bb83d1753a814c510b1583da6867408a5f7e21b new=7bb83d1753a814c510b1583da6867408a5f7e21b
ts=2020-06-10T09:09:01.6130559Z caller=sync.go:539 method=Sync cmd=apply args= count=3
ts=2020-06-10T09:09:20.2097034Z caller=sync.go:605 method=Sync cmd="kubectl apply -f -" took=18.5965923s err="running kubectl: error: unable to recognize \"STDIN\": an error on the server (\"\") has prevented the request from succeeding" output=
ts=2020-06-10T09:09:38.7432182Z caller=sync.go:605 method=Sync cmd="kubectl apply -f -" took=18.5334244s err="running kubectl: error: unable to recognize \"STDIN\": an error on the server (\"\") has prevented the request from succeeding" output=
ts=2020-06-10T09:09:57.277918Z caller=sync.go:605 method=Sync cmd="kubectl apply -f -" took=18.5346491s err="running kubectl: error: unable to recognize \"STDIN\": an error on the server (\"\") has prevented the request from succeeding" output=
ts=2020-06-10T09:09:57.2779965Z caller=sync.go:167 component=daemon err="<cluster>:namespace/dev: running kubectl: error: unable to recognize \"STDIN\": an error on the server (\"\") has prevented the request from succeeding; <cluster>:namespace/prod: running kubectl: error: unable to recognize \"STDIN\": an error on the server (\"\") has prevented the request from succeeding; dev:service/hello-world: running kubectl: error: unable to recognize \"STDIN\": an error on the server (\"\") has prevented the request from succeeding"
ts=2020-06-10T09:09:57.2879489Z caller=images.go:17 component=sync-loop msg="polling for new images for automated workloads"
ts=2020-06-10T09:09:57.3002208Z caller=images.go:27 component=sync-loop msg="no automated workloads"

From what I understand, Flux passes the resource definitions to kubectl, which then applies them?
The way I interpret the error would mean that kubectl isn't passed anything to. However I opened a shell in the container and made sure Flux was in fact checking something out - which it did.
I tried raising the verbosity to 9, but it didn't return anything that I deemed relevant (detailed outputs of the http requests and responses against the Kubernetes API).
So what is happening here?

A: The problem was with the version of kubectl used in the 1.19 flux release, so I fixed it by using a prerelease: https://hub.docker.com/r/fluxcd/flux-prerelease/tags


text:
Q: iso installed debian 8.2.0, but boot fails with strange textscreen artifact with red character I got it to install on dev/sdb from DVD. (debian-8.2.0-amd64-DVD-1.iso)
Basic install, default desktop. No extra packages from DVD#2#3 or via package manager installed.
During startup, the textscreen suddenly goes half-the-brightness(or another screen mode), and after some seconds, on top of the text screen, a blank line and a red square character appears?!
I couldn't find any errors in the /var/log/
(Foto's and video here)
(jfyi: I installed GRUB on /dev/sdb, and instructed bios to boot from the Seagate drive. (The Maxtor /dev/sda had sectors relocated, so decided not to use it). Also the graphical linux environment 'partedmagic' from Hirens BootCD 14 works fine)

note: i got a reply on reddit forum:

ECPilot - I had some similar issues with the DVD install...but, no issues at all
  using the "net install" .iso. --- good luck.

But i really like the dvd install to work.
I hope someone knows where to start. i'm fairly new to this. thx

A: I found the issue.  Something with the graphics was wrong.
i disabled the 'nouveau' NVIDIA driver by following this GRUB2 instruction
And although i did see the weird blank line and red dot while starting, then it did continue into a graphic environment! :)
Then i could install the latest NVIDIA drivers, using
https://wiki.debian.org/NvidiaGraphicsDrivers#Debian_8_.22Jessie.22


text:
Q: Usage of Array of abstract types in Julia I'm exploring Julia so I'm a newbie. Now I'm exploring its strongly typed features. What I'm realizing is that I can't see the usage of abstract types for arrays. Let me explain with an example:
Let's suppose that I would like to create a function which accepts arrays of reals, no matter its concrete type. I would use:
function f(x::Array{Real})
  # do something
end

This function can be never called without raising a f has no method matching f(::Array{Float64,1})
I would like to call f([1,2,3]) or f([1.,2.,3.]) as long as the type of the element is Real.
I've read that you could promote or convert the array (p.eg f(convert(Array{Real}, [1, 2, 3])) or so) but I see that way really non-dynamic and tedious.
Is there any other alternative rather than getting rid of the strongly typed behaviour?
Thanks.

A: To expand upon the solution by @user3580870, you can also use a typealias to make the function definition a little more succinct:
typealias RealArray{T<:Real} Array{T}
f(x::RealArray) = "do something with $x"

And then you can use the typealias in anonymous functions, too:
g = (x::RealArray) -> "something else with $x"

A: Since there's been an updated since the orginal answer, the keyword typealias is gone so that the solution of @Matt B. would now be
const RealArray{T<:Real} = Array{T}
f(x::RealArray) = "do something with $x"

I'll just put this here for the sake of completeness ;)

A: You can do this explicitly using the <: subtype operator:
function f(x::Array)
    return zero.(x)
end

function f(x::Array{<:Real})
    return one.(x)
end

@show f([1, 2])
@show f([1.0, 2.0])
@show f([1im, 2im])

prints
f([1, 2]) = [1, 1]
f([1.0, 2.0]) = [1.0, 1.0]
f([1im, 2im]) = Complex{Int64}[0+0im, 0+0im]


text:
Q: From PowerShell Get Refresh History In Group from Power BI REST APIs and export do CSV I'm trying to get the PowerBI update history through the API URL through Powershell and export do CSV, I don't know much about Powershell but I'm trying to learn, since it's being very useful in the BI area where I work, I've tried to run the code through this site POWERBI SCHEDULED REFRESHES IN YOUR ORGANIZATION and also tried to edit to extract but with no success.
The site script runs without errors but does not return any results in CSV, is it because the URL is wrong?
Website script:
$myCred = Get-Credential
Connect-PowerBIServiceAccount -Credential $myCred

$Workspaces = Get-PowerBIWorkspace
$ExportFile =  "D:\Users\F02579\Documents\PowerBIRefreshHistory.csv"
Remove-Item $ExportFile -Force -ErrorAction SilentlyContinue

foreach($workspace in $Workspaces)
{

    $DataSets = Get-PowerBIDataset -WorkspaceId $workspace.Id | where {$_.isRefreshable -eq $true}
    foreach($dataset in $DataSets)
    {

        $URI = "groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
        #$OutFile = $ExportFolder + '\' + $workspace.Name + '-' + $dataset.Name + '.json'
        $Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

        foreach($result in $Results.value)
        {
            $errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

            $row = New-Object psobject
            $row | Add-Member -Name "Workspace" -Value $workspace.Name -MemberType NoteProperty
            $row | Add-Member -Name "Dataset" -Value $dataset.Name -MemberType NoteProperty
            $row | Add-Member -Name "refreshType" -Value $result.refreshType -MemberType NoteProperty
            $row | Add-Member -Name "startTime" -Value $result.startTime -MemberType NoteProperty
            $row | Add-Member -Name "endTime" -Value $result.endTime -MemberType NoteProperty
            $row | Add-Member -Name "status" -Value $result.status -MemberType NoteProperty
            $row | Add-Member -Name "errorCode" -Value $errorDetails.errorCode -MemberType NoteProperty
            $row | Add-Member -Name "errorDescription" -Value $errorDetails.errorDescription -MemberType NoteProperty
            $row | Export-Csv -Path $ExportFile -Append -Delimiter ';' -NoTypeInformation
        }

    }

}

I tried to put the URL that Microsoft provides in this link, but also without success.
My script:
Import-Module MicrosoftPowerBIMgmt.Admin

$myCred = Get-Credential
Connect-PowerBIServiceAccount -Credential $myCred

$Session = New-PSSession -ConfigurationName Microsoft.Exchange `
    -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
    -Credential $credential `
    -Authentication Basic `
    -AllowRedirection

Import-PSSession $Session

$Workspaces = Get-PowerBIWorkspace -Scope Organization -All
#Remove-Item $ExportFile -Force -ErrorAction SilentlyContinue

$DataSets =
ForEach ($workspace in $Workspaces)
    {
    Write-Host $workspace.Name
    ForEach ($dataset in (Get-PowerBIDataset -Scope Organization -WorkspaceId $workspace.Id))
        {
            #$URI = "groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
            $URI = "https://api.powerbi.com/v1.0/myorg/groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
            #$OutFile = $ExportFolder + '\' + $workspace.Name + '-' + $dataset.Name + '.json'
            $Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

            foreach($result in $Results.value)
            {
                $errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

                $ItemResult = New-Object System.Object
                $ItemResult | Add-Member -type NoteProperty -name WorkspaceID           -value $workspace.Id
                $ItemResult | Add-Member -type NoteProperty -name DatasetID             -value $dataset.Id
                $ItemResult | Add-Member -type NoteProperty -name RefreshID             -value $result.Id
                $ItemResult | Add-Member -type NoteProperty -name RequestId             -value $result.requestId
                $ItemResult | Add-Member -type NoteProperty -name RefresheType          -Value $result.refreshType
                $ItemResult | Add-Member -type NoteProperty -name StartTime             -Value $result.startTime
                $ItemResult | Add-Member -type NoteProperty -name EndTime               -Value $result.endTime
                $ItemResult | Add-Member -type NoteProperty -name Status                -Value $result.status
                $ItemResult | Add-Member -type NoteProperty -name ErrorCode             -Value $errorDetails.errorCode
                $ItemResult | Add-Member -type NoteProperty -name ErrorDescription      -Value $errorDetails.errorDescription

                # Put the item result and append it to the result object
                $Result +=$ItemResult
            }
        }
    }
$DataSets | Export-Csv "D:\Users\F02579\Documents\PowerBIRefreshHistory.csv" -NoTypeInformation -Encoding UTF8

Remove-PSSession $Session

Disconnect-PowerBIServiceAccount

Error on my scripp:

A: After making some calls with Microsoft, with some engineers that works with PowerBI and Powershell conector, I'm now able to get those information.
Powershell script:
$authUrl = "https://login.windows.net/common/oauth2/token/"
$clientId = "Your clientID"
$pbiUsername = "Your user email"
$pbiPassword = "Your password"

$body = @{
    "resource" = "https://analysis.windows.net/powerbi/api";
    "client_id" = $clientId;
    "grant_type" = "password";
    "username" = $pbiUsername;
    "password" = $pbiPassword;
    "scope" = "openid"
}
$authResponse = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body

$DatasetID = "Your datasetID"
$restURL = "https://api.powerbi.com/v1.0/myorg/datasets/$DatasetID/refreshes"

$headers = @{
    "Content-Type" = "application/json";
    "Authorization" = $authResponse.token_type + " " + $authResponse.access_token
}

$restResponse = Invoke-RestMethod -Uri $restURL –Method GET -Headers $headers | Select-Object -ExpandProperty value
$restResponse


text:
Q: Touch screen operations for .NET windows application? We are building a Windows application in .NET and one of its requirements is touch screen monitor. Other than that, it's a normal windows form based application. But except for making UI items little bigger for touch, I can't find anything I as a developer need to do for the requirement since touch screen is basically mouse operations. Am I missing something?

A: No, you are not missing anything.  Do get the actual hardware hooked up so you can test it, "little bigger" is invariably underestimating the problem of fat fingers.  Everything should work from a single click, right-clicks are horribly impractical, double-clicks are best avoided.
The only other thing you'll want to do is go into the Control Panel + Display applet and change the size of standard Windows UI elements.  Pick a large window caption font if you want to allow the user to drag or close windows.  Make the scrollbars at least twice as wide.  And the menu and message box font.  Go in the Mouse applet to increase double-click range and time if you want to support that.

A: If you do not need touch-specific event handling I think it's all you have to do. But touch means more than that and you may want to support it in a better way: http://archive.msdn.microsoft.com/WindowsTouch/Release/ProjectReleases.aspx?ReleaseId=2127


text:
Q: How to make ProgressBar of style large Thinner in width android? I have the mic icon and surrounding the mic icon, I need to place the Progress Bar to handle some running process like below:
<ImageView
            android:id="@+id/iv_mic_movable"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="68dp"
            android:src="@drawable/record" />

        <ProgressBar
            android:id="@+id/pb_assist"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="53dp"
            android:visibility="gone" />

The above code shows the UI as follows:

I want to show the progress bar like this, But this progress is very Thick. How to make it somewhat thinner with only 1dp?

A: Here is custom ProgressBar. You can set thickness of progress inside shape.
<ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="172dp"
        android:layout_height="172dp"
        android:indeterminate="false"
        android:max="100"
        android:visibility="visible"
        android:progress="0"
        android:layout_gravity="center_horizontal" //updated line
        android:layout_marginTop="53dp"            //updated line
        android:background="@drawable/circle_shape"
        android:progressDrawable="@drawable/circle_progress_foreground"
        />

circle_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadiusRatio="2.2"
android:thickness="5dp"
android:useLevel="false">

<solid android:color="#ABBAC2" />

</shape>

circle_progress_foreground.xml
Change android:thickness as per your requirement
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="270"
    android:toDegrees="270">

    <shape
        android:innerRadiusRatio="2.7"
        android:shape="ring"
        android:thickness="2dp"
        android:useLevel="true">

        <solid android:color="#fbcb09" />

    </shape>

</rotate>

A: None of the above answers worked for me. Struggling around found a below working solution.
progressbar_circular.xml. Use android:thicknessRatio for thickness of the circle. More the value will be, thinner it will be.
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="0"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="40"
        android:useLevel="false" >

        <size
            android:height="48dip"
            android:width="48dip" />

        <gradient
            android:centerColor="@color/colorPrimary"
            android:centerY="0.50"
            android:endColor="@color/color_black"
            android:startColor="@color/colorPrimary"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

Progress bar layout will be like below:
<ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        style="?android:attr/progressBarStyleLarge"
        android:indeterminateDrawable="@drawable/progressbar_circular"
        android:layout_gravity="center_horizontal"
        android:visibility="visible"/>

A: try to add this below style on your xml progessBar layout,
    style="@android:style/Widget.ProgressBar.Large.Inverse"

Update
try to add this property:
android:progressDrawable="@android:drawable/progress_horizontal"

A: You can also achieve this by adding mimimum width and height
<ProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="23dp"
    android:layout_marginTop="20dp"
    android:indeterminate="false"
    android:max="100"
    android:minHeight="5dp"
    android:minWidth="200dp"
    android:progress="1" />


text:
Q: Apex Controller variable not updating in visualforce upon rerender This is making me slightly insane. I cannot, for the life of me, figure out how to get this dang rerendering working in Visualforce.
I am doing something like this on my visualforce page:
<apex:form id="theForm">
    <apex:outputPanel id="criteriaTableScript">
        <script>
            var criteriaTable;
            var fieldCriteriaList = JSON.parse('{!fieldCriteria}');
            function instantiateCriteriaTable(){
                var fieldCriteriaList = JSON.parse('{!fieldCriteria}');
                console.log('Updated Criteria: ', fieldCriteriaList);
                if(fieldCriteriaList.length > 0){
                    dependencyTable.destroy();
                    $Lightning.use('FSTR:FieldUpdateApp', function(){
                        console.log('Creating lightning component');
                        $Lightning.createComponent(
                            'c:CriteriaTableViewComponent',
                            {
                                Id: '{!myObj.Id}',
                                criteriaObject: 'Criteria__c',
                                criteria: JSON.parse('{!fieldCriteria}')
                            },
                            'sfd-section',
                            function(cmp){
                                criteriaTable = cmp;
                                console.log('Component created');
                                //component created
                            }
                        );
                    });
                }
            }
        </script>
    </apex:outputPanel>
    <apex:actionFunction name="addCriteriaToList" action="{!addCriteriaToList}" onComplete="instantiateCriteriaTable();" reRender="criteriaTableScript">
        <apex:param name="criteriaDataStr" value='' />
    </apex:actionFunction>
</apex:form>

There is more stuff in the form afterwards, but just wanted to show this to indicate the outputpanel and action function are at the very top level of the form, nothing is preventing their rendering or anything.
So... a user creates a criteria, saving the criteria triggers the action function, which does this in the controller:
public PageReference addCriteriaToList(){
    String criteria = ApexPages.currentPage().getParameters().get('criteriaDataStr');
    PCE_Step_Field_Dependency__c newSFD = (Criteria__c)JSON.deserialize(criteria, Type.forName('Criteria__c'));
    fieldCriteria.add(newSFD);

    return null;
}

All it does is add the new criteria to a global variable fieldCriteria then returns.
My action function is then supposed to rerender the outputPanel, so the script inside should grab the updated values of '{!fieldCriteria}', it then should call the function inside the outputPanel.
but fieldCriteria remains an empty list, all the time. It just doesn't seem to be rerendering.
I came to this solution by finding this post
But it just will not update...


text:
Q: Parallel execution of the functions and waiting for their completion How can I wait until the end of the two functions, and only after calling callbacks for them to continue the script.
I paid attention to jQuery deferred.then(), but I do not understand how to use it in my case
GoogleDriveModule.checkAuth(function(authResult) {
  if (authResult) {
    return parts_count += 1;
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  if (authResult) {
     return parts_count += 1;
  }
});

A: Create two deferred objects and resolve them within the callbacks. Then you can wait on both deferreds with $.when:
var googleDone = $.Deferred(),
    dropboxDone = $.Deferred();

GoogleDriveModule.checkAuth(function(authResult) {
  googleDone.resolve();
  if (authResult) {
    return parts_count += 1;
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  dropboxDone.resolve();
  if (authResult) {
     return parts_count += 1;
  }
});

$.when(googleDone, dropboxDone).then(function() {
    alert("Both authentication checks completed.");
});

A: You could have 2 boolean and check in a callback function if they are ready :
var gDriveREADY = false, dBoxREADY = false;
GoogleDriveModule.checkAuth(function(authResult) {
    if (authResult) {
        return parts_count += 1;
    }
    gDriveREADY = true;
    doSomething()
});

DropboxModule.isAuthenticated(function(authResult) {
    if (authResult) {
        return parts_count += 1;
    }
    dBoxREADY = true;
    doSomething();
});

function doSomething(){
    if(dBoxREADY && gDriveREADY){
        //Your code
    }
}

A: In the callbacks you could toggle a simple flag which the other function checks:
var driveDone = 0
  , dropDone = 0
  ;
GoogleDriveModule.checkAuth(function(authResult) {
  driveDone = 1;
  if (authResult) {
    parts_count += 1;
  }
  if(dropDone){
   bothDone();
  }
});

DropboxModule.isAuthenticated(function(authResult) {
  dropDone = 1;
  if (authResult) {
     parts_count += 1;
  }
  if(driveDone){
   bothDone();
  }
});
function bothDone(){}

This has less overhead than the deferred method, but is not quite as clean.


text:
Q: Retrieving the primary key from a database Is it possible to return the last primary key given in a database?
This is partly how I'm connecting to and adding stuff to my database, but if you need more infor please ask.
public partial class MainWindow : Window
{

System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;

DataSet sessions;

Main
public MainWindow()
{
    InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    con = new System.Data.SqlClient.SqlConnection();

    sessions = new DataSet();

    con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\md\\PokerDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

    con.Open();

    string sql = "SELECT * From Sessions";
    da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
    da.Fill(sessions, "Sessions");

    con.Close();

    System.Data.SqlClient.SqlCommandBuilder cb;
    cb = new System.Data.SqlClient.SqlCommandBuilder(da);

    DataTable dt = sessions.Tables["Sessions"];

    DataRow table = sessions.Tables["Sessions"].Rows[position];
    table[0] = "Some Data";
    table[1] = "Some Data";
    table[2] = "Some Data";
    table[3] = 2;
    table[4] = 3;
    sessions.Tables["Sessions"].Rows[2].Delete();
    sessions.Tables["Sessions"].Rows.InsertAt(table, 2);

    da.Update(sessions, "Sessions");
}
}

Thanks for having a look!

A: I guess you are asking for the last inserted primary key value? Then SCOPE_IDENTY is your friend. Take a look here and MSDN for detailed information

A: If you want to get the last primary key from a table and you have it increments automatically on every insert, then you can just ask for its maximal value. If you want from the database, then you can use scope identity.


text:
Q: Why Nodejs serves a file with 80x more CPU usage than Nginx? Take the same code that sits on nodejs.org home page. Serve a static file that is 1.8Mb. And do the same with Nginx, and watch the difference.
Code       : http://pastie.org/3730760
Screencast : http://screencast.com/t/Or44Xie11Fnp
Please share if you know anything that'd prevent this from happening, so we don't need to deploy nginx servers and complicate our lives.
ps1. this test is done with node 0.6.12. out of curiosity, i downgraded to 0.4.12 just to check if it's a regression, on the contrary, it was worse. same file used 25% twice.
ps2. this post is not a nodejs hate - we use nodejs, and we love it, except this glitch which actually delayed our launch (made us really sad), and seemed quite serious to me. i've never read, heard, seen or expected to come across.

A: The problem with your node benchmark is that you store the static file in a variable inside the V8 heap. Due to the way how V8 handles memory it can't directly send data contained in javascript variables to the network, because addresses of allocated objects may change during runtime, therefore V8 has to make a copy of your 1.8MB string on every request, sure that kills performance.
What you could do is to use a Buffer:
replace: longAssString = fs.readFileSync(pathToABigFile, 'utf8');
with: longAssString = fs.readFileSync(pathToABigFile);
that way you have your static file in a buffer, buffers are stored outside of V8s heap and require no copy when sent to the network and should therefore be much faster.


text:
Q: "Cast a spell on people" vs. "cast a spell over people"? What's the difference between the two? Example:

She cast a strange, yet beautiful spell on people.
She cast a strange, yet beautiful spell over people.

A: Over can imply that people refers to a vast crowd of people and that the spell is cast upon all them as a whole.  This further makes the sentence possibly imply that you mean something like where a speaker "casts a spell over" his/her audience.
On would tend to imply that the effect is more about "any person" or individual people.


text:
Q: Find all primes $p$ for which $2017^{p-1}+p^3$ is a perfect square
Find all primes $p$ for which $2017^{p-1}+p^3$ is a perfect square.

Note that $p \neq 2017$ and let $2017^{p-1}+p^3 = k^2$ for some integer $k$. By Fermat's Little Theorem, $2017^{p-1} \equiv 1 \pmod{p}$ and so $$2017^{p-1}+p^3 \equiv 1 \pmod{p}.$$ Thus $k = \pm1+pm$ for some integer $m$. If $k = 1+pm$, then $$2017^{p-1} = 1+2pm+p^2m^2-p^3 = 1+p(2m+pm^2-p^2)$$ and therefore $$2017^{p-1}-1 = p(2m+pm^2-p^2).$$
I didn't see how to continue from here.

A: Note $p=2$ is a solution.
If $p$ is odd,
$$2017^{p-1}+p^3 = k^2 \implies p^3=(k-2017^{\frac{p-1}{2}})(k+2017^{\frac{p-1}{2}})$$
Since $k-2017^{\frac{p-1}{2}}<k+2017^{\frac{p-1}{2}}$, we have that $(k-2017^{\frac{p-1}{2}}, k+2017^{\frac{p-1}{2}})=(1,p^3)$ or $(p,p^2)$.
However, note that the difference between $(k-2017^{\frac{p-1}{2}}$ and $k+2017^{\frac{p-1}{2}}$ is larger than $p^3-1$ $p^2-p$ for all $p$.
So we have that it is impossible when $p \equiv 1 \pmod{2}$.
So the answer is $p=2$.


text:
Q: 301 Redirect in Wordpress not working in htaccess I've tried multiple blocks of code and none of them work, i.e.:
RewriteEngine on
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

and
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]

among others.
Here is the contents of htaccess file:
RewriteEngine on

    Options +FollowSymLinks
    RewriteEngine on
    RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

<Files 403.shtml>
order allow,deny
allow from all
</Files>

# TEMPORARILY DISALLOW SEARCH INDEXING
User-agent: *
Disallow: /

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# Prevents directory listing
Options -Indexes

# BEGIN DEFLATE COMPRESSION
<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
 AddOutputFilterByType DEFLATE application/javascript
 AddOutputFilterByType DEFLATE application/rss+xml
 AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
 AddOutputFilterByType DEFLATE application/x-font
 AddOutputFilterByType DEFLATE application/x-font-opentype
 AddOutputFilterByType DEFLATE application/x-font-otf
 AddOutputFilterByType DEFLATE application/x-font-truetype
 AddOutputFilterByType DEFLATE application/x-font-ttf
 AddOutputFilterByType DEFLATE application/x-javascript
 AddOutputFilterByType DEFLATE application/xhtml+xml
 AddOutputFilterByType DEFLATE application/xml
 AddOutputFilterByType DEFLATE font/opentype
 AddOutputFilterByType DEFLATE font/otf
 AddOutputFilterByType DEFLATE font/ttf
 AddOutputFilterByType DEFLATE image/svg+xml
 AddOutputFilterByType DEFLATE image/x-icon
 AddOutputFilterByType DEFLATE text/css
 AddOutputFilterByType DEFLATE text/html
 AddOutputFilterByType DEFLATE text/javascript
 AddOutputFilterByType DEFLATE text/plain
 AddOutputFilterByType DEFLATE text/xml
</IfModule>
# END DEFLATE COMPRESSION

   <ifModule mod_expires.c>
 ExpiresActive On
 ExpiresDefault "access plus 5 seconds"
 ExpiresByType image/x-icon "access plus 2592000 seconds"
 ExpiresByType image/jpeg "access plus 2592000 seconds"
 ExpiresByType image/png "access plus 2592000 seconds"
 ExpiresByType image/gif "access plus 2592000 seconds"
 ExpiresByType application/x-shockwave-flash "access plus 2592000 seconds"
 ExpiresByType text/css "access plus 2592000 seconds"
 ExpiresByType text/javascript "access plus 2592000 seconds"
 ExpiresByType application/javascript "access plus 2592000 seconds"
 ExpiresByType application/x-javascript "access plus 2592000 seconds"
 ExpiresByType text/html "access plus 600 seconds"
 ExpiresByType application/xhtml+xml "access plus 600 seconds"
 </ifModule>

#Gzip Compression
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

#Protect htaccess file
<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>

ExpiresActive on

# Add a far future Expires header for fonts
ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
ExpiresByType application/x-font-ttf "access plus 1 year"
ExpiresByType application/x-font-opentype "access plus 1 year"
ExpiresByType application/x-font-woff "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"

# Block spam IP's

deny from 208.80.194.26
deny from 199.217.119.217
deny from 196.44.162.14
deny from 194.28.87.135
deny from 151.213.104.194
deny from 141.8.193.26
deny from 122.144.9.251
deny from 90.156.201.106
deny from 88.152.196.9
deny from 82.146.63.24
deny from 82.146.62.183
deny from 81.177.139.93
deny from 181.65.101.189
deny from 122.150.67.57
deny from 190.195.174.151
deny from 202.59.224.56
deny from 105.101.150.31
deny from 92.111.57.75
deny from 97.92.162.132
deny from 88.109.139.18
deny from 27.147.226.76
deny from 83.132.173.100
deny from 85.73.91.157
deny from 174.2.81.222
deny from 190.122.146.5
deny from 75.74.10.220
deny from 99.8.78.131
deny from 196.207.91.111
deny from 41.218.19.132
deny from 99.8.78.131
deny from 85.135.210.16
deny from 24.15.104.240
deny from 138.201.125.143
deny from 115.28.43.234
deny from 115.135.6.46
deny from 115.188.146.137
deny from 115.28.240.215
deny from 142.161.98.92
deny from 51.255.65.42
deny from 52.71.155.178
deny from 176.9.118.102
deny from 70.90.119.26
deny from 70.90.213.86
deny from 86.143.107.221
deny from 180.216.56.20

SetEnvIfNoCase Referer darodar.com, priceg.com, iedit.ilovevitaly.com, toddard.com, intained.com, icalc.ilovevitaly.com, ilovevitaly.co, co.lumb.co/, co.lumb.co, semalt.semalt.com, semalt.com, buttons-for-website.com, semalt.semalt.com, a.xtopoly.com, hulfingtonpost.com, forum.topic29421116.darodar.com, spamlink=yes

 Order allow,deny

 Allow from all

 Deny from env=spamlink

#AddType application/x-httpd-php53 .php

# php -- BEGIN cPanel-generated handler, do not edit
# Set the "ea-php71" package as the default "PHP" programming language.
<IfModule mime_module>
  AddType application/x-httpd-ea-php71 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

Requirements:

*

*Redirect from old site to new site and keep the url path the same

*Redirect subdomains to a new path i.e. 'category.old-domain.com' > new-domain.com/category

*Most efficient for SEO

*HTTP + HTTPS from old domain to HTTPS on new domain

What am I missing? Thanks.


text:
Q: Save Hash in DB and generate URL i'm using an open api which works with session ids.
A little background:
A user enters my site and get's a url and session:
domain.tld/somelongsessionhash (which is usually 50 characters long)
A user can now share this url to do some collab work on a file.
i now want to to shorten the somelongsessionhash which i get from the api-service.
i thought i could do it this way:

*

*Save the somelongsessionhash in the db

*Generate my own shorter hash

*If the own shorter url gets called, php checks the db and gets the real session.

I'm new to php and would love to solve this. Any hints appreciated! :)

A: Well, I'll give you a short example of what you can do.
Let's say you store your hash in temporary variable ($hash).
To generate a short string for your URL you can use something like this:
$short_hash = substr(str_shuffle($hash), 0, 8);

Use that variable and store the value in DB. The only thing left to do is to check if the current URL( www.example.com/f65fcb33/ - for example) matches a record in your DB, and do whatever you want.
This is just a sample method, you can always search internet for something more to expand.


text:
Q: How to forward an email using Office JS Add-in API? I'm trying to develop an add-in using Office 365 Javascript API for Outlook. I'm using Microsoft's reference to look for methods that will allow me to forward the currently opened email when I click a button. The issue is that there's not a single method on the reference that can do that, how can I forward an email using Office JS API?
I imagine it should be something like that:
var item = Office.context.mailbox.item;  # item represents the currently opened email
item.Forward(email)

A: There isn't a method for forwarding the current email included in Office.js.
One alternative solution would be to use Microsoft Graph for this. You'll need to register an Application ID using the steps outlined in Authenticate a user with an single-sign-on token in an Outlook add-in.
Once you have a token and the message's id, you call into Microsoft Graph /forward endpoint:
POST https://graph.microsoft.com/v1.0/me/messages/{id}/forward
Content-type: application/json

{
  "comment": "",
  "toRecipients": [
    {
      "emailAddress": {
        "name": "recipient-name",
        "address": "recipient-email"
      }
    }
  ]
}

A: Currently the feature you requested is not part of the product.
However, we track Outlook add-in feature requests on our user-voice page. Please add your request there.
Feature requests on user-voice are considered when we go through our planning process.
[Outlook Add-ins Engineering Team]


text:
Q: Are these duplicates just because they have similar answers: "capital of France" vs "largest city in France"? As a general practise across different Stack Exchange communities, is it true that that one of these two questions should always be closed as a duplicate, since both questions have similar answers?

*

*"What is the capital of France?"

*"What is the largest city of France, in terms of population?"

The questions are clearly different, they only happen to have the same answer.
This issue came up recently when people tried to close one of my questions as a duplicate, and succeeded. I posted this comment:

Just because there are duplicate answers, that does not mean the questions are duplicates necessarily. "Paris" is the answer to both "what is the capital of France?" and "what is the largest city of France?"

To my amazement, some people responded that having a duplicate answer is enough of a reason to close a question as duplicate (some of these comments have since been deleted). They pointed to this meta post as the authoritative evidence to argue their reasoning:

How should duplicate questions be handled?

And they quoted:

Questions may be duplicates if they have the same (potential) answers. This includes not only word-for-word duplicates, but also the same idea expressed in different words.

Is it really the rule that different questions should always be closed if they have the same answers?
(I'm asking about the general and simplified case. The post that raised the issue for me obviously isn't quite as simple as the questions about France, and I don't want to get caught in the weeds of the specifics, my question post can remain closed as far as I am concerned.)

A: Each site has some leeway in this but in general, the questions, as that quote states, should be largely the same question.
If you asked the same question about the US or India, they'd quite clearly not be duplicate questions because the cities in each case aren't the same, so you wouldn't even be having this discussion in the first place.
So, there are a couple of alternate examples here that might be useful to keep in mind:

*

*What is the most populous city in France?

*What are the top ten cities in France by population?

I think you'd argue that these are duplicates, no? They're about the same subject, the same metric, one is broader than the other but they are the same and number 2 is more useful to a bigger audience because it has more information in it.
So, what if we compare question one with question three:

*What are the capital and most populous cities for each country in Europe?

These, too, are similar enough to be useful to a wide audience in a way the individual questions for each wouldn't be - they'd even be arguably less useful if asked individually because you'd have to find each one (and ask a new one if one didn't already exist), so sometimes grouping information is helpful - Wikipedia even has such a page for all countries.
On Stack Exchange, this would be called a canonical question. They can be difficult to get right but they're useful to sites that get many very similar questions that are generally answered the same way or that make more sense as a collection because of how related they are. For example, on Cooking, instead of having one question for "What's the difference between biscuit in American English and British English", there's a helpful glossary of differences between English variants all in one post.
Admittedly, in some cases, canonical questions can get too big and may be overwhelming for users, so it's important to balance the breadth of the canonical question with ease of use. If it's going to take 20+ minutes to sift through a giant answer to find the exact thing you're looking for, then it may be better to divide things up.

When it comes to an answer on one question being broader than the question needs and answers another question - as in the example:

Q: What is the capital city of France?
  A: Paris is the capital city and also the most populous city in France.

If this is going to be a dupe target for "What is the most populous city in France?" I'd much rather someone edited the question to ask both than just outright closing the new question as a dupe. Why? Because that leads to a lot of potential for overreach with duplicate closures.
With this example question, this is very simple because both the question and answer are very brief, so handling both questions simultaneously is going to be more useful in the end than having two separate questions. It may even eventually turn into question three above if this one question starts spawning identical versions for every country in Europe. Yes, we should consider whether editing the question would invalidate existing answers or not... keep reading...
If someone asks a specific question that's complicated and needs a longer answer and someone goes out of their way to write an exhaustive answer that covers tons more information than the question asks for they may be obscuring the answer to the question asked in their long answer, making it less useful to the OP and others coming after and they may also be over-answering - broadening the question beyond what would normally be OK on the site.
Stack Exchange thrives on having multiple answers to the same question - we even look for it in determining which sites are ready to graduate from Beta. If someone asks a question that is answered in another, but only in one of several answers because that wasn't the intent of the original question, there may be alternate or even better solutions or explanations that are never addressed because of it.
This is what I encourage duplicate close voters to be wary of - they should ask themselves:

*

*Is this information so related that failing to include it does the question a disservice and most if not all of the existing answers already address it?

*Is this information added to an answer because it's an interesting related piece of information and only one person thought to mention it?

If it's the former, then the older question can probably be edited to include the new question and all of the best answers (rather than a single one) should have already taken it into account. If it's the latter, we're forcing the person asking the new question to filter through several answers to find the one that actually addresses their question and it may not even do so adequately. In this case, the questions should not be considered duplicates.

A: I will go out on a limb here and argue that those two are not the same answer. The word Paris happens to describe two distinct "ideas" (if you will).
I have seen this best described by Richard U in chat here:

Even if a common answer is "A pound", it doesn't mean "What is a unit of measurement that represents 16 ounces", "Where is a stray dog taken", and "What is the standard currency of the UK" are duplicate questions.

Wikipedia has lots of disambiguation pages to enlist the same word/term being used differently in different contexts.
A better example of two questions being duplicates for having the same answer would be:

*

*Which is the largest city in France in terms of population?

*In which French city do most people live?

(OR)

*

*Which is the capital city of France?

*Which city houses most of the administrative setup of the French government?

Those are differently worded questions describing the same idea.
One of the reasons why we mark questions as duplicates is Search Engine Optimization (SEO), or in other words, to allow people posting different phrases into internet search engine box to arrive at their answer here. Marking questions as duplicates because they happen to have homonymous answers goes against it.

A: If "What is the capital of France?" was closed as a duplicate of "What is the largest city of France, in terms of population?" where an answer say

The largest French city is Paris, which is also the French Capital

then the duplicate would be ok because the answer there covers both questions.
That's on the 'It is easy to figure out my answer is there' side of the guidances for duplicates:

It depends how easy it is to figure out one example from the other.

Your exemple here is a little problematic as the answers are coincidentally related only and have no reasons to be the same, a more proper analogy would be a question about the reasons of Paris district 16th being the 16th closed as a duplicate of another question asking about how much districts are inner Paris where an answer address all districts and the reasons of their numbering.
Answering both question may raise a plagiarism problem for cases of where you search for a duplicate, think it worth being tailored to question and end up using the other answer as a start base. It also bring duplicated answers, from various persons on multiple question, each with its bit of specificity but spread this in multiple places less useful for future readers, closing as duplicate helps putting more complete answers on a unique place which are more likely to help future readers with their specific point also.
To continue on your exemple and assuming there's few answers covering more than just the largest city and capital, dropping a word of two about Paris population in time and how it is split in districts, then more questions can be closed as duplicate and answers can be edited to better address the new duplicate when needed, bringing a better overview for someone searching about the subject than separated answers on multiple questions with no link to each others.


text:
Q: Как получить доступ к массиву, если он запакован в object На входе метода я получаю тип object внутри которого имею массив. Вопрос, как мне подступиться к элементам массива. Object[0] не получается, хотя я вижу что там массив и элементы с индексами.
Вот код метода, который возвращает object.
 public object GetImportedFromSQLite(string connstring, string idrecord,string tablename,string Idname)
        {
            object imported = null;
            using (SQLiteConnection connect = new SQLiteConnection(connstring))
            {
                connect.Open();
                using (SQLiteCommand fmd = connect.CreateCommand())
                {
                    var sb= new StringBuilder();
                    var que = sb.Append("SELECT * FROM "+tablename+" where "+Idname+"="+idrecord);

                    fmd.CommandText = que.ToString();
                    fmd.CommandType = CommandType.Text;
                    SQLiteDataReader r = fmd.ExecuteReader();

                    while (r.Read())
                    {
                        object[] values = new object[r.FieldCount];
                        r.GetValues(values);
                        imported= values;
                    }

                }
            }
            return imported;
        }

Вот так я хочу получить из него массив, а потом элементы массива.Но выходит ошибка.
var rezultFromSqLite=INSTANCE.GetImportedFromSQLite
string[]parametrsFromSqLite=(string[])rezultFromSqLite;

Получаю ошибку приведения.

A: Нужно привести тип к массиву:
//неявное приведение к объекту
object obj = new int[]{1, 2, 3};
//явное приведение к массиву
int[] arr = (int[]) obj;

Укажите нужный тип массива вместо int.
Дополнение в комментарии:

Да с упаковкой и распаковкой я знаком и ваше решение правильное, но оно тривиальное. я думал так, вот у меня есть целый object внутри него массив, это поля от запроса к базе, я думал, что, так как это массив и значит в этой последовательности можно как то обратиться короче и сразу к нужному элементу, например в моем случае это 1 и второй элемент. нулевой элемент мне не нужен.

Не думаю, что есть хороший способ делать это без явного приведения. Если бы к элементам массива можно было обращаться через переменную типа object, то сам тип массива потерял бы смысл.
Приведение можно писать в одну строку:
int a = ((int[]) obj)[1];

но это некрасиво.
Впрочем, вижу два варианта для сокращения и улучшения кода.

*

*Нормальное ООП: если метод принимает массив, объявите аргумент как массив.

Вместо
void Method(object obj)

Сделайте:
void Method(int[] arr)

и обращайтесь по индексам свободно. Если метод должен принимать иногда массив, а иногда другие объекты, то сделайте несколько перегрузок метода.
Так Вы получите проверку типа и безопасное обращение к массиву.

*Использовать динамическую типизацию.

Если так напрягает статический тип, то используйте динамический. Объявите аргумент метода как dynamic:
public static void Main()
{
    Method(new []{1, 2, 3});
}

private static void Method(dynamic obj) {
    Console.WriteLine(obj[1]);
}

C# поддерживает тип dynamic который может принимать любой тип и через который можно обращаться к элементам массива. При этом Вы потеряете проверку на соответствие типа, но т.к. сейчас у Вас там object, её у Вас и так нет.
Дополнение по обновлению вопроса:
var rezultFromSqLite=INSTANCE.GetImportedFromSQLite
string[]parametrsFromSqLite=(string[])rezultFromSqLite;

rezultFromSqLite переменная типа object, которая содержит массив типа object[].
Массив объектов нельзя напрямую привести к массиву строк. Вот такое приведение сработает, например:
object[]parametrsFromSqLite=(object[])rezultFromSqLite;

Но, раз метод у Вас возвращает массив, то лучше и указать это в сигнатуре метода:
//возвращаем массив объектов
 public object[] GetImportedFromSQLite(string connstring, string idrecord,string tablename,string Idname)
{
     //object imported = null; обойдемся без
     ...
     while (r.Read())
     {
          object[] values = new object[r.FieldCount];
          r.GetValues(values);
          return values;
     }
     ...
     return null;
}

После этого никакого приведения не требуется:
var rezultFromSqLite=INSTANCE.GetImportedFromSQLite
Console.WriteLine(rezultFromSqLite[0]);

И если нужен массив строк, а не объектов, то приведите массив объектов к массиву строк и возвращайте его:
//возвращаем массив строк
public string[] GetImportedFromSQLite(string connstring, string idrecord,string tablename,string Idname)
{
     ...
     while (r.Read())
     {
          object[] values = new object[r.FieldCount];
          r.GetValues(values);
          return values.Select(v => v?.ToString()).ToArray();
     }
     ...
     return null;
}