text:
Q: Does Jessica Jones have any issues from her treatment? We know that the experiments done on Jessica can potentially lead to psychological issues, notably in the case of

 her mother

who exhibited severe anger management issues or even dissociative episodes.
The "Whizzer" also had psychological issues, which could possibly be attributed to the treatment, too.
Jessica occasionally seems to have some anger management problems (see: her court-ordered sessions).
She also is apparently dependent on alcohol, and even has started experiencing some hallucinations when under great stress.
On the other hand, we know Jessica has PTSD, of which alcoholism and even hallucinations can be symptoms. And her anger could just be normal for someone who has so much to deal with.
Does Jessica exhibit any psychological effects (not necessarily anger issues) from the experimental treatment used on her? Or can it all be attributed to her individual experiences?

A: Probably not
One recurring theme in the series is that Jessica Jones is psychologically broken and is barely surviving. She says something like

It took a dead coming back to show me that I was dead too.

late in Season 2. This could be a consequence of her treatment but the most likely explanation is that she has PTSD due to her past traumatic experiences (spoilers):

*

*Being mentally controlled by a psychopath and sexually abused by him.

*In particular, killing a woman under his influence.

*Having to shot her lover (Luke Cage).

*An abusive adoptive mother.

*Losing her family in a car accident. It is explicitly mentioned in the second season that she feels guilty for the accident as her father was looking at her and not the road at the moment of the accident.
That's a lot for one person.
The difference between Jessica and Alisa, her mother, is that Alisa's injuries were more severe, and she had to follow a heavier treatment, to the point that her physical appearance changed. Doctor Malus also explains that she had to be put on induced coma after each treatment and that long comas can have consequences on the brain. Here is  a quote from Karl Malus in the seventh episode of Season 2 "AKA I want your cray cray" (taken from the MCU wikia)

Dr. Malus: "When we got you, you were pretty much a goner. We had to induce a coma after each treatment to manage the side effects. But the way you've come through it... it's mind-blowing."
Alisa Jones: "Come through what, exactly?"
Dr. Malus: "Cutting-edge genetic editing. It stimulates healing through cell regeneration."

In addition, Alisa explained in a later episode that Jessica's relational difficulties are not due to her accident, but that she was a loner even before the accident.


text:
Q: How to solve the error from read_docx when exporting a flextable to word I kept on receiving the error message when trying to export the flextable to word document.
Example:

doc <- read_docx()
  Error in utils::unzip(file, exdir = tmp) :
    argument "file" is missing, with no default
  doc <- body_add_flextable(doc,value=t13,align = "center",split = TRUE)
  Error in inherits(x, "rdocx") : object 'doc' not found
  print(doc,target = "Table13.docx")
  Error in print(doc, target = "Table13.docx") : object 'doc' not found

Among all the errors returned, it seems read_docx() function is not applied correctly.  I have no idea how to fix it.  Anyone has any ideas?  Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the numbering list style in Microsoft Word to custom ordinals How may I change the numbering list style to something other than the built-in ordinal style (First, Second, Third, ...) in Microsoft Word 2010, for example to something like zuerst, zweite, dritte, ... in German, or to change the ordinals in my custom way in Kurdish as the following:
یک instead of the "First",
and دوو instead of the "Second",
and سه instead of the "Third" and likewise for the other ones.

A: You can get the ordinals for some languages. Let's say you have already numbered a list using the English ordinals. Then, to change a particular bllet to use German, you need to select its paragraph mark and mark the language as German (e.g. select the paragraph mark, click the language "button" in the status bar at the bottom of the Word window, and select German (Germany). In that case, I think First is "Erste." rather than "Zuerst."
That only seems to work for some languages. It isn't obvious to me why, for example, it does not work for others (e.g. Arabic). It could be one of those things that depends on the installation language or the "primary editing language" - I just don't know. But as far as I know, Kurdish isn't supported at all, so you could not use that approach.
For unsupported languages I think you would have to implement your own numbering, perhaps using field codes. There are various ways you could consider doing that. For example, suppose you wanted your numbering to go up to 100. You could then insert { SET } fields like this:
{ SET Kurdish1 "the kurdish text for 'first' }{ SET Kurdish2 "the kurdish text for 'second' } ...and so on.
Then, to insert the appropriate text for each bullet, you could use the nested field code.
{ REF "Kurdish{ SEQ bullet }" }

All the { } have to be the special field code brace pairs that you can insert on Windows Word using ctrl-F9. You may also have to work a bit harder to get this to work for right-to-left scripts. Unlike the built-in paragraph numbering, you have to select these fields and update them using F9 when, for example, you insert or delete a bullet.
{ SET } fields can easily be damaged by the user. Instead you could put the ordinals into Custom Document Properties called Kurdish1, Kurdish2 etc., and use
{ DOCPROPERTY "Kurdish{ SEQ bullet }" }

My personal preference would be to use VBA to put the texts into Document Variables that you can only see using programming or by looking inside the .docx, e.g.
Activedocument.Variables("Kurdish1").Value = "the kurdish word for 'First'"
etc.
Then use:
{ DOCVARIABLE "Kurdish{ SEQ bullet }" }


text:
Q: $\mathfrak{c} = 2^{\aleph_0}$ I know a few proofs over this theorem (where $\mathfrak{c}$ is the cardinality of $[0,1]$ and $\aleph_0$ is the cardinality of $\mathbb{N}$) where they construct two injections and then use Schröder-Bernstein (via the Cantor set or something like that).
Now I was wondering if I could do something like this:
Define $s: \{0,1\}^\mathbb{N} \to [0,1]$ by
$$s(x) = \sum_{i = 1}^\infty \frac{x(i)}{2^i}.$$
Now this is clearly a surjection because this is just a binary expansion of numbers in $[0,1]$, but not injective because these expansions are not unique. Is there a way to make this work? Can I use this to construct a bijection?

A: Yes, but in my opinion, it's really not worth it.  Binary expansions are unique for all real numbers except dyadic rationals $\frac{k}{2^n}$, since they can end with a string of zeroes or a string of ones.  But there are only countably many dyadic rationals.  So define $s : \{ 0, 1 \}^{\mathbb{N}} \to [0, 1]$ to be what you said for all strings that don't end with a string of zeroes or a string of ones, and for the countably many exceptions pick any bijection you like.  For example, if a sequence $a_i \in \{ 0, 1 \}^{\mathbb{N}}$ ends with a string of ones, send it to $0.1 a_1 a_2 a_3 ...$, and if it ends with a string of zeroes, send it to $0.0 a_1 a_2 a_3 ...$.
But really, there's no point in not using Schroeder-Bernstein.  Explicit bijections are highly overrated; in general it is much easier to construct an injection and a surjection.


text:
Q: Selecting polygons based on geometry (specifically right angles) using ArcGIS Desktop? I have some land registry data and I would like to know if there is a way of selecting all the polygons that contain a right angle.
I'm using (basic license) Arcgis 10.5.1.
Here's and image of part of the data with the an example polygon I would like to capture

A: You can use (Calculate Polygon Main Angle)
First you need to add numerical field to your shapefile (call it e.g angle)
Then open the (Calculate Polygon Main Angle) and define you dataset, and the angle field.

Then,  select by attribute, select when Angle = 0,90,-90
"Angle" = 0 OR "Angle" = 90 OR "Angle" =-90

And the result:

PS: this method in not totally accurate because the computed angle (The dominant angle of a polygon is the angle of longest collection of segments that have similar orientation. This angle will be stored in the specified field in decimal degrees from true north)[ARCGIS].


text:
Q: Function to flag duplicates in within query Postgresql I would like to write a function that flags duplicates in specified columns in postgresql.
For example, if I had the following table:
country | landscape | household
--------------------------------
TZA     | L01       | HH02
TZA     | L01       | HH03
KEN     | L02       | HH01
RWA     | L03       | HH01

I would like to be able to run the following query:
SELECT country,
       landscape,
       household,
       flag_duplicates(country, landscape) AS flag
FROM mytable

And get the following result:
country | landscape | household | flag
---------------------------------------
TZA     | L01       | HH02      | duplicated
TZA     | L01       | HH03      | duplicated
KEN     | L02       | HH01      |
RWA     | L03       | HH01      |

Inside the body of the function, I think I need something like:
IF (country || landscape IN (SELECT country || landscape FROM mytable
                            GROUP BY country || landscape)
    HAVING count(*) > 1) THEN 'duplicated'
ELSE NULL

But I am confused about how to pass all of those as arguments.  I appreciate the help.  I am using postgresql version 9.3.

A: You don't need a function to accomplish that. Using function for every row in result set is not so good idea because of performance. A way better solution is use pure SQL (even with subqueries) and give database engine chance to optimize it. In your very example it should be something like that:
SELECT t.country,t.landscape,t.household,case when duplicates.count>1 then 'duplicate'end
FROM mytable t JOIN (
SELECT count(household) FROM mytable GROUP BY country,landscape
) duplicates ON duplicates.country=t.country AND duplicates.landscape=t.landscape

which produces exactly the same result.
Update - if You want to use function at all cost, here is working example:
CREATE FUNCTION find_duplicates(arg_country varchar, arg_landscape varchar) returns varchar AS $$
BEGIN
    RETURN CASE WHEN count(household)>1 THEN 'duplicated' END FROM mytable
    WHERE country=arg_country AND landscape=arg_landscape
    GROUP BY country,landscape;
END
$$
LANGUAGE plpgsql STABLE;

A: select
  *,
  (count(*) over (partition by country, landscape)) > 1 as flag
from
  mytable;

For function look at the @MarcinH answer but add stable to the function's definition to make its calls faster.


text:
Q: jQuery function string This isn't working:
function checkIt(String rep) {
         if (counter[$(rep).val()] == undefined) {
         count++;
         result = Math.round((count * 100 )/howMany);
         $('.percent').text(result);
         $('#perc_in').animate({'width': result+'%'}, 500);
         counter[$(this).val()] = 1;
         $('#counter').text(result);
         }
}

Like, at all... <_< I mean I think I am doing the function wrong.
Then inside the case statement I have this:
checkIt($(this).val());

A: Javascript is weak typed, so what in the world is this?
function checkIt(String rep) {

Just change it to
function checkIt(rep) {

It's also a bit odd that you are try to create a new jQuery object from the value of another form element. And this line:
if (counter[$(rep).val()] == undefined) {

This may be a little dangerous if you're just checking for the non-existence of an array element, since $(rep).val() could also be undefined depending on the situation.


text:
Q: Zend PHP, porting from Linux to Windows -> setting baseUrl Recently I was tasked with porting a PHP website, built on Zend, from an Arch Linux server to a Windows server.  I have no experience with PHP.  I pulled all the files back and tried bringing it up on IIS with PHP and CGI installed, to no effect.  After changing some /'s to \'s in the pathing, I was still having issues and installed Zend studio.
I stepped through the page and found that the following bit, which seems off:
$baseUrl = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], '/index.php'));
$front_controller = Zend_Controller_Front::getInstance();
$front_controller->setBaseUrl($baseUrl);

When I debug the page, I find that $baseUrl is being set to (string:0).  If I comment out this line and the line that set the base url of the front controller the page will actually load and displays the login page; however, images an links from that page don't appear to work correctly.  If I hard set $baseUrl to '/index.php', the login page also loads, but when I try to interact with it, it recursively adds '/index.php' to the URL until the browser dies.
I've searched google, and these forums, to try to determine what this actually needs to be set to.  When I look at the PHP_SELF property of $_SERVER in the debugger, it is
(string:90) C:\Users\[userid]\AppData\Local\Temp\dummy.phpC:\Users\[userid]\AppData\Local\Temp\dummy.php

The page being hosted on IIS is currently under C:\WEBPAGE\ctcAB.
I've tried a variety of things including the windows path with \'s and /'s, .\ctcAB, .\ctcAB\index.php, and a number of permutations of the URL I get in the browser, both with and without http:// (which, from what I've read, I understand to be incorrect.).
So, when running a Zend PHP page on IIS on Windows, what does one need to set the base url of the Zend_Controller_Front to be?  Is it relative to the file path that IIS is pointing to?  Is it relative to the URL displayed at the root?
I saw another suggestion to get the baseUrl from $this; however, when I try that, I'm informed by the debugger that $this isn't in context.
Any help would be greatly appreciated.


text:
Q: Comparing values in different columns with same id tag I have an excel sheet containing a list of IDs each one of which has a few different values associated with it in other columns. For example, one id will have a 5 under a Height tab, and a 120 under a weight tab. Some ids get repeated twice and I want to have a formula which can compare the second id to the first one in each of the categories and return the difference between the two of them. For example if my chart is:
Table
I want to compare the height and weight of row 1 and 3 and return -1 and -20 to store in new columns. Is there a way of easily doing this?

A: Yes, there are a few ways you could approach this. My suggested approach would be to use the following (formulas entered using CTRL+SHIFT+ENTER):
Height_Diff: ={MIN(IF(A$2:A$4=A2,B$2:B$4))-MAX(IF(A$2:A$4=A2,B$2:B$4))}
Weight_Diff: ={MIN(IF(A$2:A$4=A2,C$2:C$4))-MAX(IF(A$2:A$4=A2,C$2:C$4))}
This would result in the following table:
+----+--------+--------+-------------+-------------+
| id | Height | Weight | Height_Diff | Weight_Diff |
+----+--------+--------+-------------+-------------+
|  1 |      5 |    100 |          -1 |         -20 |
|  2 |      4 |    123 |           0 |           0 |
|  1 |      4 |     80 |          -1 |         -20 |
+----+--------+--------+-------------+-------------+


text:
Q: ItemDecoration not drawn on last cell I have written a small snippet to show a vertical line and a little ball in each and every item of a RecyclerView.
But the last one or when there is 1 item only is never getting drawn.
My Decoration:
public class MarkerDecoration extends RecyclerView.ItemDecoration {

    Paint paint;

    public MarkerDecoration() {
        paint = new Paint();
        paint.setColor(Color.parseColor("#cccccc"));
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++) {
            View v = parent.getChildAt(i);
            c.save();

            if (childCount > 1) {
                if (i == 0)
                    c.drawLine(v.getX() + v.getPaddingLeft(), v.getHeight() / 2 - v.getY(), v.getX() + v.getPaddingLeft(), v.getHeight(), paint);
                else if (i == childCount - 1)
                    c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getY() - v.getHeight() / 2, paint);
                else
                    c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getHeight() + v.getY(), paint);
            }

            c.drawCircle(v.getX() + v.getPaddingLeft(), v.getY() - v.getHeight() / 2, 8, paint);
            c.restore();
        }
    }
}

And the layout it is getting called on:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="32dp"
    android:paddingEnd="@dimen/line_item_paddings"
    android:paddingLeft="@dimen/line_item_text_padding"
    android:paddingRight="@dimen/line_item_paddings">

    <TextView
        android:id="@+id/post_date_row"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerInParent="true"
        android:paddingEnd="@dimen/line_item_text_padding"
        android:paddingLeft="@dimen/line_item_text_padding"
        android:paddingRight="@dimen/line_item_text_padding"
        android:paddingStart="@dimen/line_item_text_padding"
        android:text="3 JUL"
        android:textColor="@color/light_gray" />

    <TextView
        android:id="@+id/title_row"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_toEndOf="@+id/post_date_row"
        android:layout_toLeftOf="@+id/amount_row"
        android:layout_toRightOf="@+id/post_date_row"
        android:layout_toStartOf="@+id/amount_row"
        android:ellipsize="end"
        android:maxLines="1"
        android:paddingEnd="@dimen/line_item_text_padding"
        android:paddingLeft="@dimen/line_item_text_padding"
        android:paddingRight="@dimen/line_item_text_padding"
        android:text="GTX Telecom" />

    <TextView
        android:id="@+id/amount_row"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerInParent="true"
        android:paddingEnd="@dimen/line_item_text_padding"
        android:paddingLeft="@dimen/line_item_text_padding"
        android:paddingRight="@dimen/line_item_text_padding"
        android:text="54,00" />

</RelativeLayout>

What I am missing here ?
Thanks !

A:
or when there is 1 item only is never getting drawn.

take a look at this snippet from your code of the decoration class
if (childCount > 1) {
    if (i == 0)
        c.drawLine(v.getX() + v.getPaddingLeft(), v.getHeight() / 2 - v.getY(), v.getX() + v.getPaddingLeft(), v.getHeight(), paint);
    else if (i == childCount - 1)
        c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getY() - v.getHeight() / 2, paint);
    else
        c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getHeight() + v.getY(), paint);
}

the c.drawlines get executed only when the childCount is greater than 1, just change the if condition to if(childCount >= 1) That should fix this problem.
This answer atleast solves one of your problem ill still keep looking trying to find whats causing the decoration to not show on the last item, for the last item I suppose this line should executed
c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getY() - v.getHeight() / 2, paint);

But I don't know exactly whats wrong with it
EDIT
I solved your 2nd problem too, the 2nd to last argument you pass to drawline v.getY() - v.getHeight() / 2 you are essentially drawing a line starting from the top left corner of the view and ending it at somewhere above the view(about v.getY() - v.getHeight()/2 exactly) just change this to v.getY() + v.getHeight()/2 instead
this 2nd to last argument the one before the paint argument, is the float stopY so you are asking line to start from top left of view and end v.getY() - v.getHeight() above the view, which is out of this view's bounds and hence can't see the line.
So your fixed code would look like this
if (childCount >= 1) {
    if (i == 0)
        c.drawLine(v.getX() + v.getPaddingLeft(), v.getHeight() / 2 - v.getY(), v.getX() + v.getPaddingLeft(), v.getHeight(), paint);
    else if (i == childCount - 1)
        c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getY() + v.getHeight() / 2, paint);
    else
        c.drawLine(v.getX() + v.getPaddingLeft(), v.getY(), v.getX() + v.getPaddingLeft(), v.getHeight() + v.getY(), paint);
}

   c.drawCircle(v.getX() + v.getPaddingLeft(), v.getY() + v.getHeight() / 2, 8, paint);


text:
Q: Insert before parent or itself (depending on if parent exist) JQuery maybe you could help me, I have this code (If the parent exist insert before the parent, if not insert before itself)
if ($editingElem.parent(".form-submit").length) {
       $editingElem.parent().before(response.d.htmlUpdate);
}
else {
       $editingElem.before(response.d.htmlUpdate);
}

Is there a way I can do this in one line of code in JQuery (because this kind of thing is repeat many times in my code)? Thanks broverflows!

A: If I understand correctly this problem you should write this code in an external function and call it each time when you need it.

A: Try use method:
condition ? true : false
$editingElem.parent(".form-submit").length ? $editingElem.parent().before(response.d.htmlUpdate) : $editingElem.before(response.d.htmlUpdate);

A: If you have to call code more than on time, it´s the best to put this code in a function, that you can call multiple times.
If you have to make any changes in the future, you just have to edit in you function an every call will be affected by this changes.
Functions
To declare a function in javascript, write this:
function exampleFunction() {
   // insert your code here
}

To call this function, you just type this:
exampleFunction();

If you need any variables to be given to your function, your could use function parameters:
function exampleFunction(parameterA, parameterB) {
   // insert your code here
   console.log(parameterA + parameterB);
}

exampleFunction(1, 4); // would log 5 to your console

The solution for your problem
 function(selector, response) {
     if (selector.parent(".form-submit").length == 1) {
         selector.parent().before(response);
     }else {
         selector.before(response);
     }
 };

njow you can insert this function-call at everywhere you need it:
insertResponse($editingElem, response.d.htmlUpdate);


text:
Q: Concatenate two tables in MySQL What I have:
Table1
╔════╦═══════╦═════╗
║ ID ║ NAME  ║ AGE ║
╠════╬═══════╬═════╣
║  0 ║ John  ║  15 ║
║  1 ║ Chris ║  20 ║
╚════╩═══════╩═════╝

Table2
╔════╦════════════╦═════════════╗
║ ID ║ OCCUPATION ║   ADDRESS   ║
╠════╬════════════╬═════════════╣
║  0 ║ Bus Driver ║ None        ║
║  1 ║ Lawyer     ║ some adress ║
╚════╩════════════╩═════════════╝

Desired output:
Table 3
╔════╦═══════╦═════╦════════════╦═════════════╗
║ ID ║ NAME  ║ AGE ║ OCCUPATION ║   ADDRESS   ║
╠════╬═══════╬═════╬════════════╬═════════════╣
║  0 ║ John  ║  15 ║ Bus Driver ║ None        ║
║  1 ║ Chris ║  20 ║ Lawyer     ║ some adress ║
╚════╩═══════╩═════╩════════════╩═════════════╝

While I can accomplish this task by using PHP mysql_query("SELECT .. "); mysql_query("INSERT .."); -ish ways, I want to use pure SQL for this task.

A: JOIN the two tables:
SELECT
  t1.ID,
  t1.Name,
  t1.Age,
  t2.Occupation,
  t2.Address
FROM table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID;

SQL Fiddle Demo
This will give you:
| ID |  NAME | AGE | OCCUPATION |     ADDRESS |
-----------------------------------------------
|  0 |  John |  15 | Bus Driver |        None |
|  1 | Chris |  20 |     Lawyer | some adress |

If you want to create a new table table3 directly from this select, do this:
CREATE Table Table3
AS
SELECT
  t1.Name,
  t1.Age,
  t2.Occupation,
  t2.Address
FROM table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID;

Like this

A: try this
 SELECT t1.* , t2.*
 FROM table1 t1, table2 t2
 WHERE t1.id = t2.id

SQL FIDDLE DEMO

A: This should do,
SELECT a.id, name, age, occupation, address
FROM table1 a, table2 b
WHERE a.id = b.id;


text:
Q: What are the semantics of non-decision variables in MiniSat? When using MiniSat as C++ library, every new variable can be created as either a decision var or a non-decision var.
My rough understanding of this is that when the solver decides on which variable to use next during branching, non-decision vars are not considered. However, in my project, I ran into trouble when non-decision vars were on the left side of implication, instead of being in an equivalence relationship, as the solver returned SAT, even though the formula was actually UNSAT.
Further experimentation shows, that this only happens when the non-decision vars are in a formula that is longer than 2 variables (I guess 2-variable-formula path is a special cased in the solver, so it behaves differently).

A: Non-decision variables can only have their values set via inference.  The only method of inference Minisat uses is the unit rule.  So if setting all the decision variables doesn't cause the unit rule to be invoked to set all the non-decision variables, then the latter variables will be never be set.
The usual reason to have non-decision variables is that you know that the CNF instance is structured such that setting a fixed set of decision variables will imply values for all the other variables.
An example of this is a CNF instance to find the prime factors of some n-bit integer.  The instance will necessarily implement a chain of shift-adder circuits that implement multiplication, but you only need ever set the 2(n-1) bits that are inputs to the multiplication circuit.  The variables representing those bits will be the decision variables and all the other variables can be safely declared as non-decision variables.


text:
Q: How to make my profile background image as darker blur I am trying to make my image as darker blur.How can I do that darker blur?
I am making my image as blur ,working fine but that one not darker.That too I am using Network image view,my images are dynamic coming from service api. How can I make my images darker blur.
Thanks in advance.
I am using the below code.
 public static Bitmap blur(Context ctx, Bitmap image) {
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        RenderScript rs = RenderScript.create(ctx);
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);

        return outputBitmap;
    }

A: you can use setColorFilter
imageView =(ImageView) findViewById(R.id.image_view) ;
imageView.getDrawable().setColorFilter(0x76ffffff, PorterDuff.Mode.MULTIPLY );

average black color 0xff555555
Check my answer here
or you might like to work with this github project https://github.com/wasabeef/Blurry
Blurry.with(context)
  .radius(10)
  .sampling(8)
  .color(Color.argb(66, 255, 255, 0))
  .async()
  .onto(rootView);


text:
Q: iframe on('load, function () {}) doesn't fire, why? .ready() fires

$("#twitter-widget").on("load", function() {
    console.log('Loaded');  //doesn't fire
});

On my page twitter twit is used. Loaded as iframe. Event doesn't fire on load, when I use ready instead - it fires. Can anyone please help?

A: Browsers act differently on this. Some don't fire the 'load' event if the src is not set.
Try setting:
src="about:blank".


text:
Q: How to remove first array values PHP I tried to export csv files so I got an array like
Array
(
    [0] => Name
    [1] => Emp Code
    [2] => Designation
    [3] => Basic
    [4] => DA
    [5] => HRA
    [6] => CCA
    [7] => Conveyance
    [8] => Others
    [9] => Mgt Contr PF
    [10] => PL Encashment
    [11] => Income Tax
    [12] => Prof Tax
    [13] => Welfare Fund
)
Array
(
    [0] => Li
    [1] => 60
    [2] => Web Designer
    [3] => 14400
    [4] => 9600
    [5] => 4800
    [6] => 4800
    [7] => 1600
    [8] => 12800
    [9] => 800
    [10] => 0
    [11] => 0
    [12] => 0
    [13] => 20
)

Here first array values are the csv file column name, so I don't want to save them in database.
Here is my code
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
                            $num = count($data);

                            for ($c=0; $c < $num; $c++) {
                                $importData_arr[$i][] = $data[$c];
                            }
                            $i++;
                        }
                          fclose($file);
                            $skip = 0;
                             foreach($importData_arr as $data){
                                 echo '<pre>';print_r($data);
                             }
        }

How can I remove column name from array. Please help me

A: You can skip the first row by reading it prior to the loop. You can also massively simplify your code:
fgets($file);
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
    $importData_arr[] = $data;
}
fclose($file);
$skip = 0;
foreach($importData_arr as $data){
    echo '<pre>';print_r($data);
}

A: use unset function:
unset($importData_arr[0]);


text:
Q: Position down all the scroll in ionic 3 I'm creating a chat and my problem is that the div that has the messages inside it I put a scroll, but I can not keep it under everything.
This is the view code and styles:
<ion-grid>
    <ion-row>
        <ion-col col-12>
            <button ion-button block color="success" style="text-transform: none" (click)="seeMembers()">See members</button>
        </ion-col>
        <ion-col col-12 class="div_chat" #div_theme>
            <ion-list insert>
              <button ion-item>

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

test

              </button>
            </ion-list>

There are no new Topics

        </ion-col>
    </ion-row>
</ion-grid>

This is my stylesheet
page-see-theme{
  .div_chat{
    width: 100%;
    height: 300px;
    overflow-y: auto;
  }

}

Any idea is very useful, thanks for your help


text:
Q: Postfix: Allow SMTP AUTH only from specified IP address ranges can one implement an IP address based restriction for SMTP AUTH in Postfix?
Scenario:
I'm running a Postfix mail server that receives mails from all over the Internet. But the server doesn't only receive mails, it also allows its authenticated users to send mails to internal users or to external ones. So far no problem.
Unfortunately, I'm always getting a little scared when reading the log files. There are thousands of unsuccessful, illegal login attempts every day from IP addresses from all over the world.
But actually the legitimate sender hosts only come from a handful of known ip address ranges. So I know only someone from (for example)

*

*134.500.0.0/16

*134.700.42.0/24

*134.800.133.7

might even be a legitimate sender at all. (I know that the IP address given in the example above are malformed. I just don't wanted to unveil the real ones.)
So if the sender comes from a different ip range, he's for sure none of my users and therfore not allowed to relay anything.
I don't want someone from outside of these subnets to be able to relay even if he figures out a valid username/password combination for SMTP AUTH. If he's from a non-white-listed ip address range, he mustn't send. Under no circumstances. So permit_sasl_authenticated alone is not enough. As long as someone from "certain" countries (I don't want to name them explicitly...) is able to login with stolen/brute-forced/spyed credentials, it's not secure enough. :-) (Think of social engineering, trojan keyloggers that steal account data, lightheaded users with easy-to-guess passwords, etc.)
=> So is it possible to implement an ip address restriction for SMTP AUTH login attempts?
(The receiving of incoming mails must not be affected by this. For that I have policyd-weight etc. Here it's only about outgoing / to be relayed mails.)
Solutions that won't work:

*

*iptables firewall restriction. As I want to be able to receive mails from all over the Internet on port 25, I cannot implement restrictions on transport layer level. - Moreover, I want the legitimate users to be able to connect on port 25 to admit new outgoing mails into the server. So allowing mail sending only via a subnet restricted-mystery tcp port, e.g. 24343, is no solution, too.

*permit_mynetworks: Not everybody from the known ip ranges is a legitimate user. So I can't allow everybody from there to send. SMTP AUTH login is necessary to determine whether someone is an authorized user.

A: How about putting your SMTP AUTH on another port like 587, and using iptables to restrict access to that port? 587 isn't a hidden port, it's an RFC defined mail submission port. Mail to you arrives on 25, mail through you needs to go over 587.
https://www.rfc-editor.org/rfc/rfc6409

A: Pretty old question, but if you like me come here from Google - this can be done via smtpd_discard_ehlo_keyword_address_maps feature.
You just add parameter
smtpd_discard_ehlo_keyword_address_maps = cidr:/etc/postfix/discard_ehlo_keyword

to your Postfix main.cf config (usually located at /etc/postfix/main.cf) where /etc/postfix/discard_ehlo_keyword is a path to Postfix lookup table.
Next let's create a file via e.g. sudo nano /etc/postfix/discard_ehlo_keyword and put content inside it:
# this is your trusted ip ranges you want to send AUTH:
134.500.0.0/16      silent-discard
134.700.42.0/24     silent-discard
# and this is another world you don't want to send AUTH to:
0.0.0.0/0           silent-discard, auth
::/0                silent-discard, auth

After save run sudo postmap /etc/postfix/discard_ehlo_keyword to generate Postfix lookup table (you should do this after every edit of /etc/postfix/discard_ehlo_keyword).
And don't forget to restart Postfix!

A: You want to use a negated form of smtpd_sasl_exceptions_networks.
smtpd_sasl_exceptions_networks = !134.500.0.0/16 !134.700.42.0/24 !134.800.133.7
You might also be interested in smtpd_client_connection_rate_limit.

A: I would advice you to use a HIDS like OSSEC to temporarily block IPs that tried to log in. You can also add a rule in OSSEC to exclude your trusted networks from this rule, so legitimate users don't get blocked after a few attempts.
I'm proposing this as I don't think Postfix actually has a way to complement my_networks and SASL.

A:
There are thousands of unsuccessful, illegal login attempts every day from IP addresses from all over the world.

install fail2ban and tweak an existing or create a new filter to trap for these.  I use:
failregex =\[<HOST>\]\: SASL LOGIN authentication failed


text:
Q: math - how to properly use MDAS rule in SQL Server i'm getting the net value of a query. So far here is my problem. Whereas the Cost EUL UL is the only column while NetValue is a query only opened upon the computation.
Cost   EUL   UL   NetValue
9000   5     1    7380 // this is what I want to be displayed

My formula is like this in programming
temp=cost-(.10*cost);
temp2=temp/EUL;
temp3=temp2*UL;
temp4=temp3-cost

so far here is my query
Cost*.10/eul*n_asset_ul //which will be the new column NetValue

and the output of my query is
Cost   EUL   UL   NetValue
9000   5     1    180

Can somebody help?
EDIT: Answers will sometime/always be negative. So i also needed it to be absolute value

A: Are you sure the NetValue is equal to cost-(.10*cost))/EUL*UL?
It is a sample:
SELECT (Cost-(0.1*Cost))/EUL*UL AS NetValue1 --you r formula
       ,Cost-((Cost-(0.1*Cost))/EUL*UL) AS NetValue2
       ,Cost*(1.0-(0.9/EUL*UL)) AS NetValue3
FROM (VALUES( 9000,5,1)) t(Cost,EUL,UL)

NetValue1          NetValue2           NetValue3
--------------     ---------------     ---------------------------------------
1620.000000000000   7380.000000000000  7380.000000000000


text:
Q: Cannot access CartoDB with OGR I'm having issues using OGR to interact with tables on my CartoDB account.  Initially I was trying to upload data using ogr2ogr:
ogr2ogr --config CARTODB_API_KEY abcdefghi -t_srs EPSG:4326 -f CartoDB "CartoDB:thementat" agg.json

This error out, suggesting that I was attempting to create a database... something the CartoDB driver doesn't support:
ERROR 1: HTTP error code : 404
ERROR 1: HTML error page returned by server
ERROR 1: CartoDB driver doesn't support database creation.
ERROR 1: CartoDB driver failed to create CartoDB:thementat

Research had indicated that that I probably shouldn't trust this  so I tried to simplify using ogrinfo:
ogrinfo -ro "CartoDB:thementat tables=parcel"

This returned the following error:
ERROR 1: HTTP error code : 404
ERROR 1: HTML error page returned by server
FAILURE:
Unable to open datasource `CartoDB:thementat tables=parcel' with the following drivers.
  -> PCIDSK
  -> netCDF
  -> PDF
  -> ESRI Shapefile
  -> MapInfo File
  -> UK .NTF
  -> OGR_SDTS
  -> S57
  -> DGN
  -> OGR_VRT
  -> REC
  -> Memory
  -> BNA
  -> CSV
  -> NAS
  -> GML
  -> GPX
  -> KML
  -> GeoJSON
  -> Interlis 1
  -> Interlis 2
  -> OGR_GMT
  -> GPKG
  -> SQLite
  -> WAsP
  -> PostgreSQL
  -> OpenFileGDB
  -> XPlane
  -> DXF
  -> Geoconcept
  -> GeoRSS
  -> GPSTrackMaker
  -> VFK
  -> PGDUMP
  -> OSM
  -> GPSBabel
  -> SUA
  -> OpenAir
  -> OGR_PDS
  -> WFS
  -> HTF
  -> AeronavFAA
  -> EDIGEO
  -> GFT
  -> SVG
  -> CouchDB
  -> Cloudant
  -> Idrisi
  -> ARCGEN
  -> SEGUKOOA
  -> SEGY
  -> ODS
  -> XLSX
  -> ElasticSearch
  -> CartoDB
  -> AmigoCloud
  -> SXF
  -> Selafin
  -> JML
  -> PLSCENES
  -> CSW
  -> VDV
  -> TIGER
  -> AVCBin
  -> AVCE00
  -> HTTP

I suspect it isn't connecting to my CartoDB account, because this works:
ogrinfo -ro "Carto:gdalautotest2 tables=tm_world_borders_simpl_0_3"

Any ideas?


text:
Q: How to create folder in "root directory" with Flutter? I made a request to api via ""http"". A list is returned. This list contains the names of the files I want to create. Now I want to use these names when creating files automatically with Flutter. What path should I follow?

A: Use a directory for the app to store files that only it can access. As a bonus the app doesn't need any additional permissions.
final directory = await getApplicationDocumentsDirectory();

See Read and write files for details.


text:
Q: VBA Conditional Formatting with variable in formula Trying to create a relatively simple macro to cycle through every sheet apart from the one at the start (named) and apply conditional formatting to all of the used cells within a specific column, based off the numerical average of the cells in question.
I've gotten stuck with getting the conditional formatting formula to enter correctly into the cell.
Example: The formula I want is =R2>2(Average(R2:R*))  (where * is the last used row)
However, what's im getting in the formula box is: ="R2>2(Average(R2:R230))" (230 is the last used row on that sheet)
Removing the speechmarks from the script breaks it with "Expected:End of Statement"
Code here, because there might be other stuff wrong with it too:
Sub Bread()
    Dim LastRow As Long

    For Each Sheet In Sheets

    If Sheet.Name = "Base Details" Then

    Else
        Sheet.Cells.ClearFormats

        LastRow = Sheet.UsedRange.Rows.Count

            With Sheet.Range("R2:R" & LastRow)
                .FormatConditions.Add Type:=xlExpression, Formula1:="R2" & ">" & "2" & "(" & "Average" & "(" & "R2:R" & LastRow & "))"
                With .FormatConditions(.FormatConditions.Count)
                .SetFirstPriority
                With .Interior
                     .Color = RGB(255, 0, 0)

                End With
                End With

            End With
            With Sheet.Range("R2:R" & LastRow)
                .FormatConditions.Add Type:=xlExpression, Formula1:="R2" & "<" & "0.1" & "*" & "(" & "Average" & "(" & "R2:R" & LastRow & "))"
              With .FormatConditions(.FormatConditions.Count)
                .SetFirstPriority
                With .Interior
                     .Color = RGB(255, 255, 0)

                 End With
                 End With

            End With

    End If

Next Sheet

End Sub

Thanks a lot!

A: I think this is what you're looking for:
Sub Bread()

    Dim ws As Worksheet
    Dim LastRow As Long

    For Each ws In ActiveWorkbook.Sheets
        If ws.Name <> "Base Details" Then
            ws.Cells.ClearFormats
            LastRow = ws.UsedRange.Rows.Count
            With ws.Range("R2:R" & LastRow)
                .FormatConditions.Add Type:=xlExpression, Formula1:="=R2>2*Average($R$2:$R$" & LastRow & ")"
                .FormatConditions(.FormatConditions.Count).Interior.Color = RGB(255, 0, 0)
                .FormatConditions.Add Type:=xlExpression, Formula1:="=R2<0.1*Average($R$2:$R$" & LastRow & ")"
                .FormatConditions(.FormatConditions.Count).Interior.Color = RGB(255, 255, 0)
            End With
        End If
    Next ws

End Sub

A: I see two problems. First as Scott Craner noted, you're missing an operator between 2 and Average. Second, you need an = at the beginning of your formula (before the first instance of R2):
Formula1:="=R2" & ">" & "2 * " & "(" & "Average" & "(" & "R2:R" & LastRow & "))"

Hope that helps.


text:
Q: Why we need secant equation to approximate Hessian matrix in Quasi-Newton method? As mentioned in this wiki page, after approximating function value with Taylor expansion to the 2nd order, we have the secant equation $\nabla f(\vec{x_k}+\Delta \vec{x})=\nabla f(\vec{x_k})+B\Delta \vec{x}$ to solve for the approximated matrix of Hessian, $B$.
My question is why don't we directly use the Hessian of $f(\vec{x_k})$?


text:
Q: Remove head part from loading I'm trying to load a page from a click on product thumbnail. I'm using this
     $(".kategorie").click(function(){
    var post_id = $(this).attr("href");

    $("#categories_box").load(post_id);
return false;
});

However It loads the whole website, I mean the header part as well, I don't think it is a good thing ;) Also after loading a page few times, I'm receiving jquery error "undefined is not a function " . I think it's cuz of that double header part, Can I stop loading header somehow ? Or the problem is different that I think ? ;)
If I didn't explain it well, please ask me a question. Here's the website http://usb-solutions.pl/

A: You can add a jquery selector to you .load. just add a space between the url and the selector :
$("#categories_box").load(post_id + " body");//Will get only the body

A: you can simply write below code
$("#categories_box").load(post_id + " body");


text: Q: AUCTeX LaTeX-insert-item not environment-specific for tabular When Emacs is in AUCTeX's LaTeX mode, the command LaTeX-insert-item (C-c C-j or M-<Ret>) starts with a new \item in an itemize (or similar) environment. According to the AUCTeX manual, the command should be aware of the tabular environment and yield a new line in the table (with the &s and \\). This is not working for me (Emacs 24.3.1, AUCTeX 11.87). Any idea?


text:
Q: Natural progression from Blighttown I've just been through Blighttown and defeated Quelaag(sp?) and was just wondering where I should be going next as I have a variety of areas open to me now? Cinematics would suggest that I should go through the gate I just opened near the Undead Parish but then I also found the key for New Londo Ruins? There is the area up the ladder after defeating Hydra as well as the Catacombs, the area after defeating Quelaag(Demon Ruins?) and the Great Hollow although this was accessed through the secret tunnel.
Does it even matter? I am soul level 40 (thereabouts), should I be steering clear of places still or shall I just go hack things up?

A: The giant gate through the Undead Parish leads to an area called Sen's Fortress. This is the major path to advancing the main storyline. Your level is in the right area for heading this route, so you won't have any more problems than normal.
After Quelaag, the next area is the Demon Ruins and it requires you to fight a boss called the Ceaseless Discharge. Minor tip about this fight:

 The boss doesn't permanantly aggro until you take an item at the end of the area. I suggest not taking it until afterwards, so you can retrieve any souls if you lose. You can enrage the boss each time with magic or arrows.

This boss is required to progress in the long run, but it can be put off. The amount of trouble people have with it depends on the person, so I advise only trying it if you don't have many souls to lose. If you want to simply loot this area you'll receive the Gold-Hemmed set, which is extremely effective against poison and fire. If you want to avoid truly fighting the Ceaseless Discharge, you can simply run from where you pick up the Gold-Hemmed armour (at the end of the area), back to the fog wall at the entrance. This will cause him to fall, and you'll get the Victory Achieved notification.
Finally, the area accessible near the Hydra is connected to the Darkroot Basin and is also ultimately required to progress. This area, like the Demon Ruins can be put off until later. If you have 20,000 souls to spare however, I recommend buying the Crest of Artorias from Andre the blacksmith. This will unlock another entrance to the extended Darkroot Garden. If you do this you can farm about 7000 souls in a very short amount of time, and do this as many times as you like. You'll also be able to pick up the Stone armor and the Eastern armor here.
Ultimately, I would recommend heading to Sen's Fortress next as it is the logical progression of the game. If you consider it from a story standpoint, you wouldn't have reason to head to the Demon Ruins or the Darkroot Garden yet anyways.


text:
Q: How to call a procedure and print it? Hello before everthing I am new to assembly and trying to understand it. I have a procedure for tasm and I'm trying to make a system call and print a output from this procedure but i can't find how to make a system call.
    .MODEL small
        .DATA
        ;The string to be printed
        STRING DB '047119047', '$'

        .CODE

;   Purpose:
;       Calculates the check digit for a ten digit ISBN, converts that
;       digit to its ASCII representation and returns that answer.
;
;   Entry:
;
;      isbn = a nine digit ASCII string containing the ISBN
;             (with or without the check digit which is not used here)
;
;   Register usage within the routine:
;
;        AL = current ISBN digit
;        AH = sum of digits so far
;        BX = start pointer into ISBN for each outer loop
;        CX = digit counter (inner loop)
;        DX = start value for digit counter
;        SI = points to current ISBN digit
;
;   Exit:
;
;        AX = ASCII representation of calculated check digit
;
;   Trashed:
;       none
;
;***************************************************************************/

isbncheck proc C isbn:ptr byte
        push    bx
        push    cx
        push    dx
        push    si
        mov     bx,[isbn]               ;
        mov     dx,9                    ; number of digits in raw ISBN
        xor     ax,ax                   ; clear out our total
        cld                             ; count up
@@bigloop:                              ;
        mov     si,bx                   ; point to a digit in the ISBN
        mov     cx,dx                   ; get digit count in CX
@@AddEmUp:                              ;
        lodsb                           ; fetch digit into AL
        and     al,0fh                  ; convert from ASCII
        add     ah,al                   ; add it to our total in AH
        loop    @@AddEmUp               ; do all digits
        inc     bx                      ; and advance the digit pointer
        dec     dx                      ; now decrement digit count
        jnz     @@bigloop               ;   keep going if digits left
        mov     al,ah                   ; move sum into al
        xor     ah,ah                   ; clear out high half
        mov     cl,11                   ; we'll be doing a mod 11 operation
        div     cl                      ; ah = sum mod 11
        mov     al,ah                   ; move calculated check digit to AL
        xor     ah,ah                   ; clear out high half
        or      al,30h                  ; convert to ASCII digit
        cmp     al,3Ah                  ;
        jnz     NotTen                  ;
        mov     al,'X'                  ;
NotTen:                                 ;
        pop     si
        pop     dx
        pop     cx
        pop     bx
        ret                             ; return
isbncheck endp

        END

I hope you guys can help me.If my question is not clear please tell me.So i can explain it more clear.

A:
I'm trying to make a system call and print a output from this procedure
;The string to be printed
STRING DB '047119047', '$'

Since I can see that the string is '$' terminated, I'll show you how to do it in the DOS environment:
mov dx, offset STRING
mov ah, 09h             ; DOS.PrintString
int 21h

This will output those 9 digits (not including the '$' character that only served as a terminator) on the screen starting from where the cursor was. Hereafter the cursor will be beyond the last character.
Alternatively, you can use a loop. This would allow you to not have to use that '$' terminator (mandatory on function 09h):
    mov si, offset STRING
    mov dl, [si]
More:
    mov ah, 02h       ; DOS.PrintChar
    int 21h
    inc si
    mov dl, [si]
    cmp dl, '$'
    jne More


text:
Q: elements in list input I've been learning some lists lately and I wanted to make program that asks for x nubmer of elements that should list contain and then ask for elements in lists and if there is x elements in list while loop breaks and print out elements and how much elements there are so thats my code:

    num = input("How many numbers you want to put into a list?: ")

while True:
    list = [input()]
    if len(list) == num:
        break

def get_number_of_elements(list):
    count = 0
    for element in list:
        count = count + 1
    return count

print(get_number_of_elements(list))

print(list)

and when i run code it still asks for elements in list and i dont know what to do.

A: If you want to stick with how you coded it yourself:
# make the input into an int because you want to compare it with a length in the while loop
num = int(input("How many numbers you want to put into a list?: "))
# don't name your variables after a type. 'list' is already the name of a type
l = [input("Enter number: ")]

# while the length of the list is not equal to the num, keep prompting
while len(l) != num:
    # add on to the list 'l'. Before you were creating a new list every loop
    l.append(input("Enter next number: "))

def get_number_of_elements(l):
    count = 0
    for element in l:
        count = count + 1
    return count

print(get_number_of_elements(l))
print(l)

Instead, you can just do this:
l = []
for _ in range(int(input("How many numbers you want to put into a list?: "))):
    l.append(int(input("Enter number: ")))

print("Number of elements:", len(l))
print("Here's your list:", l)


text:
Q: YOURLS Redirect with Javascript Currently I am using YOURLS PHP URL shorterning script.
In their functions.php, seems like they support both redirection which is with PHP header location and javascript.
Functions.php
I want to redirect with javascript, which will show me the message before redirect. I found this coding inside functions.php
// Redirect to another page using Javascript. Set optional (bool)$dontwait to false to force manual redirection (make sure a message has been read by user)
function yourls_redirect_javascript( $location, $dontwait = true ) {
    if( $dontwait ) {
    echo <<<REDIR

    (if you are not redirected after 10 seconds, please click here)
REDIR;
    } else {
    echo <<<MANUAL

Please click here

MANUAL;
    }
}

But I don't know how to do it. Is that coding currently commented or ? What should i change to redirect with javascript ?
Please help me out. Thanks.

A: The function is all ready to go.  A javascript redirect will occur on the client side, so this script outputs the appropriate javascript.  Call it like so:
<?php # http://www.myurl.com/was/here.php

yourls_redirect_javascript('http://www.myurl.com/go/here.php');

?>

When this page loads javascript will be used to redirect the user.  If the javascript fails, there will be a link for them to click to follow the redirect.
I suspect that the "here document" syntax is throwing you off a bit.  Read the PHP Docs to learn more about echo <<<
http://php.net/manual/en/function.echo.php


text:
Q: this is my code and the onClick method's else if condition is not going to next activity after clicking ImageButton twitter @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        mAuth = FirebaseAuth.getInstance();
        database =FirebaseDatabase.getInstance();
        dref=database.getReference();
        setContentView(R.layout.activity_welcome);
        findViewById(R.id.twitter).setOnClickListener(this);
        findViewById(R.id.google).setOnClickListener(this);

                // Configure Google Sign In
                 gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestIdToken(getString(R.string.web_client_id))
                        .requestEmail()
                        .build();
                // [END config_signin]
                mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

                // [START initialize_auth]
                // Initialize Firebase Auth
                mAuth = FirebaseAuth.getInstance();
                // [END initialize_auth]
    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if(currentUser != null){
            Intent myIntent = new Intent(WelcomeActivity.this,HomeActivity.class);
            WelcomeActivity.this.startActivity(myIntent);
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                assert account != null;
                firebaseAuthWithGoogle(account);
            }  catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                Toast.makeText(WelcomeActivity.this,"Google Sign In Failed.",Toast.LENGTH_SHORT).show();
            }
        }
    }
    // [END onactivityresult]

    private void onAuthSuccess(FirebaseUser user) {
        // Write new user
        writeNewUser(user.getUid(), user.getDisplayName(), user.getEmail());
        // Go to MainActivity
        startActivity(new Intent(WelcomeActivity.this, HomeActivity.class));
        finish();
    }

    private void writeNewUser(String userId, String name, String email) {
        User user = new User(name, email);

        dref.child("users").child(userId).setValue(user);
    }

    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        onAuthSuccess(Objects.requireNonNull((Objects.requireNonNull(task.getResult())).getUser()));
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(WelcomeActivity.this,"Google Sign In Failed.",Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void signInGoogle() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.google) {
            signInGoogle();
            finish();
        }
        else if (i == R.id.twitter)
        {
        Intent intent=new Intent(this,TwitterLoginActivty.class);
        startActivity(intent);
        }

    }

    // [END auth_with_google]
}

A: Use YourActivityName.this instead of this
Because when you use only "this", it refers to the current context. And in your case, you are using this inside the onClick and it refers to the OnClickListener(an anonymous class), not to the activity.
@Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.google) {
            signInGoogle();
            finish();
        }
        else if (i == R.id.twitter)
        {
        Intent intent=new Intent(WelcomeActivity.this,TwitterLoginActivty.class);
        startActivity(intent);
        }

    }

A: If you are passing "this" as a context reference inside onClick it will pass onClickListener instance instead of your activity, you should pass "WelcomeActivity.this"
@Override
public void onClick(View v) {
    int i = v.getId();
    if (i == R.id.google) {
        signInGoogle();
        finish();
    }
    else if (i == R.id.twitter)
    {
    Intent intent=new Intent(WelcomeActivity.this,TwitterLoginActivty.class);
    startActivity(intent);
    }

}


text:
Q: OpenSSH: What is the interval for TCPKeepAlive option? In sshd config you can specify the option TCPKeepAlive yes. These Pakets are not encrypted so the could be spoofed.
With the options
ClientAliveInterval
ClientAliveCountMax
ServerAliveInterval
ServerAliveCountMax

you can specify the interval of the keep alive packets and the timeout (*CountMax) after which the connection is dropped. See also here What options `ServerAliveInterval` and `ClientAliveInterval` in sshd_config exactly do?
With TCPKeepAlive you can only enable it.
So what is the interval for the TCP-Pakets beeing sent?
After how many unsuccessful packets the connection is regarded broken and closed? Since default values are:
#TCPKeepAlive yes
#ClientAliveInterval 0
#ClientAliveCountMax 3

As far as I understand: The detection and closing of broken/inactive connections solely depends on the TCPKeepAlive option in the default configuration. So it is quite important to know that values.

A: The reason why OpenSSH doesn't offer any tweaks for TCPKeepAlive (which is implemented by the OS) is probably because there's no portable way to change its parameters; the only portable thing is turning it on or off with setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &on_off).
On Linux, you can see (and change) the default values via the /proc filesystem, as documented in the tcp(7) manpage:
grep -T . /proc/sys/net/ipv4/tcp_keepalive*
/proc/sys/net/ipv4/tcp_keepalive_intvl: 75
/proc/sys/net/ipv4/tcp_keepalive_probes:        9
/proc/sys/net/ipv4/tcp_keepalive_time:  7200

So, it will wait 2 hours until it will consider a connection idle, and then send 9 probes at the interval of 75 seconds.
On Linux, FreeBSD and NetBSD (but not on OpenBSD) you can also change those options on a per-socket basis with
setsockopt(fd, IPPROTO_TCP, TCP_KEEP{CNT,IDLE,INTVL}, &val)
but, as mentioned, OpenSSH doesn't do that.


text:
Q: How to get the font name of the excel cell I am iterating all cells of the excel sheet and printing out the values. Same time i also want to print the font name they are using. Is there any function to get the specific cell font name in phpexcel ? Thanks.
below is the code snippet

 include('lib/phpexcel/Classes/PHPExcel/IOFactory.php');

  //Use whatever path to an Excel file you need.
  $inputFileName = 'text.xlsx';

  try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
  } catch (Exception $e) {
    die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' .
        $e->getMessage());
  }

  $sheet = $objPHPExcel->getSheet(0);
  $highestRow = $sheet->getHighestRow();
  $highestColumn = $sheet->getHighestColumn();

  foreach ($sheet->getRowIterator() as $row) {
  echo '
' . "\n";
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(false);
  foreach ($cellIterator as $cell) {
// Is there any similar $cell->getFont() function ?? which will echo"time new roman"
    echo '' .$cell->getValue(). '	' . "\n";
  }

  echo '
' . "\n";
}
  ?>

A: The font is an aspect of the style of a cell; so you need to get the style details for the cell, and read the font information from that:
$cell->getStyle()
    ->getFont()
    ->getName();

Note that you can also get font size, italic, bold, underlining, super/subscript, strikethru, and the font colour in a similar manner.... the font object holds more information than simply the font name.


text:
Q: Sync Oracle Database with SQL Azure I would want to sync up on-premises Oracle database with SQL Azure. Currently I have a DTS package setup for my on-premises applications (both Oracle and SQL Server being on-premise). If I move the SQL Server to Azure, how should this process be designed?

A: you have to options for moving to Azure:

*

*Move to Azure SQL Database

*Provision a SQL Server VM in Azure

the latter will have the same feature set as your regular on-premise SQL Server. The former is not fully-feature equivalent to SQL Server. Azure SQL Database is just the Database engine part, no SSIS, SSAS, Replication and even TSQL is not fully equivalent to SQL Server.
If you use the VM approach, its safe to assume you can still run your existing packages. However, you need to consider latency between Azure in the cloud and your on-premise Oracle database.
you may also build a custom solution to sync the databases or even use Sync Framework. see: Database Sync: Oracle and SQL Compact 2-Tier , just replace the SQL Compact with the SqlSyncProvider which works with the Azure SQL Database. You can change the sample to use an n-tier approach if you want to use WCF as well.

A: There are few differences between SQL Server and Azure SQL Database (SQL Azure renamed) so I suppose your code can work on Azure too with little effort. Azure SQL Databases do not have the same features and AFAIK the DTS package cannot run in the Azure environment. But I suppose you can think, if logic/traffic/latency permits, of running the DTS on premises interacting with the Azure SQL Database and Oracle.
You may find SQL Data Sync interesting:

SQL Data Sync is a web service that you use to keep your data synchronized across multiple servers in different locations


text:
Q: Xfce 4.12 + KWin5 I installed Xubuntu 15.04 with Xfce 4.12.
I would like to use KWin as the window manager.
With previous versions of Xfce and KWin replacing xfwm with kwin was pretty straightforward, but now both Xfce and Kwin seem to have changed significantly and old instructions (see for instance: here) are not valid anymore.
Additional notes:

*

*With in KWin5, the program kwin has been replaced by kwin_x11 and kwin_wayland.

*If I run kwin_x11 --replace, I get no decorations.

*If I try to install kwin-style-qtcurve (as indicated here for an older Xfce), I get a dependency problem on libkdecorations4abi2:
$ sudo env LANG=en_US apt-get install kwin-style-qtcurve
...
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 kwin-style-qtcurve : Depends: libkdecorations4abi2 (>= 4:4.11.1) but it is not installable
                      Recommends: kde-style-qtcurve but it is not going to be installed
E: Unable to correct problems, you have held broken packages.


text:
Q: What's the maximum data that vuex can store? I have a blog app using vuex to store the post data that users have visited so that if they visit the same post again they don't need to fetch the data from the server again.
Is it a good idea to store all those post data in vuex?
Will it slow down the app?
Are there any memory leak issues with this approach?

A: Your store is held completely in memory. That means you have as much storage available as the user device allows you to use memory.
Most apps stay around 30-100 MB memory usage.  You should try to stay in this range as well (nobody likes insanely memory hungry apps that slow down your computer).
That being said, you probably fetch your blog posts from a server. Hence, your browser will be able to just cache these requests so he does not have to load them again.
What you should look into instead is how to set up a browser cache policy. This is set in the headers of your server response as 'exipres' header.


text:
Q: Is there a database, API, or parsable text for getting verb conjugations? This isn't directly a programming question, so I apologize in advance. I've been working on a grammar-free random sentence generator for a typing game I'd like to make, and I've been having a difficult time finding any parsable (or callable) data for getting verb conjugations. Ultimately, if I can't find anything like this, I'm going to have to go through the dictionary I've created and add first-person singular and plural, second-person singular and plural, third-person singular and plural, simple past, past participle, and present participle forms for every irregular verb.
This wouldn't be a problem in many languages, but there are so many irregular English verbs that this could take a long, long time to do manually. I'm not against the worse option, but I want to make sure I'm not going to be wasting obscene hours doing it myself when there is some database I can use instead.
I've seen http://www.scientificpsychic.com/verbs1.html and spoken with the creator, but he doesn't release his exact dictionary (just the classes for it). I've also seen sites like http://www.verbix.com/webverbix/English/find.html, which would be great for scraping, but that's a bit of a pain as well.
This question has been asked here before ( Verb Conjugations Database ), but the question was left unanswered, and the asker alluded to solving the problem but never said what the solution was.

A: MorphAdorner (Java) has a simple Verb conjugator (with online demo).
But if you are interested with an exhaustive listing you can check Lexical Tools' Inflection Variants. After downloading Lexical Tools, you will be importing the data to your database server. Then you can just query the database using their library (Java).
SimpleNLG also has this feature, and is very much related to Lexical Tool.


text:
Q: Display validation error in tabs using laravel In my view I've 3 tabs where different types of data are displayed. In my 3'rd tab i post some data where i use laravel validation. My problem is the validation errors are displayed in my first tab. What should i do to display the errors in the 3'rd tab.
my controller
$validator = Validator::make($request->all(), Rules::Event($request));
        if ($validator->fails()) {
           return back()->withErrors($validator)->withInput();
        }

view page

Upcoming Events

Popular Events

Post an Event and sell ticket

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

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

                @if (count($errors) > 0)

                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

{{ t('Oops ! An error has occurred. Please correct the red fields in the form') }}

                                @foreach ($errors->all() as $error)

{{ $error }}

                                @endforeach

                @endif

How to implement this? Please help me,Waiting for a response......

A: you can try this one:
add error class to li

{{ $error }}

then use this script:
   if ($(".tab-content").find('.error').text()) {
    $.each($(".tab-content").find('.error'), function (index, value) {
        if ($(this).text()) {
            $(".tab-content").children('.tab-pane').removeClass('active');
            $(this).closest('.tab-pane').addClass('active');
            $(".nav-tabs").children('li').removeClass('active');
            var id = $(this).closest('.tab-pane').attr('id');
            $.each($(".nav-tabs").children('li'), function (i, a) {
                if (('#' + id) == $(this).children('a').attr('href'))
                    $(this).addClass('active');
            });
            return false;
        }
    });
}


text:
Q: How to make a Password Generator from User using list? I am trying to create a random password generator in python .
How do I select like 3 or 4 or 5 random number from a list using user.
For example :
numbers = ['0','1','2','3,','4','5','6','7','8',9']

numbers_in = int(input('how many numbers would you love to be in your password:').

If i choose 4 as a user how will get four random numbers from a list like 4791

A: Here you go:
>>> from random import choice
>>> from string import digits
>>> N = int(input('How many numbers would you love to be in your password: '))
How many numbers would you love to be in your password: 4
>>> "".join(choice(digits) for _ in range(N))
'1786'

Shorter version of the last statement provided by @furas in comments:
"".join(choices(digits, k=N))


text:
Q: Сериализация Item'ов Подскажите, как сериализовать созданные Item'ы в панели, их текст, значение CheckBox и кнопку Delete, и дессериализовать при перезапуске программы? Понимаю, как сделать это с простым текстом или классом, а что делать с целым User Control'ом понятия не имею...

A: Сериализовать элементы управления полностью не нужно.
Сериализация данных на то и сериализация, что мы преобразовываем их в формат, удобный для чтения, отправки и записи.
На скриншоте я вижу, что вы собираетесь сериализовать список ваших дел. Что минимально нужно, чтобы представить одно дело? Описание дела и статус.
Значит пишите в JSON или подобный формат массив, один элемент которого выглядит так:
{description: "Meet with Sergey", status: false}

А дальше читаете ваш файлик, плодите нужное количество чекбоксов, пихаете их на панель и заполняете согласно содержимому файла.

A: Для сохранения состояния в .NET не нужно изобретать велосипед с сериализацией. Просто запишите ваши данные в Settings, и при следующем старте они автоматически восстановятся. (Картинки смотрите тут.)


text:
Q: Extend $T$ to a bounded linear operator... Let $X$ be the real inner product space of real-valued continuous functions on $[0,2\pi]$ with the standard inner product. Consider the map $T:X \to H$, where $H=L^2[0,2\pi]$ (the completion of $X$), defined by
$$Tx = \int_0^{2\pi}cos(t-s)x(s)ds.$$
Also, keep in mind that $(1/\sqrt{2\pi},\cos(t)/\sqrt{\pi},\sin(t)/\sqrt{\pi},\cos(2t)/\sqrt{\pi},\sin(2t)/\sqrt{\pi},\dots)$ is a total orthonormal sequence in $H$.

*

*Prove that $T$ is a bounded linear operator.

*Extend $T$ to a bounded linear operator $T^*:H \to H$.

I have already shown part (1). I am not sure how to proceed with part (2). I know there are Theorems that say that we can extend bounded linear operators, but I am not seeing how to use them.


text:
Q: Wine QLDrivers No ODBC drivers I run
winecfg
and terminal throw err:
0012:err:winediag:SQLDrivers No ODBC drivers could be found. Check the settings for your libodbc provider.

how to fix this?

A: I solved this problem in the following way: I installed CDBC on Ubuntu software store, also UnixODBC by terminal, also mysql-shell on Ubuntu software store. I don't know if all of these were really necessary, but I did.
Than, I installed and used playonlinux to install my Database interface app. And, the most important, I installed "mdac28" component into the virtual disc created to run Database interface app. This mdac28 component is necessary to the Database interface app can talk to remote Database server. You can install mdac28 clicking over your Database interface app created inside playonlinux, than, click (in the left side) on "configuration", than clicking on "install component". Scroll up to down until to find mdac28. Than click or double click over it and install it.
After all, click run to use your app.
OK.
Best regards.


text:
Q: Linux file ACL and secondary groups The Problem:
CentOS does not seem to look at secondary groups when using ACL's on a folder or file
Scenario: CentOS 6 basic install, uses LDAP accounts to authenticate users. I am trying to setup fairly complex permissions on some folders. I have ensured that the file system is mounted with ACL support and determined that LDAP users are able to log in correctly.
Steps to Reproduce:
As a test I have a simple folder structure. The folder test1 is owned by root and has 770 permissions, I have added another group to that folder setfacl -m g:testgroup:rwx test1/ The getfacl output for the folder looks like this:
getfacl: Removing leading '/' from absolute path names
# file: share/test1/
# owner: root
# group: root
user::rwx
group::rwx
group:testgroup:rwx
mask::rwx
other::---

The user andrew belongs to the domain group and testgroup as shown by groups andrew. The group domain is the users primary group. If the user andrew tries to read anything located in test1 a permission denied error was shown. If however the users primary group is changed to testgroup the user can then interact with the contents of the folder.
Can anybody tell me what is going on here and if there is a way to get the expected behaviour?
EDIT This appears to be a problem related to LDAP. I just tested using local user accounts and everything works as expected.

A: As you say this problem is related to the use of LDAP for user information. Your Centos6 machine is configured in a way that is incompatible with the LDAP server, so that when it tries to get the list of supplementary groups the user belongs to, it doesn't find anything.
Unfortunately there are several standards for how to interpret LDAP attributes relating to POSIX groups - rfc2307, rfc2307bis, IPA
Centos 6 uses SSSD for managing interwork with remote directories and authentication databases. The default settings for SSSD are to use rfc2307.
You will probably find your LDAP server is using rfc2307bis. We have a Centos 5 directory server, it was configured by default for rfc2307bis. As a further complication, our C5 directory was using the attribute 'uniqueMember' instead or 'member' for group members.
To fix it, edit /etc/sssd/sssd.conf and add the following lines:
ldap_schema = rfc2307bis
ldap_group_member = uniqueMember

You might also like to refer to the following:

*

*man pages for sssd.conf and sssd-ldap

*http://www.couyon.net/1/post/2012/04/enabling-ldap-usergroup-support-and-authentication-in-centos-6.html

*https://bugzilla.redhat.com/show_bug.cgi?id=580402

A: Have you tried looking at the numeric ids of both the groups the user belongs to, and the ACL of the directory? Try getfacl -n test1 and compare the groups listed with the output of id -G andrew. See if there is any discrepancy there and try resolve it.


text:
Q: How do I use Azure Storage Tables in an Azure Function? I'm afraid this might be a simple case of me completely misunderstanding how asynchronous works.
I'm working with the NPM module azure-storage. The problem I'm having is that the function appears to complete before the callback is executed. What's worse is that Azure Functions has some magic in that you "finish" your function by setting context.res property.
They used to require you to call context.done() but something changed from v1 to v2 and now I guess it's not that way anymore. But still, even if that were the case, the function would be ended before the call back executed.
What's worse is that my entity is not even being inserted but I can't tell why.
var azure = require('azure-storage');
var validate = require('validate.js');

var constraints = {
    PartitionKey: {
        presence: true,
        email: true
    },
    description: {
        presence: true
    },
    dueDate: {
        presence: true
    }
};

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (!(req.body && req.body.PartitionKey)
        || !(req.body && req.body.description)
        || !(req.body && req.body.dueDate)) {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }

    var tableSvc = azure.createTableService();
    var input = req.body;

    context.log('PartitionKey: ' + input.PartitionKey);
    context.log('description: ' + input.description);
    context.log('dueDate: ' + input.dueDate);

    context.log(validate({ PartitionKey: input.PartitionKey }, constraints));
    context.log(validate({ description: input.description }, constraints));
    context.log(validate({ dueDate: input.dueDate }, constraints));

    var entGen = azure.TableUtilities.entityGenerator;
    var task = {
        PartitionKey: entGen.String(input.PartitionKey),
        RowKey: entGen.String('1'),
        description: entGen.String(input.description),
        dueDate: entGen.DateTime(input.dueDate)
    };

    tableSvc.insertEntity('events', task, function (error, result, response) {
        if (!error) {
            // Entity inserted
            context.log(result);
            context.res = {
                // status: 200, /* Defaults to 200 */
                body: {
                    result: result,
                    response: response
                }
            };
        }
        else {
            context.log(error);
            context.res = {
                status: 400, /* Defaults to 200 */
                body: error
            };
        }
    });
};

A: When exporting an async function, you can configure an output binding to take the return value. This is recommended if you only have one output binding. See doc
To assign an output using return, change the name property to $return in function.json.
{
  "type": "http",
  "direction": "out",
  "name": "$return"
}

In this case, your function should look like the following example:
module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    // You can call and await an async method here
    return {
        body: "Hello, world!"
    };
}

This should work.
Your async function will not wait for the callback. You have to make it wait till the callback is finished.
var azure = require('azure-storage');
var validate = require('validate.js');

var constraints = {
    PartitionKey: {
        presence: true,
        email: true
    },
    description: {
        presence: true
    },
    dueDate: {
        presence: true
    }
};

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (!(req.body && req.body.PartitionKey)
        || !(req.body && req.body.description)
        || !(req.body && req.body.dueDate)) {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }

    var input = req.body;

    context.log('PartitionKey: ' + input.PartitionKey);
    context.log('description: ' + input.description);
    context.log('dueDate: ' + input.dueDate);

    context.log(validate({ PartitionKey: input.PartitionKey }, constraints));
    context.log(validate({ description: input.description }, constraints));
    context.log(validate({ dueDate: input.dueDate }, constraints));

    var entGen = azure.TableUtilities.entityGenerator;
    var task = {
        PartitionKey: entGen.String(input.PartitionKey),
        RowKey: entGen.String('1'),
        description: entGen.String(input.description),
        dueDate: entGen.DateTime(input.dueDate)
    };

    let res = await tablework(task, context);

    if(res.success) {
        return {
            status: 200,
            body: {
                result: res.result,
                response: res.response
            },
            headers: {
                'Content-Type': 'application/json'
            }
        };
    }
    else{

        return {
            status: 400, /* Defaults to 200 */
            body: res.error,
            headers: {
                'Content-Type': 'application/json'
            }
        };
    }

};

function tablework(task, context){
    return (new Promise((resolve, reject) => {
        var tableSvc = azure.createTableService();

        tableSvc.insertEntity('events', task, function (error, result, response) {
            if (!error) {
                // Entity inserted
                context.log(result);
                resolve({
                    success: true,
                    result: result,
                    response: response
                });
            }
            else {
                context.log(error);
                resolve({
                    success: false,
                    error: error
                });
            }
        });
    }));
}


text:
Q: Is it bad practice to use production code in the Arrange phase of a test? When writing tests in an Arrange-Act-Assert pattern, is it okay to use production code in the arrange phase to put the SUT in a certain state?
Context
I have created a service for handling backups of a database in an SQL Server instance. I want to test this service, specifically the RestoreFromBackup method.
The unit test I want to write is RestoreBackup_BackupExists_NoExceptionThrown; if a backup exists and the service is asked to restore the database from that backup, there should be no exceptions thrown as a result.
When the test starts, there exists no backup to restore the database from, I need to create it in the Arrange phase of the test. I would like to put only the RestoreFromBackup method under test, so I've essentially copied the CreateBackup method from the service to the test project and I've used that to create the backup.
Snippet of my test project:
// _dataAccessService is the service I'm testing.
// LocalHelpers is a static helper class with some methods to use only in tests,
// but they're essentially all copies of methods in _dataAccessService.

[Test]
public void RestoreBackup_BackupExists_NoExceptionThrown()
{
    // Arrange
    string backupName = $"{LocalHelpers.GenerateDatabaseBackupName()}.bak";
    LocalHelpers.CreateDatabaseBackup(backupName);

    // Act
    TestDelegate createBackupAction = () => _dataAccessService.RestoreFromBackup(backupName);

    // Assert
    Assert.Throws<ArgumentException>(createBackupAction);
}

private static class LocalHelpers
{
    public static string GenerateDatabaseBackupName(string? connectionString = null)
    {
        // Generate a unique name like "database_guid.newguid().bak".
        // Pretty much copy of production code.
    }

    public static string CreateDatabaseBackup(string backupName, string? connectionString = null)
    {
        // Creates a full database backup of a database in SQL Server's DATA folder.
        // Pretty much copy of production code.
    }
}

This feels kind of silly to copy the code, but I'm hesitant to put the "real" method for creating a backup in the test, since then a unit test for Restore could fail because the Create method breaks in the future when refactoring or whatever.
How should I approach this?


text:
Q: How to set ManyToOne relationship in Flask- SQL alchemy? I am new to Flask and SQLalchmey. I am trying to crate two tables and establish a manytoone relationship between them.
Here is what I did.
table_hub
      class Hub(db.Model):
          __tablename__ = 'hub'

          id = db.Column(db.Integer, primary_key=True)
          name = db.Column(db.String(),nullable=False,unique=True)

tbl_vehicle
      class vehileMaster(db.Model):
          __tablename__ = 'res.vehicle'

          id = db.Column(db.Integer, primary_key=True)
          name = db.Column(db.String, nullable=False)
          hub_id = db.Column(db.Integer,db.ForeignKey('hub.id'))
          hub = db.relationship('Hub')

Here is what I need to achieve,

*

*while creating a new vehicle in table res.vehicle I need to choose a hub from the list of hubs.

I don't know whether what i already did is correct or not.

A: The standard way of implementing a foreign key relationship would be:
class Hub(db.Model):
    __tablename__ = 'hub'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False,unique=True)
    vehicles = db.relationship('res.vehicle', backref='hub', lazy=True)

class vehicleMaster(db.Model):
    __tablename__ = 'res.vehicle'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    hub_id = db.Column(db.Integer, db.ForeignKey('hub.id'))


text:
Q: newbie: issues with updating / redirect profile and friendly_id Trying to rewrite my profile controller wich is broken at this point. Im using friendly_id to have urls like below with partials edit_basics.haml, edit_details.haml, etc.

*

*/users/me/edit/basics

*/users/me/edit/interests

*/users/me/edit/details

The problem is in updating my profile and redirect to the correct path after the update.
I have searched and tried several things to no avail so far.

*

*after submit edit form it redirects to /profiles/me

*after updating /users/me/edit/basics it should return to this location
The updating throws an error in
undefined method `update_attributes' for #<#:0x007f876e77d768>
{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"wqDebPGdHvXszFvXcaeWwRewA6puTVlv5iCXX1ZD3KU=",
 "profile"=>{"form"=>"basics",
 "description"=>""},
 "commit"=>"Save",
 "id"=>"myusername"}
Ofcourse ID can't be the username
Routes
  match '/users/:username' => "profiles#show"
  match '/users/:username/edit/:what' => "profiles#edit", :as => :edit_user

Update Action:
  def update

    @profile = Profile.where(params[:id])

    respond_to do |format|
      if @profile.update_attributes(params[:profile])
        format.html { redirect_to @profile, :action => "edit", :what => @profile.form,  notice: 'Profile was correctly updated.' }
      else
        format.html { @profile, :action => "edit", :what => @profile.form }
      end
    end
  end

Edit action:
def edit

@profile = Profile.find(params[:username])
what = params[:what]

if not what.nil?
  if ["basics", "location", "details", "photos", "interests"].member?(what)
    render :action => "edit_#{what}"
  else
    render :action => "edit_basics"
  end
end

end
UPDATE:
It seems that id attribute always contains the username of the user and therefore cannot update

A: Try updating this line:
@profile = Profile.where(params[:id])

In your controller to this, and see if that helps:
@profile = Profile.where({ :id => params[:id] }).first

That will return the instance of the Profile, not the criteria.
Hope it helps.
\\ Emil


text:
Q: Azure Virtual Machine log in denied - redeploy doesn't solve I can't log in into my WS2019 Azure Virtual Machine (via remote desktop). Every time I attempt to do so, I get this error:
Screenshot
The Local Session Manager service failed the sign-in.
The request is not supported.
Redeploying the machine doesn't help. I can't reset configuration because of:
VM has reported a failure when processing extension 'enablevmaccess'. Error message: "VMAccess Extension does not support Domain Controller.".
I can't seem to find any appropiate solution for it since I can't log in into my account nor into cmd (same password prints out a "Unable to authenticate" error.)

A: As per this page you should reset the domain password via special script:

Create a script in a notepad as script.ps1
         net user <Username> <Password>

Select the VM you want to change domain password
Go to extensions in the VM left panel
Click on +ADD at the top
Select custom Script Extension option

After selecting the Custom Script extension option.
Click on the Create option in the bottom of the page
Browse the script file saved on your desktop.
Then Click OK

Then the script gets uploaded and you will get a notification in
  notification bar.
You could also do this by using PowerShell (you need to host the
  script somewhere on webserver):

Set-AzureRmVMCustomScriptExtension -ResourceGroupName myRG -VMName myVM -Location vmLocation -FileUri "http://url/script.ps1" -Run 'script.ps1' -Name resetpassword

A: Sounds that you have a VM which is a domain controller so you don't have any local admin and it also sounds that your VM couldn't activate the windows license and the grace period has past. Correct?
In that case try to open your NSG and make sure the vNet have DNS servers that can resolve public domains. Then try rebooting the server and hope it can activate it against Microsoft's KMS.


text:
Q: How to model enum types in phantom dsl? My case class contains enum parameter like as follows:
case class User(role: UserRole.UserRole, name: String)

object UserRole extends Enumeration {
  type UserRole = Value
  val ADMIN, USER = Value
}

How to model this case as in this example?
Any code samples provided will be helpful.

A: You need to use EnumColumn, which is created for this very reason. If you want to use the enum as a key, then you also need to create a primitive using the default helper methods.
You can use both flavours of defining an enum.
object Records extends Enumeration {
  type Records = Value
  val TypeOne, TypeTwo, TypeThree = Value
}

object NamedRecords extends Enumeration {
  type NamedRecords = Value
  val One = Value("one")
  val Two = Value("two")
}

object enum extends EnumColumn[Records.type](this, Records)

In your case this would be:
object role extends EnumColumn[UserRole.type](this, UserRole)

To use this as an index, you will need:
implicit val userRolePrimitive = Primitive(UserRole)

Update As of Phantom 2.0.0+
object role extends EnumColumn[UserRole](this)

You don't need to define any additional implicits, Enums  are now natively suported as indexes.


text:
Q: Keep hover div open after mouseleave and close it with click outside the div window or close button I have the following jquery which opens and close the div "shopping_cart" when hover on "shopping_button"
$('#shopping_button, .shopping_cart').on('mouseenter',function(){
  $(this).css('z-index','300');
  $(this).css('visibility','visible');
 })
$('#shopping_button, .shopping_cart').on('mouseleave',function(){
  $(this).css('z-index','189');
  $(this).css('visibility','hidden');
  $(this).css('opacity','0');
 });

Need help with what I'm trying to achieve is that "shopping_cart" remain open on mouseleave and only close on if click outside the "shopping_cart" div or can add close button inside the "shopping_cart" div to close it.
Thanks guys.
Edited
I added the following to above code
$('html').click(function () {
    $('.shopping_cart').css('visibility','hidden');
});

and it does the job, only close the window when click outside "shopping_cart" div, but now if again hover on "shopping_button" it won't open the "shopping_cart" div, on inspect element it shows
$('#shopping_button, .shopping_cart').on('mouseenter',function(){
  $(this).css('z-index','300');
  $(this).css('visibility','visible'); <---This Remain Hidden
 })

Any Suggestion?
sorted
added this into mouseenter funtion
  $('.shopping_cart').css('visibility','visible');

And vollhhaaaa....:D
Still looking for more clean solution, if anybody have....
Thanks for all the help.

A: Try to check out this JSFiddle: http://jsfiddle.net/m8nrzL7d/2/
$('#shopping_button').mouseenter(function(){
   $("#shopping_cart").css('display','block');
})
$('#btn-close').click(function(){
   $("#shopping_cart").css('display','none');
})
$('html').click(function() {
   $("#shopping_cart").css('display','none');
});

$('#shopping_cart').click(function(event){
    event.stopPropagation();
});

I've changed a bit your code, but it's simple: I added a button, because it's quicker to be implemented; then I replaced the cart with an ID instead of a class, because in my experience I had troubles event on classes and jquery.
I used display: none instead of visibility: none, because I think the cart shouldn't occupy space (or does it have to? See here)
EDIT: I also added the function to close the cart if you click outside! See here for the explaination!
I hope I helped you...

A: It is much better to use css class for formating element:
.shopping_cart {
z-index: 189;
visibility: hidden;
opacity: 0;
}
.shopping_cart_active{
z-index: 300;
visibility:visible;
}

So you add class shopping_cart_active on hover:
$('#shopping_button, .shopping_cart').on('hover',function(){
$(this).addClass('shopping_cart_active');
});

And when you want outside of it  you can use this:
$(html).on('click', function(){
$('.shopping_cart.).removeClass('shopping_cart_active');
})


text:
Q: Finding previous candle doesn't work because of DateTime.AddSeconds I'm using Binance.Net as a Binance API wrapper and recently I ran into a problem with DateTime.AddSeconds.
The following code is supposed to find the candle before the last order.
// OpenTime and CloseTime are both DateTime
var openTime = lastOrder.OpenTime; // 10:50:00
var closeTime = lastOrder.CloseTime; // 10:54:59

// It should return 10:55:00 - 10:50:00 = 5 minutes
// The reason I'm doing this is because I don't know the exact interval my bot is working with.
// What I know is the OpenTime (begin) and CloseTime (end).
var difference = closeTime.AddSeconds(1) - openTime; // closeTime.AddSeconds(1) doesn't work

var dateTime = openTime - difference; // 10:50:00 - 00:05:00.9990000 = 10:39:99

// 10:39:99 is an invalid startTime/endTime
var kline = _client.GetKlines(symbol, interval, startTime: dateTime, endTime: dateTime, limit: 1).Data;

The problem:
The problem is that .AddSeconds(1) doesn't actually add that second and as a result _client.GetKlines fails.
I don't know if there is a better way to get the previous candle in Binance's API but if there is, I would accept it as a solution.
Problem visual representation:

Edit:
Fixed it! When I checked the DateTime properties, I realized that I missed the miliseconds in the CloseTime property. So in the end, it was a wrong calculation. Instead of .AddSeconds(1), I made it .AddMiliseconds(1).


text:
Q: Automatic updates not working/plugins not installing I am trying to run an automatic update from Wordpress 3.0 to 3.02.  However, I get the following error message:
"Unable to locate WordPress Root directory.
Installation Failed"
I also cannot install plugins on the same server.  The error message for the plugins is quite similar:
"Plugin could not be deleted due to an error: Unable to locate WordPress Plugin directory."
I have contacted the host but they have not been much help.
Any ideas would be greatly appreciated.
Thank you!
Jeff

A: Jeff, unfortunately this looks like a problem with your hosting setup, so your host will be the only one who can help.  If they can't, and the problem doesn't correct itself, I'd recommend exporting your site and moving to a more supportive host.
In the meantime, though, who is your current host?  If you have FTP access, try manually updating a plug-in by transferring the new files to your server.  If that works, then you can manually update WordPress using the standard upgrade instructions.
If you don't have FTP access and still can't auto-update, there's not much more we can do without going through your host directly.