text:
Q: When do we need fully quantum mechanically treatment of photon? I'm wondering when do we need fully quantum mechanically treatment of photon.(i.e. quantized photon and quantum matter.)
I kind of know that for sub-Poisson(photon statistics) light, fully quantum mechanically treatment was necessary.
However, I heard that some other experiments like photoelectric effect was shown to be able to treat semi-classically. The interference experiment was also some where semi-classical treatment was popular, but sometimes fully quantum theory was necessary.

A: You cannot treat a photon quantum mechanically.
In the sense that quantum mechanics cannot describe photons.
For several reasons:

*

*Quantum mechanics is just built for few-body problems, it does not extend well (in terms of tidiness) to many-body problems, such as large sources of photons/high intensities

*Normalisation. Photons can be absorbed / emitted, i.e. (dis)apperaing from thin air. Cannot normalise the wavefunction

*Causality. Quantum mechanics does not preserve causality. Relativistic quantum mechanics (where the Hamiltonian $H=\sqrt{p^2+m^2}$) does not either. And for photons, moving at $c$, causality is quite important.

Hence, a new framework is needed, quantum field theory, where the wavefunction is not the protagonist but rather the quantum field operators. When people talk about "quantum treatment" of light, they mean quantum field theory.
Quantising light means that you define the creation operator $a^\dagger_{\mathbf{k}}$, such that you create one photon at momentum $\mathbf{k}$ from the vacuum $|0\rangle$:
$$a^\dagger_{\mathbf{k}} |0\rangle = |\mathbf{k}\rangle .$$
Semi-classical treatments usually see the atoms being treated* quantum mechanically*, meaning they have discrete energy levels and obey the Schrödinger equation, while the light is treated classically, i.e. made of a continuum of photons of given intensity I.
The semi-classical approximation is what's behind the usual treatment of light-matter interactions (look up "dipole approximation"), light absorption from a medium, photoelectric effect etc.
It breaks down for single or few photon events, where you really need to consider photons individually. It also breaks down for spontaneous emission, because this process involves the various "photon modes" of the vacuum (different $a^\dagger$) coupling to your specific system. In these cases you need to quantise both the atom and the light, see e.g. here.


text:
Q: What networking tools do video games use to get real-time communication? I'm interested in understanding the networking technology behind video games -- specifically I'm interested in large multiplayer games and how companies are able to simulate real-time connection in these games.
What technology is generally used? Is it just WebSockets or is it something more sophisticated?

A: So an up and coming technology being used to implement real-time communications in video games is Web Real-time Communications (WebRTC). It's just beginning to be used in the entertainment space for video games, live streaming, and more.
BlogGeek.Me goes into a few specific instances where WebRTC is valuable for gaming. Games like Agar.io, Deip.io and others were built with WebRTC way back before 2016. Definitely something to look into when building a video game with peer-to-peer communication.
As a note - if I had to guess, this question was most likely downvoted because it is too vague, could elicit spam and personal opinions, and lacked research by the poster beforehand. There are a lot of articles on the underlying technology behind video games available with a quick Google search, which is outside of the scope of questions/answers on StackOverflow.

redpajama_set_name: RedPajamaStackExchange


text: Q: Не могу понять, как на нативном JS получить JSON(лежит там же где и index.html) Задача в том, чтоб без использования библиотек и фреймворков получить json, а дальше парсить его. Вопрос, как это сделать? Нашел вариант, где можно просто в html-ке его прописать типа вот так <script type="text/javascript" src="source/questions.json"></script> , но тогда вопрос как с ним работать в script.js ?


text:
Q: How to detect if number of associated objects change? class Post < ActiveRecord::Base
  has_many :comments

  after_save :do_something, if: -> (post) { [ something like post.comments.count.changed? ] }
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

How to execute do_something if number of comments change ?
I want to execute do_something if I detect more than 3 changes by example : 2 comments added, 2 deleted.


text:
Q: Integer overflows when stored into 'Int Phone Number In xcode 8, I am getting an error when I try to archive. This is the code:
@IBAction func dialNumber(_ sender: AnyObject) {

    if let url = URL(string: "tel://\(8708382937)") {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}

On the line that begins with "if let..." I am getting this error:
Integer literal '8708382937' overflows when stored into 'Int'

A: This is expected and a correct error. Why are you putting the number in \()? That evaluates it as Swift. As Swift that's a literal number, which is too big to fit in an Int. You almost certainly mean this:
"tel://8708382937"

Or more sensibly:
"tel:8708382937"

(The slashes are specifically part of the HTTP URL-scheme. They are not a general part of URLs and do not belong on tel URLs.)

A: There's no reason not to just use a string literal for the URL.
if let url = URL(string: "tel://8708382937") {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}


text:
Q: Rewrite first level subdirectory to root directory passing folder name .htaccess I have an application where I pass in the customer name to determine which information to show on the page.
Previously I had it setup to be subdomain based, for example https://client1.company.com, https://client2.company.com. I would parse the subdomain to determine the customer name, and each subdomain pointed to the same set of files on the server.
I have to change this to be subdirectory based, so it would now be https://company.com/client1/, https://company.com/client2/, etc.
Is there an .htaccess rewrite rule I can use to basically rewrite any request with a subdirectory back to the root directory? This way when an ajax request goes to the server from https://company.com/client2/ it will redirect the request to https://company.com/ajax.php as opposed to sending the request to https://company.com/client2/ajax.php and it not being found.
When loading stylesheets, etc. it would redirect https://company.com/client1/assets/css/style.css to https://company.com/assets/css/style.css.

A: You may use this rule in your site root .htaccess:
RewriteEngine On

# redirection to a level up
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^[\w-]+(/.*)$ $1 [L,R=301]


text:
Q: Policies and Procedures Database I'm trying to create a database for work purpose, and I need you guys to help me. I don't know if my idea possible or not but i want to give a chance to apply it.
As the title I want to make database for all policies and procedures in our organization. The purposes of this database are whenever my manager want to review any policy he can search for the policy by keyword, or title, or the code of each policy, also in order to make any change on that policy, he can review, edit the policy and print it. While he doing some changing on a specific policy I want to keep the original policy as well, so if I want to make a historical report for that policy I can generate all changes happens on that policy, the original one, the first change, the second change and so on.
What I want to is creating a " Master Table " Consist of all updated Policies for "  4 Departments " and I want to create a separate tables for each department. And then create a relationship between all those table, (all of them link with the Policy code column -if possible-). So, whenever the user enter data from the displayed form, this data will be record in master table, and the entered data will be saved in the related department table ( if he enter a data related to the department 1, the data will be saved in the master table and the department 1 table, and etc. ). So the result of all of these are whenever I want to make a report for all entered policies I can generate it from the master table, and whenever I want to make a separate report for each policy I can do that too.
My question is, if this database possible to be create, how i can create it, where I faced a lot of problems while I tried to create it, and if it's not possible, What should I do in order to get that features that my manager want?
Waiting your response.
The Features that I want to be exist are:
1- Display the policy in proper formatting (Making a Report)
2- Editing an existing policy.
3- Adding New Policy.
4- Make a historical report for each policy.
5- Searching bar to be search by keyword, title, policy code, and column name
6- Printing that policy
7- all document should be different by the unique version number.

A: If this were my project, I would run away from MS Access. A content management system or wiki would be a better choice - formatting and versioning are built in and you don't have to code it from the ground up.


text:
Q: Xamarin.Forms isn't changing media I'm doing:
Xamarin Forms App Icon Correct way,
Launch Screens for Xamarin.iOS Apps
On simulator all working good, but when i run Visual Studio from Windows with my iPhone, it wasn't working. Just nothing doesn't change.


text:
Q: Openshift: Installing Django 1.5 causes Server 500 error I have created a Django 1.3 application on Openshift.
I wanted to upgrade to Django 1.5. So I updated setup.py to install Django 1.5
#!/usr/bin/env python

from setuptools import setup

setup(
    name='<Application name>',
    version='1.0',
    description='',
    author='',
    author_email='',
    url='http://www.python.org/sigs/distutils-sig/',
    install_requires=['Django>=1.5'],
)

The server returns http 500.
If setup.py has install_requires=['Django<=1.4'] it works fine.
How can I install Django 1.5 on Openshift?
Update: I can see a github commit where in the install_requires for Django is changed from >=1.3 to <=1.4 for the handling this same issue. But I still cannot figure out what caused that server 500 and how can we install Django 1.5 on openshift

A: It might come from your code, did you check the backwards incompatibilities mentioned in the release notes (mainly ALLOWED_HOSTS required in your settings.py)
It could also come from the {% url %} tag syntax change, see here.

A: When i installed Django app on OpenShift, Django version was 1.5.1.  I think OpenShift install last version Django, because the condition Django  >= 1.4, that is no lower this version.
That is screenshot, when i installed app

A: I had the same issue : from your screenshot you're using python2.6 ?
Try to use python2.7 with this configurations put on the application file:
#!/usr/bin/env python

import os
import sys

sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR']))

os.environ['DJANGO_SETTINGS_MODULE'] = 'mywebsite.settings'

virtenv = os.environ['OPENSHIFT_HOMEDIR'] + 'python/virtenv/'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.7/site-packages')

virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
    execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
    pass
#
# IMPORTANT: Put any additional includes below this line.  If placed above this
# line, it's possible required libraries won't be in your searchable path
#

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

And as refered by @Charles L try to set the settings using allowed host


text:
Q: Mathematical model for Hanoi Towers The strategy for the Hanoi Tower puzzle is quite simple. It is based on parity only. In an $n$-pieces puzzle, $2^n-1$ moves are sufficient to carry the whole pile from one pole to another one. My question is

Is there any mathematical (algebraic, logical, ...) structure associated with the Hanoi Tower puzzle? Does the optimal strategy translate into some mathematical result about this structure?

A: The language which I have usually seen it written in is that of self-similar groups, which are automorphisms of rooted trees. I'd say this mostly falls under the label of geometric group theory, and is quite useful in the study of dynamical systems. The language of finite automata is useful in understanding these groups though.
@John Mangual did a fairly thorough rundown of references. I might add V Nerkrashevych's book "Self-similar groups" or "From fractal groups to fractal sets" for the theory, though I forget off hand if the Hanoi towers game is in there. I'll give a quick overview of how the model works.
Let's stick with 3 pegs, and $n$-disks, it gets confusing with more pegs. The set of configurations of the game are represented by a string of $n$ $1$'s, $2$'s, or $3$'s. The $k$th entry of the string is which peg the $k$th smallest disk is on. This uniquely represents a configuration because larger disks need to be below smaller disks. So the goal becomes how many moves does it take to transform $11\cdots 1$ to $33\cdots 3$.
We represent moves by three actions $a_{12}$, $a_{23}$, $a_{13}$. Where $a_ij$ represents moving a disk from the $i$th peg to the $j$th peg or visa versa or doing nothing if there are no disks on the $i$th or $j$th peg. (again only one of these is a legal move because small disks sit on larger ones) If you look at the Schreier graph (undirected graph where two elements are connected if there a generator that transforms one into the other) generated by these group elements acting on the strings, you get the Sierpinski gasket-looking graph that John posted. The number of moves in the optimal strategy is the same as the diameter of this graph.
If you regard the collection of all strings of $1$'s, $2$'s, or $3$'s of all lengths as a rooted tree where two words are connected when one can be obtained from the other by appending an number to the right, i.e. $112$ is connected to $1121$. (we also need to add the "empty word," --- the word of length 0 so everything is connected). Then these $a_{ij}$ are automorphisms of this tree, and we can study the group they generate. The action of the group on the tree induces a relation on the boundary of the tree such the the boundary modulo the relation is the Sierpinski gasket with an induced self-covering. (in general a contracting self similar group induces a limiting dynamical system in this way)
I hope this helps!

A: Most mathematical models I know of are related to graphs (every vertex corresponds to a configuration of discs, and edges correspond to valid moves), and optimal strategies can be related to distances on these graphs.
There is a recent comprehensive monograph on the Tower of Hanoi and related puzzles (such as the Chinese Rings puzzle or the Tower of London). For the historically interested reader, there is also an in-depth account of the history of the puzzle and its mathematical treatment.
Hinz, A.M., Klavžar, S., Milutinović, U., Petr, C.,
The Tower of Hanoi – Myths and Maths,
Birkhäuser Basel, 2013.

A: The fundamental group of the Menger Cube is an uncountable locally free and residually free group that contains the fundamental groups of all one-dimensional separable metric spaces as subgroups. It is known to frighten children and mathematicians alike. One can work within this group using a reduced path calculus; however, there is also an interesting word calculus (due to Hanspeter Fischer and Andreas Zastrow) that can be framed in terms of a variation of the Towers of Hanoi game. This is possible because the Menger cube may be realized as the inverse limit of finite groups each of which is the state-graph $X_n$ of a variation of the classical game using $n+1$ two-sided disks.
Hanspeter even created an ipad app that allows the user to move around within the approximating graphs $X_2$ (image below) while seeing the game state at the same time. It had dramatic whooshing and ringing sounds so naturally I spent too much time playing around with it.

Hanspeter Fischer, Andreas Zastrow, Word calculus in the fundamental group of the Menger curve, Fundamenta Mathematicae 235 (2016) 199-226. https://arxiv.org/abs/1310.7968
From the introduction of the cited paper regarding the details of the variation:

In our version of the Towers of Hanoi, the placement of the disks is restricted to within the well-known unique shortest solution of
  the classical puzzle, while we allow for backtracking within this solution and for the
  turning over of any disk that is in transition. We color the disks white on one side
  and black on the other. Then the state graph of this new "puzzle" is isomorphic
  to $X_n$, with edges corresponding to situations where all disks are on the board
  and vertices marking the moments when disks are in transition. The exponents of
  the edge labels ($x^{\pm 1}$ or $y^{\pm 1}$) indicate progress ("$+1$") or regress ("$−1$") in solving the classical puzzle (we add a game reset move when the classical puzzle is solved) and their base letters indicate whether the two disks to be lifted at the respective vertices of this edge are of matching ("$x$") or mismatching ("$y$") color. Hence, each edge-path through $X_n$ corresponds to a specific evolution of this game, as recorded by an observer of the movements of the $n + 1$ disks.
Our word calculus can be modeled by aligning an entire sequence of
  such puzzles with incrementally more disks into an inverse system,
  whose bonding functions between individual games simply consist of
  ignoring the smallest disk. Subsequently, every combinatorial notion
  featured in the description of the generalized Cayley graph has a
  mechanical interpretation in terms of this sequence of puzzles

A: I searched "Tower of Hanoi" on arXiv (with 18 results at time of last edit):

*

*The Group of Symmetries of the Tower of Hanoi Graph

*The Tower of Hanoi and Finite Automata

*Shortest paths in the Tower of Hanoi graph and finite automata

*Asymptotic aspects of Schreier graphs and Hanoi Towers groups
A search on Wikipedia returned the Tower of Hanoi and Magnetic Tower of Hanoi.  Also the Flag Tower of Hanoi.

People are interested in the graph of Tower of Hanoi positions, which seems to be related to the Sierpinski Gasket, the longest solution and Hamiltonian paths. (sources: wikimedia.org)

There seems to be a language (in the sense of automata theory) related to the Tower of Hanoi, and a fractal structure.


text:
Q: Simplifying a set of linear equations using Scipy/Python I have a very large and sparse set of linear equations such that in matrix format they are of the form [A][x]=[B]. Moreover:
[A] is a square matrix. All values in both [A] and [B] are signed integers of size 8 bits (-128 to +128). Each row in the matrix [A] consists of only half a dozen entries so the matrix is very sparse.
The objective is to convert/simplify this set of linear equations or problem to a form [A]'[x]=[B]' where:

*

*[A]' has been tranformed into a matrix such that each column/row consists of a single entry, while all other entries are 0.

*The solution space for the new system is same as the original one i.e. the set of solutions for both: [A][x]=[B] and [A]'[x]=[B]' is always the same.

*Note that we are not solving the set of equations but just simplifying them.

We can do this manually, using Gaussian Elimination for small matrices.
I am hopeful this can be achieved easily using one of its inbuilt functions in Scipy or one of other python libraries. Can someone please help me with this?
P.S. I am very new to Scipy and struggling with this so if someone could break it down, i would be grateful.


text:
Q: SQL Query with Exists in Where Clause I have a query I have built that is to pull records up if changes are found in a change log table based on certain fields in my database being changed.  If changes aren't made, no record exists.  I have built my query which works really well to give me what I want BUT the problem is that when I narrow this down to a date range, if there are no records in the changelog to check against, I get nothing back.  Is there a way to do a "If Exists" of sorts in the where statement to check for date and if a record doesn't exist, still allow results to come back since I have coded result text in my select statement?  Here is my code:
Declare @StartDate as date
Declare @EndDate as date

Set @StartDate = '9/20/2021'
Set @EndDate = '10/1/2021'

Select DISTINCT n.ID, n.FULL_NAME, n.Company, n.Status, n.Email,
    Case
        when Coalesce(CLDP.CurrentValue, 'No Update Found') <> 'No Update Found' then CLDP.CurrentValue
        When Coalesce(CLDP.CurrentValue, 'No Update Found') = 'No Update Found' and b.PROFESSION <> '' then b.PROFESSION
        when Coalesce(CLDP.CurrentValue, 'No Update Found') = 'No Update Found' and b.PROFESSION = '' then 'No Update Found'
    end as ProfessionUpdate,

    Case
        when Coalesce(CLDE.CurrentValue, 'No Update Found') <> 'No Update Found' then CLDE.CurrentValue
        When Coalesce(CLDE.CurrentValue, 'No Update Found') = 'No Update Found' and b.ETHNICITY <> '' then b.ETHNICITY
        when Coalesce(CLDE.CurrentValue, 'No Update Found') = 'No Update Found' and b.ETHNICITY = '' then 'No Update Found'
    end as EthnicityUpdate,

    Case
        when Coalesce(CLDG.CurrentValue, 'No Update Found') <> 'No Update Found' then CLDG.CurrentValue
        When Coalesce(CLDG.CurrentValue, 'No Update Found') = 'No Update Found' and b.Gender <> '' then b.Gender
        when Coalesce(CLDG.CurrentValue, 'No Update Found') = 'No Update Found' and b.Gender = '' then 'No Update Found'
    end as GenderUpdate,

    Case
        when Coalesce(nl.LOG_TEXT, 'No Update Found') <> 'No Update Found' then nl.Log_Text
        When Coalesce(nl.LOG_TEXT, 'No Update Found') = 'No Update Found' and Cast(n.BIRTH_DATE as varchar) <> '' then Cast(n.BIRTH_DATE as VarChar)
        when Coalesce(nl.LOG_TEXT, 'No Update Found') = 'No Update Found' and Cast(n.BIRTH_DATE as varchar) = '' then 'No Update Found'
    end as BirthDateUpdate

from Customer as n inner join
    Members as b on b.ID = n.ID left join
    Profession as CLDP on n.ID = CLDP.ID left join
    Ethnicity as CLDE on n.ID = CLDE.ID Left Join
    Gender as CLDG on n.ID = CLDG.ID Left Join
    BirthDate as nl on nl.ID = n.ID
Where n.ID in ('12345', '67890') and
    cldp.createdon between @startDate and @endDate and
    clde.createdon between @startdate and @enddate and
    cldg.createdon between @startdate and @enddate and
    nl.date_time between @StartDate and @EndDate

A: You may use outer apply with left table containing a single dummy row. Like the below:

select *
  into t
from(values
    (1, 'a'),
    (2, 'b'),
    (3, 'c')
) as t(id, val)

select t.*
from (
  select 1 as dummy
) as dummy
  outer apply (
    select *
    /*Your query goes here*/
    from t
    where id > 10
  ) as t

  id | val
---: | :---
null | null

select t.*
from (
  select 1 as dummy
) as dummy
  outer apply (
    select *
    /*Your query goes here*/
    from t
    where id > 1
  ) as t

id | val
-: | :--
 2 | b
 3 | c

db<>fiddle here


text:
Q: TensorFlow Placeholder shape using batch size bigger than 1 I define two placeholders, x with shape [None,11] and y with shape [None,10]. Using None as first dimension I should be able to use the model with various batch sizes.
If I run in a stochastic gradient descent mode, using batch size one, everything works.
sess.run(train, {x: [df.values[i][0:11]], y: [df.values[i][11:]]})

In this case the placeholders x and y have shapes of (1,11) and (1,10).
If I run in full batch gradient descent mode, using the batch size 1000,
I get incompatible matrix operation errors.
In this case the placeholders x and y have shapes of (1000,11) and (1000,10).

InvalidArgumentError (see above for traceback): Incompatible shapes:  [10,10] vs. [1000,10]
[[Node: gradients/Sub_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"](gradients/Sub_grad/Shape, gradients/Sub_grad/Shape_1)]]

Of course I can't subtract a (10,10) and a (1000,10).
But I think TensorFlow would handle that "batch sizes" for me?
Thank you.
import pandas as pd
import tensorflow as tf
import numpy

## Import the Dummy Data from Excel
df = pd.read_excel("../data/DummyData.xlsx", sheetname=0, header=0, skiprows=1 )

x = tf.placeholder(tf.float32, shape=[None,11])
y = tf.placeholder(tf.float32, shape=[None,10])

# layer 1
W1 = tf.Variable(tf.random_normal(shape=[11,10]))
b1 = tf.Variable(tf.random_normal(shape=[10,1]))
prop_fn_1 = tf.matmul(x,W1) + b1
akt_fn_1 = tf.sigmoid(prop_fn_1)

# layer2
W2 = tf.Variable(tf.random_normal(shape=[10,10]))
b2 = tf.Variable(tf.random_normal(shape=[10,1]))
prop_fn_2 = tf.matmul(prop_fn_1, W2) + b2
akt_fn_2 = tf.sigmoid(prop_fn_2)

init = tf.global_variables_initializer()
# error
loss = tf.reduce_sum(tf.square(tf.subtract(akt_fn_2,y)))
opt = tf.train.GradientDescentOptimizer(0.0001)
train = opt.minimize(loss)

# Train Stochastic
# Using Gradient Descent

sess = tf.Session()
sess.run(init)
for i in range(1000):
    sess.run(train, {x: [df.values[i][0:11]], y: [df.values[i][11:]]})

    if i % 100 == 0:
        print( sess.run(loss,{x: [df.values[i][0:11]], y: [df.values[i][11:]]} ))
sess.close()

print("*****************")

# Train with Max Batch Size
# Using Gradient Descent
sess = tf.Session()
sess.run(init)
for i in range(1000):
    sess.run(train, feed_dict={x: df.values[:,:11], y: df.values[:,11:]})

    if i % 100 == 0:
        print(sess.run(loss, feed_dict={x: df.values[:,:11], y: df.values[:,11:]}))
sess.close()

A: Can you try this for me?
b1 = tf.Variable(tf.random_normal(shape=[10]))
b2 = tf.Variable(tf.random_normal(shape=[10]))


text:
Q: I can't figure out how to extract a string in bash I am trying to make a bash script that will download a youtube page, see the latest video and find its url. I have the part to download the page except I can not figure out how to isolate the text with the url.
I have this to download the page
curl -s https://www.youtube.com/user/h3h3Productions/videos > YoutubePage.txt

which will save it to a file.
But I cannot figure out how to isolate the single part of a div.
The div is
Why I'm Unlisting the Leafyishere Rant

And I need to isolate the href at the end but i cannot figure out how to do this with grep or sed.

A: With sed :
sed -n 's/]*>/\n&/g;s/.*<a.*href="\([^"]*\)".*/\1/p'  YoutubePage.txt

To just extract the video ahref :
$ sed -n 's/]*>/\n&/g;s/.*<a.*href="\(\/watch\?[^"]*\)".*/\1/p' YoutubePage.txt
/watch?v=q6TNODqcHWA
/watch?v=q6TNODqcHWA
/watch?v=ix4mTekl3MM
/watch?v=ix4mTekl3MM
/watch?v=fEGVOysbC8w
/watch?v=fEGVOysbC8w
...

To omit repeated lines :
$ sed -n 's/]*>/\n&/g;s/.*<a.*href="\(\/watch\?[^"]*\)".*/\1/p' YoutubePage.txt | sort | uniq
/watch?v=2QOx7vmjV2E
/watch?v=4UNLhoePqqQ
/watch?v=5IoTGVeqwjw
/watch?v=8qwxYaZhUGA
/watch?v=AemSBOsfhc0
/watch?v=CrKkjXMYFzs
...

You can also pipe it to your curl command :
curl -s https://www.youtube.com/user/h3h3Productions/videos | sed -n 's/]*>/\n&/g;s/.*<a.*href="\(\/watch\?[^"]*\)".*/\1/p' | sort | uniq

A: You can use lynx which is a terminal browser, but have a -dump mode which will output a HTML parsed text, with URL extracted. This makes it easier to grep the URL:
lynx -dump 'https://www.youtube.com/user/h3h3Productions/videos' \
  | sed -n '/\/watch?/s/^ *[0-9]*\. *//p'

This will output something like:
https://www.youtube.com/watch?v=EBbLPnQ-CEw
https://www.youtube.com/watch?v=2QOx7vmjV2E
...

Breakdown:
-n '                             # Disable auto printing
    /\/watch?/                   # Match lines with /watch?
              s/^ *[0-9]*\. *//  # Remove leading index: " 123. https://..." ->
                                 # "https://..."
                               p # Print line if all the above have not failed.
                                '


text:
Q: Loop not getting executed properly I am trying to create a function which counts the length of elements in the list and then run an if / elif loop on them:
k_nearest_samples_class = training_data[sorted_indices[:k]][:, -1]
# print(k_nearest_samples_class)
# counting number of occurrences of either 0's or 1's with below 2 lines
class_0_count = len(k_nearest_samples_class[k_nearest_samples_class == 0])
class_1_count = len(k_nearest_samples_class[k_nearest_samples_class == 1])
class_2_count = len(k_nearest_samples_class[k_nearest_samples_class == 2])

# Combining > & = sign so even in tie-up cases the instance will be classified to malignant - assumed it
# would be okay in order to reduce false positives
if class_0_count >= class_1_count and class_2_count:
    print("0", class_0_count)
    return 0
elif class_1_count >= class_0_count and class_2_count:
    print("1", class_1_count)
    return 1
else:
    print("2", class_2_count)
    return 2

Giving input one by one like:
[0.0]
[1.0]
[2.0]

currently, my if loop is working illogically.

A: This line:
if class_0_count >= class_1_count and class_2_count:

is equivalent to:
if class_0_count >= class_1_count and class_2_count > 0:

you need to change it to:
if class_0_count >= class_1_count and class_0_count >= class_2_count:

or you can compare with the maximum value of the two:
if class_0_count >= max(class_1_count, class_2_count):

A: Expanding on @MoeA's answer above:
A (alternative) Pythonic way to perform this test is to use  the all() function like:
if all([class_0_count >= class_1_count, class_0_count >= class_2_count]):
    ...


text:
Q: Graphing difference of sets Question:
Let $ S = (-10,10) \times (-10,10)$
Let $ \ T\ =\ \left\{\left(x,y\right):\ x^2+y^2\le 100\right\}$
Graph $S-T$
My attempt:

This is my attempt. I am not sure if it is correct. Will the boundary of the circle be included?

A: Almost correct.
You just have to remove the boundary of the circle as they are in the set $T$ which are to be removed by definition of $S-T$.


text:
Q: Problem With Routing On Two Default Gateways I have setup a box/small server with three interfaces. One interface leads to an internal net and owns a default route in routing table rt1. Another interface is connected to a Fritz!Box and leads into the internet and also has a default route in routing table rt2.
I have put up two default gateways (table rt1 and rt2) and now I want to ping something in the internet on a certain interface (eth0.103), which leads to the Fritz!Box (and the internet), or even on both, but that does not work, although traceroute and even an SSH connection are working on this interface. I mean, I can even contact/connect to that box (eth0.103) from outside/over the Fritz!Box/internet. Also, on eth0.101 there is no routing or pinging happening.
The Fritz!Box has the address 192.168.178.1 and eth0.103 (192.168.178.20) is connected to it directly.
command
ping -I eth0.103 8.8.8.8
ping -I eth0.101 8.8.8.8

/etc/iproute2/rt_tables
#
# reserved values
#
255     local
254     main
253     default
0       unspec
#
# local
#
#1      inr.ruhep
1 rt1
2 rt2

/etc/network/interfaces
auto eth0.101
    iface eth0.101 inet static
    address 172.19.2.2
    netmask 255.255.255.0
    post-up ip route add 172.19.2.0/24 dev eth0.101 src 172.19.2.2 table rt1
    post-up ip route add default via 172.19.2.1 dev eth0.101 table rt1
    post-up ip rule add from 172.19.2.2/32 table rt1
    post-up ip rule add to 172.19.2.2/32 table rt1

auto eth0.102
    iface eth0.102 inet manual

auto eth0.103
    iface eth0.103 inet static
    address 192.168.178.20
    netmask 255.255.255.0
    post-up ip route add 192.168.178.0/24 dev eth0.103 src 192.168.178.20 table rt2
    post-up ip route add default via 192.168.178.1 dev eth0.103 table rt2
    post-up ip rule add from 192.168.178.20/32 table rt2
    post-up ip rule add to 192.168.178.20/32 table rt2

auto br0
    iface br0 inet static
    bridge_ports eth0.102 wlan0
    bridge_waitport 0
    address 192.168.1.254
    network 192.168.1.0
    netmask 255.255.255.0

ip route show
172.19.2.0/24 dev eth0.101  proto kernel  scope link  src 172.19.2.2
192.168.1.0/24 dev br0  proto kernel  scope link  src 192.168.1.254
192.168.178.0/24 dev eth0.103  proto kernel  scope link  src 192.168.178.20

ip route show table rt1
default via 172.19.2.1 dev eth0.101
172.19.2.0/24 dev eth0.101  scope link  src 172.19.2.2

ip route show table rt2
default via 192.168.178.1 dev eth0.103
192.168.178.0/24 dev eth0.103  scope link  src 192.168.178.20

I cannot figure out, if I did something wrong with those gateways or the routing rules/tables maybe. Also, I find it weird, that I can connect over the Fritz!Box's public IP address to the server, while pinging from it does not work. Thank you in advance, guys.

A: Alright, with a lot of googling and reading on Linux sites and here in Stack Overflow I found the solution.
The routing tables were fine, but somehow not transmitting the default gateways to the main table. Therefore I could not ping or achieve anything, but still traceroute was working. Even static routes were working.
So, I added those two important lines (with the metric values) in /etc/network/interfaces and now the default gateways of both routing tables are transmitted to the main routing table.
/etc/iproute2/rt_tables
#
# reserved values
#
255     local
254     main
253     default
0       unspec
#
# local
#
#1      inr.ruhep
101 rt1
102 rt2

/etc/network/interfaces
auto eth0.101
    iface eth0.101 inet static
    address 172.19.2.2
    netmask 255.255.255.0
    post-up ip route add 172.19.2.0/24 dev eth0.101 src 172.19.2.2 table rt1
    post-up ip route add default via 172.19.2.1 dev eth0.101 table rt1
    post-up ip rule add from 172.19.2.2/32 table rt1
    post-up ip rule add to 172.19.2.2/32 table rt1
    post-up ip route add default via 172.19.2.1 metric 100 dev eth0.101
    post-down ip rule del from 0/0 to 0/0 table rt1
    post-down ip rule del from 0/0 to 0/0 table rt1

auto eth0.102
    iface eth0.102 inet manual

auto eth0.103
    iface eth0.103 inet static
    address 192.168.178.20
    netmask 255.255.255.0
    post-up ip route add 192.168.178.0/24 dev eth0.103 src 192.168.178.20 table rt2
    post-up ip route add default via 192.168.178.1 dev eth0.103 table rt2
    post-up ip rule add from 192.168.178.20/32 table rt2
    post-up ip rule add to 192.168.178.20/32 table rt2
    post-up ip route add default via 192.168.178.1 metric 101 dev eth0.103
    post-down ip rule del from 0/0 to 0/0 table rt2
    post-down ip rule del from 0/0 to 0/0 table rt2

auto wlan0
    iface wlan0 inet manual

auto br0
    iface br0 inet static
    bridge_ports eth0.102 wlan0
    bridge_waitport 0
    address 192.168.1.254
    netmask 255.255.255.0


text:
Q: What are the recommended steps to take before selling an iPhone? I "lost" my iPhone at work, could not find it anywhere. I reported it lost, and got another through the insurance. A month later, I found it hiding in a file in one my desk drawers. The phone is just less than a year old, in near new condition, and it seems a waste to discard it. What has to be done to be able to sell it to someone who needs a working phone?

A: In terms of privacy - unlink your AppleID account and just go to Settings > General > Reset. Clean everything (Reset All Settings & Erease All Content and Settings) and you're ready to sell / give your phone.


text:
Q: Find out if ImageView will respect orientation I build a "gallery" application. I have an issue with the orientation of images. I've created the images (camera) and believe that have set the orientation correctly. It can be shown in the built-in gallery and on my application on various devices.
Strangely on Sony Xperia, the ImageView of my application did not show correctly (built-in gallery showed correctly). Then I tried to set a rotation matrix for an ImageView and set the scaleType to matrix, yet it still did not work. I had to rotate the Bitmap itself before putting it in the ImageView.
So here is the question at last. How to check if an ImageView will work the orientation by itself, or not (and then the code should do what it has to do). I don't believe it is an Android version. My Sony Xperia is Android 4.4.4.

A: You can rotate an bitmap of an imageview by using the below code
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    // Decode Image using Bitmap factory.
    Bitmap bMap = BitmapFactory.decodeFile(uriimage.getPath(), bmOptions);

    // Create object of new Matrix.
    Matrix matrix = new Matrix();

// set the rotation as per your requirement
        matrix.postRotate(90);
    // Create bitmap with new values.
    Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(),
            bMap.getHeight(), matrix, true);

//now set the bitmap to imageview
imageview.setBitmap(bmapRotate);
Hope it will help you

A: Prasad thank you.
Just after posting the question, I've found (in SO) the easy solution also for Sony Xperia.
Use: imageView.setRotation(orientation); Found it here: https://stackoverflow.com/a/14509371/1614089


text:
Q: Как передать информацию из класса Main в другой класс java вот класс Main, в него пользователь вносит свои данные
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your name: ");
        String name = scan.nextLine();
        System.out.println("Enter your login: ");
        String login = scan.nextLine();
        System.out.println("Enter your age: ");
        int age = scan.nextInt();
        System.out.println("Enter your hobbies: ");
        String hobbies1 = scan.nextLine();
        String hobbies = scan.nextLine();

мне необходимо из этого класса передать данные в этот конструктор, который примет все данные от пользователя
public class Scanning extends Main {
  public Scanning(){}
  public Scanning(String name, String login, int age, List<String> hobbies){
  }
}

я не понимаю как это сделать, я еще совсем новичек, так что не бейте, если тут все супер просто)

A: Вы все правильно делаете, осталось добавить поля класса и инициализировать их.
public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your name: ");
        String name = scan.nextLine();
        System.out.println("Enter your login: ");
        String login = scan.nextLine();
        System.out.println("Enter your age: ");
        Integer age = Integer.valueOf(scan.nextLine());
        System.out.println("Enter your hobbies: ");
        String hobbies1 = scan.nextLine();
        String hobbies2 = scan.nextLine();

        Scanning scanning = new Scanning(name, login, age, hobbies1, hobbies2);

    }
}

public class Scanning {

    private String name;
    private String login;
    private Integer age;
    private List<String> hobbies;

    public Scanning(String name, String login, Integer age, String ... hobbies) {
        this.name = name;
        this.login = login;
        this.age = age;
        this.hobbies = Arrays.asList(hobbies);
    }

}

A: В первую очередь скорее всего вам нет необходимости писать extends Main т.к. это наследование, а оно вам вероятно не особо тут поможет.
В вашем классе Scanning присутствует 2 конструктора, один пустой (public Scanning(){}), другой принимающий параметры (public Scanning(String name, String login, int age, List<String> hobbies){}).
Для передачи данных в другой класс мы будем использовать второй.
Что бы вызвать конструктор, нужно создать экземпляр интересующего нас класса и передать ему параметры, которые требует второй конструктор, для этого создадим лист и запишем в него наши хобби (т.к. в вашем втором конструкторе требуется лист):
List hobbies = new LinkedList();
hobbies.add(hobbies1);
hobbies.add(hobbies2);

Теперь вызовем конструктор, создав новый экземпляр и передав необходимые данные:
Scanning scanning = new Scanning(name, login, age, hobbies);

Готово, мы передали данные в конструктор класса Scanning
UPD:
Так же мы можем поменять конструктор, как показал @Дмитрий в своем сообщении на:
public Scanning(String name, String login, Integer age, String ... hobbies)

Что бы он принимал набор строчек, тогда не будет необходимости создавать лист перед передачей данных, однако обратите внимание, что потом вам будет всеж нужно его обработать


text:
Q: Catching all unhandled C++ exceptions? Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?
I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.
something like:
global_catch()
{
    MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
    exit(-1);
}
global_catch(Exception *except)
{
    MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
    exit(-1);
}

A: Without any catch block, you won't catch any exceptions. You can have a catch(...) block in your main() (and its equivalent in each additional thread). In this catch block you can recover the exception details and you can do something about them, like logging and exit.
However, there are also downside about a general catch(...) block: the system finds that the exception has been handled by you, so it does not give any more help. On Unix/Linux, this help would constitute creating a CORE file, which you could load into the debugger and see the original location of the unexcepted exception. If you are handling it with catch(...) this information would be already lost.
On Windows, there are no CORE files, so I would suggest to have the catch(...) block. From that block, you would typically call a function to resurrect the actual exception:
std::string ResurrectException()
   try {
       throw;
   } catch (const std::exception& e) {
       return e.what();
   } catch (your_custom_exception_type& e) {
       return e.ToString();
   } catch(...) {
       return "Ünknown exception!";
   }
}

int main() {
   try {
       // your code here
   } catch(...) {
       std::string message = ResurrectException();
       std::cerr << "Fatal exception: " << message << "\n";
   }
}

A: Update: This covers c++98 only.
From More Effective C++ by Meyers (pg 76), you could define a function that gets called when a function generates an exception that is not defined by its exception specification.
void convertUnexpected()
{
    // You could redefine the exception here into a known exception
    // throw UnexpectedException();

    // ... or I suppose you could log an error and exit.
}

In your application register the function:
std::set_unexpected( convertUnexpected );

Your function convertUnexpected() will get called if a function generates an exception that is not defined by its exception specification... which means this only works if you are using exception specifications. ;(

A: Provided that C++11 is available, this approach may be used (see example from: http://en.cppreference.com/w/cpp/error/rethrow_exception):
#include <iostream>
#include <exception>

void onterminate() {
  try {
    auto unknown = std::current_exception();
    if (unknown) {
      std::rethrow_exception(unknown);
    } else {
      std::cerr << "normal termination" << std::endl;
    }
  } catch (const std::exception& e) { // for proper `std::` exceptions
    std::cerr << "unexpected exception: " << e.what() << std::endl;
  } catch (...) { // last resort for things like `throw 1;`
    std::cerr << "unknown exception" << std::endl;
  }
}

int main () {
  std::set_terminate(onterminate); // set custom terminate handler
  // code which may throw...
  return 0;
}

This approach also allows you to customize console output for unhandled exceptions: to have something like this
unexpected exception: wrong input parameters
Aborted

instead of this:
terminate called after throwing an instance of 'std::logic_error'
  what():  wrong input parameters
Aborted

A: This is what I always do in main()
int main()
{
    try
    {
        // Do Work
    }
    catch(std::exception const& e)
    {
         Log(e.what());
         // If you are feeling mad (not in main) you could rethrow!
    }
    catch(...)
    {
         Log("UNKNOWN EXCEPTION");
         // If you are feeling mad (not in main) you could rethrow!
    }
}

A: This can be used to catch unexpected exceptions.
catch (...)
{
    std::cout << "OMG! an unexpected exception has been caught" << std::endl;
}

Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.

A: Check out std::set_terminate()
Edit: Here's a full-fledged example with exception matching:
#include <iostream>
#include <exception>
#include <stdexcept>

struct FooException: std::runtime_error {
    FooException(const std::string& what): std::runtime_error(what) {}
};

int main() {
    std::set_terminate([]() {
        try {
            std::rethrow_exception(std::current_exception());
        } catch (const FooException& e) {
            std::cerr << "Unhandled FooException: " << e.what() << std::endl;
        } catch (const std::exception& e) {
            std::cerr << "Unhandled exception: " << e.what() << std::endl;
        } catch (...) {
            std::cerr << "Unhandled exception of unknown type" << std::endl;
        }

        std::abort();
    });

    throw FooException("Bad things have happened.");
    // throw std::runtime_error("Bad things have happened.");
    // throw 9001;
}

A: You can use SetUnhandledExceptionFilter on Windows, which will catch all unhandled SEH exceptions.
Generally this will be sufficient for all your problems as IIRC all the C++ exceptions are implemented as SEH.

A: Use catch (...) in all of your exception barriers (not just the main thread). I suggest that you always rethrow (...) and redirect standard output/error to the log file, as you can't do meaningful RTTI on (...). OTOH, compiler like GCC will output a fairly detailed description about the unhandled exception: the type, the value of what() etc.


text:
Q: Using NServiceBus in CQRS I am trying to implement a CQRS model for our website. The main idea is that each service(module) will be called via json web service which will in turn fire off update commands. Now my CQRS project is a just  a simple class library written in c# . When i have to publish the event at the end I need the Bus object, which I am not getting(i.e. the bus object is null) because I am not running nservice bus as an external application. Is there a way in which i can initialize the bus without running the application from an external line command.
Any help would be appreciated,
Thank you

A: In order to host NServiceBus in IIS, you will need to manually configure it.  Instructions for this are here.
NServiceBus can be hosted in any process, however, there can be reasons why hosting in IIS is not the best idea in some scenarios.  It is usually best to send a command to a generic host that is hosting your NServiceBus handlers.  This is usually deployed as a windows service and handles a particular type of message (command).
Hope this helps.


text:
Q: Associating aiohttp requests with their responses Very simply, I would simply like to associate responses from aiohttp asynchronous HTTP requests with an identifier, such as a dictonary key, so that I know which response corresponds to which request.
For example, the function below calls URIs suffixed with the dict values 1, 2 and 3. How could it be modified to return the the keys associated with each result? I just need to be able to keep track of which request is which… Doubtless trivial for someone familiar with asyncio
import asyncio
import aiohttp

items = {'a': '1', 'b': '2', 'c': '3'}

def async_requests(items):
    async def fetch(item):
        url = 'http://jsonplaceholder.typicode.com/posts/'
        async with aiohttp.ClientSession() as session:
            async with session.get(url + item) as response:
                return await response.json()

    async def run(loop):
        tasks = []
        for k, v in items.items():
            task = asyncio.ensure_future(fetch(v))
            tasks.append(task)
        responses = await asyncio.gather(*tasks)
        print(responses)

    loop = asyncio.get_event_loop()
    future = asyncio.ensure_future(run(loop))
    loop.run_until_complete(future)

async_requests(items)

Output (abbreviated):
[{'id': 2, ...}, {'id': 3, ...}, {'id': 1...}]

Desired output (for example):
{'b': {'id': 2, ...}, 'c': {'id': 3, ...}, 'a': {'id': 1, ...}}

A: Pass keys to fetch(), to return them with the corresponding response:
#!/usr/bin/env python
import asyncio
import aiohttp  # $ pip install aiohttp

async def fetch(session, key, item, base_url='http://example.com/posts/'):
    async with session.get(base_url + item) as response:
        return key, await response.json()

async def main():
    d = {'a': '1', 'b': '2', 'c': '3'}
    with aiohttp.ClientSession() as session:
        ####tasks = map(functools.partial(fetch, session), *zip(*d.items()))
        tasks = [fetch(session, *item) for item in d.items()]
        responses = await asyncio.gather(*tasks)
    print(dict(responses))

asyncio.get_event_loop().run_until_complete(main())


text:
Q: Vagrant to automatically clone git repo into specific folder during provision? I'm using VCCW: http://vccw.cc/ to have a local wordpress development environment, I need to have a vagrant box as one git repo, and the wordpress installation separately, because of amazon elastic beanstalk, my idea is to have the vagrant box automatically clone the wp installation repo during provision, how can this be accomplished?
Thanks

A: As you say, you can do that with simple shell provisioning:
Vagrant.configure(2) do |config|
  blablabla

  config.vm.provision "shell",
    inline: "git clone <path to git file>",
    run: "always",
    privileged: "false"
  end

Notes:

*

*you can do rebase or pull depending if your repo exists or not

*run: "always" makes sure this provisioning is run everytime you do up or reload

*privileged: "false" will make sure git is run with your vagrant user, so if you need to update you will not have privileges issue

*you need to make sure git is installed on the vm


text:
Q: R: Assigning values to data I have data from participants in a research study. I'm trying to score their responses by assigning a value of 1 if their response is correct and 0 if it is not.
In this case, Q1 represents the responses to the first question. "Yes" is the correct response. I entered:
if (is.na(Q1) || Q1 == "Yes") {Q1 <- 1} else {Q1 <- 0}

And all of the data in Q1 was replaced with 1, just 1, nothing else, while I was expecting a set of 0s and 1s.
Could you please tell me where I went wrong?

A: You should use ifelse :
ans <- ifelse(is.na(Q1) | Q1 == "Yes", 1, 0)

You can also do this without ifelse by casting the logical values to integer.
ans <- as.integer(is.na(Q1) | Q1 == "Yes")

A: We can also use + to coerce the logical to binary
ans <- +(is.na(Q1)| Q1 == "Yes")


text:
Q: Pandas dataframe- create new list column consisting of aggregation of strings from grouped column I've been struggling with this one a bit and am feeling a bit stuck.
I have a dataframe consisting of data like this, named merged_frames (it is a single frame, created by concatenating a handful of frames with the same shape):
          fqdn               source
0         site1.org          public_source_a
1         site2.org          public_source_a
2         site3.org          public_source_a
3         site1.org          public_source_b
4         site4.org          public_source_b
5         site1.org          public_source_b
6         site4.org          public_source_d                                 ...
7         site1.org          public_source_c
...

What I am trying to do is create a new column in this frame that contains a list (ideally a Python list as opposed to a command delimited string) of the sources when grouping by the fqdn value. For example, the data produced for the fqdn value site1.org should look like this based on this example data (this is just a subset of what I would expect, there should also be rows for the other fqdn values as well)
fqdn        source_list                                           source
site1.org   [public_source_a, public_source_b, public_source_c]   public_source_a
site1.org   [public_source_a, public_source_b, public_source_c]   public_source_b
site1.org   [public_source_a, public_source_b, public_source_c]   public_source_c
site1.org   [public_source_a, public_source_b, public_source_c]   public_source_d

Once I have the data in this form, I will simply drop the source column and then use drop_duplicates(keep='first') to get rid of all but one.
I dug up some old code that I used to do something similar about 2 years ago and it is not working as I expected it to. It's been quite a while since I've done something like this with Pandas. What I had was along the lines of:
    merged_frame['source_list'] = merged_frame.groupby(
        'fqdn', as_index=False)[['source']].aggregate(
            lambda x: list(x))['source']

This is behaving very strangely. While it is in fact creating source_list as a list/array, the data in the column is not correct. Additionally, quite a few fqdn values have a null/NaN value for source_list
I have a feeling that this I need to approach this completely different. A little help with this would be appreciated, I'm completely blocked now and am not making any progress with it, despite having what I thought were very relevant example blocks of code I used on a similar dataset.
EDIT:
I have made a little progress by just starting with the fundamentals and have the following, though this joins the strings together rather than making them a list:
    merged_frame['source_list'] = merged_frame.groupby('fqdn').source.transform(','.join)

I'm pretty sure with a simply apply here I can split them back into a list. But what would be the correct way to do this in one shot so that I don't need to do the unnecessary join and then apply(split(','))?

A: Create the data frame from the example above:
df=pd.DataFrame({'fqdn':['site1.org','site2.org','site3.org','site1.org','site4.org','site1.org','site4.org','site1.org'],\
                 'source':['public_source_a','public_source_a','public_source_a','public_source_b','public_source_b','public_source_b',\
                 'public_source_d','public_source_c']})

Use groupby and apply(list)
df_grouped=df.groupby('fqdn')['source'].unique().apply(list).reset_index()

Merge with original df and rename columns
result=pd.merge(df,df_grouped,on='fqdn',how='left')
result.rename(columns={'source_x':'source','source_y':'source_list'},inplace=True)


text:
Q: Change RGB value to a single value by converting its RGB without a loop Say I have a coloured image img.  Now, I want to create a new NumPy array based on the RGB value of the image.  I can do this by doing a loop, based on img values and compute the new array value based on the RGB values: say, newVal = R * val + G * val2 + B * val3. The newVal will then be appended to a NumPy array variable newNumpyVar.
Say I have this
img = [[[1 2 3] [0 0 1] [ 1 1 1]] [[0 0 0] [1 1 1] [ 0 0 0]]]

Its a 3 x 2 image. The results should be a 6 newVal array. 1st array is 1*1 + 2*2 + 3*3, 2nd array is = 0*1 + 0*2 + 1*3, 3rd is = 1*1 + 1*2 + 1*3 and so on.
I know that there is a way to do this in a NumPysh way.  But I just don't know how.

A: Simplest, but without control of how much each channel contributes (color_im is a numpy array):
gray_im = color_im.mean(axis=-1)

With weights:
gray_im = color_im[...,0]*R_weight + color_im[...,1]*G_weight + color_im[...,2]*B_weight # assumes RGB ordering of channels

The weighted version can be equivalently rewritten as:
gray_im = (color_im * np.array([R_weight, G_weight, B_weight])).sum(axis=-1)

A: You are looking for a sum-product of your image with a list of weights. If you have an image img of shape (M, N, 3) and weights vR, vG, vB, you can do any of the following to get a weighted (M, N) image:
img @ [vR, vG, vB]
np.dot(img, [vR, vG, vB])
np.einsum('mnc,c->mn', img, [vR, vG, vB])
np.sum(img * [vR, vG, vB], axis=-1)


text:
Q: How do I create batch file that opens windows command script file? I tried to search a lot but couldn't find any answer.
I have a windows command script file (anySoftware.cmd) which I'm trying to open it by a batch file.
I tried:
start "C:\myPath\anySoftware.cmd"

And:
start cmd.exe "C:\myPath\anySoftware.cmd"

And:
start anySoftware.cmd "C:\myPath"

All is not working.
Appreciate your help! Thanks!

A: Easiest solution:
"C:\myPath\anySoftware.cmd"

This works, too:

*

*CALL "C:\myPath\anySoftware.cmd" - Read more about CALL

*START "" "C:\myPath\anySoftware.cmd" - Read more about START


text:
Q: SSL Problem, Where should I insert the certificate.crt? I'm using startSSL. I've got a private key.key, a certificate.crt and a decrypted key.key for private key.key. What should I do with this files and where should I upload them? How can I get https for my website?
p.s.  I'm using a free web host. So I can't submit tickets for additional help, that's why I'm asking here.

A: If you are using apache check your httpd.conf and/or ssl.conf and add the appropriate lines.
from httpd.conf:
##SSL
SSLCertificateFile /etc/certs/example.com.crt
SSLCertificateKeyFile /etc/certs/example.com.key
SSLCertificateChainFile /etc/certs/intermediate.crt

from ssl.conf
SSLCertificateFile /etc/certs/example.com.crt
SSLCertificateKeyFile /etc/certs/example.com.key
SSLCACertificateFile /etc/certs/intermediate.crt

Make sure permissions are correct!!
Permissions from /etc/certs:
-rwxr-xr-x   1 root root 1.7K Oct  8 04:26 example.com.crt
-rw-r--r--   1 root root 1.1K Oct  8 04:15 example.com.csr
-rw-------   1 root root 1.7K Oct  8 04:35 example.com.key
-rw-r--r--   1 root root 1.5K Jul 27 19:20 intermediate.crt

Other server configs can be found here:
https://www.startssl.com/?app=20


text:
Q: How to mux audio signal output if power is applied I have the following inputs on an audio device:

*

*DAC audio signal

*Secondary audio input signal

The device has one analog audio output.  I want the output to source from the DAC when powered, and to source from the analog input when powered off. Originally I used a mux IC, but the power off condition does not work (DUH). How should I switch between these two audio signals based on the device's power state?

A: Any kind of an analog switch will need a bias voltage to operate. If you could bootstrap one from your external audio signal that might be just enough to get the job done. Then use the main power state to select the DAC.


text:
Q: The use of "over" in the following sentence
He was despondent over the breakup of his marriage.

You could say
A. He was despondent regarding/concerning the breakup of his marriage
B. He was despondent because of/due to/as a result of the breakup of his marriage.

*

*There is no difference in the meaning whether "because of" or "concerning" is used here. Am I right?

*"Over" could mean any one of "A & B" . Am I right?

A: You normally use the prepositions over or about after despondent. Some people also use "at".
Although the use of "because, due to, and as a result of" with despondent conveys the same sense as about/over and seems correct grammatically, they are not usually used.

A: The simplest preposition after despondent is about (BrE). AmE prefers over.
Your variants are all possible, but they are longer and normally the shortest way to express an idea is preferred.

A: It's a preposition.
There's actually a few different prepositions that would work there, with slightly different shades of meaning.  I'll provide some examples with a shorter sentence.

She was upset at her husband

^ Husband did something to upset her, and maybe she is angry at him.  For example he said something rude in front of dinner guests.

She was upset over her husband

^ Something was happening to her husband, or her husband was involved in some situation which upset her.  For example, he is sick.

She was upset because of her husband

Husband did something that directly upset her.  Perhaps he was pushing her buttons that morning.

She was upset with her husband

^ She is definitely angry at him. Maybe he forgot her anniversary.

She was upset about her husband

^ She is definitely not angry at him.  Something happened to her husband that is upsetting.  Maybe he is being targeted in an upsetting lawsuit.


text:
Q: If I have a quadratic form, is there a fast way to find its matrix? Suppose I have a quadratic form such that:
$$ q(x,y,z)= 5x^2 + 5y^2 + 2z^2 - 2xy + 4xz + 4yz$$
Its matrix in the standard basis is:
$$ \begin{bmatrix}
5 &  -1& 2\\
-1 &  5& 2\\
 2&2  &2
\end{bmatrix} $$
Is there a fast way to find it? Doing it the slow way is the only way I know. I.e the slow way is to pick all the elements $e_i$ and $e_j$ from the standard basis and see what the bilinear form $\phi$ such that $\phi(x,x) = q(x)$ gives for all $\phi (e_i, e_j)$.
So any suggestions?

A: If $A=[a_{ij}]$ is the matrix of $q$, then we have
$$ q(x_1,\dots,x_n)=\sum_{i,j=1}^na_{ij}x_ix_j $$
This means that $a_{ii}$ is equal to the coefficient of $x_i^2$ in $q$, while if $i\neq j$ then $a_{ij}$ and $a_{ij}$ are each equal to half the coefficient of $x_ix_j$ in $q$.
Note that this works with your example if we replace $x,y,z$ with $x_1,x_2,x_3$.

A: It is correct, if the mixed coefficients $yz,zx,xy$ are all even, then the form
$$ A x^2 + B y^2 + C z^2 + R yz + S zx + T xy $$ gives Gram matrix (half Hessian)
$$
\left(
\begin{array}{rrr}
A & \frac{T}{2} & \frac{S}{2} \\
\frac{T}{2} & B & \frac{R}{2} \\
\frac{S}{2} & \frac{R}{2} & C
\end{array}
\right)
$$
If $R,S,T$ are not even, usually this is doubled, just use the Hessian matrix of second partial derivatives
For the doubled version see page 401 in Lehman or page 104 of Watson
$$\begin{array}{l}\text{If I had a quadratic form,}\cr
\text{I'd form in the morning}\cr
\text{I'd form in the evening}\cr
\text{All over this land}\cr
\text{I'd form out danger}\cr
\text{I'd form out a warning}\cr
\text{I'd form out the love between}\cr
\text{My brothers and my sisters}\cr
\text{All over this land.}\end{array}$$
Pete Seeger (1956)
Peter, Paul, and Mary (1963)

A: For the quadratic form $ax^2+by^2+cz^2+2fyz+2gzx+2hxy$ the corresponding matrix is $$\left(\begin{matrix}a&h&g\\h&b&f\\g&f&c\end{matrix}\right)$$


text:
Q: GAE NDB restore fails with "Unexpected error contacting datastore" I'm used to performing regular backup and restore of my NDB datastore, often restoring to a different 'project', where I will be testing a new version of the application.   Up to now, it has worked fine.
Now, Ndb restore operation fails in a systematic way, with the trace in the log:
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/_internal/mapreduce/handlers.py", line 526, in handle
    ctx.flush()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/_internal/mapreduce/context.py", line 455, in flush
    pool.flush()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/datastore_admin/utils.py", line 695, in flush
    datastore._GetConnection()._reserve_keys(self.keys)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 2170, in _reserve_keys
    self._async_reserve_keys(None, keys).get_result()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 921, in get_result
    results = self.__rpcs[0].get_result()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
    return self.__get_result_hook(self)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 2211, in __reserve_keys_hook
    self.check_rpc_success(rpc)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1371, in check_rpc_success
    raise _ToDatastoreError(err)
InternalError: Unexpected error contacting datastore (2016-11-19T18:01:37+00:00).

Any clue ?  I may have missed something, but I would swear nothing has changed as compared to last week's situation where such restore worked ok.
Just in case there was something wrong with my latest backup, I tried to restore an old backup, which had been successfully restored a couple of times.  Same InternalError on restore.   Including in a brand new GAE project.
Having tried many (many) times now, I found the 'unexpected errors' always happen for the same entities.  The whole backup/restore involves about 30 different kinds, of which 5 fail with said error.   Among these, in some cases there are entities that are restored, but not all, in other cases no entities have been restored.   It's like some specific entities could be responsible for the exception.   But, once again, this also happens for old backups, which had worked in the past.
There are few questions related to Ndb backup and restore (and fewer answers still).   Don't Ndb applications use backups ?

A: So the final word on this is not hidden at the bottom of a long list of comments, I'll post an answer.
It seems this was a bug that had appeared a few days/weeks back, which a few users like me have experienced when restoring to another project.
The Google project team did a great job, fixing the issue promptly.   Many thanks to @Ed Davisson.


text:
Q: TFS - Souce Code Not Matching I am working with another developer using TFS.
When I first pulled the source code the solution would not build on my machine. I managed to fix it by applying a number of updates using Nuget.
It's a c#.net MVC web application.
On my machine the modal popups work correctly but the developer at the other end is saying that they are not working on their machine.
I have made sure I have pushed all my changes and the developer at the other end is saying that have done a recursive pull. So, surely, we have the same code?
Can anyone suggest why the developer at the other end is not seeing the modals?
I suspect it's something to do with nugget packages but I could be wrong?
Can anyone give me any pointers where to look for this problem?

A: First 'enable nuget package restore' for your solution by right clicking on solution file from Visual Studio and select that option. So that the nuget packages will be downloaded to the solution on build.
Regarding the missing modal please ensure that the packages.config file is also committed/checked in since only the packages listed in the file only be installed to the project.
If possible to come up with the error that would be helpful to find.


text:
Q: Image not resizing properly: image gets cut off when window is resized I at least got the following to render the image, but when the window is resized past a certain point: part of the image  gets cut off.
#header {
  background-image: image-url('my_header.png'); #image-url is a helper in rails
  background-repeat: no-repeat;
  height: 100px;
  background-size: 100%;
  border-radius: 1em;
}

And then showing how I specify the image at the top of the body in application.html.erb:

What I want to happen is for the image to scale proportionality  but not get cut off. I do not want any specific height set.  I want it to automatically scale as needed (however, I wasn't able to get the image to render unless I specified the height with px).

A: @Pangloss deserves recognition for providing a fantastic answer at this jsfiddle which he referenced in the comments.
Here is his css:
#header {
    background-image: url('http://i.imgur.com/zOZVQaf.jpg');
    background-repeat: no-repeat;
    background-size: contain;
    border-radius: 1em;
    border: 1px solid blue;
}
#header img {
    display: block;
    visibility: hidden; /*hidden but reserve the space*/
    width: 100%;
    height: auto;
}

And the html:

@Pangloss provided this answer in the comments.  If/when he posts an answer to this question, I will switch it over to his answer.


text:
Q: The styles in the recent posts widgets plugin not working I am trying to add a wordpress recent posts widget plugin in a theme
but somehow even after adding the same class the styles ae not reflecting in the front end
i tried to enqueue style in the plugin but that too didnt help
here is the plugin code
<?php echo $args[ 'before_widget' ]; ?>

<div id="rpwwt-<?php echo $args[ 'widget_id' ];?>" class="mb-50 mb-sm-30">
    <?php if ( $title ) echo $args[ 'before_title' ] . $title . $args[ 'after_title' ]; ?>

    <?php while ( $r->have_posts() ) { $r->the_post(); ?>

          <a href="<?php the_permalink(); ?>"<?php echo $this->customs[ 'link_target' ]; ?>><?php
            if ( $bools[ 'show_thumb' ] ) {
                $is_thumb = false;
                // if always only the default image
                if ( $bools[ 'use_default_only' ] ) {
                    echo $default_img;
                // if only first image
                } elseif ( $bools[ 'only_1st_img' ] ) {
                    // try to find and to display the first post image and to return success
                    $is_thumb = $this->the_first_post_image();
                } else {
                    // look for featured image
                    if ( has_post_thumbnail() ) {
                        // if there is featured image then show it
                        the_post_thumbnail( $this->customs[ 'thumb_dimensions' ] );
                        $is_thumb = true;
                    } else {
                        // if user wishes first image trial
                        if ( $bools[ 'try_1st_img' ] ) {
                            // try to find and to display the first post image and to return success
                            $is_thumb = $this->the_first_post_image();
                        } // if try_1st_img
                    } // if has_post_thumbnail
                } // if only_1st_img
                // if there is no image
                if ( ! $is_thumb ) {
                    // if user allows default image then
                    if ( $bools[ 'use_default' ] ) {
                        echo $default_img;
                    } // if use_default
                } // if not is_thumb
                // (else do nothing)
            } // if show_thumb ?>

            <?php
            if ( $bools[ 'show_categories' ] ) {
                ?>
<?php echo $this->get_the_categories( $r->post->ID ); ?>
<?php
            }
            // show title if wished
            if ( ! $bools[ 'hide_title' ] ) {
                ?><a href="<?php the_permalink(); ?>">
<?php if ( $post_title = $this->get_the_trimmed_post_title() ) { echo $post_title; } else { the_ID(); } ?>
<?php
            }
            ?><?php

            if ( $bools[ 'show_date' ] ) {
                ?>
<?php echo get_the_date(); ?>
<?php
            }
        ?>

    <?php } // while() ?>

<?php echo $args[ 'after_widget' ]; ?>

here is the output

Recent Posts

Recipes

The secret of the perfect italian pizza

2020-06-15

Recipes

Paneer Pizza

2020-06-15

Recipes

Recipe of the week: Tomato pastas

2020-06-15

i tried to enque style like this but that too didnt help
<?php echo $args[ 'before_widget' ]; ?>
<?php //add styles
add_action('wp_enqueue_scripts','rpwwt_styles');
function rpwwt_styles(){

  wp_register_style('custom',plugins_url('css/custom.css',__FILE__));
  wp_enqueue_style('custom');

}?>
<div id="rpwwt-<?php echo $args[ 'widget_id' ];?>" class="mb-50 mb-sm-30">
    <?php if ( $title ) echo $args[ 'before_title' ] . $title . $args[ 'after_title' ]; ?>

    <?php while ( $r->have_posts() ) { $r->the_post(); ?>

          <a href="<?php the_permalink(); ?>"<?php echo $this->customs[ 'link_target' ]; ?>><?php
            if ( $bools[ 'show_thumb' ] ) {
                $is_thumb = false;
                // if always only the default image
                if ( $bools[ 'use_default_only' ] ) {
                    echo $default_img;
                // if only first image
                } elseif ( $bools[ 'only_1st_img' ] ) {
                    // try to find and to display the first post image and to return success
                    $is_thumb = $this->the_first_post_image();
                } else {
                    // look for featured image
                    if ( has_post_thumbnail() ) {
                        // if there is featured image then show it
                        the_post_thumbnail( $this->customs[ 'thumb_dimensions' ] );
                        $is_thumb = true;
                    } else {
                        // if user wishes first image trial
                        if ( $bools[ 'try_1st_img' ] ) {
                            // try to find and to display the first post image and to return success
                            $is_thumb = $this->the_first_post_image();
                        } // if try_1st_img
                    } // if has_post_thumbnail
                } // if only_1st_img
                // if there is no image
                if ( ! $is_thumb ) {
                    // if user allows default image then
                    if ( $bools[ 'use_default' ] ) {
                        echo $default_img;
                    } // if use_default
                } // if not is_thumb
                // (else do nothing)
            } // if show_thumb ?>

            <?php
            if ( $bools[ 'show_categories' ] ) {
                ?>
<?php echo $this->get_the_categories( $r->post->ID ); ?>
<?php
            }
            // show title if wished
            if ( ! $bools[ 'hide_title' ] ) {
                ?><a href="<?php the_permalink(); ?>">
<?php if ( $post_title = $this->get_the_trimmed_post_title() ) { echo $post_title; } else { the_ID(); } ?>
<?php
            }
            ?><?php

            if ( $bools[ 'show_date' ] ) {
                ?>
<?php echo get_the_date(); ?>
<?php
            }
        ?>

    <?php } // while() ?>

<?php echo $args[ 'after_widget' ]; ?>

check screenshots for reference

A: I got this fixed
the proble was in the custom.css
where i added
.s-right{
    margin-top:-30px;
}

i removed that and that fixed the margin issue


text:
Q: Inflating class map fragment error when return to the previous map fragment I have a FragmentActivity which replaces differents fragment to show information. One of those fragments (StepTwoAddressFragment) has a map contained in its layout. The first time, this fragment draws the views correctly, but when I back to this fragment in the stack, the app crashes. I need to add this fragment to the fragment back stack.
android.view.InflateException: Binary XML file line #9: Error inflating class fragment
FragmentActivity
switch (mCurrentSection) {
    case SECTION_STEP_TWO_MAPS_ADDRESS:
        SelectNewPositionFragment fragm = SelectNewPositionFragment.newInstance();
        mCurrentFragment = fragm;
        break;

    case SECTION_STEP_TWO_ADDRESS:
        mCurrentFragment = StepTwoAddressFragment.newInstance();
        break;

    case SECTION_STEP_TWO_WHY_GO:
        mCurrentFragment = StepTwoWhyGoFragment.newInstance();
        break;
}

if (mCurrentFragment != null) {
    FragmentTransaction ft = mFragmentManager.beginTransaction().replace(R.id.main_content_frame, mCurrentFragment);
    if (hasToAddToBackStack()) {
        ft.addToBackStack(null);
    }
    ft.commit();
}

private boolean hasToAddToBackStack() {
    return mCurrentSection != SECTION_STEP_TWO_MAPS_ADDRESS || mCurrentSection != SECTION_STEP_TWO_ADDRESS;
}

fragment_selected_new_position_layout.xml

................

<fragment
    android:id="@+id/map"
    class="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

................

SelectNewPositionFragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    v = inflater.inflate(R.layout.fragment_selected_new_position_layout, container, false);

    //mapFragment = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map));
    mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
    map = mapFragment.getMap();

}

@Override
public void onDestroyView() {
    super.onDestroyView();
    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
    if (mapFragment.isResumed()) {
        ft.remove(mapFragment);
        ft.commit();
    }
}

I tried this code too:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        view = inflater.inflate(R.layout.map, container, false);
    } catch (InflateException e) {
        /* map is already there, just return view as it is */
    }
    return view;
}

SOLUTION
I change the fragment view in the layout and change it with a FrameLayout
<FrameLayout
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and I create a new class MapBaseFragment which extends the SupportMapFragment class and initializes the map.
public class MapBaseFragment extends SupportMapFragment {

...

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setUpMap();
    }

...

}

and the Fragment which contains the map
mapFragment = new MapBaseFragment();
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.replace(R.id.map, mapFragment);
ft.commit();

Finally, delete the onDestroyView code.
It's right for me.

A: You can always use FragmentTransaction.add() instead of FragmentTransaction.replace().
This will keep that fragment that contains the map underneath your new fragment.
You will probably want to set the background opaque and add it to the back stack with FragmentTransaction.addToBackStack()


text:
Q: Executing python compiled script (.pyc) in Java I have a python compiled script (script.pyc , I haven't the .py file)that work well from my windows command prompt, and I want to execute it from my Java's application.
I tried to use runtime() method :
        Runtime runtime = Runtime.getRuntime();
    runtime.exec(new String[] {"C:\\toto\\tools\\script.pyc" ,"arg","arg2" });

but I get an error :
Exception in thread "main" java.io.IOException: Cannot run program "C:\Nuance\VoCon Hybrid\SDK_v4_3\tools\clctodict.pyc": CreateProcess error=193, %1 n?est pas une application Win32 valid

The script work well in my terminal ("arg" is a txt file, "arg2" is the output name, and the script does its job without any problem).
I also try to launch my script with getDesktop() :
        File fie = new File("C:\\toto\\tools\\script.pyc" ,"arg","arg2");
    Desktop.getDesktop().open(fie);

There is no problem, but I can't add argument, so I can just see a terminal windows opening during a few second before disappearing instantly.
I have also tried to use JPython, without success too (maybe we can't use methode "execfile" on a .pyc????)

A: Just like you need a jvm to run a .class, you need a python interpreter to run a .pyc.
Try something like:
runtime.exec(new String[] {"c:\\Python26\\bin\\python.exe", "C:\\toto\\tools\\script.pyc" ,"arg","arg2" });

A: You can do something like
Process p = Runtime.getRuntime().exec(new String[]{"python.exe" ... other args)

Then you can invoke p.waitFor() to wait for the end of the process and p.exitValue() to test if the program exited successfully.
You can also get the output stream via p.getOutputStream() to retrieve the text printed by your python script
Please refer to the class documentation for further information : http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html


text:
Q: Timeout in SSRS How does paging work in SSRS?
Does it fetch whole data at one go and then just displays certain records per page or on clicking 'Next Page' it makes a DB call and pulls data from database and shows on screen everytime.
In my SSRS report, it ia taking considerable time to fetch around 3000 to 3500 records and show it on screen. So I want to know if Pagination can solve this problem.
To resolve timeout issue, I have mentioned Timeout as 36000 (Seconds) in Dataset properties.Also in Site settings of report manager, I have selected 'Do not timeout Report' Option.

A: According to this artical it depends on the SQL server version you have:
http://www.c-sharpcorner.com/UploadFile/bc1c71/custom-paging-in-sql-server-2012/
In SQL server 2012:

Microsoft SQL Server 2012 comes with two extended clauses of ORDER BY and they are OFFSET & FETCH. These two clauses are used with Order By clause and make our SQL Engines to read only the specified number of records given with Fetch after the Offset value.


text:
Q: "Robo 3T" cannot be opened because the developer cannot be verified I have installed the Robo 3T using the Homebrew tool.
brew install --cask robo-3t

after installing I am getting pop-up windows asking on macOS.

"Robo 3T" cannot be opened because the developer cannot be verified.

A: I had the same problem, and HERE's how I solved it: I executed it on the command line
sudo xattr -r -d com.apple.quarantine /Applications/Robo\ 3T.app

A: Workaround:
Go to System Preferences -> Security and Privacy -> General
Towards the bottom, a message is shown that Robo 3T is blocked. Select Open Anyway.
That should do the work!

A: This worked for me:
Finder > Applications > Robo3t > right click (two fingers) > Open


text:
Q: IBM App Connect Rest RequestNode; Basic authorization Use IBM app connect to create a message flow. Within the message Flow, an API endpoint is being consumed but security is enabled on the endpoint. so I want to know how to add the username and password for the Request Node that connects to the API.
Didn't try anything yet because I don't know which root to take

A: The basic "task" you need to follow is this one: https://www.ibm.com/docs/en/app-connect/12.0?topic=security-configuring-identity-propagation, the part you want to enable is the bit where it says an output or request node can be configured to send a locally stored identity in the output message by configuring it with a security profile with propagation enabled, and the local identity referenced.
So you'll want to register the u/p in the credential store (https://www.ibm.com/docs/en/app-connect/12.0?topic=security-configuring-identity-propagation#provide) (I'd suggest following the links to using the mqsicredentials approach rather than mqsisetdbparms as it provides better protection of your passwords, but ultimately it's all stored on disk in either case. Specifically, if you look in https://www.ibm.com/docs/en/app-connect/12.0?topic=commands-mqsicredentials-command you want to register a rest credential type for an External REST API).
then once you've created a security profile referencing the stored credential, you can use that Security Profile from any node that needs to be able to use that particular identity to connect to a remote endpoint.
Hope this helps, I might have got one or two parameters wrong as I'm used to using the basic HTTP nodes rather than the REST nodes built on top.


text:
Q: ASP.NET MVC Script Bundle Takes Too Long To Load I am out of ideas on this one. An MVC site we developed takes too long to load. The Network tool shows it takes over seconds to load the JavaScript! It is in a bundle and being minimized. I can't figure out why this bundle could take so long. Any ideas?
bundles.Add(new ScriptBundle("~/scripts/site").Include(
                         "~/Scripts/lib/jquery-1.10.2.js"
                       , "~/Scripts/lib/jquery-migrate-{version}.js"
                       , "~/Scripts/lib/json2.js"
                       , "~/Scripts/lib/knockout-{version}.js"
                       , "~/Scripts/lib/jquery.unobtrusive*"
                       , "~/Scripts/lib/jquery.validate*"
                       , "~/Scripts/lib/jquery-ui*"
                       , "~/Scripts/lib/jquery.lockSubmit*"
                       , "~/images/jquery.js"
                       , "~/images/script.js"
                        ));

Here is the Network Tab of the Dev Tools:

A: Looking by your network tab screen grab, you have bundled a lot of files together and the size is 0.63 MB which is too big a size for minimized js files.
One thing you could do is split your js files into seperate bundles. Also could u share the actual size of the js files you are using, I find it very strange that the files you mentioned after minimized is still too big.


text:
Q: How to install an app by drag-and-drop onto the Simulator window? I have seen the following feature in the change log for Xcode 8.2
https://itunes.apple.com/us/app/xcode/id497799835?mt=12

*

*Simulator installs an app by drag-and-drop onto the Simulator window

But I have tried drag-and-drop with .app file built for the Simulator, but nothing happens. Does anyone know how this feature is supposed to be used?

A: I wrote a small blog post about this.
In brief: use an .app that is built for iphonesimulator.


text:
Q: Login with Facebook using Sentry in Laravel I am facing a problem as the one posted here
The problem is this piece of code
$profile = $user->profiles()->save($profile);

which results in this error
Call to undefined method Illuminate\Database\Query\Builder::profiles()

I tried to do what was suggested here
but it didn't work for me. It seems the problem has been solved in a link provided which no longer works.
I wrote my question briefly since the same question has been asked by the user in the link I gave. I will appreciate any help. Thanks

A: Sentry provides their own User model. If you would like to add relationships to the User, you will need to extend Sentry's User model and update the Sentry config to point to your new User model.
First, create your User model which extends the Sentry User model:
<?php
use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel;

class User extends SentryUserModel
{
    public function profiles()
    {
        return $this->hasMany('Profile');
    }
}

Next, update the Sentry config to look at your User model instead of the default Sentry User model. To do this, publish the Sentry config file:
php artisan config:publish cartalyst/sentry

Once published, open the app/config/packages/cartalyst/sentry/config.php file.  Update the 'users'.'model' value to use your new User model.  For example:
'model' => 'User', // assumes non-namespaced custom User model

Sentry will now use your custom User model created above, with the defined relationships.


text:
Q: Is Time machine able to restore my Windows Partition? I have 2 partitions on my computer. One with mac os x, another for Windows XP. I want to replace the disk with another one and I  wanted to know if Time  Machine will be able to restore the Windows partition too?

A: Winclone 3 is the best way to backup/restore a Windows Boot Camp partition. I have used it numerous times to restore such a partition.
http://twocanoes.com/software.php?software=1

A: No Time Machine does not restore whole partitions: it backs up files and directories on mounted drives and restores files and directories.
Untested
You can create an image of the Windows partition with DiskUtility, backup the image (copy it on a different disk) and restore it later.


text:
Q: Adding a watermark to a GIF with reasonable quality using FFMPEG so I got this code to add a logo onto a folder full of GIFs
@echo off
setlocal
for %%G in ("%~dp0webm\*.gif") do (
    ffmpeg -i %%G -i watermark.png -filter_complex "[0:v]scale=trunc(iw/2)*2:trunc(ih/2)*2[v0];[1:v][v0]scale2ref=trunc(iw/5):trunc(ih/16)[logo][0v];[0v][logo]overlay=W-w-3:H-h-4 [v]" -map "[v]" "C:\Users\Propietario\Desktop\Conversion\gif\%%~nG.gif"
    )
)
endlocal
pause

However, the output quality is rather low, similar to an issue I had with converting from video to GIF which was solved by creating a palette.
ffmpeg -i input.gif -filter_complex palettegen[PAL];[0:v]fifo[v0];[v0][PAL]paletteuse output.gif

Issue is, both solutions use -filter_complex so I don't know exactly how to combine the two in a way in which I'll be able to turn GIFs into watermarked GIFs with reasonable quality.

A: Use
@echo off
setlocal
for %%G in ("%~dp0webm\*.gif") do (
    ffmpeg -i %%G -i watermark.png -filter_complex "[0:v]scale=trunc(iw/2)*2:trunc(ih/2)*2[v0];[1:v][v0]scale2ref=trunc(iw/5):trunc(ih/16)[logo][0v];[0v][logo]overlay=W-w-3:H-h-4,palettegen [v]" -map "[v]" "C:\Users\Propietario\Desktop\Conversion\gif\%%~nG-palette.png"
    ffmpeg -i %%G -i watermark.png -i "%%~nG-palette.png" -filter_complex "[0:v]scale=trunc(iw/2)*2:trunc(ih/2)*2[v0];[1:v][v0]scale2ref=trunc(iw/5):trunc(ih/16)[logo][0v];[0v][logo]overlay=W-w-3:H-h-4[ov];[ov][2]paletteuse [v]" -map "[v]" "C:\Users\Propietario\Desktop\Conversion\gif\%%~nG.gif"
    )
)
endlocal
pause

A: You can't add watermark to GIF without quality loss.
GIF have upto 256 color and must be treated as pixel art, not smooth images as video. Tools for video processing expected video as sequence of smooth images. Somewhere here conversion between world of crisp pixels and world of smooth images, which CAN NOT BE done without loss. GIF also uses many tricks, like very adaptive palette, for example, so if you want add white logo, here may be no white color in palette. And here no "alpha blending" any attempt to combine colors will change palette map dramatically, all image will be distorted.
If you really want add overlay, if theory, you can unpack pixels as PALETTE IMAGE (video processing tools in our time can't do it), analyze watermark, adapt watermark for current palette (yes, you must change your watermark, if you don't want change image), add watermark to image and repack image again. This is complex task and I don't know tools for it. As internet user, I don't support practice, when good content labeled by someone with unneeded watermarks, I prefer originals, so I don't like to write such software.


text:
Q: Hooking into Qi charger status LED to power something more I have a Qi charging module and I want to light up a higher-power string of LEDs when my phone is charging through it.
The module has a blue status LED to show it's charging, which I think is where I would hook into. My question is, could I use a transistor or relay where the status LED is to switch on my string of lights. Or, should I use some sort of current monitoring on the coil instead of relying on the status LED?
I'm kinda new to hobby electronics so sorry if I've made some silly assumptions along the way.

A: Check what IC is used in this charger. Get the datasheet and check the sink/source capability of that pin.
A bipolar transistor would probably work, a logic level FET would work, a relay is unlikely to work, due to the pin not having enough drive current.


text:
Q: call Windows Color System from Java I need to call Windows Color System functions from Java. Following this tutorial i tried to call DLL function using Java Native Access. All examples from this tutorial works fine. When i try to load and use Mscms.dll (one of the WCS libraries) that DLL seems to be loaded successfully, but i can not call any functions. List of functions is here.
I got a message:
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function 'GetColorDirectory'

What's wrong with my code? Could you help me please?
import com.sun.jna.Library;
import com.sun.jna.Native;

public class WCS_test {

public interface Mscms extends Library {
    // http://msdn.microsoft.com/en-us/library/dd316928%28v=vs.85%29.aspx
    boolean GetColorDirectory(String pMachineName, String[] pBuffer, int pdwSize);
}

private static Mscms mscms = (Mscms) Native.loadLibrary("C:/Windows/system32/Mscms.dll", Mscms.class);

public static void main(String[] args) {

    if (mscms != null)
        System.out.println("Library loaded\n");
    else
        System.err.println("Library loading error\n");

    String[] pBuffer = new String[1024];
    mscms.GetColorDirectory(null, pBuffer, pBuffer.length);
}
}

A: When you get a java.lang.UnsatisfiedLinkError that means that it could not find the function 'GetColorDirectory' inside of the Mscms.dll. Looking at the link from your source code http://msdn.microsoft.com/en-us/library/dd316928%28v=vs.85%29.aspx you should try the Unicode name GetColorDirectoryW.


text:
Q: Parse date of csv with multiple date formats I have a csv file which has dates in multiple formats like this:
Date              X1     X2
12/6/2017 23:00 928.88  3.19
12/6/2017 23:20 928.86  3.37
12/6/2017 23:40 930.26  3.38
13-06-17 0:00   930.37  3.41
13-06-17 0:20   930.39  3.49
13-06-17 0:40   930.15  3.54
13-06-17 1:00   930.36  3.46

I wanted to parse the dates but the format is different:
I tried:
date_formats = ["%d/%m/%Y %H:%M","%d-%m-%Y %H:%M"]
for x in date_formats:
    try:
        dateparse = lambda dates: datetime.strptime(dates, x)
    except ValueError:
        dateparse = lambda dates: datetime.strptime(dates, x)

df2 = read_csv("Copy.csv", parse_dates=True,
              index_col="Time", date_parser=dateparse)

But i am getting the format errors.
ValueError: time data '5/6/2017 0:00' does not match format '%d-%m-%Y %H:%M'

Is there any other way to parse different date formats of csv files?
Any help would be appreciated.

A: the built in dateparser in pandas is man/woman enough to handle this already, so just pass param parse_dates=[0] to tell read_csv to parse the first column as datetimes, additionally you need to pass dayfirst=True:
In[19]:
import pandas as pd
import io
t="""Date,X1,X2
12/6/2017 23:00,28.88,3.19
12/6/2017 23:20,928.86,3.37
12/6/2017 23:40,930.26,3.38
13-06-17 0:00,930.37,3.41
13-06-17 0:20,930.39,3.49
13-06-17 0:40,930.15,3.54
13-06-17 1:00,930.36,3.46"""
df = pd.read_csv(io.StringIO(t), parse_dates=['Date'], dayfirst=True)
df
Out[19]:
                 Date      X1    X2
0 2017-06-12 23:00:00   28.88  3.19
1 2017-06-12 23:20:00  928.86  3.37
2 2017-06-12 23:40:00  930.26  3.38
3 2017-06-13 00:00:00  930.37  3.41
4 2017-06-13 00:20:00  930.39  3.49
5 2017-06-13 00:40:00  930.15  3.54
6 2017-06-13 01:00:00  930.36  3.46


text:
Q: Emacs24 auto-complete error: (void-variable ac-source-c) I tried to install auto-complete and auto-complete-clang-async. When I write something like std::, emacs says "auto-complete is not active".
My auto-complete conf is:
(require 'auto-complete)
(require 'auto-complete-config)
(add-to-list 'ac-dictionary-directories "~/.emacs.d/elpa/auto-complete/dict")
(set-default 'ac-c-sources
         '(ac-source-abbrev
           ac-source-dictionary
           ac-source-yasnippet
           ac-source-words-in-buffer
           ac-source-words-in-same-mode-buffers
           ac-source-semantic))
(ac-config-default)
(dolist (m '(c-mode c++-mode java-mode))
(add-to-list 'ac-modes m))
(global-auto-complete-mode t)

;auto-complete-clang-async
(require 'auto-complete-clang-async)

(defun ac-cc-mode-setup ()
  (setq ac-clang-complete-executable "~/.emacs.d/clang-complete")
  (setq ac-sources '(ac-source-clang-async))
  (ac-clang-launch-completion-process)
)

(defun my-ac-config ()
  (add-hook 'c-mode-common-hook 'ac-cc-mode-setup)
  (add-hook 'auto-complete-mode-hook 'ac-common-setup)
  (global-auto-complete-mode t))
(my-ac-config)

The error is:
auto-complete error: (void-variable ac-source-c)


text:
Q: How can I find a character in a substring of a string in C++? I have a string abcda. I want to search for a but just in the substring bcda and not the whole string. Is there any ways to do that? Something like:
s.find('a',s.begin() + 1, s.end())

I could do:
string substr = s(s.begin() + 1, s.end();
size_t l = substr.find('a');

but this won't return the position in s but rather the position in substr.


text:
Q: Integrating two vi in Labview I am trying to combine two different VI in labview, and am not sure where to start. I am at a beginner level, and I tried copy and pasting the block diagram from one VI into the block diagram of another. I don't know where to go from there; the controls for the second diagram don't show up after copy pasting it, and I couldn't put the whole thing into a subvi since it has more than 28 connectors. I don't think copy pasting it will work, but I was wondering if anyone knew where to start.

A: How about using SubVIs?
"After you create a VI, you can use it on the Block Diagram of another VI."


text:
Q: Command line (or even programmatically) retrieving portions of an image I have an app that does some processing on screen shots on the server (linux) and specifically I want to split the image into 4 or 6 parts. It's possible that the image has 4 images (one in each quadrant). So is there a way to split this using a command line tool? Six in some other cases. Let's assume I will know how many to cut the images into.
So is there a command line utility to do this? Irrespective of the size of the image there has to be linux utilities to do this. I am drawing a blank.

A: with imagemagick you can split an image in tiles, such as:
convert -crop <width>%x<height>%@ original_file.png  tile_%d.png

with <width>% and <height>% given in percentage of the dimension.
So for the four tiles case you can split the image as:
convert -crop 50%x50%@ original_file.png  tile_%d.png

and for the six tiles:
convert -crop 50%x33%@ original_file.png  tile_%d.png

(or 33%x50%@ if there are three horizontally)


text:
Q: Firestore Rules: Limit users using an old version? I have users using the iOS app from TestFlight that has long been deprecated! Is there a way to block them until they upgrade their app?
I haven't been able to find out documentation about what's inside the request — does anyone have a definitive documentation about this other than the Firebase tutorials? I find the tutorial do not exhaustively cover all the properties of this object and I am curious if there any information about the originating request!
rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
        function isBanned(uid) {
                return uid in [
        "3g...V2",
        "z7...w2"
        ];
        }
        allow read, write: if request.auth != null && !isBanned(request.auth.uid);
    }
  }
}