text:
Q: Why can't root use modules installed by pip3 I have updated my operating system to Fedora 27, and I experienced a problem when running Python by root. I cannot import modules I installed with pip3, like psutils
I have installed psutil by pip3
[user@localhost ~]$ sudo pip3 install psutil
WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.
Requirement already satisfied: psutil in /usr/local/lib64/python3.6/site-packages

I can import psutil by a normal user
[user@localhost ~]$ python3
Python 3.6.3 (default, Oct  9 2017, 12:07:10)
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages', '/usr/lib/python3.6/site-packages/pykakasi-0.24-py3.6.egg']
>>> import psutil
>>>

But I cannot import psutil when running root.
[user@localhost ~]$ sudo python3
Python 3.6.3 (default, Oct  9 2017, 12:07:10)
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.path)
['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages', '/usr/lib/python3.6/site-packages/pykakasi-0.24-py3.6.egg']
>>> import psutil
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'psutil'
>>>
[user@localhost ~]$

It seems that when running a normal user, '/usr/local/lib64/python3.6/site-packages' and '/usr/local/lib/python3.6/site-packages' are added to sys.path, but how can I add these to python3 when running with root?


text:
Q: Infinite wp_mail loop I'm trying to send mail using wp_mail. I have done the following:
add_action ('publish_party', 'party_contact_suppliers');

function party_contact_suppliers($post_id){
    $post = get_post($post_id);
    // get the address cache
    $address_cache = get_option( 'toolset_maps_address_coordinates' );
    $alerts = new WP_Query (array (
        'post_type'    => 'alert',
        'post_status' => 'publish'));
    foreach($alerts as $alert) {
    // find the address within the cache
    foreach ($address_cache as $key => $value) {
         if ( $value['address'] == $alert->center-location ) {
             $lat = $value['lat'];
             $lon = $value['lon'];
             break;
        }
    }

    $to = $alert->post_author;
    wp_mail('myemail@gmail.com','New Party Published', 'Author : '.$to.'     Latitude : '.$lat.'     Longitude : '.$lon);
}
return 0;
}

For some reason this has started an infinite loop of mails. There are only 2 alerts in the database.
Can anybody see why this is just looping forever?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to do automated clean install for Fedora Linux server? I have a Fedora 10 64-bit server where I want to set up a nightly fresh install.  The server is an exact clone of our customer's hardware and is used for running acceptance tests.
I would have liked to set this up using a virtual machine, but that's prohibited due to problems we've had with the different video and network drivers on the VM.
Here are the basic steps I need to automate:

*

*Reinstall base Fedora 10

*Update to the latest packages

*Install additional packages (some of these come from the rpmfusion repository and our own private repository, so the repo files for these need to be added to the configuration)

*Restore file system table to include a NAS mount

*Restore users and home directories.

I've looked at using Kickstart to do the installation, but it looks as if that will only satisfy the first step above by just answering all the questions that you'd normally answer interactively during installation.  Does anyone know of a more suitable tool that I could use ?
Edit: looks like respin could also be very useful here.

A: You could look at something like
fog  - http://www.fogproject.org/
clonezilla - http://clonezilla.org/
Basically these two applications are for the automated, unattended deployment of backup images to machines. They tend to be used in large enterprises but can be used for what you want to achieve.
I have only used clonzilla but fog can apparently run script after a pxe boot install. You could clone the device after all the steps above and just push down the image with a nightly reboot , you could use clonezilla or fog for this, or you could use fog with a script to apply the chances after a clean image has been installed on the server

A: Kickstart can do more using a %post section

A: Just wanted to elaborate to @BenBruscella's %post post.
Kickstart has a section where you can include or call up any post-install script to start after the main installation stuff is done.
With this you could easily do your package updates and mounts.


text:
Q: OpenCV C++: Create Column Range for Mat type data from indices stored in int vector Some (discontinuous)indices are stored in a vector vec. Given a Mat type data, how to create a subset of data with only those columns whose indices are specified in the vector vec?
For rows, I can specify Range::all(); but I couldn't specify column range for this subset.
std::vector<int> vec = {1, 4, 7, 13, 21, 51, 87};
cv::Mat data, subData;
subData= data(Range::all(), colRange); //Not sure, what to write in place of colRange

A: As suggested by Miki, I did the following:
    for (int index = 0; index < vec.size(); index++)
        data.col(vec[index]).copyTo(subData.col(index)); //loop over the vector, copy the data from vec[index] column to subData[index]


text:
Q: Getting Array From Firestore Database EDITED: The mistake was on my end. Getting the document from Firestore comes back as a list.
I upload an array to Firestore as a List<String> but when I try to get the array back, it comes back as a _internalLinkedHashMap<dynamic, dynamic>.
When I try to cast it back to the list, I get this error,
    flutter: The following assertion was thrown building
    StreamBuilder<QuerySnapshot>(dirty, state:
    flutter: _StreamBuilderBaseState<QuerySnapshot,
    AsyncSnapshot<QuerySnapshot>>#f4f4e):
    flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not
    a subtype of type 'List<String>'

I then tried to do List.from(document.data['myData']) I get the error
    flutter: The following assertion was thrown building
    StreamBuilder<QuerySnapshot>(dirty, state:
    flutter: _StreamBuilderBaseState<QuerySnapshot,
    AsyncSnapshot<QuerySnapshot>>#f4f4e):
    flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not
    a subtype of type 'Iteratable<dynamic>' <--------This changed

Does anyone have any ideas on how I can get/convert the response from Firestore from a _internalLinkedHashMap<dynamic, dynamic> to a  List<String>?


text:
Q: Sorting the keys and values in counter This is the code am working on and I want the output as the count in descending and if the count is same then order by name.
from collections import Counter
import re
from nltk.corpus import stopwords
import operator
text = "The quick brown fox jumped over the lazy dogs bowl. The dog was angry with the fox considering him lazy."
def tokenize(text):
    tokens = re.findall(r"\w+|\S", text.lower())
    #print(tokens)
    tokens1 = []
    for i in tokens:
        x = re.findall(r"\w+|\S", i, re.ASCII)
        for j in x:
            tokens1.append(j)

    return tokens
tok = tokenize(text)

punctuations = ['(',')',';',':','[',']',',', '...', '.', '&']

keywords = [word for word in tok if not word in punctuations]

cnt = Counter()
d= {}
for word in keywords:
    cnt[word] += 1
print(cnt)
freq = operator.itemgetter(1)

for k, v in sorted(cnt.items(), reverse=True, key=freq):
    print("%3d  %s" % (v, k))

Current output:
  4  the
  2  fox
  2  lazy
  1  quick
  1  brown
  1  jumped
  1  over
  1  dogs
  1  bowl
  1  dog
  1  was
  1  angry
  1  with
  1  considering
  1  him

Required output:
  4  the
  2  fox
  2  lazy
  1  angry
  1  bowl
  1  brown
  1  considering
  1  dog
  1  dogs

etc.

A: Use a sorting function that returns a tuple.  The first item in the tuple is the inverse of the count (the value in your dictionary) and the second is the string (the key in your dictionary).  You can do this by removing the variable freq, removing the keyword reverse in the call to sorted, and supplying a little lambda function that returns (-value, key) for each item in the dictionary.  The last few lines of the program are:
print(cnt)
for k, v in sorted(cnt.items(), key=lambda item: (-item[1], item[0])):
    print("%3d  %s" % (v, k))

The reason for the - sign in the lambda function is to get the correct sort order, since the default sort order is lowest to highest.


text:
Q: Theano with opencl GPU I have configured theano as follows:
[idf@localhost python]$ more ~idf/.theanorc
[global]
device = opencl0:0
floatX = float32

[lib]
cnmem=100
[idf@localhost python]$

I also needed to
[idf@localhost python]$ export MKL_THREADING_LAYER=GNU

although interestingly enough, if I install openblas and add
[blas]
ldflags = -lopenblas

to the .theanorc file, I no longer need to:
export MKL_THREADING_LAYER=GNU

Using a program I found on the internet which I modified slightly to use gpuarray, I am attempting to use theano with an Intel GPU through opencl:
import os
import shutil

from theano import function, config, shared, gpuarray
import theano.tensor as T
import numpy
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core
iters = 1000

rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))

f = function([], T.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in xrange(iters):
    r = f()
t1 = time.time()

print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r))

if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
    print('Used the cpu')
else:
    print('Used the gpu')

When I run the program, it seems as if it recognizes the GPU, but at the end the message "used the cpu" is printed.
[idf@localhost python]$ python theanoexam1.py
Mapped name None to device opencl0:0: Intel(R) HD Graphics 5500 BroadWell U-Processor GT2
[GpuElemwise{exp,no_inplace}(<GpuArrayType<None>(float32, vector)>), HostFromGpu(gpuarray)(GpuElemwise{exp,no_inplace}.0)]
Looping 1000 times took 1.231896 seconds
Result is [ 1.23178029  1.61879337  1.52278054 ...,  2.20771813  2.29967737
  1.62323284]
Used the cpu
[idf@localhost python]$

I am skeptical of the message "used the cpu": 1.231896 seconds seems fast for an Intel i3 with four cores.
Is there an extra configuration that is needed to use opencl with theano? Or did this program indeed show that theano is configured to use  the GPU through opencl?

A: Firstly thank you for you post.
I am running on Ubuntu 16.04, with Conda, and I have manually installed libgpuarray - all of which is well documented on the web.
I used the same test program you did (thank you for providing it).
So here are my settings
export MKL_THREADING_LAYER=GNU

The file ~/.theanorc looks like this
[global]
device = opencl0:0
floatX = float32

[lib]
cnmem=100

When I run the code
python test.py

I see the output
DRM_IOCTL_I915_GEM_APERTURE failed: Invalid argument
Assuming 131072kB available aperture size.
May lead to reduced performance or incorrect rendering.
get chip id failed: -1 [2]
param: 4, val: 0
Mapped name None to device opencl0:0: Ellesmere
[GpuElemwise{exp,no_inplace}(<GpuArrayType<None>(float32, vector)>), HostFromGpu(gpuarray)(GpuElemwise{exp,no_inplace}.0)]
Looping 1000 times took 0.282664 seconds
Result is [1.2317803 1.6187935 1.5227805 ... 2.207718  2.2996776 1.6232328]
Used the gpu

I can not figure out how to use the 2nd GPU (also OpenCL) - but I am happy at the moment that at least I have 1 GPU running.


text: Q: Use dedicated per-user log file for cron and? On Ubuntu 12.04 how can I configure cron to log to a particular file when it runs jobs as a particular user? I am interested in redirecting both the messages that go into auth.log and those going into syslog.


text:
Q: SFTP disconnect() method not working with Laravel I'm running the following script inside a Laravel job (OperatorSubmissionJob) to upload multiple files to the SFTP server. Everything working well. But I have to disconnect the SFTP connection to end the session after the uploading finished.
$count=1;
$sftp = Storage::disk('sftp');
foreach ($request['image'] as $key => $image) {
    $image_array_1 = explode(";", $image);
    $image_array_2 = explode(",", $image_array_1[1]);
    $data = base64_decode($image_array_2[1]);
    $imageName = Carbon::now()->format('Ymd_his') . $key . '.jpeg';

    // FTP server upload
    $ftp_image_name = $ftp_path . "_" . $count . '.jpeg';
    try {
        $isUploaded = $sftp->put("$ftp_path/" . $ftp_image_name, $data, 'public');
        if ($isUploaded) {
            Log::info("FTP image uploaded (UserID-" . $id . ", CustomerID-" . $mail_history->CustomerID . "): " . $count);
        } else {
            Log::info("FTP image upload failed (UserID-" . $id . ", CustomerID-" . $mail_history->CustomerID . "): " . $count);
        }
        $count++;
    } catch (\Exception $e) {
        Log::error($e->getMessage());
    }
}
// have to disconnect $sftp here. I have tried the following:
// $sftp->disconnect(); // error: undefined method disconnect
// $sftp->getDriver()->getAdapter()->disconnect(); // error: undefined method disconnect
// $sftp->getFilesystem()->getAdapter()->getClient()->disconnect();
//

Used techs:
Laravel 9 league/flysystem-sftp-v3
None of the disconnect scripts working in my case. Please help..
I have tried with the following scripts:
$sftp->disconnect();
$sftp->getDriver()->getAdapter()->disconnect();
$sftp->getFilesystem()->getAdapter()->getClient()->disconnect();


text:
Q: Position representation of spin states and spin operators How can   we represent a spin states
$  \lvert S_x:+\rangle, \lvert S_y:+\rangle,\lvert S_z:+\rangle ,\lvert S_x:-\rangle, \lvert S_y:-\rangle  $ and $\lvert S_z:-\rangle$  in position representation  like
$    \langle x\lvert S_z:+\rangle$ ?
Is there any position representation for spin operators $ S_z, S_y, S_z $?
Zettili says in his book of Quantum mechanics that  "Spin cannot be described by a differential operator". Does it mean spin cannot have a position representation? He does not talk about it more.

A: I'll try to give a simple and rough answer.
There is no position representation for the spin.
Roughly, that is because spin is a different space. Spins are things that live in a different space, which is independent of Hilbert's space.
On the one hand, you've got wavefunctions, which live in Hilbert's space.
$\psi(x) \in \mathcal{H}$
You can use Dirac notation:  $|\psi \rangle$.
On the other hand, spins are objects living in $\mathbb{C}^n$. With $s=½$, we've got $n=2$, so ½-spins live in $\mathbb{C}^2$. We use a basis that is
$$\lbrace \left( \begin{array}{c} 1 \\ 0 \end{array} \right); \ \left( \begin{array}{c} 0 \\ 1 \end{array} \right) \rbrace$$
The first one corresponds to spin-up and the second one corresponds to spin down.
So, the full wavefunction is the tensor product of those tow things, that is
$\psi(x)\otimes \left( \begin{array}{c} a \\ b \end{array} \right) $
The symbol $\otimes$ is usually ommited. So basically, a spinor is
$$\left( \begin{array}{c} \phi(x) \\ \varphi(x) \end{array} \right)$$
and it is the result of doign the tensor product of a wavefunction and a spin vector.
Only things in Hilbert space can have a position representation.
On the other hand, spins belong to an independent complex space $\mathbb{C}^n$.

A: Indeed, there is no position space representation of the spin states. That is because its Hilbert space is simply different from the Hilbert space of something like particle in a box. A very crude classical example would be think of a seesaw hinged at a place. Its configuration is given by two possible configurations: left-side-up or right-side-up (for simplicity assume you can't see an intermediate position).
If your seesaw wasn't fixed at a place but can move around in the park, then you will have something that needs to be described by both its position in the park as well as whether left or right side is up. In that case you will still have position as an additional information and you really can't write the configuration in terms its position (it is not like the seesaw being right-side-up is same as it being in the right-hand corner of the park). Such a description is what you will call a direct product of position space with spin space. An example of that would be a gas of spinning particles (say, electrons).
Alternatively, you can have an array of seesaws in the park. In that case you have to tell me which seesaw you are talking about in the park (described by its location in the park) and what's it configuration (left/right-side-up). Once again you don't have a position space representation but the position now becomes a label for the seesaws. Equivalent of that would be something like Heisenberg model where you have spins at different sites of a lattice.

A: Unlike the angular momentum operators which inherit their position representation from the position representation of $\hat x$ and $\hat p$:
$$
\hat L_z\to -i\hbar (y\partial_x -x\partial_y)
$$
it is not possible to write $\hat S_z$  in terms of the classical position and momenta because spin is an "intrinsic" rather than spatial degree of freedom: dimensional analysis shows that only products like $yp_x$ have units of angular momentum so, after accounting for the commutation relations to be respected, a position representation of spin would be more or less identical to the position representation of "ordinary" angular momentum.
Moreover, quantizing angular momentum necessarily leads to integer values of $\ell$ through the use of (spherical) coordinates
see:

Gatland, Ian R. "Integer versus half-integer angular momentum." American Journal of Physics 74, no. 3 (2006): 191-192.

Thus a position-based representation for spin could not accommodate half-integer values.

A: Here's the fifth answer, in a more mathematical fashion.
Using the standard terminology, for a massive non-specially relativistic particle with spin in three dimensions, the set of operators $\{x,y,z,p_x,p_y,p_z, S_x,S_y, S_z\}$ is irreducible, which means there is no linear or non linear functional dependence between them. This is a consequence of the representation theory of the Galilei algebra. We are then forced to the algebraic commutation relations which derive from the representation theory of the Galilei algebra (ignore i and hbar):
$$ [x_i,p_j] = \delta_{ij}, [x_i, S_j] =0, [p_k, S_l] =0, [S_m,S_n]=\epsilon_{mnq}S_q .$$
Let us call the vector space of this representation $ V$.
That $x$ and $p_x$ are irreducible and do not commute, it means that there are conditions to apply the famous uniqueness theorem of Stone and von Neumann to conclude that $ V$ must have $L^2 (\mathbb R^3)$ as a subspace, so it is necessarily infinite-dimensional.
Let us now consider that the spin operators S form a representation of $\text{so}(3)$ on $V$ by (essentially) self-adjoint operators. We know that $\text{so}(3)$ is the compact Lie algebra of the compact group $\text{SO(3)}$, so, by the theorem of Peter-Weyl, the representation space of the commutation relation must be finite-dimensional.
We are to conclude that the commutation relation for the spin operators should take place on a finite-dimensional subspace of $V$, we call $\mathcal S_{fin}$. Of course, $\mathcal S_{fin}$ is isomorphic as a vector space to $\mathbb {C}^n$ for a particular finite $n$.
There are two options. The first:
$$ V = L^2 (\mathbb R^3) \otimes \mathcal S_{fin},$$
which basically answers the question (the spin states do not have a position representation), because they live in different (rigged) Hilbert spaces and, by convention/definition, the scalar product between a spin state and a position (eigen)state is nil. The same applies to momentum and spin.
The second option would be $$ V= L^2 (\mathbb R^3), \mathcal S_{fin} < L^2 (\mathbb R^3). $$
One can easily show that the three essentially self-adjoint operators $\epsilon_{ijk}x_j p_k$ satisfy the $\text{so(3)}$ commutation relations on $L^2 (S_2) <L^2 (\mathbb R^3)$ whose dimension is necessarily an even integer. We have that, due to a coordinate change implemented unitarily,  $L^2 (\mathbb R^3) = L^2 (S^2) \otimes L^2 ((0,\infty), r^2 dr) $. The dimension of $\mathcal S_{fin}$, however, can be any natural number. So, for integer spins, we have that the representation spaces of the same algebra are isomorphic. It follows that the generators are one the multiple of the other, hence the position, momentum, spin cannot be irreducible anymore.
The existence of spin comes purely from enforcing a projective unitary representation of the Galilei group on a (rigged) Hilbert space. Group theory shows that we are actually representing the universal covering group of which has a subgroup isomorphic to $\text{SU(2)}$. Had we not been forced to use projection representations, but only vector ones, we would have had no way to exhibit a spin operator. The same goes for the specially relativistic case.


text:
Q: Handling network problems while inserting in MongoDB I am working on a project with large amount of live data by asp.net core 2.0, C# and MongoDB. I have thousands of sensors which send live data to the server. I have a problem with network issues. This is possible that my web-server for a few minutes can not communicate with database Server.
I've tried to test it locally, if it is about 20 or 30 seconds, web-server will resume, but if it goes to more than a minute, web-server will lost the connection and after that I need to restart the application. I tried to use connectionTimeOutMS and socketTimeOutMS but those couldn't help me.
How can I prevent that and handle this problem? Is there any solution or backup plan to handle this?

A: Thanks to @JohnnyHK for great help. I could solve the problem by adding serverSelectionTimeoutMS to the connection string.


text:
Q: ffmpeg decoding on a encoded stream (coming as buffer) I am getting enocded data in a uin8_t* buffer with the buffer size, can I use ffmpeg decoder to decode this data ?
If so How can I convert uint8_t* encoded_data to the AvPacket required by ffmpeg?
do I need to initialize any metadata parameters ?

A: AVPacket *pkt = av_packet_alloc();
av_new_packet(pkt, size);
memcpy(pkt->data, data, size);
..
av_packet_free(&pkt);

And in ".." would then be your packet handler, typically calls to avcodec_send_packet() and avcodec_receive_frame().


text:
Q: Span element with fontawesome icon class in Jquery script automatically replaced by SVG ? Strange behaviour I'm doing this in a jquery module:
$('#myId').find("li.myClass").each(function () {
                var rightNavButton = $("", {"class": "right fas fa-arrow-alt-circle-right"});
                myButton.prependTo($(this));
            });

my html5 output dissappoints me with an SVG and out-commented SPAN :
<svg class="svg-inline--fa fa-arrow-alt-circle-right fa-w-16 right" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="arrow-alt-circle-right" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M256 8c137 0 248 111 248 248S393 504 256 504 8 393 8 256 119 8 256 8zM140 300h116v70.9c0 10.7 13 16.1 20.5 8.5l114.3-114.9c4.7-4.7 4.7-12.2 0-16.9l-114.3-115c-7.6-7.6-20.5-2.2-20.5 8.5V212H140c-6.6 0-12 5.4-12 12v64c0 6.6 5.4 12 12 12z"></path></svg>

Why does it happen? I searched for information about replacing functions inside of font-awesome, but didn't found anything yet. Is this behaviiour normal? What am I missing?
The javascript is included on page bottom,
the css in page head.
All dists are up to date and the order is correct.

A: Found the answer here:
https://fontawesome.com/how-to-use/on-the-web/using-with/jquery
You can protect the replacement of Span tags and let the icon embbed into the tags, for the reason that you can use events on the span or other tags.
Nice to know the trick


text:
Q: Можно ли как-то константный метод в наследуемом классе сделать неконстантным? C++ Допустим есть абстрактный класс:
class MyClass {

public:

    virtual foo() const = 0;

}

Можно ли в наследуемом классе как-то сделать foo() неконстантным? Переопределение без const не работает.


text:
Q: VBA code loop that will search and copy/paste based on list of criteria I have a sheet with data more then 30 000 rows and I want to copy all rows to a new excel file if column of  a certain (for example "B") row contains certain values (list of these values will be in other sheet "Code").
So for example:

*

*In sheet "Code" I have ten (could be even 30) different numbers (criteria) in column "A".

*Start search to copy all rows (in new excel file) that contain any of these numbers from sheet "Code" in column "A".

Not very good at VBA yet but working on it:)
Thanks for everyone for help!

A: Filter By Multiple Criteria and Export to Another Workbook

*

*Just to demonstrate why the question is not so well received. It's sort of 50 questions in one.

*Adjust the values in the constants section, and you should be good to go.

*"Sheet2" is actually your worksheet "Code". "Sheet1" is the first worksheet.

The Code
Option Explicit

Sub exportMultiToWorkbook()

    ' Error Handler

    ' Initialize error handling.
    Const procName As String = "exportMultiToWorkbook"
    On Error GoTo clearError ' Turn on error trapping.

    ' Constants

    ' Criteria
    Const critName As String = "Sheet2"
    Const critFirstCell As String = "A2"
    ' Source
    Const srcName As String = "Sheet1"
    Const srcFirstCell As String = "A1"
    Const srcCritColumn As Long = 2
    Dim wbs As Workbook
    Set wbs = ThisWorkbook ' The workbook containing this code.
    ' Target
    Const tgtFirstCell As String = "A1"
    Dim tgtPath As String
    ' The same path as Source Workbook ('wbs'). Change if necessary.
    tgtPath = wbs.Path & Application.PathSeparator & "Criteria"
    ' Other
    Dim Success As Boolean
    Dim AfterCop As Boolean

    ' Criteria

    ' Define Criteria Worksheet ('crit').
    Dim crit As Worksheet
    Set crit = wbs.Worksheets(critName)
    ' Define Criteria First Cell Range ('fcel').
    Dim fcel As Range
    Set fcel = crit.Range(critFirstCell)
    ' Define Criteria Processing Column Range ('pcr').
    Dim pcr As Range
    Set pcr = fcel.Resize(crit.Rows.Count - fcel.Row + 1)
    ' Define Criteria Last Non-Empty Cell Range ('lcel').
    Dim lcel As Range
    Set lcel = pcr.Find(What:="*", _
                       LookIn:=xlFormulas, _
                       SearchDirection:=xlPrevious)
    ' Validate Last Non-Empty Cell Range.
    If lcel Is Nothing Then
        GoTo ProcExit
    End If
    ' Define Criteria Column Range ('cr').
    Dim cr As Range
    Set cr = crit.Range(fcel, lcel)
    ' Write values from Criteria Column Range to 1D Criteria Array ('Criteria'),
    ' probably using Criteria 2D Array ('Crit2D').
    Dim Criteria As Variant
    Dim i As Long
    If cr.Rows.Count > 1 Then
    ' Criteria Column Range has multiple cells (rows).
        ' Write values from Criteria Range to Criteria 2D Array.
        Dim Crit2D As Variant
        Crit2D = cr.Value
        ' Write values from Criteria 2D Array to 1D Criteria Array.
        ReDim Criteria(1 To UBound(Crit2D, 1))
        For i = 1 To UBound(Crit2D)
            Criteria(i) = CStr(Crit2D(i, 1)) ' AutoFilter prefers strings.
        Next i
    Else
    ' Criteria Column Range has one cell (row) only.
        ' Write the only value from Criteria Column Range to Criteria Array.
        ReDim Criteria(1)
        Criteria(1) = CStr(cr.Value) ' AutoFilter prefers strings.
    End If

    ' Source

    ' Define Source Worksheet ('src').
    Dim src As Worksheet
    Set src = wbs.Worksheets(srcName)
    ' Define Source First Cell Range ('fcel').
    Set fcel = src.Range(srcFirstCell)
    ' Define Source Last Cell Range ('lcel').
    Set lcel = fcel.End(xlToRight).End(xlDown)
    ' Define Copy Range
    Dim cop As Range
    Set cop = src.Range(fcel, lcel)
    ' Turn off screen updating.
    Application.ScreenUpdating = False
    ' Turn off filter, if on.
    If src.FilterMode Then
        cop.AutoFilter
    End If
    ' Filter data. AutoFilter prefers the whole range.
    cop.AutoFilter Field:=srcCritColumn, _
                   Criteria1:=Criteria, _
                   Operator:=xlFilterValues
    ' Enable the use of 'SafeExit' instead of 'ProcExit' after possible error.
    AfterCop = True

    ' Target

    ' Add a new workbook.
    With Workbooks.Add
        ' Copy Copy Range to the first sheet of a new workbook.
        cop.Copy .Worksheets(1).Range(tgtFirstCell)
        ' I prefer to save this way; always a different file.
        tgtPath = tgtPath & " " & Format(Now, "YYYYMMDD_HHMMSS")
        .SaveAs Filename:=tgtPath, _
                FileFormat:=xlOpenXMLWorkbook ' i.e. ".xlsx"
         ' If you prefer the file to have the same name and for it to be
         ' overwritten without Excel complaining, then rather use the following:
'        Application.DisplayAlerts = False
'        .SaveAs Filename:=tgtPath, _
'                FileFormat:=xlOpenXMLWorkbook ' i.e. ".xlsx"
'        Application.DisplayAlerts = True
        .Close
    End With
    Success = True

SafeExit:

    ' Source

    ' Turn off filter.
    cop.AutoFilter
    wbs.Saved = True

    ' Turn on screen updating.
    Application.ScreenUpdating = True

ProcExit:

   ' Inform user.

    If Success Then
        MsgBox Prompt:="Created file '" & tgtPath & "'.", _
               Buttons:=vbInformation, _
               Title:="Multiple Criteria Filter - Success"
    Else
        MsgBox Prompt:="Could not finish task.", _
               Buttons:=vbCritical, _
               Title:="Multiple Criteria Filter - Fail"
    End If

    Exit Sub

clearError:
    Debug.Print "'" & procName & "': " & vbLf _
              & "    " & "Run-time error '" & Err.Number & "':" & vbLf _
              & "        " & Err.Description
    On Error GoTo 0 ' Turn off error trapping.
    If Not AfterCop Then
        GoTo ProcExit
    Else
        GoTo SafeExit
    End If

End Sub

A: I understand you are new and don't want to discourage you from seeking help in the future.   Please attempt to ask more specific questions in the future.  For example, you could ask how to find out if the value of one cell matches the value of any cell in a range of cells.  That said, I have the sense you didn't know where to start, so I'll give it a shot.  VBasic 2008 already provided an excellent answer, and actually wrote code for you, which you should not expect.  VBasic 2008's code is great but be a more than you need and also a bit much for a beginner to understand.  In the code below, you really only need to modify the three "set" lines in the CopyFilteredDemo procedure.
Below is simple code that makes several simplifying assumptions.  Based on your request, I assume this meets your needs.  If not, add more specificity.  Many of these limitations of the assumptions listed below are easily overcome, but I don't want to write code for the heck of it.

*

*Either the source and destination workbooks are the same, or they are both open. (I only tested different sheets in the same workbook, but it should work across workbooks.)

*The source and destination worksheets are not the same.  An error is intentionally raised if they are the same.

*The destination worksheet already exists.
$) The desitnation worksheet will be completely cleared and overwritten.  Change True to False in CopyFilteredDemo so as to pass, so as to pass False to CopyFiltered.

*Search only the first column of the source range for a an exact match in the filter range.  Since the whole row is copied, it doesn't matter what column you set as the first column in fromRange.  Just pick the column you wish to compare to values in filterRange.

*Where not filtered out, the entire worksheet row will be copied.

*No duplicates in filter criteria.  I have not tested this to see if it causes duplicates in the destination worksheet.

*Not performance tested on thousands of rows.  If you see issues, first set Application.ScreenUpdating = False.  Turn it on again at the end. Be sure you have error handling to turn in back on in case of an error. Otherwise ScreenUpdatingwill remain off, which you'll find is highly undesirable.  If this is beyond your current comfort level, don't disable ScreenUpdating.

As an outline, the main procedure is CopyFiltered, which copies data from one sheet to another.  This procedure calls the IsInRange function, which returns true if argument valueToFind exactly matches a value in the range specified by argument RangeToSearch.  So, when comparing the source range (fromRange) to the filter criteria (filterRange), the first column of fromRange is compared.  fromRange does not determine which columns are copied, since you requested to copy entire rows.  Rather fromRange has 2 purposes.  First, it determine the rows from which to copy.  Second, the first column of fromRange is compared to the filterRange for a match.
I placed a good amount of comments in the code, so I hope it is relatively easy to understand.
Option Explicit
' Option Explicit must be the first line of code in the module.
' It forces you to declare every variable.  It may seem a nuisance
' to a beginner, but you will quickly learn its value.  It will
' keep you from spelling the same variable two ways and failing
' to understand why your code failed.  There are other benefits
' that you'll pick up over time, such as conserving memory and
' forcing data typing.

Public Function IsInRange(ByVal valueToFind, ByVal RangeToSearch As Range)
    ' If any cell in RangeToSearch = valueToFind, return True
    ' Else return False.
    Dim x

    ' If valueToFind is not in RangeToSearch, expect
    ' error 91.  That's okay, we'll handle that error
    ' and return False.  If we get a differnt error,
    ' we'll raise it.
    On Error GoTo EH
    x = RangeToSearch.Find(valueToFind)
    On Error GoTo 0

    ' If we made it this far, we found it!
    IsInRange = True

Exit Function
EH:
    If Err.Number = 91 Then
        ' this error is expected if valueToFind is not in RangeToSearch
        IsInRange = False
        Err.Clear
    Else
        ' Unexpected error.
        Err.Raise Number:=Err.Number, Source:=Err.Source _
                  , Description:=Err.Description
    End If
End Function

Sub CopyFiltered(ByVal fromRange As Range, ByVal toRange As Range _
                 , ByVal filterRange As Range _
                 , Optional clearFirst As Boolean = True)

' Arguments:
'   fromRange: the full range from which to copy
'   toRange: the top left cell fromRange will be pasted to the
'              top left cell of toRange.  The size of toRange
'              is irrelevant.  Only the top left cell is used
'              for reference.
'   fitlerRange: a range containing values with which to filter.
'   clearFirst: if True, clear all content from range containing
'               toRange before pasting new values.

    Dim rng As Range, rowOffset As Integer
    Dim rowNum As Integer, colNum As Integer, i As Integer
    Dim errMsg As String, cell As Range

    Set toRange = toRange.Cells(1, 1)
    Set fromRange = fromRange.Columns(1)

    ' If fromRange and toRange are on the same worksheet,
    ' raise an exception.
    If fromRange.Worksheet.Name = toRange.Worksheet.Name Then
        errMsg = "fromRange and toRange cannot be on the same worksheet."
        Err.Raise 1000, "CopyFiltered", errMsg
        Exit Sub
    End If

    ' Clear all content from the destination worksheet.
    toRange.Worksheet.Cells.ClearContents

    '
    ' Loop through each row of fromRange
    rowOffset = -1
    For i = 1 To fromRange.Rows.Count
        Set cell = fromRange.Cells(i, 1)
        Debug.Print cell.Address
        ' If the the cell in the first column of fromRange
        ' exaclty equals any cell in filterRange, proceed.
        If IsInRange(cell.Value, filterRange) Then
            ' Add one to rowOffset, so we copy this row
            ' below the last pasted row of the sheet
            ' containing toRange
            rowOffset = rowOffset + 1
            cell.EntireRow.Copy toRange.Offset(rowOffset, 0).EntireRow
        End If
    Next i

End Sub

Sub CopyFilteredDemo()
    Dim fromRange As Range, toRange As Range, filterRange As Range

    ' Set our to, from and filter ranges
    Set fromRange = Sheets("Sheet1").Range("c10:c40")
    Set toRange = Sheets("Sheet2").Range("A2")
    Set filterRange = Sheets("Sheet1").Range("B2:B6")

    ' Run our filtered copy procedure.
    CopyFiltered fromRange, toRange, filterRange, True
End Sub


text:
Q: gradle difference between testRuntime and testProvided Single question:
In gradle, there are several configurations provided out of the box.
For example testCompile, testProvided, testRuntime, javaCompile, javaProvided, and so on...
Could you explain what's the difference?

A: In addition to Ethan's answer: the provided configurations contain dependencies that are used during compile but are not packaged to the final artifact. This is for example useful when you develop for a container that provides these dependencies already in its installation.

A: Configurations allow you to scope dependencies. Given this configuration hierarchy:
testRuntime -> testCompile -> runtime -> compile

Each configuration helps you limit where your dependencies are. *Runtime configurations allow you to include a dependency, but not have it as a compile dependency. This is helpful when you want to keep a framework loosely coupled from a project. A runtime dependency means that you need it for the app to run, but don't need it to compile.
The same thing applies for the test* configurations.
Ref:

*

*Gradle Docs - Dependency configurations


text:
Q: How to increase the Page Speed in PWA (Progressive Web App) By using ionic 3 How can I increase the page speed for my PWA web application by using ionic 3 ?
I had check speed for my pwa web application it shows 0. How can I increase the speed for it.

A: What do you use to check the speed of your app?
There are several technoques you can use to improve the performance of your web app. In case of a PWA, I would suggest to implement the proper caching strategies, so that you can save network calls and deliver data from the local cache.
For example the cache first strategy, always attempt to deliver the requested assets from the cache, falling back to network if nothing is found.
Hava a look at this article describing in detail how Service Workers function and which caching strategies you can adopt in your context.


text:
Q: puppeteer : The first link work, the others dont this is my first post. Im learning JS with Nodejs. So I saw the Puppeteer script to take screenshot of the elements and I copy and change it. But have some problems here.

        const express = require('express')

        const app = express()
        const port = 3000

        app.get('/', (req, res) => res.send('Veamos Kia!'))

        app.listen(port, () => console.log(`App de ejemplo escuchando el puerto ${port}!`))
        app.get("/scrapping", function (req, res) {
            res.send('Estamos listos para empezar');
        })

        const puppeteer = require("puppeteer");
        const mkdirp = require('mkdirp')

        //Vemos y formateamos la fecha en la que las capturas se hacen
        let date = new Date()

        let day = date.getDate()
        let month = date.getMonth() + 1
        let year = date.getFullYear()

        if(month < 10){
        console.log(`${day}-0${month}-${year}`)
        }else{
        console.log(`${day}-${month}-${year}`)
        }
        //fecha formateada a DD/MM/AAAA
        let dateFormat = `${day}${month}${year}`;

        //fecha formateada todo seguido
            let dateNumber = Number(date);
            const fs = require("fs");

            //ES LA BASE

            //const puppeteer = require('puppeteer');           // include lib
            (async () => {                                    // declare function
                const browser = await puppeteer.launch({'defaultViewport' : { 'width' : 1920, 'height' : 545 }});       // run browser
                const page = await browser.newPage();           // open new tab
                const navigationPromise = page.waitForNavigation()

                await page.goto('https://www.fiat.cl/modelo/ducato-pasajeros/ducato-pasajeros-precios-y-versiones/#top');

                await page.waitForSelector('div.small-12.large-12.columns.container');          // wait for the selector to load
                let element = await page.$('div.small-12.large-12.columns.container');        // declare a variable with an ElementHandle
                await element.screenshot({path: `fiat/${dateFormat}/1.png`}); // take screenshot element in puppeteer

                await page.goto('https://www.fiat.cl/modelo/argo/argo-precios-y-versiones/#top');
                await navigationPromise

                await page.waitForSelector('div.small-12.large-12.columns.container');          // wait for the selector to load

                await element.screenshot({path: `fiat/${dateFormat}/2.png`}); // take screenshot element in puppeteer

                await browser.close();                          // close browser
    })();

The log throw me this;
"(node:17856) UnhandledPromiseRejectionWarning: Error: Node is either not visible or not an HTMLElem"
The first screenshot is ok but the second has the error.
What am I doing wrong? Sorry for my grammatical mistakes, Im not an english speaker but I´m trying to improve it day by day.

A: Most likely second screenshot does not work, because you've got a handle to an old element which is no longer accessible (you navigated to other page already). You have to re-initialize the element variable:
const express = require('express')

const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Veamos Kia!'))

app.listen(port, () => console.log(`App de ejemplo escuchando el puerto ${port}!`))
app.get("/scrapping", function (req, res) {
    res.send('Estamos listos para empezar');
})

const puppeteer = require("puppeteer");
const mkdirp = require('mkdirp')

//Vemos y formateamos la fecha en la que las capturas se hacen
let date = new Date()

let day = date.getDate()
let month = date.getMonth() + 1
let year = date.getFullYear()

if(month < 10){
console.log(`${day}-0${month}-${year}`)
}else{
console.log(`${day}-${month}-${year}`)
}
//fecha formateada a DD/MM/AAAA
let dateFormat = `${day}${month}${year}`;

//fecha formateada todo seguido
    let dateNumber = Number(date);
    const fs = require("fs");

    //ES LA BASE

    //const puppeteer = require('puppeteer');           // include lib
    (async () => {                                    // declare function
        const browser = await puppeteer.launch({'defaultViewport' : { 'width' : 1920, 'height' : 545 }});       // run browser
        const page = await browser.newPage();           // open new tab
        const navigationPromise = page.waitForNavigation()

        await page.goto('https://www.fiat.cl/modelo/ducato-pasajeros/ducato-pasajeros-precios-y-versiones/#top');

        await page.waitForSelector('div.small-12.large-12.columns.container');          // wait for the selector to load
        let element = await page.$('div.small-12.large-12.columns.container');        // declare a variable with an ElementHandle
        await element.screenshot({path: `1.png`}); // take screenshot element in puppeteer

        await page.goto('https://www.fiat.cl/modelo/argo/argo-precios-y-versiones/#top');
        await navigationPromise

        await page.waitForSelector('div.small-12.large-12.columns.container');          // wait for the selector to load
        let elementAfterNavigation = await page.$('div.small-12.large-12.columns.container');        // re-initialize element!
        await elementAfterNavigation.screenshot({path: `2.png`}); // take screenshot element in puppeteer

        await browser.close();                          // close browser
})();

Notice the elementAfterNavigation. This is why such functionality (eg. single screenshot) deserves its own function with scoped variables.


text:
Q: convert ascii character to signed 8-bit integer python This feels like it should be very simple, but I haven't been able to find an answer..
In a python script I am reading in data from a USB device (x and y movements of a USB mouse). it arrives in single ASCII characters. I can easily convert to unsigned integers (0-255) using ord. But, I would like it as signed integers (-128 to 127) - how can I do this?
Any help greatly appreciated! Thanks a lot.

A: Subtract 256 if over 127:
unsigned = ord(character)
signed = unsigned - 256 if unsigned > 127 else unsigned

Alternatively, repack the byte with the struct module:
from struct import pack, unpack
signed = unpack('B', pack('b', unsigned))[0]

or directly from the character:
signed = unpack('B', character)[0]

A: from ctypes import c_int8
value = c_int8(191).value

use ctypes with your ord() value - should be -65 in this case
ex. from string data
from ctypes import c_int8
data ='BF'
value1 = int(data, 16) # or ord(data.decode('hex'))
value2 = c_int8(value1).value

value1 is 16bit integer representation of hex 'BF' and value2 is 8bit representation

A: I know this is an old question, but I haven't found a satisfying answer elsewhere.
You can use the array module (with the extra convenience that it converts complete buffers):
from array import array

buf = b'\x00\x01\xff\xfe'
print(array('b', buf))

# result: array('b', [0, 1, -1, -2])

A: Use this function to get a signed 8bit integer value
def to8bitSigned(num):
    mask7 = 128 #Check 8th bit ~ 2^8
    mask2s = 127 # Keep first 7 bits
    if (mask7 & num == 128): #Check Sign (8th bit)
        num = -((~int(num) + 1) & mask2s) #2's complement
    return num

A: To convert any input bytes into signed integers:
def signed8bit_to_int(input):
    (((input >> 7) * 128) ^ input) - ((input >> 7) * 128)

Examples:
signed8bit_to_int(0xc0) = -64
signed8bit_to_int(0xbf) = -65
signed8bit_to_int(0x0f) = 15

Explanation with 0xC0 as an example:

*

*0xc0  '0b1100 0000', its last bit is a 1, meaning it is a signed byte

*step 1: test for signed bit: (((input >> 7) * 128)

*step 2: if it is a signed bit, invert the input bites:
 from: 100 0000 to 0111 1111 (63 of base 10)

*step 3: convert the above by substantiating 128:
63 - 128 = -65

A: The question doesn't clearly state if the single character is given as str or bytes.
The following answer is especially useful, if the input is an instance of bytes:
Since Python 3.2 there is a class method int.from_bytes:
int.from_bytes(b'\x81', byteorder='big', signed=True)  # -127
int.from_bytes(b'a', byteorder='big', signed=True)  # 97

For 16-bit integers, one would simply pass 2 bytes instead of 1:
int.from_bytes(b'\x81\x80', byteorder='big', signed=True)  # -32384
int.from_bytes(b'ab', byteorder='big', signed=True)  # 24930

Of course, you may need to specify byteorder='little'.
However, if the input is an ASCII character (0 - 128), I don't understand why you want a signed integer, because the result for your input will always be positive anyway (if I'm not mistaken). Python's integers use a flexible amount of bytes.


text:
Q: Can anyone make sense of this sentense? It is a headline on NY Times:

'Candyman' Review: Who Can Take a Sunrise, Sprinkle It With Blood?"

"Who Can Take a Sunrise, Sprinkle It With Blood" what does author mean by that?
The comma is getting me confused, can I replace the comma for "AND"??

A: This is a reference to a song, called "The Candyman" From Willy Wonka & the Chocolate Factory (1971) (and not related to the horror film)

Who can take a sunrise,
Sprinkle it in dew,
Cover it in chocolate
and a miracle or two?
The candyman!
The candyman can.

The song has the form of a list of things that the owner of the candy store can do.
But for the headline about a horror film, the lyric has been changed to make it horrific.  Grammatically you could use "and", but that would then not reference the song so well.


text:
Q: Various versions of chrome on linux I'm looking for the way to conduct cross-browser compatibility test on my ubuntu. Firefox and opera don't cause problems, but I didn't find any guide how to install older versions of chrome. Do you know how to check my code in this browser on my computer?

A: You can take screenshots in different versions in Browserstack. Also you can browse there using different browsers, but you will need to pay for that.

A: In general, there is no need to test compatibility against anything but the latest version of Chrome, since Chrome updates itself automatically. Just expect that anyone using Chrome to view your site will have the latest version.


text:
Q: How to bind a list of list to a view? There are 2 classes. One is a parent that contain a list of the second class as a property.
The second class has a list also.
The problem is the application doesn't bind the list inside the second class.
The application will display a list of grid that bind from the second class list (in the parent class) and each grid will display information from the list inside the second class.
Now each grid doesn't bind value
Class Parent{
   public List<NestedClass> Child { get; set; }
    .
    .
    .
}

Class NestedClass{
    public ObservableCollection<SomeParameter> Params{ get; set; }
    public string Name
    {
        get
        {
            return "Hello world";
        }
    }

    .
    .
    .
}

The xaml as below.
    <ItemsControl  HorizontalContentAlignment="Stretch" ItemsSource ="{Binding Child}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Child.Params}" >
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="80"/>
                                    <ColumnDefinition Width="80"/>
                                </Grid.ColumnDefinitions>
                                <Grid Grid.Column="0">
                                    <TextBlock Text="{Binding Count}" />
                                </Grid>
                                <Grid Grid.Column="1"></Grid>
                                <Grid Grid.Column="2"></Grid>
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

The output window show as below

System.Windows.Data Error: 40 : BindingExpression path error: 'Params' property not found on 'object' ''NestedClass' (HashCode=16626097)'. BindingExpression:Path=Params; DataItem='NestedClass' (HashCode=16626097); target element is 'ItemsControl' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')

Edited#1 Added the xaml
Edited#2 Added the output message
Edited#3 Added the name property in the NestedClass

A: Whether you tried it or not and whether it worked or not, the correct way to do this is as @groupgrip mentioned:
<ItemsControl HorizontalContentAlignment="Stretch" ItemsSource="{Binding Child}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding Params}">
                ...
            </ItemsControl>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The DataContext of the DataTemplate will be set to an item from the Child collection which is of type NestedClass. This class has a property called Params, so we can Bind directly with that property from inside the DataTemplate. There should also be a property named Count in that class as you are also trying to Bind to that from inside the DataTemplate.
Either way, the way to fix these types of problems on your own is to read what the errors say in the Output Window of Visual Studio. You often get errors that say something like 'can't find this property on that object' which should help you to track down and fix any problems.

A: For "Parent" class use HierarchicalDataTemplate, for child - DataTemplate. Define both templates in resources.
<Grid>
    <Grid.Resources>
        <HierarchicalDataTemplate DataType="{x:Type vm:Parent}" ItemsSource="{Binding Children}">... </>
        <DataTemplate DataType="{x:Type vm:Child}">...</>
    </Grid.Resources>
    <ItemsControl ItemsSource="{Binding Parents}">...</>
</Grid>


text:
Q: Android application crashes on Volley JsonObject POST request I'm trying write a splash screen that attempts to authenticate the users' credentials if they exist already in SharedPreference, but the application shuts itself down without warning on the line the request is added to the RequestQueue. What should I do to resolve this issue?
File prefFile = new File("/data/data/"+getPackageName()+"/shared_prefs/"+getPackageName()
            +"_preferences.xml");
    System.out.println(prefFile.toString());
    if(prefFile.exists()) {
        System.out.println("Found Preference File");
       final SharedPreferences pref = new SecurePreferences(getApplicationContext());

        Map<String, String> authParams = new HashMap<String, String>();
        authParams.put("key", pref.getString("key",""));
        authParams.put("action", "validate");

        System.out.println("now authenticating");
        JsonObjectRequest authRequest = new JsonObjectRequest(Request.Method.POST, AUTH_URL,
                new JSONObject(authParams), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
              /*  Intent intent = new Intent(LaunchScreen.this, BaseActivity.class);
                startActivity(intent); */
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                NetworkResponse response = error.networkResponse;
                System.out.println(response.toString());
                System.out.println(error.getMessage());
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Authorization", "Token " + pref.getString("key",""));

                return headers;
            }

            @Override
            public String getBodyContentType() {
                return "application/json";
            }
        };
        System.out.println("adding to queue");
        Volley.newRequestQueue(getApplicationContext()).add(authRequest);
    } else {
        System.out.println("Opening Login Activity");
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

A: You could try this in the onErrorResponse method:
VolleyLog.e(error.getMessage());

Then, check your logs in Android ADB monitor


text:
Q: Serenity BDD Getting Started I'm trying to learning Serenity BDD framework but i encounter some issues which need guidance from expect.I have downloaded serenity-cucumber4-starter-master from github.
Problems:

*

*AFAIK, there is Tasks, Screen and Actions classes creation but I did not found it in the project according to this theory.

*How is the implementation of this example different from screenplay design patterns?

My Code so far:
public class LoginTask implements Task {

    private HomepageScreen hp;

    @Override
    @Step("Landing on Guru Bank Website")
    public <T extends Actor> void performAs(T obj) {
        obj.attemptsTo(Open.browserOn(hp));

   }
}

@RunWith(SerenityRunner.class)
public class CucumberTestSuite {

    @Managed(driver = "chrome")
    private WebDriver browser;

    private Actor john = Actor.named("john");

    // =================================================================================
    @Before
    public void setup() {
        john.can(BrowseTheWeb.with(browser));
    }

    @Test
    public void login() throws InterruptedException {
        //givenThat(john).can(BrowseTheWeb.with(browser));
        System.out.println("Automate web browser");
        //givenThat(john).wasAbleTo(LoginTask.);

        Thread.sleep(9000);
    }

}

givenThat() method is undefined. Where to get the import location?
Please help. Thanks.

A: The givenThat() method (and other similar methods) are defined in net.serenitybdd.screenplay.GivenWhenThen.
import static net.serenitybdd.screenplay.GivenWhenThen.seeThat;


text:
Q: RegEx for matching URLs and failing non-URLs I am trying to extract separated urls from srcset of an image.
This is for extracting and downloading all the files present in the row.
I am not hard coding it because row can differ from time to time.
txt = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

reg = re.compile(r"((?:[^\s,]+))(?:.*?,)?").finditer

for i in list(reg(txt)):
   print(i.group(1))

I expect the result to be two urls
images/1x/1083bce6__color_272x92dp.png
images/2x/b3716cd2_color_272x92dp.png

But I get three with extra being
2x

A: Here, we would add a quantifier to a simple char class in an expression such as:
[^\s]{4,}

to get our desired URLs.
Demo
Test
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"[^\s]{4,}"

test_str = "images/1x/1083bce6__color_272x92dp.png 1x, images/2x/b3716cd2_color_272x92dp.png 2x"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx
If this expression wasn't desired, it can be modified/changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:


text:
Q: Ansible-Playbook: Failed to connect to the host via ssh: no such identity I am trying to run a playbook on some servers I am trying to setup with Ansible playbook. To do this I created a hosts file for dev inventories:
all:
  servers:
    hosts:
      my_server1:
      my_server2:
  vars:
    ansible_ssh_user: myremoteuser
    ansible_ssh_private_key_file: "{{ private_key }}"

I populate the private_key from my vault like so:  private_key: "{{vault_private_key | b64decode}}"
vault_private_key is the base64 encoded private 2048 rsa key that I generated, and I can see that it correctly decodes in the error message like so:
   "msg": "Failed to connect to the host via ssh: no such identity: -----BEGIN OPENSSH PRIVATE KEY-----\n

I generated the ssh key with the following command:
ssh-keygen -b 2048 -t rsa -f myremoteuser_key -C myremoteuser
When I ssh into my_server1 or 2, I can verify that /home/myremoteuser/.ssh/authorized_keys has the public key generated in there, which I verified by greping the public key text.
I can ssh via commandline. Is there something I am missing when attempting to set the private key?

A: I can't quite tell from your question -- can you confirm you are not confusing private key file path with private key file contents?
Are you writing the private key to disk?  If so, are you setting the permissions to 0600?  SSH won't read a private key file where the permissions are too broad.
I suspect you are running into an issue with permissions.
Why don't you just use a template task to populate the contents of your private key?  See https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html
You can put a variable into your template file, {{vault_private_key | b64decode}}


text:
Q: Calculating timespan with t-sql Given two date/times:
@start_date = '2009-04-15 10:24:00.000'
@end_date = '2009-04-16 19:43:01.000'

Is it possible to calculate the time elapsed between the two dates in the following format
1d 9h 19m

A: You can get the difference between the two dates to whatever resolution you want (in your example, minutes):
DATEDIFF(minute, @start_date, @end_date)

From there it's a simple matter of dividing minutes into hours and hours into days and modding the remainder.

A: DATEDIFF can return unintuitive values. For example, the two dates below differ by one second yet DATEDIFF with the parameters below and interpreted as others have interpreted it above returns 1 year:
SELECT DATEDIFF(year, '2005-12-31 23:59:59', '2006-01-01 00:00:00')
Look at the MSDN documentation for DATEDIFF to understand how it works.

A: I know this thread is older and the original participants are likely no longer watching, but I stumbled upon it, and had already written some code fairly recently to do something very close to what jdiaz is requesting. The result is rendered as a string in D:H:M:S format.
Step one would be to get the time span in seconds:
DECLARE @ElapsedS INT
SET @ElapsedS = DATEDIFF(second, @start_date, @end_date)

Now create the following scalar function:
CREATE FUNCTION [dbo].[udfTimeSpanFromSeconds]
(
    @Seconds int
)
RETURNS varchar(15)
AS
BEGIN
DECLARE
    --Variable to hold our result
      @DHMS varchar(15)
    --Integers for doing the math
    , @Days int --Integer days
    , @Hours int --Integer hours
    , @Minutes int --Integer minutes
    --Strings for providing the display
    , @sDays varchar(5) --String days
    , @sHours varchar(2) --String hours
    , @sMinutes varchar(2) --String minutes
    , @sSeconds varchar(2) --String seconds

--Get the values using modulos where appropriate
SET @Hours = @Seconds/3600
SET @Minutes = (@Seconds % 3600) /60
SET @Seconds = (@Seconds % 3600) % 60

--If we have 24 or more hours, split the @Hours value into days and hours
IF @Hours > 23
BEGIN
    SET @Days = @Hours/24
    SET @Hours = (@Hours % 24)
END
ELSE
BEGIN
    SET @Days = 0
END

--Now render the whole thing as string values for display
SET @sDays = convert(varchar, @Days)
SET @sHours = RIGHT('0' + convert(varchar, @Hours), 2)
SET @sMinutes = RIGHT('0' + convert(varchar, @Minutes), 2)
SET @sSeconds = RIGHT('0' + convert(varchar, @Seconds), 2)

--Concatenate, concatenate, concatenate
SET @DHMS =  @sDays + ':' + @sHours + ':' + @sMinutes + ':' + @sSeconds

RETURN @DHMS

END

Now feed your timespan into the newly created function:
SELECT TimeSpan = dbo.udfTimeSpanFromSeconds(@ElapsedS)

Should produce '1:09:19:01'

A: CONVERT(
  varchar(8),
  (
    CAST(@end_date AS DATETIME)
    -
    CAST(@start_date AS DATETIME)
  )
  ,108
)

This'll give it to you as HH:MM:SS
Cheers

A: datediff(datepart, date1, date2);
Rex's answer is more complete.

A: Here's how you format the datediff (50d 8h 35m) in a query:
Declare @Date1 as Datetime, @Date2 as Datetime
Set @Date1 = '2005-01-01 08:00:00'
Set @Date2 = '2005-02-20 16:35:30'

Select
CAST(DATEDIFF(Minute,@Date1, @Date2)/60/24 as Varchar(50)) ++ 'd ' ++
CAST((DATEDIFF(Minute,@Date1, @Date2)/60)-((DATEDIFF(Minute,@Date1, @Date2)/60/24)*24) as Varchar(50)) ++ 'h ' ++
CAST((DATEDIFF(Minute,@Date1, @Date2)) - (DATEDIFF(HOUR,@Date1, @Date2)*60) as Varchar(50)) ++ 'm' as FormattedDateDiff

A: DECLARE @FirstDate DATETIME, @SecondDate DATETIME, @result VARCHAR(MAX)
SELECT @FirstDate = '2017-03-01 09:54:00.637', @SecondDate = GETDATE()

DECLARE @Day INT,@Month INT,@Hour INT, @Minute INT,@TotalSeconds INT,@Year INT
SELECT @TotalSeconds = ABS(DATEDIFF(SECOND,@FirstDate,@SecondDate))

-- Standard values in seconds
DECLARE @YearSeconds INT, @MonthSeconds INT, @DaySeconds INT, @HourSeconds INT, @MinuteSeconds INT

SELECT  @MinuteSeconds = 60
SELECT  @HourSeconds = 60 * @MinuteSeconds
SELECT  @DaySeconds = 24 * @HourSeconds
SELECT  @MonthSeconds = 30 * @DaySeconds
SELECT  @YearSeconds = 12 * @MonthSeconds

--SELECT @MinuteSeconds AS [Minutes], @HourSeconds AS [Hours], @DaySeconds AS [Day],@MonthSeconds AS [Month],@YearSeconds AS [Year]

IF @TotalSeconds < @MinuteSeconds
BEGIN
    SELECT @result = CAST(@TotalSeconds AS NVARCHAR(20)) + ' seconds ago'
END
ELSE IF @TotalSeconds < @HourSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(MINUTE,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' minutes ago'
END
ELSE IF @TotalSeconds < @DaySeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(HOUR,@FirstDate,@SecondDate)) AS     NVARCHAR(20)) + ' hours ago'
END
ELSE IF @TotalSeconds < @MonthSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(DAY,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' days ago'
END
ELSE IF @TotalSeconds < @YearSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(MONTH,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' months ago'
END
ELSE IF @TotalSeconds > @YearSeconds
BEGIN
    SELECT @result = CAST(ABS(DATEDIFF(YEAR,@FirstDate,@SecondDate)) AS NVARCHAR(20)) + ' year ago'
END

SELECT @result


text:
Q: How to Integrate Braintree to Dear Systems Can Braintree can be integrated with Dear Systems? I would like to ask anyone to give me some advices, suggestions, documentations or sample of implementations on how to integrate BrainTree in Dear Systems.

A: Dear Systems is an inventory management package.  Braintree is a payment processor.  So you would integrate both of those into an ecommerce platform (not one with the other).  For example, Dear has integrations with Shopify and Magento, as does Braintree.  So you'd want to pick and ecommerce system that has prebuilt integrations for both these components and go from there.
Here's Dear's integration page:
http://dearsystems.com/inventory-software/partners/
and here's Braintree's: https://www.braintreepayments.com/features/third-party-integrations
(Although Braintree's list is only partial, since so many small e-commerce platforms have integrated with them.)


text:
Q: RegEx for computer name validation (cannot be more than 15 characters long, be entirely numeric, or contain the following characters...) I have these requirements to follow:

Windows computer name cannot be more than 15 characters long, be
  entirely numeric, or contain the following characters: ` ~ ! @ # $ % ^
  & * ( ) = + _ [ ] { } \ | ; : . ' " , < > / ?.

I want to create a RegEx to validate a given computer name.
I can see that the only permitted character is - and so far I have this:
/^[a-zA-Z0-9-]{1,15}$/
which matches almost all constraints except the "not entirely numeric" part.
How to add last constraints to my RegEx?

A: You could use a negative lookahead:
^(?![0-9]{1,15}$)[a-zA-Z0-9-]{1,15}$

Or simply use two regular expressions:
^[a-zA-Z0-9-]{1,15}$
AND NOT
^[0-9]{1,15}$;

Here is a live example:

var regex1 = /^(?![0-9]{1,15}$)[a-zA-Z0-9-]{1,15}$/;
var regex2 = /^[a-zA-Z0-9-]{1,15}$/;
var regex3 = /^[0-9]{1,15}$/;

var text1 = "lklndlsdsvlk323";
var text2 = "4214124";

console.log(text1 + ":", !!text1.match(regex1));
console.log(text1 + ":", text1.match(regex2) && !text1.match(regex3));
console.log(text2 + ":", !!text2.match(regex1));
console.log(text2 + ":", text2.match(regex2) && !text2.match(regex3));


text:
Q: Logging Database Row alteration I am using a strongly typed dataset in my C# application and I would like to be able to log any changes a user makes to a row. What is the best way to do this?

A: Do you want to be able to access the changes from your C# application?  Or is this just for logging/auditing purposes?  Is your strongly typed dataset an XSD dataset that maps to a SQL Server table?
Triggers on the SQL server
In a large ordering system I helped developed at CB Richard Ellis, we created extra tables to hold versioned data.  Say you have a Request table.  Create a Request_changes table.  Then you set up triggers for INSERT and UPDATE like this:
CREATE TRIGGER [dbo].[tr_Request_update]
ON [dbo].[Request]
FOR UPDATE
AS
    SET NOCOUNT ON
    INSERT INTO dbo.Request_changes
    (
        --ID,      // taken care of by IDENTITY(1,1)
        --LogDate, // uses default value of GetDate()
        ChangeAction,
        SQLServerUser,

        RequestID,
        UserIDContact,
        etc
    )
    SELECT
        'UPDATE',
        system_user,

        -- Request fields
        RequestID,
        UserIDContact,
        etc
    FROM
        inserted

    SET NOCOUNT OFF
GO

create TRIGGER [dbo].[tr_Request_insert]
ON [dbo].[Request]
FOR INSERT
AS
    SET NOCOUNT ON
    INSERT INTO dbo.Request_changes
    (
        --ID,      // taken care of by IDENTITY(1,1)
        --LogDate, // uses default value of GetDate()
        ChangeAction,
        SQLServerUser,

        RequestID,
        UserIDContact,
        Title,
        etc
    )
    SELECT
        'INSERT',
        system_user,

        -- Request fields
        RequestID,
        UserIDContact,
        etc
    FROM
        inserted

    SET NOCOUNT OFF
GO

You don't necessarily have access to the _changes table (unless you map that to another XSD dataset), but it's great for logging and auditing and tracking down bugs and history.
Other options
Perhaps you have an XSD dataset that isn't backed by a persistent store such as SQL server, and you're just using in memory datasets.  There are plenty of other design patterns and well known constructs to notify you when property values have changed.
Also, if you are using XSD data sets, is it because you are working on an existing code base or a legacy application?  If you are doing new development, I would steer away from them.  It's an old technology that MS is no longer actively developing.  If you want to stay in the MS stack that ships with current versions of Visual Studio, your best bets would be Linq to Sql or Entity Framework, both of which should be easier to deal with, and are more flexible (for instance, I don't think XSD data sets handle null values very well, and they don't support .NET nullable types in the generated classes).


text:
Q: How to paginate over Stripe API results? Issue: I want to find a way to paginate over Stripe API results past a certain number.  The issue is, as time goes on and more API documentation appears, a page will be loaded with way too much data.  Preferably I would like to have a months worth of data per page.
Question: How can I limit to results on the views side and create pagination for it.
For example, I have this in my controller:
  @payouts = Stripe::Payout.list(
      {
        limit: 100,
        expand: ['data.destination']
      },
      { stripe_account: current_user.stripe_token }
    )

Views:
 #table html stuffs
    ...
    <% @payouts.each do |payout| %>

            <%= number_to_currency(as_table_row_payout(payout["amount"] / 100.00 )) %>
            <%= as_table_row_payout(Time.at(payout["arrival_date"]).strftime('%m/%d/%Y')) %>

  <% end %>
    ...

I have the will_paginate gem but that didn't seem to work.  So I figured there may be a way with jquery / JS to solve this.  Does anyone have a solution to limit the amount of API JSON data that is requested on the view page?
Somewhat of an update and a bit off topic... (sorry if this strays from the post itself and starts a new conversation)
I have found a gem for will_paginate to paginate through API requests
I have found the api-pagination gem here: https://github.com/davidcelis/api-pagination
Although, when i installed the gem and followed the directions, nothing seemed to happen - I manually created an api_pagination.rb config file and did what it seems like the docs say to do as well... Anyone use this before?

A: The Stripe API uses cursors for pagination rather than just specifying a page and a page size (which is what will_paginate and kaminari do).
If you look at the api docs for listing payouts the arguments you'll need to use are ending_before and starting_after.
If you retrieve 10 payouts with ids [1, 2, ..., 10] and you want the next "page" of results you'll need to make the request again with starting_after=10. I.e. from the payout with id=10 get me the next 10 payouts.
I'm not aware of any gem support for this (although that definitely doesn't mean that there isn't any!) and I've tended to roll my own by generating "Next" and "Previous" links to set starting_after the id of the last payout in my current page or ending_before the id of the first payout in my current page. E.g.
<%= link_to 'Previous', list_payouts_url(first_payout_id: @payouts.first.id) %>
<%= link_to 'Next', list_payouts_url(last_payout_id: @payouts.last.id) %>

and then setting the ending_before or starting_after to params[:first_payout_id] and params[:last_payout_id].


text:
Q: ui-grid multiple on same page onRegisterApi I try to register a dynamic number ui-grid on same page so when I have only 1 on page I can user onRegisterApi function but if I have more than 1 how can I register the event on each ui-grid. So similar to onRegisterApi I have same problem on definition because every grid have custom definition.
I need to register the event because I want to connect/link event from page to 1 or more ui-grid in the page (es filter, change color, etc)


text:
Q: PHP Regex: split a string on numeric value I have a code that can receive 2 types of string:

*

*text number text
danny levitt 48 new york

*text number [comma] text
danny levitt 48, new york

The text on both size can be a single word or more, and the language might not be english.
I need those strings to return to me in an array as follows:
    Array (
        0 => "danny levitt",
        1 => "48",
        2 => "new york"
    )

How can I do that?
Thanks.

A: Split your input according to the space which exists just before to the number and the space which follows the same number. \K discards the previously matched characters.
$string = "danny levitt 48, new york";
$regex = '~\s+(?=\b\d+,?)|\b\d+\K,?\s+~';
$splits = preg_split($regex, $string);
print_r($splits);

Output:
Array
(
    [0] => danny levitt
    [1] => 48
    [2] => new york
)


text:
Q: oclint: error: violations exceed threshold via Jenkins can't win oclint. I really don't know what to do, i try to make some changes in build script but nothing help.
script:
$XCODE_COMMAND -reporter json-compilation-database:${WORKSPACE}/compile_commands.json clean build
#${oclint.path}/bin/oclint-xcodebuild
${oclint_path}/bin/oclint-json-compilation-database \
${oclint_in} ${oclint_ex} -- -o=$BUILD_WORK_DIR/oclint/lint.xml \
-report-type=pmd -stats -max-priority-1=9999 -max-priority-2=9999 -max-priority-3=9999 -rc LONG_LINE=500 -rc LONG_VARIABLE_NAME=100
sed -i .bak 's/\&\&/\&/g' "$BUILD_WORK_DIR"/oclint/lint.xml

mistake:
18:22:18 + oclint/bin/oclint-json-compilation-database -- -o=/Users/ep/jenkins- slave/workspace/test_RGP-ODC_RacingPost_iPad_staging/./build/oclint/lint.xml -report-type=pmd -stats -max-priority-   1=9999 -max-priority-2=9999 -max-priority-3=9999 -rc LONG_LINE=500 -rc LONG_VARIABLE_NAME=100
18:27:22
18:27:22 oclint: error: violations exceed threshold
18:27:22 P1=2[9999] P2=3662[9999] P3=11784[9999]
18:27:23 Build step 'Execute shell' marked build as failure

A: Why not just increase the threshold over 9999?

maxPriority=15000
${oclint_in} ${oclint_ex} -- -o=$BUILD_WORK_DIR/oclint/lint.xml
  -report-type=pmd -stats -max-priority-1=$maxPriority -max-priority-2=$maxPriority -max-priority-3=$maxPriority -rc LONG_LINE=500 -rc LONG_VARIABLE_NAME=100


text:
Q: Programmatically assign users to Azure AD Application using Graph API I am trying to write a script to assign users to an Azure AD application (servicePrincipal) using Graph API. I am testing this in my sandbox, where I have defined the app and assigned users to it.  However, when I query the servicePrincipal, I don't see the users anywhere in the response.
Questions:

*

*Based on the documentation, shouldn't there be appRoleAssignment?

*The documentation says this field is read-only, so how are you supposed to assign users?

A: The accepted answer is a bit outdated now.
The URL you need is:
https://graph.microsoft.com/v1.0/<tenantID>/users/<userObjectID>/appRoleAssignments

Send a HTTP POST with a content of:
{
  "principalId": "<objectId-of-user>",
  "resourceId": "<objectId-of-service-principal>",
  "principalType": "User",
  "appRoleId": "<id of role>"
}

The easiest way to test is via the Microsoft Graph Explorer
Or the way im doing it is via  bash script, calling the azure cli
cat <<- EOF > roleAssignment.json
{
  "appRoleId": "${UUID}",
  "principalId": "{$USER_ID}",
  "principalType": "User",
  "resourceId": "${SP}"
}
EOF

az rest --method post --headers Content-type="application/json" --url "https://graph.microsoft.com/v1.0/${TENANT_ID}/users/${USER_ID}/appRoleAssignments" --body @roleAssignment.json

A: You can get the appRoleAssignments of a user via the navigation property when querying the Graph API:
https://graph.windows.net/tenant-id/users/user-id/appRoleAssignments?api-version=1.6

You can create assignments by making an HTTP POST to:
https://graph.windows.net/tenant-id/users/user-id/appRoleAssignments?api-version=1.6

The object that you need to send looks like this:
{
  "id": "id-of-role",
  "principalId": "objectId-of-user",
  "resourceId": "objectId-of-service-principal"
}

If your app does not have any roles, but you still want to assign a user, it seems you can just set the id to all zeros:

Where the resource does not declare any permissions, a default id (zero GUID) must be specified.

So something like:
{
  "id":"00000000-0000-0000-0000-000000000000",
  "resourceId": "a27d8321-3dc6-44a1-bf19-2546a9f2806e",
  "principalId": "c4f810b8-2ea1-4580-9595-30275a28c2a2"
}


text:
Q: boot2docker equivalent of docker exec First time dorking with Docker and Go, and I'm unfamiliar with linux commands, so I could be mucking up in any aspect of this: I'm running boot2docker on a windows machine and I'm trying to get inside a running instance to debug why my Go isn't executing. Using docker exec containerId /bin/bash returns:
$ docker exec 1755 /bin/bash
exec: "C:/Program Files (x86)/Git/bin/bash": stat C:/Program Files (x86)/Git/bin/bash: no such file or directory
Cannot run exec command 0368f06b90454cf3f8bb0b29f0cacb66503907f6c7fb806c09e97f83
fef8c48b in container 17557fbf39f4419d509c58563a1ba17d6d269d91395b76ea4266c1898e
8665cf: [8] System error: exec: "C:/Program Files (x86)/Git/bin/bash": stat C:/Program Files (x86)/Git/bin/bash: no such file or directory
Error starting exec command in container 0368f06b90454cf3f8bb0b29f0cacb66503907f
6c7fb806c09e97f83fef8c48b: Cannot run exec command 0368f06b90454cf3f8bb0b29f0cac
b66503907f6c7fb806c09e97f83fef8c48b in container 17557fbf39f4419d509c58563a1ba17
d6d269d91395b76ea4266c1898e8665cf: [8] System error: exec: "C:/Program Files (x86)/Git/bin/bash": stat C:/Program Files (x86)/Git/bin/bash: no such file or directory

Which is obviously not right.  What's with the chain of containers, boot2docker itself then the one I entered? I'm seeing alternatives like nsenter, but those claim that docker exec renders them obsolete. What's the catch with Windows/Boot2Docker?
A comprehensive explanation with the answer would be lovely.

A: Try with the double slash // instead, like this:
docker exec -it <container-id> //bin/bash
source: http://www.mingw.org/wiki/Posix_path_conversion
Also mentioned here: https://stackoverflow.com/a/30184356/2167517


text:
Q: SQL require literal value in foreign column Is it possible to require a specific literal value in a foreign key constraint?
For example
CREATE TABLE a (
  id bigserial primary key,
  b_id bigint not null,
  foreign key (b_id, true) references b(id, flag)
);

CREATE TABLE b (
  id bigserial primary key,
  flag boolean
);

where we want to require that rows in a reference only rows in b with a flag set to true.

A: The syntax in the question is not valid (see CREATE TABLE). You can get the desired effect as follows:
CREATE TABLE b (
    id bigserial,
    flag boolean,
    primary key(id, flag)
);

CREATE TABLE a (
    id bigserial primary key,
    b_id bigint not null,
    flag boolean default true check (flag),
    foreign key (b_id, flag) references b(id, flag)
);

A: You probably want something along these lines. I did away with the superfluous a.id column to make it easier to read.
CREATE TABLE b (
  id bigserial not null,
  flag boolean not null,
  primary key (id),
  unique (id, flag)
);

The primary key constraint on id prevents duplicate id numbers. The overlapping constraint on id, flag allows this pair of columns to be the target of a foreign key constraint.
CREATE TABLE a (
  b_id bigint not null,
  flag boolean not null default true
    check (flag = true),
  primary key (b_id, flag),
  foreign key (b_id, flag) references b (id, flag)
    on delete cascade
);

In order for a row in a to reference only those rows in b where flag is true, every row in a must have flag set to true. The default and the check constraint on flag guarantees that.
Now let's try inserting some rows.
insert into b (flag) values (true);
insert into b (flag) values (true);
insert into b (flag) values (false);

So far, so good. Now some rows for a.
insert into a (b_id, flag) values (1, true);
insert into a (b_id, flag) values (2, true);

But this one should fail.
insert into a (b_id, flag) values (3, true);

--ERROR:  insert or update on table "a" violates foreign key constraint "a_b_id_fkey"
--DETAIL:  Key (b_id, flag)=(3, t) is not present in table "b".

And this one should fail.
insert into a (b_id, flag) values (3, false);

--ERROR:  new row for relation "a" violates check constraint "a_flag_check"
--DETAIL:  Failing row contains (3, f).

One more thing
You need to think about what you want to happen when you update a flag in table b. You can't cascade updates; that would result in a row in a referencing a row that has false in b.
update b set flag = false where id = 1 and flag = true;
-- ERROR:  update or delete on table "b" violates foreign key constraint "a_b_id_fkey" on table "a"
-- DETAIL:  Key (id, flag)=(1, t) is still referenced from table "a".

How you deal with that is application-dependent. In some apps, it might be appropriate to delete the row in a when the row in b updates to false. In other apps, it might be appropriate to just revoke update permissions on b. (There are other options.) In any case, you'll need to write a trigger.


text:
Q: Can't use Lapack: Class 'Lapack' not found in After installing lapack via:
yum install lapack lapack-devel

and restarting httpd service I still get
Fatal error: Class 'Lapack' not found in /var/www/html/metody_obliczeniowe/proj1/3.php on line 135

when trying to use the example from:
http://php.net/manual/en/lapack.solvelinearequation.php

A: You need to install the lapack extension.
# pecl install lapack


text:
Q: URL RewriteRule Im trying to rewrite my urls and I have the following in my htaccess where the pageid is the mysql id for each page and title is the page title.
RewriteRule ^([^/]*)/([^/]*)\.html$ content.php?pageid=$1&title=$2 [L]

Current URL structure based on this rule is:
http://domian.com/3/Contact.html
And would like to change it to:
http://domian.com/Contact.html
Also I have this php function that changes the URL:
  function createPageLink($id)
  {
      global $db, $core;

      $sql = "SELECT id, slug FROM pages WHERE id = '".(int)$id."'";
      $row = $db->first($sql);

      $slug = $row['slug'];

      if ($core->seo == 1) {
          $display = $core->site_url . '/' . intval($id) . '/' . sanitize($slug) . '.html';
      } else {
          $display = $core->site_url . '/content.php?pageid=' . intval($id);
      }
      return $display;
  }

So basically remove the number after the URL and just have the title only.
I know its pretty simple but it driving me nuts. Thanks

A: You are seeking this,
RewriteRule ^([^/]*)\.html$ content.php?title=$1 [L]

The following will match both.
RewriteRule ^([^\/]*)?/?([^\/]*)\.html$ content.php?pageid=$1&title=$2 [L]

When I test it following files were used.
<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    RewriteBase /

    # Allow any files or directories that exist to be displayed directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Rewrite all other URLs to index.php/URL
    RewriteRule ^([^\/]*)?/?([^\/]*)\.html$ index.php?part1=$1&part2=$2 [L]
<IfModule mod_rewrite.c>

index.php file to test.
<?php
var_dump($_GET);
var_dump($_SERVER);
?>

A: Well, first you need make some tokens for each page. For instance: token Contact refer to id 1. You can do it with arrays, for instance, or a switch.
Example for PHP:
$token_ids = new array();
$token_ids['Home'] = 1;
$token_ids['Contact'] = 2;

$current_token = $_GET['title']; // following your example

if(!isset($token_ids[$current_token])) {
  // ERROR or REDIRECT like to home:
  $current_token = 'Home';
}

// similar to $_GET['pageid'] of example
$current_token_id = $tokens_id[$current_token];

You can do it on MySQL too, simply you need save an unique token for each page. Like:
id | token     | page_title
1    Home        Hello!
2    Contact     Contact us!

A: Seems to me, if you really don't need the id, you could simply do the following (don't forget to clean the title before you search the db though):
RewriteRule ^(.*)\.html$ content.php?title=$1 [L]


text:
Q: A view without an action, how? I have some static views in my Yii application.
It seems to me pointless to write an empty action for that view (I do need the layout though, as some widgets there are dynamic, like the one showing user logged it/logged out etc).
How is it done, if at all possible?

A: In your controller you can define a "page" action in the actions method of CController -- from the documentation:
page action renders "static" pages stored under 'protected/views/site/pages'
They can be accessed via: index.php?r=site/page&view=FileName

see: http://www.yiiframework.com/wiki/22/how-to-display-static-pages-in-yii/
(If you used yiic to create a webapp it's probably already in your controller. Also note that if you are using friendly urls, you can access pages via /site/page/view/pagename or further customize the pattern via the urlManager.)


text:
Q: Quais as diferenças entre "checkout, revert e reset" Gostaria de saber qual a diferença entre os comandos abaixo:
git revert commit ;
git reset --hard commit ;
git checkout commit ;

A: Bem, vou tentar descrever como conheço e utilizo, pois informações macros, você encontra diversas por aí, afinal o GIT é extremamente utilizado.

*

*revert - Ele faz o rollback do commit informado, basicamente um ctrl+z, imagina que você fez o commit X e percebeu que quebrou a
aplicação, na maior urgência você precisa voltar como estava antes,
você faz um revert do commit X, porém as vezes que usei, ele deixa
isso explicito, gerando um novo commit quanto a esse revert, portanto
ele constará em seu histórico.

*reset - A ideia dele é exatamente essa, retornar para um estado anterior, porém diferente do revert, ele não gera commit, ele desfaz
tudo mesmo, nunca usei ele enviando para o servidor (nem sei se rola), mas as vezes que
commitei na master por engano, fiz o reset informando o último commit
válido da master, com isso ele restaurou a master e simplesmente
eliminou meus commits incorretos

*checkout - Esse cara vai para uma branch, tag, commit etc... Ele pode mudar completamente o estado dos seus fontes, imagina que você
já está no commit 100, porém alguém relata um problema que ocorria no
commit 50, você consegue voltar para esse commit com o checkout.
Utilizo dele principalmente para mudar de branch, entre master,
inovação (RC) e versão atual da aplicação. Também utilizo o git checkout  para desfazer algo que ainda não fiz o commit, tipo git checkout app.js, ele descarta tudo que fiz e ainda não fiz o commit ou o git add.

Recomendo você criar um repositório em algum git free e brincar com esses comandos.
Além da pergunta que o hkotsubo citou, tem essa aqui que está bem legal:
Como desfaço o último commit no git?


text:
Q: Can I upload an app into playstore with starter edition of Xamarin studio? I have developed a sample app using Xamarin studio for android. But the build(apk file) will work only for 1 day. I am using trial version of xamarin studio. Please let me know if I can upload the app into play store with starter edition

A: Yes, you can publish your app to the Google Play store. If you go to http://xamarin.com/starter and scroll down (as of this printing), you can find three apps which are published to iOS and Android app stores using Xamarin Starter.
Here's one sample, "Days Until Xmas"
Xamarin Starter was recently expanded to allow creation of apps up to 128 KB in Intermediate Language (IL), but you cannot add 3rd party libraries to your apps with Starter.
Your apps will need to be relatively simple apps if you wish to remain under the 128 KB IL limit.

A: there you go, you can deploy but there is a limit on package size,
please go through Pricing page,
Quoted

Xamarin Starter allows developers to build and publish simple apps, which contain no more than 64k of compiled user code (IL), and which do not call out to native third party libraries (i.e., developers may not P/Invoke into C/C++/Objective-C/Java.

also for details about the package , you can head to this Discussion page

A: regarding this discussion: Xamarin starter edition - deploy to market, you should be able to deploy your app to store.
Edit: Oh sorry, I just checked again and you are interested in trial, not starter edition. In case of the trial edition, which has 24-hour restriction, you wont be able to publish it on Google play store, since the submission process of application to Google play takes from 1-3 days.


text:
Q: Loop sql-php conditional 5 times then exit I am not great with php/sql - still learning.
I am trying to get it so 5 url's (there are over 20 to chose from) are randomly selected from the user database and displayed on a page. In the event that the user has not filled out all 20+ url's in the members area of our site, I want it to skip the ones they have not filled out.
The problem is it is selecting and displaying 5 whether they are NULL or not and stopping after 5. Its not only counting the ones that are not null.
What do I need to fix, how would I go about this? I pasted the entire code from the page in question - hope its not to much to understand what I need.... like I say I am not that good at this stuff.
<?php
include "config.php";
if ($_GET['r']) {

    if($_COOKIE['referid']!=$_GET['r']) mysql_query("UPDATE members SET hits_unique=hits_unique+1,hits_visitor=hits_visitor+1 WHERE userid='".$_GET['r']."'");
    else mysql_query("UPDATE members SET hits_visitor=hits_visitor+1 WHERE userid='".$_GET['r']."'");

setcookie('referid', $_GET['r'], time()+365*24*60*60);
setcookie('referrer', $_SERVER['HTTP_REFERER'], time()+365*24*60*60);
}

include 'headsplash.php';
echo '';
echo '';
echo '<canvas id="theapt" style="width:100%; height:100%; position:fixed; top:0;left:0; background-color:black; z-index:-1;"></canvas>';
echo '
'.$_GET['r'].' Recommends
';
echo '
';

echo '\'s Downline Builder
';
echo '
';

//Get the user links

$ub = array();

$sql = mysql_query("SELECT * FROM builder WHERE userid = '".$_GET['r']."'");

if(@mysql_num_rows($sql)) $ub = mysql_fetch_array($sql);

$lastcat = "";

    //Get the links for each site

    $slist = mysql_query("SELECT s.*,c.name as catname FROM builder_sites s JOIN builder_cat c ON s.category=c.id ORDER BY RAND() LIMIT 5");

while($each = mysql_fetch_array($slist)) {
$user = $_GET['r'];

$found = 0;

while($found == 0) {

    //Referrer exists?

    $sql = mysql_query("SELECT m.referid FROM members m JOIN members r ON m.referid = r.userid WHERE m.userid = '".$_GET['user']."'");

    if(@mysql_num_rows($sql)) {

        $referrer = mysql_result($sql, 0);

        $sql = mysql_query("SELECT site".$each['id']." FROM builder WHERE userid = '".$_GET['r']."'");

        if(@mysql_num_rows($sql)) {

            // Found a row, check if it's empty

            $value = mysql_result($sql, 0);

            if($value) {

                //found a link, end the loop

                $links = $value;

                $found = 1;

            } else {

                //No link, next.

                $user = $referrer;

            }

        } else {

            //No row, next.

            $user = $referrer;

        }

    } else {

        //No more referrers, use default values

        $links = $each['url'];

        $found = 1;

    }

}

if($lastcat != $each['category']) ;

$lastcat = $each['category'];

?>

<form method="post"><a href="http://nullreferrer.com/go/?<? if($ub['site'.$each['id']]=="") echo $links; else echo $ub["site".$each['id']]; ?>" target="_blank"><? echo $each['desc']; ?><input type="hidden" name="sid" value="<? echo $each['id']; ?>">

<? echo $each['explain']; ?>

</form>

 <? }
echo '

<button id="button-green">Get your FREE downline builder here</button>
';

echo '
';
echo '
';

mysql_close($dblink);

?>


text:
Q: How to check if a location lies within the "accuracy" of the polygon.- e.g. if the accuracy of the function is 30m This function is to check if latitude or longitude inside or outside the polygone.
 func isAvalibleinsidePolygone{
            let latitude = lat?.text
            let longitude = lon?.text
            if latitude != "" && longitude != "" {
                //            pathOfPolygon.removeAllCoordinates()
                for p in places {
                    pathOfPolygon.add(p.coordinate)
                }
    ifGMSGeometryContainsLocation(CLLocationCoordinate2DMake(Double(latitude!)!, Double(longitude!)!), pathOfPolygon, true) {
                    alert(title:`enter code here` "YEAH!!!", msg: "You are inside the polygon")

                } else {
                 alert(title: "OPPS!!!", msg: "You are outside the polygon")
                }
            }
        }

But even i would like to check if a location lies within the "accuracy" of the polygon - e.g. if the accuracy of the function is 30m, any location that is within 30m of the polygon should still return true. So parameters will be like latitude,longitude,accuracy
 E.g:
func withinAccuracy(latitude:Double,longitude:Double,accuracy:Double){
//....
}

A: Have a look at the function
 GMSGeometryIsLocationOnPathTolerance(_ point: CLLocationCoordinate2D, _ path: GMSPath, _ geodesic: Bool, _ tolerance: CLLocationDistance) -> Bool  it does exactly what you want. link


text:
Q: Server Tomcat v8.5 Server at localhost failed to start Spring Project I cannot run a Tomcat server. I've tried to delete the servlet parts from web.xml and the org.eclipse.core.resources folder but it didn't work.
Here is the log from eclipse:
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:656)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:947)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more

sie 28, 2017 8:36:04 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
sie 28, 2017 8:36:04 PM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-nio-8009"]
sie 28, 2017 8:36:04 PM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Catalina]
sie 28, 2017 8:36:04 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
sie 28, 2017 8:36:04 PM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-nio-8009"]

Any suggestions?

A:
I Have similar problem, this solution is change the Tomcat port.

First.
Double click in Server.

Second.
In Modify the server ports change first 8 to 9.

Third.
Save the changes and Run.


text:
Q: Modelsim export wave (bitmap) batch mode Currently I run Mentorgraphics Modelsim in batch mode for a few nightly simulations.
My simulations run fantastic and in my transcript files I can see all errors/warnings/etc. but it would be nice to see the waveform for every simulation in a image, too, without simulating the projects again (it takes a long time...).
Modelsim/Questasim is able to export this bitmap in GUI mode (Select wave window and go to menu bar: "File -> Export -> Image").
Is there any opportunity to save the waveform as image in batch mode OR GUI mode with Tcl/Modelsim commands?
I read the commands about Modelsim (Modelsim SE User Manual) but I didn't find anything.
I am using Modelsim PE 10.4c @ Win7 64bit.
I am very thankful for any help/tips! :)
Michael

A: Unless your simulation is short enough, saving a bitmap of the full zoom won't help much.
What I suggest you to do is save the waveform by using vsim -wlf waveform.wlf .... Later you can view the by doing vsim -view waveform.wlf.
If you used a wave.do file to add signals when running the simulation, you must call it when viewing also, i.e.:
vsim -wlf waveform.wlf -do wave.do

And then
vsim -view waveform.wlf -do wave.do