text:
Q: Re-directing a user if they submit a URL shortener I'm trying to re-direct a user if $displayurl  is equal to bit.ly, goo.gl,  or owl.ly.  It's not working.  Is there anything wrong with the IF statement below?
$site1 = 'http://' . $cleanurl;

$displayurl = parse_url($site1, PHP_URL_HOST);

if ($displayurl == array(bit.ly, goo.gl, owl.ly))
{

   session_write_close();
   header("Location:http://www.domain.com/directory/file.php");
   exit;

}

A: you have to use this code:
$domain = array("bit.ly", "goo.gl", "owl.ly");
if (in_array($displayurl, $domain)) {
   session_write_close();
   header("Location:http://www.domain.com/directory/file.php");
   exit;
}


text:
Q: Ionic Framework / .NET application sync? I want to create a Android application (using Cordova/PhoneGap Ionic Framework, which means it's source code will be JavaScript + HTML + CSS and AngularJS as well. I need that app to sync to a cloud database service, but, I also have a .NET based project, which need to sync to the same database. I wanted to use like a Firebase-ish backend, that could manage all the database stuff, as I wrote only (at least mostly) front-end code for my app. Keeping in mind that I need a NoSQL database service.
To give an example:
I want my app to communicate with, let's say, CouchDB (IrisCouch on the cloud to be specific), and my .NET project to listen to the changes my app makes to the database, and handle them. What I need is a platform where I only need to call API's functions, or the closest I can get to that. I tried Firebase already, but that will get too expensive, as I need something cheaper, at least for now. Am I expecting too much? Do I really need to write server-side code in this case, and if so, which would you guys think it's the best way?

A: For back-end you can use ASP.NET Web-API which supports ASP.NET Identity with OAuth login like Facebook, Twitter etc. and on front-end you can you use IonicFramework with AngularJs to call those API.
Helpful resources:
ASP.NET
IonicFramework
AngularJS
Restangular (Restful operations made easy for angular)

redpajama_set_name: RedPajamaStackExchange


text:
Q: SOLVED - Index Management "Catalog Search Index" Broken I was trying some exetension, but after I installed "Ajax Search by LitExtension", my search index is broken.
Catalog Search Index says "Reindex Required". So I did.

Then I get this error. I cannot reindex it and also error message is somehow empty.

I deleted var/report as suggested here :
Catalog Search Index not changing status "required index"
but no luck.
How can I fix this?
I use magento 1.8.1.0 .

A: I solved this issue by changing Attribute to "Searchable" >> "No". In my case, to change tax_class_id did the trick.


text:
Q: Can a battery lose electrons? I asked my teacher what would happen if I have a 1Ah battery and I expel (out of the circuit, for example with an electron gun) the electrons with a current of 1A for one hour, in such a way that the battery loses electrons. He told me that the battery would explode due to the electrostatic repulsive force of the ions.
But I'm not sure if he is correct since another professor showed us experimentally how the charge is maintained, he did it by charging the capacitor of parallel plates and then moving them away, in such a way that each plate had a net charge as well as a battery without electrons, am I correct?

A: In normal operation mode, for the electrons that go out of the battery, an equal amount will return at the other end. So, no.
But then again, yes: if you connect the minus end of the battery with a large metal shield, you have a kind of capacitor, where part of the electrons leave the battery. This is negligible unless the voltage is really high.

A: If you  would do this only for 1/1000 s the batterie would have a charge of 0,001As  wich would leave it at a voltage of about 9 million Volt so it would ionizes the air around it and discharge with lightning.
Did you do any electrostatic? so you could calculate the charge of a say a spere with radius 10cm, thats what I calculated for the batterie.
The amount of charges in electrostatic experiments is very low compared to the charges transported in a current.
so you can never take away so many electrons. you teacher was right in the sense, if you could achieve it you would get a voltage of 3600000 times the 9 million volts I mentioned earlier.
If you take away a smaller amount of electrons the batterie would just be at a smaller voltage against earth, the circuit would be the same. if you connect 1 end of the batterie to 1000V you should not touch it, but it would still do the same thing in a closed circuit as before.


text:
Q: PyQT - button.toggle() method not working I have a GUI with two radio buttons inside a QButtonGroup container, which itself is inside a QGroupBox (this button group needs a right click context menu, and since a QButtonGroup doesn't have a visual representation it doesn't seem to have a setContextMenuPolicy method.)  The following code snippet is supposed to update the state of the mutually-exclusive buttons in response to incoming data from a serial link:
elif widgetName in self.buttonBoxDict:
            buttonGroup = getattr(self.ui, self.buttonBoxDict[widgetName])
            checkedButton = buttonGroup.checkedButton()
            checkedButtonName = str(checkedButton.objectName())
            if value >= self.onValue and self.buttonDict[checkedButtonName][1] == self.offValue:
                checkedButton.toggle()
                assert(not checkedButton.isChecked())
                self.windowHandler.buttonChanged(self, self.onValue, cc)
            elif value < self.onValue and self.buttonDict[checkedButtonName][1] == self.onValue:
                checkedButton.toggle()
                self.windowHandler.buttonChanged(self, self.offValue, cc)

Unfortunately this isn't working, I know initially the button selected here is checked, but the state of the button in the GUI never changes, and the assertion always fails even though the code seems to be executing properly.  Any ideas as to why this might be going wrong?

A: The problem you have is based on the fact that you are using a QButtonGroup that is set to be exclusive. If you take a look at the documentation you will see that it states the following:

the user cannot uncheck the currently checked button by clicking on it; instead, another button in the group must be clicked

I don't know the logic of you application but if you are using an exclusive button group you will need to set a diff button to be checked or do not use an exclusive group and enforce the checks yourself.
The following is a small example of what you are seeing:
import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
button1 = QtGui.QCheckBox('test 1')
group = QtGui.QButtonGroup()
group.setExclusive(True)
group.addButton(button1)
print button1.isChecked()
button1.toggle()
print button1.isChecked()
button1.toggle()
print button1.isChecked()
# toggle seems not to work, add a second button
button2 =  QtGui.QCheckBox('test 2')
group.addButton(button2)
print button2.isChecked()
button2.toggle()
print button1.isChecked()
print button2.isChecked()

A: A quick fix, thanks to the heads-up by mandel, to get things to behave the way I "expected" them to for a two-button exclusive group is to change the code to something like this:
if value >= self.onValue and self.buttonDict[checkedButtonName][1] == self.offValue:
     for button in buttonGroup.buttons():
          if button != checkedButton:
               button.toggle()


text:
Q: TThread.WaitFor on multiple consecutive threads A thread (TThreadStarter) is created and it will in turn create a number of worker threads and must wait for them to finish before proceeding. It must work under both Linux and Windows.
The approach below seems to be a solution. But is it a good one? Would you do it differently?
1) Create and put all threads in an array, then run through the array and call Start.
2) Then simply run through the array again and call WaitFor so execution stops
for the calling thread until all threads has finished.
procedure TThreadStarter.Execute;
var i1:integer;
begin
  for i1:=1 to WORK_THREAD_COUNT do ThreadArray[i1].Start;
  for i1:=1 to WORK_THREAD_COUNT do ThreadArray[i1].WaitFor;

  ..Do some work

end;

I use Lazarus and FreePascal.

A: Solution for waiting on an (almost) arbitrary count of worker threads (Windows only).
Call WaitForThreads function from your MainWorkerThread (not the normal main thread) and pass in an array of all the thread handles you want to wait for.
interface

uses
  Windows, SysUtils, Classes;

type
  THandleDynArray = array of THandle;

  TMaximum_Wait_Objects_Handles = array[0..MAXIMUM_WAIT_OBJECTS - 1] of THandle;

  EMaximum_Handles_Exceeded = class(Exception);

  TThreadWaitForThreads = class(TThread)
  strict private
    FarrHandle: TMaximum_Wait_Objects_Handles;
    FThreadWaitCount: 0..MAXIMUM_WAIT_OBJECTS;
  protected
    procedure Execute; override;
  public
    procedure AddHandle(Handle: THandle); overload;
    procedure AddHandle(HandleArray: THandleDynArray); overload;
    procedure ClearHandles;
  end;

procedure WaitForThreads(const Handles: THandleDynArray);

implementation

procedure WaitForThreads(const Handles: THandleDynArray);
var
  Wait_Result: cardinal;
  arrHandle: TMaximum_Wait_Objects_Handles;
  arrWaitThreads: array[0..MAXIMUM_WAIT_OBJECTS - 1] of TThreadWaitForThreads;
  WaitThreadsCount, i: integer;
begin
  if Length(Handles) <= 0 then
    exit;

  if Length(Handles) > MAXIMUM_WAIT_OBJECTS then
  begin
    WaitThreadsCount := Length(Handles) div MAXIMUM_WAIT_OBJECTS;

    for i := 0 to WaitThreadsCount - 1 do
    begin
      arrWaitThreads[i] := TThreadWaitForThreads.Create(true);
      arrHandle[i] := arrWaitThreads[i].Handle;

      arrWaitThreads[i].AddHandle(Copy(Handles, MAXIMUM_WAIT_OBJECTS * i, MAXIMUM_WAIT_OBJECTS));
    end;

    try
      if Length(Handles) mod MAXIMUM_WAIT_OBJECTS > 0 then
        Move(Handles[MAXIMUM_WAIT_OBJECTS * WaitThreadsCount], arrHandle[WaitThreadsCount], (Length(Handles) - WaitThreadsCount * MAXIMUM_WAIT_OBJECTS) * SizeOf(THandle));

      for i := 0 to WaitThreadsCount - 1 do
        arrWaitThreads[i].Resume;

      repeat
        Wait_Result := WaitForMultipleObjectsEx(WaitThreadsCount + Length(Handles) - WaitThreadsCount * MAXIMUM_WAIT_OBJECTS, @arrHandle, true, 10, true);
        Application.ProcessMessages;
      until ((Wait_Result <> WAIT_TIMEOUT)
        and (Wait_Result <> WAIT_IO_COMPLETION));

    finally
      for i := 0 to WaitThreadsCount - 1 do
      begin
        arrWaitThreads[i].Terminate; // terminating all WaitThreads to be on the safe side
        arrWaitThreads[i].Free;
      end;
    end;
  end
  else
  begin
    repeat
      Wait_Result := WaitForMultipleObjectsEx(Length(Handles), @Handles[0], true, 10, true);
      Application.ProcessMessages;
    until ((Wait_Result <> WAIT_TIMEOUT)
      and (Wait_Result <> WAIT_IO_COMPLETION));
  end;
end;

{ TThreadWaitForThreads }

procedure TThreadWaitForThreads.AddHandle(Handle: THandle);
begin
  if FThreadWaitCount < MAXIMUM_WAIT_OBJECTS then
  begin
    FarrHandle[FThreadWaitCount] := Handle;
    Inc(FThreadWaitCount);
  end
  else
    raise EMaximum_Handles_Exceeded.Create('You can only wait for ' + IntToStr(MAXIMUM_WAIT_OBJECTS) + ' Threads!');
end;

procedure TThreadWaitForThreads.AddHandle(HandleArray: THandleDynArray);
begin
  if FThreadWaitCount + Length(HandleArray) <= MAXIMUM_WAIT_OBJECTS then
  begin
    Move(HandleArray[0], FarrHandle[FThreadWaitCount], SizeOf(THandle) * Length(HandleArray));
    Inc(FThreadWaitCount, Length(HandleArray));
  end
  else
    raise EMaximum_Handles_Exceeded.Create('You want to wait for ' + IntToStr(FThreadWaitCount + Length(HandleArray)) + ' threads, but you can only wait for ' + IntToStr(MAXIMUM_WAIT_OBJECTS) + '!');
end;

procedure TThreadWaitForThreads.ClearHandles;
begin
  FThreadWaitCount := 0;
  ZeroMemory(@FarrHandle, SizeOf(FarrHandle));
end;

procedure TThreadWaitForThreads.Execute;
var
  Wait_Result: cardinal;
begin
  if FThreadWaitCount = 0 then
    exit;

  repeat
    Wait_Result := WaitForMultipleObjectsEx(FThreadWaitCount, @FarrHandle, true, 10, true);
  until ((Wait_Result <> WAIT_TIMEOUT)
    and (Wait_Result <> WAIT_IO_COMPLETION))
    or Terminated;

  ClearHandles;
end;

end.


text:
Q: scikit-learn NearestNeighbors .kneighbors() on tfidf gives ValueError: UPDATEIFCOPY base is read-only I am using scikit-learn NearestNeighbors to find the nearest neighbor, using tfidf on people wiki data.
In my .kneighbors() method call
res = neigh.kneighbors(obama_tfidf, return_distance=False)

a Multiprocessing module threw an exception of:
ValueError: UPDATEIFCOPY base is read-only

I have uploaded my complete code and sample data (80 MB in size) at my github location here for reference.
Here is a part of the error listing:
---------------------------------------------------------------------------
JoblibValueError                          Traceback (most recent call last)
<ipython-input-12-dbcbed49b042> in <module>()
      1 obama_word_counts = count_vectorizer.transform(['obama'])
      2 obama_tfidf = tfidf_transformer.transform(obama_word_counts)
----> 3 res = neigh.kneighbors(obama_tfidf, return_distance=False)
      4 print res

/usr/local/lib/python2.7/dist-packages/sklearn/neighbors/base.pyc in kneighbors(self, X, n_neighbors, return_distance)
    355             if self.effective_metric_ == 'euclidean':
    356                 dist = pairwise_distances(X, self._fit_X, 'euclidean',
--> 357                                           n_jobs=n_jobs, squared=True)
    358             else:
    359                 dist = pairwise_distances(

/usr/local/lib/python2.7/dist-packages/sklearn/metrics/pairwise.pyc in pairwise_distances(X, Y, metric, n_jobs, **kwds)
   1245         func = partial(distance.cdist, metric=metric, **kwds)
   1246
-> 1247     return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
   1248
   1249

/usr/local/lib/python2.7/dist-packages/sklearn/metrics/pairwise.pyc in _parallel_pairwise(X, Y, func, n_jobs, **kwds)
   1094     ret = Parallel(n_jobs=n_jobs, verbose=0)(
   1095         fd(X, Y[s], **kwds)
-> 1096         for s in gen_even_slices(Y.shape[0], n_jobs))
   1097
   1098     return np.hstack(ret)

/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.pyc in __call__(self, iterable)
    787                 # consumption.
    788                 self._iterating = False
--> 789             self.retrieve()
    790             # Make sure that we get a last message telling us we are done
    791             elapsed_time = time.time() - self._start_time

/usr/local/lib/python2.7/dist-packages/sklearn/externals/joblib/parallel.pyc in retrieve(self)
    738                     exception = exception_type(report)
    739
--> 740                     raise exception
    741
    742     def __call__(self, iterable):

JoblibValueError: JoblibValueError

I can't paste the entire Multiprocessing exception as it exceeds the S/O posting limit.
What am I missing here?

A: When n_jobs is equal to -1, then the number of jobs is set to the number of CPU cores, as mentioned in the ref.
The error happens when the sklearn NN function calls _parallel_pairwise(), which then tries to get even slices.
Try setting n_jobs to an even number, which of course is less than the number of CPU cores.

As you mentioned already, you can run this with n_jobs equal to 1, which doesn't parallelize the code, thus not exposing the error.


text:
Q: Float page always *before* reference and without page break I'm trying to create a layout where images are *always without exception* displayed before their reference, and on a page by themselves without any text above or below the image. I've tried a number of different approaches, but have not been successful.
The text needs to "flow" around the images on the alternate side, so using \FloatBarrier to force a new page is not an option.
The example below is as close as I've been able to get, but I (a) want to get rid of the text underneath the image on page 1, (b) want to move the leftover text on page 4 to page 5 (leaving the image on a page by itself).
The section that references the image will not always be at the top of the page - because of how I'd like to lay this out, there may be some leftover bits of the previous section(s) that have flowed over. An alternate way of thinking of this would be that the image is inserted as an entire page on the page before the reference would appear, pushing the contents of the book one page out.
\documentclass[]{book}
\usepackage{lipsum}
\usepackage[pagestyles]{titlesec}
\usepackage{float}
\usepackage{placeins}
\usepackage[demo]{graphicx}

\renewcommand{\thesection}{\arabic{section}}

\begin{document}

\begin{figure}[H]
  \includegraphics[width=\textwidth,height=0.8\textheight]{dummy}
\end{figure} % must appear before the section on a line below (1)
\section{}
\lipsum[1-2]
\section{}
\lipsum[1]
\section{}
\lipsum[1-6]
\begin{figure}[H]
  \includegraphics[width=\textwidth,height=0.8\textheight]{dummy}
\end{figure} % must appear before the section on the line below (4)
\section{}
\lipsum[1-2]

\end{document}

A: p figures will not drift into the document and will always be placed at the next page break if they are larger than \floatpagefraction

\documentclass[]{book}
\usepackage{lipsum}
\usepackage[pagestyles]{titlesec}
\usepackage{float}
\usepackage{placeins}
\usepackage[demo]{graphicx}

\renewcommand{\thesection}{\arabic{section}}
\renewcommand\floatpagefraction{.1}
\begin{document}

\begin{figure}[p]
  \includegraphics[width=\textwidth,height=0.8\textheight]{dummy}
\end{figure} % must appear before the section on a line below (1)
\clearpage
\section{}
\lipsum[1-2]
\section{}
\lipsum[1]
\section{}

\lipsum[1-4]
\begin{figure}[p]
  \includegraphics[width=\textwidth,height=0.8\textheight]{dummy}
\end{figure} % must appear before the section on the line below (4)
\lipsum[5-6]
\section{}
\lipsum[1-2]

\end{document}


text:
Q: Laravel связь моделей Имеется проблема.
Описание:
 - Имеется две модели (Join и Object)
В моделе Join объявлена связь :
 public function objects(){
    return $this->belongsTo('App\Object');
 }

В Моделе Object так же объявлена связь:
    public function joins(){
       return $this->hasMany('App\Join');
    }

Собственно в тинкере пытаюсь выполнить команду:
Join::find(23)->object->name;

Ошибка появляется:

PHP Notice:  Trying to get property of non-object in Psy Shell code on
  line 1

Сомнения вызывает то что имеется модель TicketStatus связи идентичны, при выполнении команды
Join::find(23)->ticketstatus->name;

Ответ верный...
В чем может быть "Затык" подскажите...

A: У вас метод objectS
public function objects(){
    return $this->belongsTo('App\Object');
 }

А в тинкере вызываете object
Join::find(23)->object->name;

A: Проблема была в том, что человек изменил настройки в БД...
Удалил миграции и запустил по новой

php artisan migrate:reset
php artisan migrate

Все заработало.
Ответ Выше можно считать верным, только я тут в тексте опечатку допустил


text:
Q: Create materialized view no refresh from existing view with index I've already got a working db view :
CREATE OR REPLACE FORCE VIEW "USER_DATA_VIEW" ("APP_USER_ID", "FIRST_NAME", "LAST_NAME", "FULL_NAME", "LOCATION_ID", "LOCATION_NAME") AS
  SELECT U.APP_USER_ID, U.FIRST_NAME, U.LAST_NAME, U.FIRST_NAME || ' ' || U.LAST_NAME FULL_NAME, U.LOCATION_ID, LOC.LOCATION_NAME
   FROM APP_USER U
   JOIN LOCATION LOC ON U.LOCATION_ID = LOC.LOCATION_ID
;

Since the user/location data doesn't change often, and it's heavily relied upon from other views and part of the app, I want to try to cache to see if I can get more performance from it.
Not being an oracle person, I m reading that materialized views might just do this.
How can I create materialized view from the existing view with the index on app_user_id column and with no refresh option?
I've tried this :
CREATE MATERIALIZED VIEW USER_DATA_VIEW_MT
BUILD IMMEDIATE
NO REFRESH
AS SELECT U.APP_USER_ID, U.FIRST_NAME, U.LAST_NAME, U.FIRST_NAME || ' ' || U.LAST_NAME FULL_NAME, U.LOCATION_ID, LOC.LOCATION_NAME
 FROM APP_USER U
 JOIN LOCATION LOC ON U.LOCATION_ID = LOC.LOCATION_ID

And couple other versions but wasn't able to create it.

A: NO REFRESH is not valid syntax, it is NEVER REFRESH. But I guess you want to refresh the mview occassionally, so REFRESH ON DEMAND is a better option.
This alone is not enough, you also need to set the parameter query_rewrite_enabled to stale_tolerated:
alter session set query_rewrite_integrity=stale_tolerated;

You also mentioned using an index, yes, you can create indexes on materialized views.
Your query is really simple, just 2 tables with a join, I do not think you need a materialized view + query rewrite for this. You could just simply index the base tables properly.
By default, query rewrite works with up-to-date materialized views, so it can provide fresh and actual data (correct results). You need to explicitly allow the database in your session to provide you old data (incorrect results) from the mview using stale_tolerated. Your mview will remain stale regardless of this parameter until you refresh it explicitly. This is required for query rewrite to work with stale data.


text:
Q: My clickgui don't work... When i click on it So, i coding a minecraft client from quickdaffy tutorial (click gui is in 7ep)..
Another So, if i click on "testMod" button, nothing happends
Link for this tutorial: www.youtube.com/watch?v=SR_NAVTTD5o&t
This is the code for click gui (without imports):
package moonlight.ui.clickgui;

public class ClickGUI extends GuiScreen {

    ArrayList<ModButton> modButtons = new ArrayList();

    @Override
    public void initGui() {
        super.initGui();
        this.modButtons.add(new ModButton(210, 60, 240, 100, Moonlight.INSTANCE.hudManager.testMod));
    }

    @Override
    public void drawScreen(int mouseX, int mouseY, float partialTicks) {
        ScaledResolution sr = new ScaledResolution(mc);
        super.drawScreen(mouseX, mouseY, partialTicks);

        Gui.drawRect(200, 50, sr.getScaledWidth(), sr.getScaledHeight(), 0x20000000);

        for(ModButton m : modButtons) {
            m.draw();
        }
    }

    @Override
    protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
        super.mouseClicked(mouseX, mouseY, mouseButton);
    }
}

And this is for gui button (without imports):
package moonlight.ui.clickgui.comp;

public class ModButton {

    public int x, y, w, h;
    public HudMod m;

    public ModButton(int x, int y, int w, int h, HudMod m) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.m = m;
    }

    public void draw() {
        Gui.drawRect(y, x, h, w, 0x20000000);
        Minecraft.getMinecraft().fontRendererObj.drawString(m.name, x + 2, y + 2, getColor());
    }

    private int getColor() {
        if(m.isEnabled()) {
            return new Color(0,255,0,255).getRGB();
        } else {
            return new Color(255,0,0,255).getRGB();
        }

    }

    public void ocClick(int mouseX, int mouseY, int button) {
        if (mouseX >= x && mouseX <= x + w && mouseY >= y && mouseY <= y + h) {
            m.toggle();
            System.out.println("HELLO");
        }
    }

}

Rly, please help


text:
Q: Qt - Get position of rectangle within widget after translate() I want to get the coordinates of a QRect or QPoint within a widget to determine if that object is overlapping the edge and would be drawn outside of the widget.
The following program is just a testprogram to show my problem. There is a window in which then a black rectangle is drawn.
By using translate() of QPainter I move the coordinatesystem. After that I cant get the correct coordinates of the rectangle.
I could keep track of all coordinate system manipulations (translate(), rotate(), scale()) but thats not a nice solution. Is there an easier way to get the position of the Rectangle in relation to the top left corner of the widget?
#include "widget.h"
#include <QPainter>
#include <iostream>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{

}

void Widget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.translate(width() / 2, height() / 2);

    QRect rectangle(100, 50, 200, 100);

    std::cout << "width(): " << this->width() << "\theight(): " << this->height()
              << "\trecLeft X: " << rectangle.x() << "\trecTop Y: " << rectangle.y()
              << std::endl;
    //Output: width(): 960  height(): 432   recLeft X: 100  recTop Y: 50
}

What I woul like to get is:
recLeft X: 580(width()/2+100)  recTop Y: 266(height()/2+50)

A: You can get the transformation matrix of the painter and apply it to your rectangle. It should be something like this:
QTransform trans= painter.combinedTransform();
QRect transformed = trans.mapRect(rectangle);


text:
Q: A property of projection on a convex and closed set Let $S$ be a convex and closed set. The projection onto $S$ is defined as $P_S(x) = argmin_{y \in S} ||x-y||_2$.
I want to show that if $x \in S$, then for any $y$,
$$
\langle P_S(y) -x,P_S(y) -y\rangle \leq 0
$$
where $\langle.,.\rangle$ is the inner product. Any suggestion? What does this statement imply?

A: Hint: if $y \in S$, then $P_S(y) = y$ and $\langle P_S(y) -x,P_S(y) -y\rangle =0$
If $y \not\in S$, then let $z = P_S(y)$, let $H$ be the hyperplane orthogonal to the line segment $yz$ and passing through $z$ and let $U$ be the closed halfspace with $H$ as its boundary that does not contain $y$. Then you can show that $S \subseteq U$ (because if $x \in S \setminus U$, there is a point on the line segment $xz$ that is nearer to $y$ than $z$). But
$$
U = \{ x \mid \langle z - x, z -y\rangle \le 0 \}.
$$
(The geometric implication of the inequality is that $x$ and $y$ are separated by $H$.)

A: Rough sketch of proof:
Find the directional derivative of the function $z \mapsto \|z - y\|_2^2$ at the minimizer $z=P_S(y)$ in the direction $x - P_S(y)$. It will be related to the inner product you have written.
Intuitively, the directional derivative along such directions $x - P_S(y)$ (from $P_S(y)$ to other points of $S$) must be nonnegative. If such a directional derivative is negative, you could take a tiny step away from $P_S(y)$ in that direction and decrease the value of the function $z \mapsto \|z - y\|_2^2$, contradicting the definition of $P_S(y)$ being the minimizer.

Geometric intuition:
You can draw a picture of the two vectors in the inner product. The inequality means that the angle between these two vectors is obtuse.


text:
Q: tkinter: how to write a for loop to destroy a list of labels? I am trying to remove these elements from the grid.  I was able to delete all of them by writing out one by one.  I then wrote a for loop to make it expandable, then I run into this error message.
"employee.destroy()
AttributeError: 'str' object has no attribute 'destroy'"

This is part of a bigger program, but as much as I can reduce to the core problem, here is my code:
import tkinter as tk
from tkinter import ttk

labelemployee={}

class Application(ttk.Frame): #inherent from frame.

    def __init__(self, parent):
        tk.Frame.__init__(self, parent, bg="LightBlue4")
        self.parent = parent
        self.Employees = ["A", "B", "C", "D"]
        self.pack(fill=tk.BOTH, expand=1)
        self.GUI()

    def GUI(self): #the function that runs all the GUI functions.
        self.buttons()
        self.create_grid()
        self.add_left_names()

    def remove(self):
        #labelemployee["A"].destroy()
        #labelemployee["B"].destroy()
        #labelemployee["C"].destroy()
        #labelemployee["D"].destroy()
        for employee in labelemployee:
            employee.destroy()

    def create_grid(self):
        for i in range (7):
             for j in range(7):
                self.label = tk.Label(self, relief="ridge", width=12,
                       height=3)
                self.label.grid(row=i, column=j, sticky='nsew')

    def buttons(self):
        self.button=tk.Button(self, text="Clear", bg="salmon", command
             = self.remove)
        self.button.grid(row=7, column=6, sticky='e')

    def add_left_names(self):
       #--------add in name labels on the side--------------
        i=2
        for employee in self.Employees:
            self.label=tk.Label(self, text=employee ,  fg="red",
               bg="snow")
            self.label.grid(row=i,column=0)
            labelemployee[employee]=self.label
            i +=1

def main():
    root = tk.Tk()
    root.title("class basic window")
    root.geometry("1000x500")
    root.config(background="LightBlue4")
    app = Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Please help me.  I think the problem is my for loop is stored a list, and I have a dictionary.  So, then I guess i don't know how to destroy labels in a dictionary.

A: You have already figured out the issue in those comments !
You already know that labelemployee is a dictionary, so iterating over it will give you, by default, the keys of the dictionary. So employee will be strings like A, B... and so on. And destroying a string object will obviously give you an error. You need to destroy the corresponding tkinter widget. So for that, you should replace employee.destroy() with labelemployee[employee].destroy() in the for loop.


text:
Q: Remove string between two variables I have a string which has some data with a few special characters, Need to remove the data between the desired special char in JavaScript.
The special char would be obtained in a variable.
var desiredChar = "~0~";

And Imagine this to be the Input string:
~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
So I'm supposed to remove the text in bold.
The desired output is supposed to be-
~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
I've tried using "Replace" and "Regex", but as the desired character is being passed in a variable and keeps changing I'm facing difficulties.

A: You can create your own regex based on whatever the bounding character(s) are that contain the text you want removed, and then replace any text that matches that regex with a blank string "".
The JS below should work for your use case (and it should work for multiple occurrences as well):

var originalText = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";

var desiredChar = "~0~";
var customRegex = new RegExp(desiredChar + ".*?" + desiredChar, "gi");

var processedText = originalText.replace(customRegex, "");
console.log(processedText);

A: Given input string you can use .indexOf(), .lastIndexOf() and .slice().
Note, OR character | passed to RegExp constructor should be escaped to avoid RegExp created by passing string interpreting | character as OR | within resulting RegExp passed to .replace().

var desiredChar = "~0~";

var str = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";

var not = str.slice(str.indexOf(desiredChar), str.lastIndexOf(desiredChar) + desiredChar.length);
// escape OR `|`
var res = str.replace(new RegExp(not.replace(/[|]/g, "\\|")), "");

console.log(res)

A: You can build your regex from the constructor with a string input.
var desiredChar = "~0~";
// use the g flag in your regex if you want to remove all substrings between desiredChar
var myRegex = new Regex(desiredChar + ".*" + desiredChar, 'ig');

var testString = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
testString = testString.replace(myRegex, "");

A: You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);

Then you can construct regexstring in any way you want.
You can read more about it at http://www.regular-expressions.info/javascript.html


text:
Q: Is kill(pid, 0) guaranteed to return 0 if a process exists? I am on Centos 4 and am using kill(pid, 0) in my C++ program to check whether there is presently a process running with the given pid. I am beginning to suspect that there is a race condition whereby shortly after a process has started, there is a small window of time wherein the kill(pid, 0) does not return zero even though there is actually a process running.
Is this a known issue?  Will kill() ever return non-zero when a pid actually exists but has just been started?  If kill() is not a reliable to test for existence, is there a better way to perform this test?

A: kill(pid, 0) will only return 0 if the process exists and you would be able to send it a signal. If the process isn't running as you (and you aren't root), then the call will fail with -EPERM.


text:
Q: Error resolve in connecting mongoose to node const mongoose = require('mongoose');
main().catch(err => console.log(err));
 async function main() {

await mongoose.connect('mongodb://localhost:27017/test');
}
error
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (E:\Web Dev\Backend\New folder\node_modules\mongoose\lib\connection.js:807:32)    at E:\Web Dev\Backend\New folder\node_modules\mongoose\lib\index.js:340:10
at E:\Web Dev\Backend\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (E:\Web Dev\Backend\New folder\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (E:\Web Dev\Backend\New folder\node_modules\mongoose\lib\index.js:1140:10)
at Mongoose.connect (E:\Web Dev\Backend\New folder\node_modules\mongoose\lib\index.js:339:20)
at Object.<anonymous> (E:\Web Dev\Backend\New folder\index.js:4:10)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) {

reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 194037884,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (E:\Web Dev\Backend\New folder\node_modules\mongodb\lib\cmap\connect.js:381:20)
at Socket. (E:\Web Dev\Backend\New folder\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:640:26)
at Socket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
}
}

A: Maybe this does the trick:

async function main () {
  const connectionOptions = {
    useNewUrlParser: true,
    useUnifiedTopology: true
   }

   try {
    await moongose.connect(/*Your URL*/,connectionOptions)
    console.log(`Connected to MongoDB`)
   } catch (err) {
    console.log(`Couldn't connect: ${err}`)
   }
}


text:
Q: Is infinite loop still undefined behavior in C++ if it calls shared library? It's said that infinite loop for(;;); is undefined behavior.

From http://en.cppreference.com/w/cpp/language/memory_model

In a valid C++ program, every thread eventually does one of the
  following:

*

*terminate

*makes a call to an I/O library function

*reads or modifies a volatile object

*performs an atomic operation or a synchronization operation

  No thread of execution can execute forever without performing any of
  these observable behaviors.
Note that it means that a program with endless recursion or endless
  loop (whether implemented as a for-statement or by looping goto or
  otherwise) has undefined behavior.

But what if it calls a function in shared library?
for(;;) sofunc();
The function could do any kind of blocking I/O, or throw exception.
In this case, does the compiler assume that the loop has some observable behaviors?

A: There are a number of places where the language of the Standard gives compilers freedoms beyond what are required for useful optimizations, but which would instead provide compilers with ways to throw the Principle of Least Astonishment out the window.  The way the rules about endless loops are written fits that category.
Most of the optimizations which would be facilitated by the rules about endless loops would be enabled by language which specified that the time required to execute a section of code, even if infinite, is not considered to be a side-effect that compilers are required to preserve.  Such a rule would allow a compiler to omit any loop iterations which don't have any direct side-effects and don't modify values that are used elsewhere.
The Standard, however, goes beyond that.  Given the code:
int foo(void)
{
  int x=0;
  do
  {
    x=functionWithNoSideEffects(x);
  } while(x != 23 && x != 42);
  return x;
}

a compiler that could show that functionWithNoSideEffects would never have
any defined side-effects and would never return 23 could replace the code for "foo" with "return 42;".  Even if the purpose of the program was to test whether functionWithNoSideEffects would ever return 42 (in which case having the generated code return 42 whether the function does or not would be unhelpful) the Standard would not require compilers to generate code to actually test that unless the loop included some kind of "side-effect".
I'm not personally convinced that the value of having a rule that says that
if compilers can show that a loop can't terminate without X being true, they
may regard X as being true whether or not there's any means by which it
could be.  Optimizations based on that principle seem popular, however.

A: Yes it is, if the library is written in C++. Otherwise the combination is not a (pure) C++ program anymore and can't be governed by the C++ standard alone.
IOW, if during or after the dynamic linking it is somehow known that 1) the combination is a C++ program, and 2) sofunc has no side effects, then it can let the nasal demons fly.


text:
Q: Best way to solve sum of an array with .each Below is some code I submitted for a array sum algorithm.  In this case I had to use .each but I feel like there is a better way to do this...
numbers = [5, 17, 2, 899, 101, 4, 66, 123, 98]
sum = 0
index = 0
numbers.each do |number|
  sum = sum + numbers[index]
  index += 1
end
puts sum

A: There is. You don't need to track index manually when using each; you can simply do
numbers.each do |number|
  sum = sum + number
end


text:
Q: 10 people flip a coin 12 times. What is the probability that at least one person gets 10 tails? I've already calculated the probability of getting 10 tails out of 12 flips:
$\frac{12!}{10! \times 2!} \times 0.5^{10} \times 0.5^{2}$
But I can't figure out how to calculate the probability of that at least one person  out of 10 gets 10 tails flipping a coin 12 times.

A: If you select a person then the probability that this person obtains the result is $\alpha$ for a certain value of $\alpha$ that you have already obtained.
Since people's results are independent between each other, the probability that none of them get the result is $(1-\alpha)^{10}$ and so the final result is $1 - (1-\alpha)^{10}$.


text:
Q: Unable to invoke the exports function from bpl I using Delphi XE, i've the following setup:
Both Mydll.dll and Package1.bpl (runtime package) contains Unit3.pas
unit Unit3;

interface

implementation

uses Dialogs;

procedure TestProc(const S: string); stdcall;
begin
  MessageDlg(S, mtInformation, [mbOK], 0);
end;

exports TestProc;

end.

Case 1:
procedure TestProc(const S: string); stdcall; external 'mydll.dll';

procedure TForm1.Button3Click(Sender: TObject);
begin
  TestProc('Button3');
end;

Case 2:
procedure TestProc(const S: string); stdcall; external 'Package1.bpl';

procedure TForm1.Button3Click(Sender: TObject);
begin
  TestProc('Button3');
end;

Case 3:
procedure TForm1.Button3Click(Sender: TObject);
var H: THandle;
    P: procedure(const S: string); stdcall;
begin
  H := LoadPackage('Package1.bpl');
  try
    @P := GetProcAddress(H, PChar('TestProc'));
    if Assigned(P) then
      P('Button3');
  finally
    UnloadPackage(H);
  end;
end;

Case 1 and Case 3 passed but Case 2 will raise Access Violation.
My question as below,

1. Case 2 is not supported?
2. Except the Case 3, is there anyway to invoke the TestProc from Package1.bpl similar as Case1?

A: Yes the case 2 is supported but you must call the LoadPackage function too to load the package in memory.
try this code
procedure TestProc(const S: string); stdcall;  external 'Package1.bpl';

var
  hPackage : Cardinal;

procedure TForm1.Button1Click(Sender: TObject);
begin
   TestProc('Button3');
end;

initialization
  hPackage := LoadPackage('Package1.bpl');
finalization
  if hPackage<>0 then
  UnloadPackage(hPackage);

A: For case 2, you could also just simply build your project with runtime packages and include Package1 in the list of runtime packages for your project (in Project Options\Packages\Runtime packages). Then you can remove the import (external declaration) and just use the unit which contains the function.


text:
Q: How to properly draw a histogram? Surely it is an easy problem but I can't find a solution. Imagine you want to simulate a Gaussian distribution of frequencies around a mean value with a certain spread. It is an easy task to write the following code
\documentclass[tikz,border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}[scale=1]
\pgfmathsetseed{431}%
\pgfmathsetmacro{\mu}{0}
\pgfmathsetmacro{\sigma}{1}

\fill[red,opacity=.5,domain=-3:3,variable=\x,smooth] plot ({\x},{(10/sqrt(2*pi)*\sigma)*exp(-((\x-\mu)^2)/(2*\sigma^2))});

\foreach \k in {-3,-2.9,...,3}
{
\pgfmathsetmacro{\y}{(10/sqrt(2*pi)*\sigma)*exp(-((\k-     \mu)^2)/(2*\sigma^2))}
\draw[xshift=-1.5pt](\k,0)rectangle(\k+1/10,\y+rand/10);
}
\end{tikzpicture}
\end{document}

But if instead one want to draw the histogram with a continue line following only the top border, what would be the code?

A: If I understood your question correctly, you can do this with a "const plot" in pgfplots. (It's not really a histogram here; it's an analytical step function.)
\documentclass[tikz,border=5pt]{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
  \pgfmathsetmacro{\mu}{0}
  \pgfmathsetmacro{\sigma}{1}
  \begin{axis}
    \addplot[samples=30,domain=-3:3,const plot] {1/(2*\sigma*sqrt(pi))*exp(-(x-\mu)^2/(2*\sigma^2))};
  \end{axis}
\end{tikzpicture}
\end{document}

which gives the result


text:
Q: How to set different style for each column from configuration This is my configuration :
"columns": [
    {
        "field": "field1",
        "style": "'color:red' if val > 0 else 'color:green'"
    },
    {
        "field": "field2",
        "style": "'color:red' if val < 0 else 'color:green'"
    }
]

and this is my code that apply the style:
for column in columns:
    if "style" in column:
        tab_df = tab_df.style.applymap(
            lambda val: eval(column.get("style")), subset=pd.IndexSlice[:, [column.get("field")]]
        )

it is work only for first style, but for the second i got :
AttributeError: 'Styler' object has no attribute 'style'"

So, there is another way to do it correctly?

A: You can define a function where you pass the list of color, depending on fields:
def highlight(x,val=0,colors={}):
    if x.name in colors:
        c0,c1 = colors[x.name]
        return np.where(x>val, f'color:{c1}', f'color:{c0}')
    else:
        return [''] * len(x)

# Apply style
df.style.apply(highlight, colors={'field1':['green','red'],
                                  'field2':{'red','green'}}
              )

Output:


text:
Q: How to get the token from api in react native I am using react native and I want to get the access token and the id from api which is created in nodejs using JWT authentication and axios.
Any suggestion please
here is my code below:
Services:
const updatePasswordEmailLink = (id, token, password, passwordConfirm) => {

  return (
    http.post(`/reset-password/${id}/${token}`, JSON.stringify({ ...{ password, passwordConfirm } }))
  )
}

ResetScreen:
useEffect(() => {
    //how can I get the id and the token

  }, [])

  const resetPasswordEmail = async () => {

    AuthService.updatePasswordEmailLink(id, token, password, passwordConfirm).then(
      () => {

        navigation.navigate('LoginScreen');
        return true;
      })
      .catch((error) => {

        Alert.alert('Error!', error.message);
        return false;
      })

  }


text:
Q: Ring theory Algebra Let F be a field of $8$ elements  and A=set of all x belongs to F such that $x^7=1$ and $x^k \neq 1$ for all $k < 7$. then the number of elements in A is

A: If $F$ is a field then every finite subgroup $G \subset F^{\times}$ is cyclic. In particular in our case $ F^{\times}$ is cyclic of order $7$, and in a cyclic group of order $7$ there are $6$ elements of order $7$, i.e. all the elements except the unit

A: Note that $0 \in F$ is not a unit.  Therefore, we are really interested in looking at $F^\times = F$ \ $\{0\}$, the set of units in $F$.  The important thing to recognize is that $F^\times$ forms a group under multiplication.
Note that $F^\times$ forms a group that is, in particular, of order $7$, which is prime.  All groups of prime order are cyclic $\Longrightarrow F^\times \cong \mathbb{Z}_7$.  Can you now apply Lagrange's theorem to finish up?


text:
Q: Use of the Negative mention class on WKS While developing a custom machine learning model for the extraction of information on CVs using WKS, we started to wonder if the usage of the negative mention class feature for anottation only has effect on the model if the mention has a relation indicated with another one, the question arises because one can change the mention class from specific (the default class asigned on a first annotation task) to negative without the need of creating a relation, but we don't know if this way of using the negative mention class is useful at all.
We already know that the ML model learns from positive and negative examples (leaving a mention without annotation) will the use of the negative mention class feature improve the performance of the model further? we ask this because, clearly we don't know how WKS works in detail under the hood.

A: as you know, below answer was posted in the Communities Forum.

Negative mention class can be used to annotate a mention of a lack of
  something.  For example, "there is no police presence in the region"
  could have "police" annotated with entity type ORGANIZATION but
  mention class NEG.  Another option however is not to use NEG and
  instead make one or more entity types for wording indicative of
  negation, doubt, or anything else other than certainty, and a relation
  type for connecting them to what they pertain to.  So could have
  no/NEGATION appliesTo police/ORGANIZATION or some such.


text:
Q: Changed Network Label on VCenter Server VM now Unable to Connect to Reset it Back I didn't think it through, in vSphere on my vCenter Server VM I changed the Network from VMNetwork to VMotion.
I did this with the intention of changing it back immediately, I sometimes do this as a trick on other VM's to fix an issue, however stupid me didn't think this through on doing it to the vCenter Server VM.
Anyway when I changed it I immediately lost connection and now I can't connect to set it back.
I can't connect directly to the host the VM is on either as I don't have the host password...after googling I think it might be on a sticker on the host (it's HP ProLiant), but it's physically located in a different part of the country nowhere near me :(
Any idea on how I can connect back to my vCenter Server so that I can change the Network back on the VM to VMNetwork?

A: You obviously killed the vCenter port group connectivity. The only way back is connecting to the host directly, either through vSphere Client or by SSH (needs to be activated first).
Another option would be to recover the vCenter server from backup, but then again, you'd need to login to a host.


text:
Q: WinUI 3 - Creating a new window with existing XAML file I have two "windows" in my program, 1st being the main page, which the user should see on start and 2nd is the small window, that I need to open when a person presses certain Button.
Main window is "MainWindow"
Second window is "Window2"
I have created a xaml file for Window2 where I have the layout (Window2.xaml), but I don't know how to specify this xaml file when creating the window
In oder to open new window I used code from this question
private void sessionWieserherstellenBtn_Click(object sender, RoutedEventArgs e)
        {
            var window2 = new Window();
            window2.Content = new TextBlock() { Text = "Hello" };
            window2.Activate();
        }

The problem is that it creates a window with just "Hello" TextBlock, since the content is set to that TextBox.
Is there any way to Basically do something like:
window2.Content = Window2.xaml ?
And also can I "link" Window2.cs file there?

A: I was able to make it work with this code:
private void sessionWieserherstellenBtn_Click(object sender, RoutedEventArgs e)
    {
        var newWindow = new Window2();
        newWindow.Activate();
    }

A: You can pass a page like this:
Window window = new()
{
    Title = "Sub window",
    Content = new SubPage(),
};

// This will close the "Sub window"
// when the MainWindow is closed.
this.Closed += (s, a) =>
{
    window.Close();
};

window.Activate();


text:
Q: Perform an action after returning from a getter I have a function that sets a getter and setter on an object or array.
My problem is that if the set value is an object I cannot detect its internal changes but only when it is accessed assuming it is accessed through the getter. At the moment the getter returns the object however I want to perform an action after returning the getter wether it was changed or not.
My code at the moment:
set = function(obj, i, val) {
    Object.defineProperty(obj, i, {
        set(newVal) {
            val = newVal
            // react to changes
            insert(val, i)
        },
        get() {
            return val
            //I want this to run after the object was accessed and possibly changed
            if (typeof val == "object") {
                insert(val, i)
            }
        },
        configurable: true,
        enumerable: true
    })
}

I have thought of one solution which is setTimeout however if the setter and getter are deleted the setTimeout could cause unwanted behaviour and I would rather the code remained synchronous.
The another idea I have considered is defining setters and getters on all of the objects properties however this would be expensive.
How can I solve this?

A:
I have thought of one solution which is setTimeout...

That's how you'd do it, that or Promise.resolve().then(...).

...and I would rather the code remained synchronous.

It can't be synchronous. You can perform an action after the getter returns, or it can be synchronous. You can't have it both ways.

That said, there's no guarantee whatsoever that doing something asynchronous soon after the getter is used will detect anything done with the object. Consider:
var o = yourObject.theProperty;
setTimeout(function() {
    o.foo = "bar";
}, 6000);

Your getter on theProperty is executed on the first line. The object isn't changed until six seconds later.
If you want to detect changes to the object, then make all of its properties getter/setter properties that can't be reconfigured, and act on changes you see to them. (You might also use Object.freeze or Object.seal to prevent new properties being added.)
If you want the object to be able to have properties you haven't defined, but you still want to react to changes to them, you'll have to use a Proxy, with the concommitant performance hit. But for a known set of properties, non-configurable getter/setter properties do the job.


text:
Q: finding NEXT Day using python conditionals I run the following code to get the next day in format year/month/day by conditional, but one gives desired output but with just a little change in code doesn't. I had taken the leap and non leap years in the nested if's wherever needed.
Here is the code that gives output:
y=int(input('Enter a year:'))
d=int(input('Enter a day:'))
m=int(input('Enter a month:'))
print('Present Day= '+str(y)+':'+str(m)+':'+str(d))
if m==2:
    if ((y%4==0 and y%100!=0) or y%400==0) and d<29:
        print('Next Day= '+str(y)+':'+str(m)+':'+str(d+1))
    elif (y%100==0 and y%400!=0) and d<28:
        print('Next Day= '+str(y)+':'+str(m)+':'+str(d+1))
    elif ((y%4==0 and y%100!=0) or y%400==0) and d==29:
        print('Next Day= '+str(y)+':'+str(3)+':'+str(1))
    elif d==28:
        print('Next Day= '+str(y)+':'+str(3)+':'+str(1))
elif m==1 or m==3 or m==5 or m==7 or m==8 or m==10:
    if d<31:
        print('Next Day= '+str(y)+':'+str(m)+':'+str(d+1))
    elif d==31:
        print('Next Day= '+str(y)+':'+str(m+1)+':'+str(1))
elif m==4 or m==6 or m==9 or m==11:
    if d<30:
        print('Next Day= '+str(y)+':'+str(m)+':'+str(d+1))
    elif d==30:
        print('Next Day= '+str(y)+':'+str(m+1)+':'+str(1))
elif m==12 and d==31:
    print('Next Day= '+str(y+1)+':'+str(1)+':'+str(1))

Here is the code that doesnt give output if line 12 is replaced by this:
    elif (y%100==0 and y%400!=0) and d==28:
        print('Next Day= '+str(y)+':'+str(3)+':'+str(1))

Can anyone explain the difference as to why this code 2 doesnt give the output as code 1?
O/P by code1:
Present day: 2019/2/28
Next day: 2019/3/1
O/P by code2:
Present day: 2019/2/28

A: As @Adam Smith mentioned in the comments, unless this is for a homework assignment you should not be doing this by hand and should use the datetime library instead.
But to answer your question, by changing that line you get no output because (y%100==0 and y%400!=0) and d==28 is false when y is 2019. Thus none of your conditions match and the program ends.


text:
Q: Use dataframe name while mutating across many dataframes in R I need to make a new column in each of 96 different dataframes that is the name of the dataframe (the name is informative). It's easiest to just show you what I mean.
> wolf <- data.frame(test1 = c(3,2,4,3),
+                    test2 = c(4,5,2,4))
> bear <- data.frame(test1 = c(3,5,6,1),
+                    test2 = c(4,6,2,4))
> wolf
  test1 test2
1     3     4
2     2     5
3     4     2
4     3     4
> bear
  test1 test2
1     3     4
2     5     6
3     6     2
4     1     4

I would like the output to be:
> wolf
  test1 test2 animal
1     3     4   wolf
2     2     5   wolf
3     4     2   wolf
4     3     4   wolf
> bear
  test1 test2 animal
1     3     4   bear
2     5     6   bear
3     6     2   bear
4     1     4   bear

Obviously, doing a dplyr::mutate command for each dataframe would take ages. I'm sure there's a way to do this with for loops and/or lapply but I don't have a good handle on how to use those functions. I also know that it's bad practice to have so many dataframes in my global environment; I'm all ears if you have suggestions for a more organized way of inputting this data to begin with (the data is coming from excel spreadsheets).
The reason I'm doing this is I want to combine all these DFs into one DF. But if I just rbind immediately, I'll lose the important information that is in each DF's name. Thanks so much for your help.

A: A possible solution, based on tibble::lst (to create a named list of the dataframes) and purrr::imap (to iterate over the list of dataframes):
library(tidyverse)

imap(lst(bear, wolf), ~ mutate(.x, animal = .y))

#> $bear
#>   test1 test2 animal
#> 1     3     4   bear
#> 2     5     6   bear
#> 3     6     2   bear
#> 4     1     4   bear
#>
#> $wolf
#>   test1 test2 animal
#> 1     3     4   wolf
#> 2     2     5   wolf
#> 3     4     2   wolf
#> 4     3     4   wolf

In the case of many dataframes to process, we can do the following, after loading all dataframes (be sure no other dataframe is loaded but only the ones needed):
# this gets all dataframes from the global environment to a named list
l <- do.call(list, eapply(.GlobalEnv, \(x) if (is.data.frame(x)) x else NULL))
l <- Filter(Negate(is.null), l)

imap(l, ~ mutate(.x, animal = .y))


text:
Q: how to take inputs seperated by new line I have an input with the line breaks. I want to convert that string into an array, and for every new line, jump one index place in the array.
If the input is:

100
  200
  300

Then I need the output to be:

110
  210
  310

I have used the following code:
public class NewClass {
    public static void main(String args[]) throws IOException {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
        String str=br.readLine();
        String [] arrOfStr = str.split("\n");int b=0;
        for (String a : arrOfStr) {
            b=Integer.parseInt(a);
            int c=b+10;
            System.out.println(c);
        }
     }
}

But it is not giving the desired output.
Note: We are not taking the input from text file. We don't know how many inputs are there in test case. We have take inputs in one go.

A: You could use a scanner.hasNext() instead as -
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    // scanner.useDelimiter("\\r\\n"); // if required to delimit the input
    while (scanner.hasNext()) {
        int c = Integer.parseInt(scanner.next()) + 10;
        System.out.println(c);
    }
}

Using the same Input as yours -

100
200
300

The Output would be -

110
210
310

A: To elaborate on my comment.
    List<Integer> intList = new ArrayList<Integer>();
    BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    while (!str.isEmpty()) {
        intList.add(Integer.parseInt(str)+10);
        str=br.readLine();

    }
    System.out.println(intList);}

This should work, I'm on my phone...


text:
Q: Creating intellgent dropdown levels in mobile menu I'm trying to build an off-canvas menu that has multiple levels. I've made a quick codepen of my early attempts.
How can I change the code below to have the menu close any open sections if another 'level 1' (+)link is opened? Currently I just have a toggle on any item that is clicked. I'd like to make it a bit more intelligent. Also if the level above is closed all levels below it will close too.
$('.off-canvas__content').on('click', '.nav-click', function(e) {
    e.preventDefault();

    $this = $(this);
    $this.children('i').toggleClass('icon-minus').toggleClass('icon-plus');
    $item = $this.parent('.nav__item');
    $item.toggleClass('nav__item--open');

});

A: Adding this to your code will make things work, I guess:
  if($item.hasClass('nav__item--open')) {
          $item.siblings().find('.nav__item--open').removeClass('nav__item--open');
          $item.siblings().find('.icon-minus').addClass('icon-plus').removeClass('icon-minus');
          $item.siblings().removeClass('nav__item--open');

     }

CodePen

A: hide all parent elements exept element on which is clicked
Edit this:
$item.toggleClass('nav__item--open').siblings().toggle();


text:
Q: How to make Google reporting API refresh the oauth2 access token when it expires? I am working on an analytics API project and when the access token expires after an hour I get "code:401, Invalid Credentials" and have to unset the php session to be able to re-authenticate. I have read that I should receive a refresh token automatically when first authorized but I'm not seeing it anywhere. I have also tried to set the refresh token manually, having obtained it from the oauth2 playground. How can I make this work? Should the refresh token be stored in $_SESSION initially?
The code in question:
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $analytics = new Google_Service_Analytics($client);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

Access token in $_SESSION
[access_token] => blahblahblah
[expires_in] => 3600
[scope] => https://www.googleapis.com/auth/analytics.readonly
[token_type] => Bearer
[created] => 1537207944

A: So, after much digging and tinkering I finally got it to work. I kept seeing reference to
$client->setAccessType('offline');

and
$client->setApprovalPrompt('force');

being the solution to my problem, but they weren't working for me. It turns out that they need to be added to oauth2callback.php, NOT any other reporting or management files. This was deceiving due to the other files also manipulating the $client object. I'm finally receiving a refresh_token in $_SESSION['access_token'] and it seems to be handling refreshes on it's own now without any further action.

A: You will only get a Refresh Token on the first auth. You might need to deauthorise your app and try again. You can store the RT anywhere you like, provided it's secure. To use your RT to obtain an Access Token, see https://developers.google.com/identity/protocols/OAuth2WebServer#offline


text:
Q: How can I a group jQuery AJAX queries? I have some code that looks like this (I left out the parts that are unimportant for the question):
$.ajax({
    type: "POST",
    url:  "prepXML.php",
    data: "method=getartists&user=" + userName + "&amount=" + amount,
    dataType: "xml",
    success: function(xml) {
        $("artist", xml).each(function(){
            // calculate and output some stuff and then call getTracks()
            getTracks(artistName, artistNamePOST, artistPlaycount, divId, artistId);
        });
    }
});

function getTracks(artistName, artistNamePost, artistPlaycount, divId, artistId){
    $.ajax({
        type: "POST",
        url:  "prepXML.php",
        data: "method=gettracks&user=" + userName + "&artist=" + artistNamePOST + "&playcount=" + artistPlaycount,
        dataType: "xml",
        success: function(xml){
            // calculate and output some stuff
        });
    }
});

When this is run, it calls getTracks() fifty times and makes quite some (server) CPU load in very short time until it all gets done. What I would like to do is to group AJAX getTrack() queries by for example 5 at a time, wait until those five are done, then call the next five, wait until the next five are done, call the next five etc. The purpose of this would be to make fewer queries at basically the same time (less and more evenly spread CPU load).
I am unsure how or even if this can be done since it kind of partially beats the point of AJAX, but I would still like to make this work if possible. Could someone please point me into the right direction? Thank you.
To better understand what I need this for and what the app does, here is a link to the app. it can be tried out with any lastfm nick (if you don't have one, you can use mine - "pootzko"). I hope I am allowed to put the link in the post(?), if not, feel free to remove it..

A: Either include all the track information in the data that is returned from getartists OR only call getTracks when someone wants to see the tracks for a specific Artist.
e.g.
Display all the Artists, and have a "View Tracks" options. Only once this is clicked then you get the tracks.
To me this is the best option because if you are loading up ALL the tracks for ALL the artists, then there is a lot of data that that probably isnt needed. No one is going to want to look through all the artists and all the artists tracks (unless the specifically want to).

A: I'd consider only retrieving track info for artists that a user has clicked on. Or possibly retrieving all of the data via a single request (perhaps then after it is retrieved process it in batches via setTimeout()).
But something along the lines of the following might work to do only five requests at a time:
$.ajax({
    type: "POST",
    url:  "prepXML.php",
    data: "method=getartists&user=" + userName + "&amount=" + amount,
    dataType: "xml",
    success: function(xml) {
      var artists = $("artist", xml),
          i = 0,
          c = 0;

      function getTracksComplete() {
         if (--c === 0)
            nextBatch();
      }

      function nextBatch() {
         for(; c < 5 && i < artists.length; i++, c++) {
            // artists[i] is the current artist record
            // calculate and output some stuff and then call getTracks()
            getTracks(artistName, artistNamePOST, artistPlaycount, divId, artistId,
                      getTracksComplete);
         }
      }

      // Optional - if you need to calculate statistics on all the artists
      // then do that here before starting the batches of getTracks calls
      artists.each(function() { /* do something */ });

      // Kick of the first batch of 5
      nextBatch();
   }
});

function getTracks(artistName, artistNamePost, artistPlaycount, divId, artistId,
                   callback){
    $.ajax({
        type: "POST",
        url:  "prepXML.php",
        data: "method=gettracks&user=" + userName + "&artist=" + artistNamePOST + "&playcount=" + artistPlaycount,
        dataType: "xml",
        success: function(xml){
            // calculate and output some stuff
        },
        complete : function() {
            if (callback) callback();
        });
    }
});

The above was just off the top of my head (so I didn't have time to build it to scale or to paint it), but the idea is that instead of using .each() to loop through all of the artists at once we will cache the jQuery object and do a few at a time. Calling the function nextBatch() (which is local to the success handler and thus has access to the local variables) will run a loop that calls getTracks() only 5 times, but starting processing from where we left off the previous time. Meanwhile getTracks() has been updated slightly to accept a callback function so when its ajax call completes (and note we do this on complete rather than success in case of errors) it can let the main process know that it has finished. Within the callback we keep track of how many have completed and when they all have call nextBatch() again.

A: My solution is to process all the artist data into the array and then start executing .ajax() requests in the batches of 5. When those 5 requests are done, next batch is executed, etc.
HERE is a working demonstration.
// just success changed
$.ajax({
  type: "POST",
  url:  "prepXML.php",
  data: "method=getartists&user=" + userName + "&amount=" + amount,
  dataType: "xml",
  success: function(xml) {
    var data = [];
    // prepare the data
    $("artist", xml).each(function(){
        data.push({ name: artistName /** rest of data */ } );
    });
    // start processing the data
    processData(data, 0);
  }
});

// process the data by sending requests starting from index
function process(data, index) {
  var xhrs = [];
  for (var i = index; i < index + 5 && i < data.length; i++) {
    (function(data) {
       xhrs.push($.ajax({
         type: "POST",
         url:  "prepXML.php",
         data: "method=gettracks&user=" + data.name /** rest of the data */
         dataType: "xml",
         success: function(xml) {
           // calculate and output some stuff
         }
       }));
     })(data[i]);
   }

  // when current xhrs are finished, start next batch
  $.when.apply(this, xhrs).then(function() {
    index += 5;
    if (index < data.length) {
      process(data, index);
    }
  });
}

A: It's difficult to clearly understand the logic of you application, but I think a better way should be collecting previously all the data you need to send (50 entries in a JSON object) and then call getTracks function only once, passing only one JSON object.


text:
Q: Quickly decode a list of avro messages using fastavro (Python) I have a Python list of avro messages. They are obtained from a Kafka consumer. Each message is of type byte, and they can all be decoded using the same avro schema.
I'm currently using the method schemaless_reader in the fastavro module (cf https://fastavro.readthedocs.io/en/latest/reader.html?highlight=schemaless_reader#fastavro._read_py.schemaless_reader). This method reads each record one by one. Is there a more efficient way to decode them?
Solutions tentatives:

*

*Convert the list of bytes to a single byte instance. This is a version of my code, and I keep getting errors like UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 12: invalid start byte:
import json, io, fastavro

parsed_schema = fastavro.parse_schema(json.loads(schema_as_str))
fo = io.BytesIO(bytes(b''.join(messages)))
result = reader(fo, parsed_schema)

*Write the list to a (possibly temporary) file fastavro.writer and read it again by blocks using fasctavro.block_reader, as in this example: https://github.com/fastavro/fastavro/blob/c43e86033a104ddc466cd66c64e40c653155b257/tests/test_block_reader.py#L27 Any inconvenience with this solution?


text:
Q: Calculations for building a mixer circuit I have been tasked with building a mixer.
\$V(output) = 1/2*V1 + 1/6*V2\$
Thinking in terms of superposition, I assume I can hook up \$V1\$ and \$V2\$ to the circuit separately, and then sum the results up to achieve \$V(output)\$.

*

*I start by connecting the circuit to V1 and ground, and add two equal resistors to each side of the output. Since the resistors are equal, V splits in half, and the first half of the task is done.

*I replace V1 with ground, and hook up V2 to where ground was. I change the relationship between resistors from \$1:1\$ to \$1:5\$ to get the 1/6 relationship. \$1/(1+5)\$.

But now I don't understand how to proceed. I can't simply add the values of the resistors together, as that will yield neither of the right relationships. Please note that this question is tagged with homework.

A: It should be possible to do this with 3 resistors:

The gain from V1 to OUT is a resistor divider with R1 as the top leg and the parallel combination of R2 and R3 as the bottom leg:
 G1 = (R2//R3) / (R1 + R2//R3) = 1/2
Similarly, you can write the equation for the gain from V2 to the output:
 G2 = (R1//R3) / (R2 + R1//R3) = 1/6
Now you have two equations and three unknowns.  That should tell you the problem is underconstrained.  With a little thought you should realize that if you have one set of resistors that meet the requirements, you can easily find others by multiplying all the resistors by the same constant.  In other words, all that matters is the ratio of the resistors as the problem is stated.  The absolute value effects apparent impedances, but those weren't specified.
To get the third constraint, you can simply pick a fixed value for one of the resistors.  For example, decide R3 is 1 Ω, then solve for the remaining two values.  If you later decided you would rather R3 were 1 kΩ, then you can multiply all the values by 1k.
So the third equation is:
 R3 = 1 kΩ
Now you have three independent equations and three unknowns.  The rest is simple algebra.  This is your problem, so I'll leave that as a exercise for you.


text:
Q: Receiving data from HTTP Post using Sockets my requirement is to receive HTTP Post request using Socket in android(Contents are JSON file). When I print socket.getInputStream(), I get:
POST/HTTP/1.1
Content length:41
Content-type: application/json
Host:10.0.2.15:5001
Connection: Keep Alive
User-Agent: Apache HTTPClient/Unavailable(Java 1.4)

CRLF(Carriage return line feed)-

Actual Contents of JSON<Data>

I used the link https://forums.oracle.com/forums/thread.jspa?messageID=7076709, but it prints only "Content-type: application/json
Host:10.0"(may be for length of 41) in Logcat.
My code is:
    serverSocket = new ServerSocket(portNumber);
    while(true){
    socket = serverSocket.accept();
    List<String> headers = new ArrayList<String>();
    String str;
    BufferedReader reader = new BufferedReader(new  InputStreamReader(socket.getInputStream()));
    while ((str = reader.readLine()) != null)
    {
    headers.add(str);
    if (str.startsWith("Content-Length: "))
    {
    break; // and don't get the next line!
    }
    }
    int contentLength = Integer.parseInt(headers.get(headers.size() - 1).substring("Content-Length: ".length()));

   for(int j=0;j<headers.size();j++)
   {
    Log.d("Headers:",headers.get(j));
    }
    StringBuilder requestContent = new StringBuilder();
    int ch;
    for (int i = 0; i < contentLength; i++)
    {
    requestContent.append((char) reader.read());
    }
    Log.d("The request content is: ",""+requestContent);

This is my output:
Headers:
 POST / HTTP/1.1
 Content-Length: 41
requestContent:
 Content-Type: application/json
 Host: 10.
Can someone please guide me how it can be done? Thanks in advance!

A: DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(serverSocket.accept(), new BasicHttpParams());
HttpRequest request = conn.receiveRequestHeader();
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
System.out.println(EntityUtils.toString(entity));

http://hc.apache.org/httpcomponents-core-ga/tutorial/pdf/httpcore-tutorial.pdf for more reference


text:
Q: C++ header file inclusion error I have a header "myHeaderFile.h" file looks as below which is used by both release exe and unit test exe.
#ifndef MYHEADERFILE_H
#define MYHEADERFILE_H

namespace myname1
{
namespace myname2
{
    class A
    {
           ...
    };
#ifdef MYTESTCLASS
    class TestABase
    {
        ...
    }
#endif
}
}
#endif

Now we have for unittest file myUnitTest.h file file as below
#ifndef MYUNITEST_H
#define MYUNITTEST_H

#ifndef MYTESTCLASS
#define MYTESTCLASS  1
#endif
#include "myHeaderFile.h"
class TestClass : public myname1::myname2::TestABase
{
  ...
};
#endif

now in myUnitTest.cpp i have following
#include "myUnitTest.h"

// Definition stuff.

When i compile i am getting error as error C2039: TestABase: is not a member of myname1::myname2'
myUnitTest.h(31): error C2504: TestABase: base class undefined
what is causing above error? Please help me in resolving above error. Note: myHeaderFile.h comes from library so i cannot change this header file.
Thanks!

A: You need to include myHeaderFile.h in myUnitTest.h. Do that after the block:
#ifndef MYTESTCLASS
#define MYTESTCLASS  1
#endif

Edit
As this did not help then there may be a problem with the MYTESTCLASS definition. Do you include myHeaderFile.h anywhere else? Maybe you can try to define the MYTESTCLASS in compiler options instead of in the myUnitTest.h header file. Maybe you can just remove the #ifdef MYTESTCLASS check to see if that is the problem.


text:
Q: NGINX proxy_pass rewrite asset uri I'm trying to do a basic NGINX reverse proxy by subdomian, to localhost/folder and am stumped getting it to rewrite my assets+links.
My http://localhost:8080/myapp/ works like a charm, but via NGINX+subdomain it fails on the subfolder assets.
I believe I'm stumped on the 'rewrite' clause for NGINX.
How can I rewrite the HTML going to the client browser to drop the /myapp/ context?
server {
    listen       443 ssl;
    server_name  app1.domain.com;
    location / {
        rewrite ^/myapp/(.*) /$1 break; # this line seems to do nothing
        proxy_pass http://localhost:8080/myapp/;
    }
}

I'm expecting my resultant HTML (via https://app1.domain.com) to be rewritten without the subfolder /myapp/, so when assets are requested they can be found instead of a 404 against https://app1.domain.com/myapp/assets/. It should just be https://app1.domain.com/assets/ (which if I manually go there they work)
--thanks.

A: Feeding from Ivan's response and finalizing my solution as:
server {
    listen       443 ssl;
    server_name  app1.domain.com;
    location / {
        sub_filter '/myapp/'  '/'; # rewrites HTML strings to remove context
        sub_filter_once off; # ensures it loops through the whole HTML (required)
        proxy_pass http://localhost:8080/myapp/;
    }
}

A: As nginx proxy_pass documentation states:

In some cases, the part of a request URI to be replaced cannot be determined:
...
When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):
location /name/ {
    rewrite    /name/([^/]+) /users?name=$1 break;
    proxy_pass http://127.0.0.1;
}

In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

So with this configuration block after you rewrite /myapp/assets/some_asset URI to /assets/some_asset and use a break flag, nginx ignores /myapp/ suffix on a proxy_pass directive and passes /assets/some_asset request to your backend. However strange it is, what you need is to use this rewrite rule instead:
rewrite ^(/myapp/.*)$ $1 break;

Another (may be even better) solution is to use two location blocks:
location / {
    proxy_pass http://localhost:8080/myapp/;
}
location /myapp/ {
    proxy_pass http://localhost:8080;
}


text:
Q: Stacked column not lining up with highcharts I am using highcharts to plot to series of data. However, I'm having a problem lining up the series on top of each other as the columns are very slightly misaligned. My code is as follows:
<!DOCTYPE html>

    <button type="button" id="button-1" onclick="updateCharts()">Update chart</button>

To illustrate the problem I am adding a series of data to the chart each time the button is pressed, and the current data is on the left hand side. I want to use the same color for each column, and just to demarcate the spaces in the bar using a line. But, the column stacks appear to be very slightly misaligned and I'm not sure why.

EDIT: I've included a link to a fiddle, but strangely this problem does not exist here.

A: If the borders are giving issues, you might want to try using a 1px height background image to show the seperation between the bars. I know it's not the ideal situation but eventually it might solve the issue after all.


text:
Q: Overriding a property value in custom JSON.net contract resolver I am attempting to implement a custom JSON.net IContractResolver that will replace all null property values with a specified string. I'm aware that this functionality is available via attributes on member of types that get serialized; this is an alternative route that we're considering.
My resolver implementation so far is as follows. StringValueProvider is a simple implementation of IValueProvider that doesn't affect the problem, which is that I can't figure out how to get the value of property as I have no knowledge in this method of the instance that supplied member so I can't pass it in as an argument to GetValue() (marked as WHAT-GOES-HERE? in the code sample).
Is there a way that I can get what I need from member or from property?
public class NullSubstitutionPropertyValueResolver : DefaultContractResolver
{
    private readonly string _substitutionValue;

    public NullSubstitutionPropertyValueResolver(string substitutionValue)
    {
        _substitutionValue = substitutionValue;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty result = base.CreateProperty(member, memberSerialization);

        PropertyInfo property = member as PropertyInfo;

        if (property == null)
        {
            return result;
        }

        // What do I use here to get the property value?
        bool isNull = property.GetValue(WHAT-GOES-HERE?) == null;

        if (isNull)
        {
            result.ValueProvider = new StringValueProvider(_substitutionValue);
        }

        return result;
    }
}

A: The contract resolver is not concerned with instances, it is concerned with types.  The value provider is concerned with instances.  In the contract resolver, you decide whether the value provider should be applied to the property based on the property type (for example, maybe you only want to use a StringValueProvider on string properties?)  Then, you make the value provider store a reference to the property (pass it in the constructor along with the substitution value).  In the value provider, you can read the value from the object instance, check if it is null and do the appropriate value substitution.
The code should look something like this:
public class NullSubstitutionPropertyValueResolver : DefaultContractResolver
{
    private readonly string _substitutionValue;

    public NullSubstitutionPropertyValueResolver(string substitutionValue)
    {
        _substitutionValue = substitutionValue;
    }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty result = base.CreateProperty(member, memberSerialization);

        PropertyInfo property = member as PropertyInfo;

        if (property.PropertyType == typeof(string))
        {
            result.ValueProvider = new StringValueProvider(property, _substitutionValue);
        }

        return result;
    }
}

public class StringValueProvider : IValueProvider
{
    private PropertyInfo _targetProperty;
    private string _substitutionValue;

    public StringValueProvider(PropertyInfo targetProperty, string substitutionValue)
    {
        _targetProperty = targetProperty;
        _substitutionValue = substitutionValue;
    }

    // SetValue gets called by Json.Net during deserialization.
    // The value parameter has the original value read from the JSON;
    // target is the object on which to set the value.
    public void SetValue(object target, object value)
    {
        _targetProperty.SetValue(target, value);
    }

    // GetValue is called by Json.Net during serialization.
    // The target parameter has the object from which to read the value;
    // the return value is what gets written to the JSON
    public object GetValue(object target)
    {
        object value = _targetProperty.GetValue(target);
        return value == null ? _substitutionValue : value;
    }
}

Here is a working demo: https://dotnetfiddle.net/PAZULK


text:
Q: Count every day entry I want to count all register users each day from past 30 days. If there is no registration return 0
Currently i'm using this
    $startDate = Carbon\Carbon::now()->subDays(30);
    $signup = User::where('created_at', '>=', $startDate)
        ->groupBy('date')
        ->orderBy('date', 'DESC')
        ->get([
            DB::raw('Date(created_at) as date'),
            DB::raw('COUNT(*) as value')
        ]);
    return $signup;

Current output
[
  {
    "date" : "2014-05-29",
    "value" : 1
  },
  {
    "date" : "2014-05-15",
    "value" : 1
  }
]

If there is no registration then display value 0 for example
[
  {
    "date" : "2014-05-29",
    "value" : 1
  },
  {
    "date" : "2014-05-28",
    "value" : 0
  },
  {
    "date" : "2014-05-27",
    "value" : 0
  },
  {
    .....
    .....
  },
  {
    "date" : "2014-05-15",
    "value" : 1
  }
  {
    "date" : "2014-05-14",
    "value" : 0
  }
]

How can I get such result.

A: Put the $result array in another array value by value,  and if lastrowdate - rowdate > 1 day, use this function to fill up the empty dates:
https://stackoverflow.com/a/4312491/3696548


text:
Q: How to compile actionscript worker swf in FlashDevelop I already know the coding part of actionscript worker. Recently I switched my IDE to FlashDevelop. I can't figure out how to compile actionscript worker swf in FlashDevelop.
I try to use Tools - Flash Tools - Build current file. But it throws error saying
Error: Type was not found or was not a compile-time constant: File.
Maybe it is because my project is a AIR project and I use AIR API in my worker.
I also try to compile worker swf using amxmlc via command line. It compiles successfully. But AIR Debug Launcher crashes when executing worker swf part. The swf which I compiled manually is nearly half size of the former one that Flash Builder generated for me. I guess I compiled a release version swf so that ADL can't debug and then crashed.
So how do I compile a worker swf in FlashDevelop to debug or to publish a release of project?

Update:
I find that the "Build current file" command in menu is a feature in FlashDevelop called quick build. By default, it will compile current file output to project root directory without arguments. We can add compiler arguments using @mxmlc ASDoc tag (see the links below for detail) to make it compile a worker swf for us. But currently in FD 5.0.1 it seems to be a bug that @mxmlc +configname=air doesn't compile air swfs. I find a workaround using @mxmlc -noplay -library-path=[Flex_SDK]\frameworks\libs\air\airglobal.swc -library-path=[Flex_SDK]\frameworks\libs\air\airframework.swc, but the path can't be surrounded with quote otherwise FD will show an error. I may look into the source and try to fix it.
links:

*

*AS3 Quick Build documentation

*Quick Build

*FlashDevelop: Compiling Multiple SWF In One Project

A: Compiling a worker is no different from compiling any swf, you will need a separate project to compile the worker, unless your main worker loads itself as a worker.
Since FlashDevelop does not manage dependencies beetween projects, you will have to compile it manually, then the main worker.
You may automate it with make or any build system outside FlashDevelop, or use Pre/Post build command lines
By the way amxmlc is just a shortcut for 'mxmlc +configname=air', -debug=true will compile debug version
I can assure you that File can be used in a worker, basically it's just some actionscript bytecode loading some other actionscript bytecode and having it run in a separate thread, so any swf can be used as a worker, except if it doesn't use flash.system.Worker class, it won't be able to communicate with other workers, or to stop itself.
To sum up, the limitations and issues are rather about communicating beetween threads and synchronizing them. For instance, being able to only copy complex objects through AMF3 serialization,pass only basic types/objects as parameters  will makes it impossible to interact with the display list from non-main workers
Dont forget to update FlashDevelop /AIR SDK for best workers support


text:
Q: How to upload a Codeigniter server to localhost in Tomcat? An attempt was made to upload a CodeIgniter server to localhost.
Below is the part that took the setting
application/config/config.php
$config['index_page'] = 'index.php';
$config['base_url'] = 'http://localhost:8080/ci/';

application/config/database.php :
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'mysql',
    'database' => 'mysql',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'port' => '8080',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

enter image description here
I'm not sure what went wrong during setup. Give me advice if you have the same mistakes as me, or someone who has solved these problems.


text:
Q: I think I bricked my SSD and my laptop won't turn on (reposting from the electronics stackexchange) I am not exactly sure where to post this as a lot of things happened so I'll just go through everything.

*

*I tried installing Gentoo

*I typed "emerge-webrsync"

*My laptop shut off.
4.I tried turning it back on and nothing happened. No light just a 'shuck' sound where the SSD is. I can't boot to BIOS. Nothing happens except that sound.

*I removed the SSD and plugged it into my desktop and now the desktop isnt turning on as well. No fan spin. No light. Nothing. Even if I remove it nothing happens.

I'm scared. What can I do? Repair shop?
If you need to know my hardware, my laptop is a Dell Vostro 5990. I have no idea how gentoo could have caused this. I just typed the command, grabbed a glass of water and it died.

A: There are two paths to take. Given that you are scared, I suggest the first one since it is the easiest and most likely to help:
Take it to repair. Contact Dell to find an Authorized Repair Center near you or send it to them for service.
The other is debug this by asking a series of questions, trying different things until your problem is either fixed or giving up. That's good to learn but will cost you a lot more in time than it will save in money. If you want, start by asking yourself: What is the worse that could happen? If it is mostly replacing an SSD because you have your important and irreplaceable data backed up, go ahead and try these things:

*

*Place the SSD in an external USB enclosure and connect it to your desktop. In the best case scenario, it will mount automatically and you can access your data that way. This is unlikely but it is important to try this first as it will give you a hint as to what happened:

*If you mounted the SSD and it does absolutely nothing. Nothing lights up, even for a brief moment, then you have a dead SSD. Nothing to do but to replace it. The command you typed itself is not directly the issue but if your SSD was faulty and about to die, installing a distro which requires plenty of I/O likely precipitated the issue.

*If the enclosure lights up but the SSD does not mount, open a disk partitioning tool such as GParted. The drive may show up there as unallocated or unpartitioned space. This is a good sign. Sometimes disks get formatted in a way that is not compatible between systems and so you will not be able to read data from it without repartioning and therefore losing all your data.   This can happen because the controller logically maps sector sizes while the other system does not. It is also possible that you cannot read the drive data because it is an encrypted disk and the key is in the firmware of your laptop. If that is the case, then you'll have to get support from Dell. This is most likely since you have a business laptop.

*If the disk appears but you cannot write to it or even partioning is disabled, then the disk is probably dead.

*If the disk appears with an accessible partition, you can try to repair it by running fsck or another similar file-system checker tool. Afterwards, you should definitely check with smartmon/smartctl to verify that the disk is not dying anyway and have to repeat the ordeal soon after.


text:
Q: Visual Studio MVC HTML Web Address So I can make an address like
www.mysite.com/person
But how can I make it so that it's like
www.mysite.com/person/john-bishop
I guess I need both ID and name, in case there are multiple john bishops?
This is what I got so far
public ActionResult Person(int id, string name)
{
    return View();
}

A: You need add an Id or unique identifier at the end.
www.mysite.com/person/john-bishop-1
www.mysite.com/person/john-bishop-2

and the RouteConfig
   routes.MapRoute("Person", "Person/{name}-{id}", new { controller = "Person", action = "Person" });


text:
Q: Limit Supremum - limit of a product Few days ago I asked about the meaning of  $$\limsup _{h\rightarrow \infty}\;\sup_{x\in \mathbb R}\; A(x,h)$$  being finite, and I got the answer. Now I'm facing another situation.
Given that $A(x,h)$ and $B(x,h)$ are two positive functions in $x$ and $h$, is it true that
$$\limsup _{h\rightarrow \infty}\;\sup_{x\in \mathbb R}\; \bigg (A(x,h)B(x,h)\bigg )\leq \bigg (\limsup _{h\rightarrow \infty}\;\sup_{x\in \mathbb R}\;A(x,h)\bigg )   \; \bigg (\limsup _{h\rightarrow \infty}\;\sup_{x\in \mathbb R}\;B(x,h)\bigg ) $$
I feel it is correct! The same inequality is true for two bounded nonegative real sequences, as I know.
Note: It is known that both of the limits in the RHS exist and nonnegative.

A: First, since $\{A(x,h).B(x,h); x\in\mathbb R\} \subseteq \{A(x,h).B(x',h); x,x'\in\mathbb R\}$, you get that $\sup_x A(x,h).B(x,h)\le \sup_x A(x,h).\sup_x B(x,h)$. (Supremum of a subset is less or equal to the supremum of the whole set.)
This yields
$$\limsup_{h\to\infty}\sup_x A(x,h).B(x,h)\le
\limsup_{h\to\infty}\left(\sup_x A(x,h).\sup_x B(x,h)\right).$$
So it remains to show that $\limsup_{h\to\infty}\left(\sup_x A(x,h).\sup_h B(x,h)\right) \le
\limsup_{h\to\infty} \sup_x A(x,h).\limsup_{h\to\infty} \sup_x
B(x,h)$ which is a special case of
$$\limsup_{h\to\infty} f(h).g(h) \le \limsup_{h\to\infty} f(h). \limsup_{h\to\infty}
g(h),$$ which is true for any positive functions $f$ and $h$ with
finite limit superior.
Proof: Just notice that for any positive $\varepsilon>0$ there is
an $h_0$ such that
$$h\ge h_0 \Rightarrow g(h)\le \limsup_{h\to\infty}
g(h)+\varepsilon.$$ Thus $$\begin{align*}\limsup_{h\to\infty} f(h).g(h) &\le
\limsup_{h\to\infty} f(h).(\limsup_{h\to\infty} g(h)+\varepsilon) \\ &=
\limsup_{h\to\infty} f(h).\limsup_{h\to\infty} g(h)+
\limsup_{h\to\infty} f(h).\varepsilon.\end{align*}$$ Since
$\limsup_{h\to\infty} f(h)<+\infty$ and the last inequality holds
for any $\varepsilon$, we get that
$$\limsup_{h\to\infty} f(h).g(h) \le \limsup_{h\to\infty} f(h). \limsup_{h\to\infty}
g(h).$$
Right now, I am not sure about the case when one of the limits superiors is infinite. I hope I did not make a mistake in the above proof.
Note that the proof is very similar to the proof of subadditivity of limit superior:
$$\limsup f(h)+g(h)\le \limsup f(h)+\limsup g(h).$$
(It can even be probably deduced from this inequality, if you prefer this approach.)

EDIT: I found in the book Wieslawa J. Kaczor, Maria T. Nowak: Problems in mathematical analysis, Volume 1 as Problem 2.4.17 the following:

Let $(a_n)$, $(b_n)$ be sequences of nonnegative numbers. Prove that (excluding the indeterminate forms of the type $0.(+\infty)$
  and $(+\infty).0$) the following inequalities hold:
  $$
\begin{align*}
\liminf a_n \cdot \liminf b_n &\le \liminf (a_n\cdot b_n) \le \\
\liminf a_n \cdot \limsup b_n &\le \limsup (a_n\cdot b_n) \le \limsup a_n \cdot \limsup b_n
\end{align*}
$$

So if you have access to that book, you can look up the proof there. (Although I have only seen some parts from this 3 volume set, I can say that I like the selection of the material.)


text:
Q: De Morgan's Law Is it correct to say that de Morgan's Law is one of an isomorphism of classical logic?
I think it is.
(A bit meta, but is this question an appropriate one for this site?)

A: You're basically right, but "an isomorphism of classical logic" is a bit vague. An isomorphism is between two objects. De Morgan's Laws provide an isomorphism between a Boolean algebra and its dual.
Let $B$ be a set and $\lor$ and $\land$ binary operations on $B$, and assume that for some unary operation $\neg$ on $B$ de Morgan's Laws hold, i.e.
$$
\begin{align}
\neg(a\lor b)=(\neg a)\land(\neg b)\;,
\\
\neg(a\land b)=(\neg a)\lor(\neg b)\;.
\end{align}
$$
for all $a,b\in B$. Then if $f:B\to B$ with $f(b)=\neg b$ is bijective, it provides an isomorphism between $(B,\lor,\land)$ and $(B,\land,\lor)$ in the sense that it is a bijection that respects the respective binary operations. In particular, if $(B,\lor,\land)$ is a Boolean algebra, then its dual $(B,\land,\lor)$ is also a Boolean algebra, and de Morgan's Laws provide an isomorphism between the two.

A: It definitely is an isomorphism. Of interest is that ¬ is its own inverse. Once you prove one of De Morgan's statements, you have established the isomorphism, and the other statement follows immediately, since it is just a statement of the isomorphism going in the other direction.  In fact, if you have an equivalence relation using only ¬, ∨, and ∧, you can negate both sides of the equivalence and, by repeated use of De Morgan's laws, end up with an equivalence identical to the original, but with ∨ and ∧ reversed.  Of course all the variable will be negated, but that is the same as having none of them negated.  As an example, once you have proved one of the distributive laws for ∨ and ∧, the other follows immediately.


text:
Q: AS3: getCharBoundaries() returns null I've been seeing this issue on and off when I use getCharBoundaries() and I'm not quite sure what's causing it. Some text I have is completely okay with it, other times it throws a fit.
Here's my code
while (copy.text.indexOf("{") != -1) //copy is a proprietary textnode type object
{
    var char:String = "tf"

    var searchString:String = "{" + char + "}";
    var index:int = copy.text.indexOf(searchString);

    var bounds:Object = copy.content.getCharBoundaries(index); //content is a flash textField
    //sprite is created elsewhere, it is not the issue
    sprite.x = copy.x + bounds.x + 4; //here we sometimes get the error that bounds is null
    sprite.y = copy.y + bounds.y - 2;

    //replace the string we used with characters that are easy to hide with the sprite and take up a decent width
    copy.text = copy.text.replace(searchString, "---" );
}

The one that breaks has 2 of the sub-strings we want to remove (called "{tf}". The 2nd one always breaks, even if I remove the first one from the string entirely. The string is not something I can post publicly as it is part of work, but suffice it to say that there are two paragraphs separated by 1 line (that is, two "returns" were typed into it). However, if I remove all of the returns, the 2nd one STILL breaks.
As much as my research has told me, it's just that getCharBoundaries() doesn't like certain characters -- punctuation most of the time -- but 99% of the time when I pass in a string, it works fine. I was hoping someone could possibly explain why getCharBoundaries() returns null (the documentation does not explain this) and what I can do to fix it.
I've tried to get all the indexes BEFORE replacing the string, but i ran into the same issues

A: Here's the issue we managed to solve. After trying to get a symbol on every line, we found it breaking after the 3rd line every time.
This helped us figure out that our textfield was too small. getCharBoundaries() is trying to find a relative point in space beyond it's width and height, and it doesn't like that. The text was spilling out of the textfield, as it is made to do, so the height of the textfield is never an issue for us until now. For all we knew, the textfield's boundaries were as large as the text appeared, but this was not the case.

A: One thing you could do if creating a textfield dynamically, is add an enterframe listener, to essentially skip to the next frame, where the textfield will be updated with the new height and width parameter.
addEventListener(Event.ENTER_FRAME, validate);

private function validate(e:Event):void
{
   removeEventListener(Event.ENTER_FRAME, validate);
   txt.getCharBounds(yourIndexHere);

}