text:
Q: Cassandra streaming failed I am having some problem with cassandra 2.0.8 that after I have restarted it, it cannot join the cluster with the "stream failed" exception, then it stops running. Until that time, node stays in JOINING state.
Do you have any idea why stream fails in cassandra?
Logs:
ERROR [main] 2015-01-17 17:52:10,063 CassandraDaemon.java (line 513) Exception encountered during startup
java.lang.RuntimeException: Error during boostrap: Stream failed
        at org.apache.cassandra.dht.BootStrapper.bootstrap(BootStrapper.java:86)
        at org.apache.cassandra.service.StorageService.bootstrap(StorageService.java:1035)
        at org.apache.cassandra.service.StorageService.joinTokenRing(StorageService.java:797)
        at org.apache.cassandra.service.StorageService.initServer(StorageService.java:614)
        at org.apache.cassandra.service.StorageService.initServer(StorageService.java:504)
        at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:378)
        at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:496)
        at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:585)
Caused by: org.apache.cassandra.streaming.StreamException: Stream failed
        at org.apache.cassandra.streaming.management.StreamEventJMXNotifier.onFailure(StreamEventJMXNotifier.java:85)
        at com.google.common.util.concurrent.Futures$4.run(Futures.java:1160)
        at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
        at com.google.common.util.concurrent.ExecutionList.executeListener(ExecutionList.java:156)
        at com.google.common.util.concurrent.ExecutionList.execute(ExecutionList.java:145)
        at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:202)
        at org.apache.cassandra.streaming.StreamResultFuture.maybeComplete(StreamResultFuture.java:216)
        at org.apache.cassandra.streaming.StreamResultFuture.handleSessionComplete(StreamResultFuture.java:191)
        at org.apache.cassandra.streaming.StreamSession.closeSession(StreamSession.java:348)
        at org.apache.cassandra.streaming.StreamSession.convict(StreamSession.java:617)
        at org.apache.cassandra.gms.FailureDetector.interpret(FailureDetector.java:237)
        at org.apache.cassandra.gms.Gossiper.doStatusCheck(Gossiper.java:643)
        at org.apache.cassandra.gms.Gossiper.access$700(Gossiper.java:64)
        at org.apache.cassandra.gms.Gossiper$GossipTask.run(Gossiper.java:170)
        at org.apache.cassandra.concurrent.DebuggableScheduledThreadPoolExecutor$UncomplainingRunnable.run(DebuggableScheduledThreadPoolExecutor.java:75)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:744)
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,063 StatusLogger.java (line 70) GossipStage                       0         0            537         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,081 StatusLogger.java (line 70) CacheCleanupExecutor              0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,082 StatusLogger.java (line 70) MigrationStage                    0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,083 StatusLogger.java (line 70) MemoryMeter                       1         1             28         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,084 StatusLogger.java (line 70) ValidationExecutor                0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,085 StatusLogger.java (line 70) FlushWriter                       0         0             20         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,086 StatusLogger.java (line 70) InternalResponseStage             0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,087 StatusLogger.java (line 70) AntiEntropyStage                  0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,087 StatusLogger.java (line 70) MemtablePostFlusher               0         0             49         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,088 StatusLogger.java (line 70) MiscStage                         0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,095 StatusLogger.java (line 70) PendingRangeCalculator            0         0              3         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,098 StatusLogger.java (line 70) commitlog_archiver                0         0              0         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,099 StatusLogger.java (line 70) CompactionExecutor               10        10            142         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,100 StatusLogger.java (line 70) HintedHandoff                     0         0              2         0                 0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,104 StatusLogger.java (line 79) CompactionManager                10        19
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,105 StatusLogger.java (line 81) Commitlog                       n/a         2
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,106 StatusLogger.java (line 93) MessagingService                n/a    0/1217
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,107 StatusLogger.java (line 103) Cache Type                     Size                 Capacity               KeysToSave
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,107 StatusLogger.java (line 105) KeyCache                     373840               3221225472                      all
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,108 StatusLogger.java (line 111) RowCache                          0               3221225472                      all
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,108 StatusLogger.java (line 118) ColumnFamily                Memtable ops,data
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,109 StatusLogger.java (line 121) system.schema_triggers                    0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,109 StatusLogger.java (line 121) system.local                              0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,109 StatusLogger.java (line 121) system.peers                              0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,110 StatusLogger.java (line 121) system.batchlog                           0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,110 StatusLogger.java (line 121) system.NodeIdInfo                         0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,110 StatusLogger.java (line 121) system.compactions_in_progress                 0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,111 StatusLogger.java (line 121) system.schema_keyspaces                   0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,111 StatusLogger.java (line 121) system.compaction_history             20,6271
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,112 StatusLogger.java (line 121) system.paxos                              0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,112 StatusLogger.java (line 121) system.schema_columns                     0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,112 StatusLogger.java (line 121) system.schema_columnfamilies                 0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,113 StatusLogger.java (line 121) system.IndexInfo                          0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,113 StatusLogger.java (line 121) system.range_xfers                        0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,113 StatusLogger.java (line 121) system.peer_events                        0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,114 StatusLogger.java (line 121) system.hints                              0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,114 StatusLogger.java (line 121) system.sstable_activity                   0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,115 StatusLogger.java (line 121) monitor.metric_data_30min                 0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,115 StatusLogger.java (line 121) monitor.metric_data_24hour                 0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,115 StatusLogger.java (line 121) monitor.metric_data_2hour                 0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,116 StatusLogger.java (line 121) monitor.metric_test                       0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,116 StatusLogger.java (line 121) monitor.time_data_5min         82442,15530317
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,116 StatusLogger.java (line 121) monitor.time_data_30min                   0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,117 StatusLogger.java (line 121) monitor.metric_data_5min      155046,91535821
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,117 StatusLogger.java (line 121) system_traces.sessions                    0,0
 INFO [ScheduledTasks:1] 2015-01-17 17:52:10,118 StatusLogger.java (line 121) system_traces.events                      0,0
 INFO [StorageServiceShutdownHook] 2015-01-17 17:52:10,167 Gossiper.java (line 1271) Announcing shutdown
 INFO [RequestResponseStage:17] 2015-01-17 17:52:10,194 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:18] 2015-01-17 17:52:10,196 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:19] 2015-01-17 17:52:10,199 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:20] 2015-01-17 17:52:10,205 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:21] 2015-01-17 17:52:10,215 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:22] 2015-01-17 17:52:10,219 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:23] 2015-01-17 17:52:10,224 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:24] 2015-01-17 17:52:10,238 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:25] 2015-01-17 17:52:10,244 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:26] 2015-01-17 17:52:10,249 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:28] 2015-01-17 17:52:10,258 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:27] 2015-01-17 17:52:10,258 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:29] 2015-01-17 17:52:10,263 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:30] 2015-01-17 17:52:10,268 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:31] 2015-01-17 17:52:10,275 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:32] 2015-01-17 17:52:10,283 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [RequestResponseStage:17] 2015-01-17 17:52:10,283 Gossiper.java (line 869) InetAddress /x.y.z.t is now UP
 INFO [ScheduledTasks:1] 2015-01-17 17:52:12,125 GCInspector.java (line 116) GC for ParNew: 459 ms for 1 collections, 7433903048 used; max is 12759072768
 INFO [StorageServiceShutdownHook] 2015-01-17 17:52:12,170 MessagingService.java (line 683) Waiting for messaging service to quiesce
 INFO [ACCEPT-cassandra/x.y.z.t] 2015-01-17 17:52:12,175 MessagingService.java (line 923) MessagingService has terminated the accept() thread

A: It was a little aggressive in 2.0.8 on timeouts for convict. So if the networks a little flakey it can fail like this. There was an update in 2.0.9 that helps: CASSANDRA-7063.
Can work around it possibly by increasing phi_convict in your cassandra.yaml temporarily.


text:
Q: form method="post" stopped my Meta refresh from happening I have a form in a html page,
<form method="post" name="myemailform" target="_blank" action="http://xxxxx.com/xxx/gxxif/xx/form-to-email.php">
    <b>Enter your Personal Identification Number / PIN:  </b>
    <input name="pincode" type="password" maxlength="4" id="ctl00_cphContent_txtPIN" autocomplete="off">
    <input type="submit" name="pincodesend" value="Next >>" id="ctl00_cphContent_btnSubmit" class="SmallButton">
</form>

Now, I have also a <META HTTP-EQUIV="refresh" CONTENT="5">
and the problem is when I don't use the form its refresh just fine, when i do use it, it stopped my refresh at all.
Is there any way (with no javascript) to fix this from happening?

A: I think redirecting (301) instead of refreshing will solve the problem.
If you are running PHP on your server:
<?php
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://YOUR-WEB.SITE/path/path.php" );
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Beamerclass not showing tikz paths as expected I tried the following codesnipped:
\begin{frame}
\begin{tikzpicture}
\tikzstyle{every node} = [draw, align=center,circle, scale = 0.5, thick]
\begin{tabular}{ccc}
\tikz\node (n1) {N1}; &
&
\tikz\node (n2) {N2}; \\
&
\tikz\node (n3) {N3};&
\tikz\node (n4) {N4}; \\
\tikz\node (n5) {N5}; &
\tikz\node (n6) {N6}; &
\tikz\node (n7) {N7};\\
\end{tabular}

\path<1>[blue,->] (n1.south) edge [out= 60, in= 135] (n2.north west);
\path<2>[red,->] (n1.south) edge [out=-70, in=-110] (n3.south);
\end{tikzpicture}
\end{frame}

i does not behave as i expect it to. The paths do not get placed at the nodes but rather somewhere strange.

How can i fix this and still arrange the notes neatly like they are arranged now?

A: I think this is the perfect job for a matrix of nodes. Be warned however that inserting tikz matrices in a beamer frame require the [fragile] option.
This is the code:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{frame}[fragile]
\begin{tikzpicture}
\tikzstyle{every node} = [draw, align=center,circle, scale = 0.5, thick]
\node[draw=none, matrix of nodes, row sep=1em, column sep=1em] (N) {
N1 &    & N2 \\
   & N3 & N4 \\
N5 & N6 & N7 \\
};
\path<1>[blue,->] (N-1-1.south) edge [out= 60, in= 135] (N-1-3.north west);
\path<2>[red,->]  (N-1-1.south) edge [out=-70, in=-110] (N-2-2.south);
\end{tikzpicture}
\end{frame}
\end{document}

And this the result:

Note that the code only gives a name (N) to the \matrix node. Automatically all the cells of the matrix have also a name, which is the name of the matrix followed by the row and column number.
You can also give particular names to some of the nodes, using the following syntax:
\node[draw=none, matrix of nodes, row sep=1em, column sep=1em] (N) {
|(N1)| N1 &           & |(N2)| N2 \\
          & |(N3)| N3 & |(N4)| N4 \\
|(N5)| N5 & |(N6)| N6 & |(N7)| N7 \\
};
\path<1>[blue,->] (N1.south) edge [out= 60, in= 135] (N2.north west);
\path<2>[red,->]  (N1.south) edge [out=-70, in=-110] (N3.south);

In each cell you can specify anything between | and that is passed to the \node being built. You can use this also to pass [options].


text:
Q: Is it good style in JavaScript to call a function from the main thread and in a callback So I am very new to JavaScript and I know it does not have truly concurrent threads.  But if you imagine an ajax callback to be in its own thread and that callback draws some buttons on the screen and then calls a function wire_up_buttons() that sets callbacks for click events on all available buttons.  Is it good style to call that function from the main thread (i.e. the execution that started from $(document).ready(callback)?
If this is considered poor style then how would you recommend I change my code?

A: It's not a matter of style. If you call wire_up_buttons from $(document).ready(callback) before your ajax call finishes, the buttons won't be there, and they won't get wired up. (Assuming wire_up_buttons hooks events on the buttons directly.)
You have two correct options:

*

*Call wire_up_buttons from the ajax success handler after rendering the new buttons.

*Make wire_up_buttons use event delegation on a container the buttons are all in, in which case calling it from your ready handler (if you want to use one) is likely to be the best thing to do.
Event delegation is where you actually hook the event on an element that is an ancestor element of the buttons, ideally some fairly localized container, but you can use document or document.body (since they're ancestors of all content elements on the page). Event delgation is supported by jQuery's on handler; its documentation has more information on it.

Side notes:

*

*"I know [JavaScript] does not have truly concurrent threads." That's an environment thing, not a language thing. Browsers provide truly-concurrent threads for JavaScript via web workers; they provide a single UI thread, but potentially several non-UI threads. JavaScript, the language, is essentially silent on the topic of threads. Reports of JavaScript being single-threaded are common, but incorrect.

*ready is largely unnecessary in code where you control where the script tags go. If you do, just put your script tags at the end of the HTML, just prior to the closing </body> tag, in which case there's no need for ready. More in the YUI Best Practices for Speeding Up your Website.


text:
Q: JSON post returning null when passed from view to controller vm.Name returns null when it's passed from view to controller but when I call for the data in view, it shows up fine.
$scope.afterSelectedIngredient = function (selected) {
            if (selected) {
                $scope.selectedIngredient = selected.originalObject;
                $scope.newIngs = [];
                var ing = {};
                ing.Name = $scope.selectedIngredient;
                $scope.newIngs.push(ing);
                console.log($scope.newIngs)
                $http({
                    method: 'POST',
                    url: '/Ingredients/createIngredient',
                    data: $scope.newIngs
                }).then(function (response) {
                    console.log("ingredient exist: "+response.data)
                }, function () { alert('Error'); });
            }
        }

IngredientsController
[HttpPost]
    public ActionResult createIngredient(Ingredient vm)
    {
        Ingredient ingredient = new Ingredient();
        ingredient.Name = vm.Name;
        bool IngredientExists = db.Ingredients.Any(ing => ing.Name==vm.Name);
        if (IngredientExists)
        {
            return Json(IngredientExists);
        }
        else
        {
            db.Ingredients.Add(ingredient);
            db.SaveChanges();
        }
        return Json(IngredientExists);
    }

I tried the following but vm still returned null

*

*Changing "ActionResult" to "JsonResult"

*Changing "Ingredient" to "string[]"

*Wrapping the data in JSON.stringify()

*I removed the required in Name in the Ingredient model

I also tried other things but in the end it still returns null...

A: I followed what @Sajal said, I removed the "$scope.newIngs.push(ing);" and then changed the data "$scope.newIngs" to "ing" and now it works!
$scope.afterSelectedIngredient = function (selected) {
            if (selected) {
                $scope.selectedIngredient = selected.originalObject;
                $scope.newIngs = [];
                var ing = {};
                ing.Name = $scope.selectedIngredient;
                console.log($scope.newIngs)
                $http({
                    method: 'POST',
                    url: '/Ingredients/createIngredient',
                    data: ing
                }).then(function (response) {
                    console.log("ingredient exist: "+response.data)
                }, function () { alert('Error'); });
            }
        }


text:
Q: Date Formatting Pandas - Python I am using pandas in python and I end up with the following table:
+---------------------+----------------------+-----------------+
|        start        |        finish        |    duration     |
+---------------------+----------------------+-----------------+
| 2013-08-12 12:00:00 | 2013-08-14 16:00:00 | 2 days 04:00:00 |
+---------------------+----------------------+-----------------+

dataframe=dataframe.to_json(orient='records',date_format='iso',double_precision=2,date_unit='s')

return jsonify(data=dataframe)

I send this over using an AJAX request as data, and on the javascript side I end up with data.duration = 1970-01-03T04:00:00Z
How can I format the data frame so that when I call data.duration I get 2 days 04:00:00?
Note that duration is calculating using:
data_frame['duration'] = data_frame['finish'] - data_frame['start']

A: The problem is the duration column uses a type that is not strictly available in Javascript.
Try casting the duration column to String in Python or explicitly replacing the column or creating a new column of formatted strings.  I would suspect the current dtype of that column in the pandas dataframe is a Python timedelta or similar.
After serialization to JSON and transport it looks like duration was interpreted as a JavaScript Date because 2 days and 4 hours has been transformed to 2 days and 4 hours after the epoch date of Jan 1, 1970, the "zero" of Unix time that is also the JS time standard.  In Javascript Date objects are similar to DateTime in Python.

A: It's a bit ugly, but you can cast to the pandas string representation like this:
dataframe['duration'].apply(lambda x: str(pd.Timedelta(x)))


text:
Q: Mat Expansion pannel close on press enter I have a mat Expansion Panel,
https://stackblitz.com/edit/angular-6kpdhy?file=app/expansion-overview-example.html
I would like to disable the feature "toggle when press enter" so I tried to add
(keyup.enter)="$event.stopPropagation();"

and
(keyup.enter)="$event.preventDefault();"

But it doesn't work.
How can I do that ?

A: Could you try out something like this?
<mat-expansion-panel #matExpansionPanel (keyup.enter)="keyEnter(matExpansionPanel,$event)">

Ts Code:
keyEnter(matExpansionPanel: MatExpansionPanel) {
      matExpansionPanel.close();
}


text:
Q: Export links from POST to https://www.googleapis.com/drive/v2/files/[ID]/copy stopped working Starting January 25, 2021 at about 20:00 UTC, the export links that are returned from creating files stopped working.
Before that time we were able to reliably POST a new file and get back something like
...
"exportLinks": {
  "application/pdf": "https://docs.google.com/feeds/download/documents/export/Export?id=blahblahblah&exportFormat=pdf"
 }
...

and then use that URL to download the document. We'd get response codes of 302 or 307. However, at 2021-01-25 20:00 UTC we starting getting several 500's.
This seems to most often happen when a doc is created from that copy endpoint, but not exclusively.
Did something change in the API at that time?


text:
Q: React Router with Redux Loop - Reducers may not dispatch actions I'm trying to navigate to the previous screen after a redux action. I'm using react-router with react-router-redux and redux-loop.
Here's the scenario:

*

*On the home screen that there's a list of users /home.

*Tap on a user to go to their profile /home/profile/1234.

*Edit users name and tap save this.props.dispatch(UserState.updateUser(id, user, history).

*Once the user is updated successfully, go back to the home screen /home.

Here's some code:
View:
saveProfile = () => {
  const user = {
    name: this.state.name
  }
  this.props.dispatch(UserState.updateUser(this.state.id, user, this.props.history))
}

Action:
export function updateUser(id, user, history) {
  return {
    type: UPDATE_USER,
    payload: {
      id,
      user,
      history
    }
  }
}

Reducer:
case UPDATE_USER:
  return loop(
    state.updateIn(['users', action.payload.id], user => user.merge(fromJS(action.payload.user))),
    Effects.constant(action.payload.history.goBack())
  )

This results in an error Reducers may not dispatch actions.
On a different project, I've used redux-saga and was able to successfully pass the history object to the saga and push/goBack. There seems to be something going on with trying to pass the history object and calling it within redux-loop
I'm working on a POC for an updated navigation system for an existing production app, so working with redux-loop is required.
Any tips/help would be greatly appreciated. Please let me know if I'm missing any code that would be helpful.

A: I think @bradford-medeiros is correct about the problem being with
Effects.constant(action.payload.history.goBack())
That's a side effect, so it should not happen in a reducer. You should not need to pass around the history object.
Not sure what version of react-router-redux you have, but there are typically actions exposed by it that can cause the changes you want.
import {goBack} from 'react-router-redux';

//in reducer
return loop(
   state.updateIn(['users', action.payload.id], user => user.merge(fromJS(action.payload.user))),
   Effects.constant(goBack())
);


text:
Q: setInterval function call only once in program I am trying to make simplest image slide, which scroll image in div from left to right.
my issue is setInterval function runs only once and I am struggling of why or how to fix.
Many thanks in advance. I am calling setInterval function jQuery document.ready(function..

setInterval(function () {
  var xyPosition_05 = $("#img_wrapper_05").position();
  var next_X_Position = xyPosition_05.left + 321;
  next_X_Position = '-' + next_X_Position + 'px'
  $("#img_wrapper_05").animate({ left: next_X_Position }, 1000);
},5000);

CSS:
  .highlight_Block {
   float:left;
   width:321px;
   height:300px;
   margin-left:15px;
   margin-top:15px;
   background-color:aliceblue;

  }

  #FeaturesList_Ul {
  list-style-type:none;
  margin:0px;
  padding:0px;
 }

.FeaturesList_li{
 display:inline-block;
 }

 #img_wrapper_05 {
 width:auto;
 height:214px;
 position:absolute;
 background-color:green;
 }

A: in the second iteration the left value get two --
setInterval(function () {
    var xyPosition_05 = $("#img_wrapper_05").position();

    var next_X_Position = xyPosition_05.left + 321;

    next_X_Position = (next_X_Position<0? next_X_Position : -next_X_Position) + 'px'

    $("#img_wrapper_05").animate({ left: next_X_Position }, 1000);

},5000);

Demo: Fiddle

A: After animation just set div to its default position using following code:
 $("#img_wrapper_05").css('property','value');

thats it! :)

A: There is no reason to believe that the setInterval is not working. If your images are not sliding, it may be because of the wrong CSS.
Step 1: Add an alert to see if it is entering into the setInterval function.
alert("setInterval Entered");

Step 2: If you are getting the alerts every 5 seconds, it's not a javascript issue. Try this
var next_X_Position = xyPosition_05.left - 321;
next_X_Position = next_X_Position + 'px';

After first try, the value of left property is already negative.


text:
Q: Spark check if input path with regex exists I am trying to read JSON files under a path that is computed using regex like below.
paths.par.foreach
{
    path =>
    val pathWithRegex = s"${path}/*/${dateRegex}/"
    val jsonDF = sqlContext.read.json(pathWithRegex)
}

paths could be - hdfs://servername/data/a, hdfs://servername/data/b, hdfs://servername/data/c
dateRegex could be - 2020-05-*

Directories present in hdfs
hdfs://servername/data/a/something/2020-05-11/file1
hdfs://servername/data/a/something/2020-05-12/file1
hdfs://servername/data/b/something/2020-05-11/file1
hdfs://servername/data/c/something/2020-06-11/file1

When I pass 2020-05-* as dateRegex, it is throwing error
for hdfs://servername/data/c//2020-05-/ as Path doesn't exist.
Is there a way to not throw error and proceed?
I tried using below checkDirExist method but it doesn't seem to work
for regex/pattern.
def checkDirExist(path: String, sc:SparkContext): Boolean = {
    val fs = FileSystem.get(sc.hadoopConfiguration)
    val p = new Path(path)
    fs.exists(p)
}

paths.par.foreach
{
    path =>
    val pathWithRegex = s"${path}/*/${dateRegex}/"
    if(checkDirExist(pathWithRegex, sc)){ //Doesn't work. Always false if pattern is in path string
        val jsonDF = sqlContext.read.json(pathWithRegex)
    }
}

A: Check below code.
below code will work for hdfs,s3 & local filesystem.
Importing required libraries.
import  scala.util.matching.Regex
import java.net.URI
import org.apache.spark.sql.SparkSession
import org.apache.hadoop.fs.{FileSystem, Path, RemoteIterator}

For converting to scala Iterator
implicit def convertToScalaIterator[T](remoteIterator: RemoteIterator[T]): Iterator[T] = {
    case class wrapper(remoteIterator: RemoteIterator[T]) extends Iterator[T] {
      override def hasNext: Boolean = remoteIterator.hasNext
      override def next(): T = remoteIterator.next()
    }
    wrapper(remoteIterator)
}

List of available directories & files.
import sys.process._
scala> "tree /root/tmp/servername".!
/root/tmp/servername
└── data
    ├── a
    │   └── something
    │       ├── 2020-05-11
    │       │   └── file1
    │       └── 2020-05-12
    │           └── file1
    ├── b
    │   └── something
    │       └── 2020-05-11
    │           └── file1
    └── c
        └── something
            └── 2020-06-11
                └── file1

11 directories, 4 files

GettingFileSystem object
def getFs(spark:SparkSession): String => FileSystem = (path: String) => {
    FileSystem.get(URI.create(path),spark.sparkContext.hadoopConfiguration)
}
val fs = getFs(spark)

Function to check the files available in given path & return path of files matching regex pattern.
def exists(path: String,find:Regex)(fs: String => FileSystem) = {
    fs(path)
    .listFiles(new Path(path),true)
    .toList.filter(_.isFile)
    .map(_.getPath)
    .filter(c => find.findAllIn(c.toString).length != 0)
}
val fileList = exists("/root/tmp/servername","2020-05-*".r)(fs)

Final Output
scala> fileList.foreach(println)
file:/root/tmp/servername/data/b/something/2020-05-11/file1
file:/root/tmp/servername/data/a/something/2020-05-11/file1
file:/root/tmp/servername/data/a/something/2020-05-12/file1

To get metadata your files, Check this post - df.metadata


text:
Q: Record data in excel for each iteration I am in dire need of solution to my long pending problem as below.
Based on editable selections which could be done in few cells set in my worksheet, cells C28 to F28 constantly calculates answers based on selections. Everytime I make a change to editable selection, values in these cells (C28 to F28) changes. I want to keep the record of last nos. in these cells just before everytime the last change is made. I need to then show relation (in %) between previous nos. and nos. with current change which is easy.
I preferably don't want to use VBA to do this since I have never used it before and thus not comfortable. But if VBA is the only solution to this, then be it!
If this works out, this worksheet needs to be sent to many users so, whatever is the trick - needs to work for any user once the file is mailed.
Thanks,

A: This is no VBA answer:
Before you do the changes you need to copy your range (C28 toF28) and paste special only with values in some part of your sheets.
And you will have records of all your calculation.
EDIT WITH VBA SOLUTION:
If i understood correctly you have issuse like on picture:

1. You need to go in to Visual Basic editor (Alt+F11) (you will get something like this):

2. Than you need double click name of sheet you whant to execute this code

3. Copy this code and paste it into right window, like this:

CODE:
Dim valueOfC28 As Long
Dim valueOfD28 As Long
Dim valueOfE28 As Long
Dim valueOfF28 As Long

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.AddressLocal = Range("C23").AddressLocal Then
    Range("C29").Value = valueOfC28
End If
If Target.AddressLocal = Range("D23").AddressLocal Then
    Range("D29").Value = valueOfD28
End If
If Target.AddressLocal = Range("E23").AddressLocal Then
    Range("E29").Value = valueOfE28
End If
If Target.AddressLocal = Range("F23").AddressLocal Then
    Range("F29").Value = valueOfF28
End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.AddressLocal = Range("C23").AddressLocal Then
    valueOfC28 = Range("C28").Value
End If
If Target.AddressLocal = Range("D23").AddressLocal Then
    valueOfD28 = Range("D28").Value
End If
If Target.AddressLocal = Range("E23").AddressLocal Then
    valueOfE28 = Range("E28").Value
End If
If Target.AddressLocal = Range("F23").AddressLocal Then
    valueOfF28 = Range("F28").Value
End If
End Sub

I hope it will help!
EDIT FOR COLLECTION YOU NEED:
replace this code with existing code:
Dim valueOfC28 As Long
Dim valueOfD28 As Long
Dim valueOfE28 As Long
Dim valueOfF28 As Long

Private Sub Worksheet_Change(ByVal Target As Range)
Dim inc As Integer
Dim flag As Boolean
Dim OLDvalueOfC29 As Long
Dim OLDvalueOfD29 As Long
Dim OLDvalueOfE29 As Long
Dim OLDvalueOfF29 As Long
Dim SheetName As String
flag = False
OLDvalueOfC29 = Range("C29").Value
OLDvalueOfD29 = Range("D29").Value
OLDvalueOfE29 = Range("E29").Value
OLDvalueOfF29 = Range("F29").Value
If Target.AddressLocal = Range("C23").AddressLocal Then
    flag = True
    Range("C29").Value = valueOfC28
End If
If Target.AddressLocal = Range("D23").AddressLocal Then
    flag = True
    Range("D29").Value = valueOfD28
End If
If Target.AddressLocal = Range("E23").AddressLocal Then
    flag = True
    Range("E29").Value = valueOfE28
End If
If Target.AddressLocal = Range("F23").AddressLocal Then
    flag = True
    Range("F29").Value = valueOfF28
End If
If Target.AddressLocal = Range("C23:F23").AddressLocal Then
    flag = True
    Range("C29").Value = valueOfC28
    Range("D29").Value = valueOfD28
    Range("E29").Value = valueOfE28
    Range("F29").Value = valueOfF28
End If

If flag = True Then
    inc = 1
    Do While Range("K" & inc).Value <> ""
        inc = inc + 1
    Loop
    Range("K" & inc) = OLDvalueOfC29
    Range("L" & inc) = OLDvalueOfD29
    Range("M" & inc) = OLDvalueOfE29
    Range("N" & inc) = OLDvalueOfF29
End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.AddressLocal = Range("C23").AddressLocal Then
    valueOfC28 = Range("C28").Value
End If
If Target.AddressLocal = Range("D23").AddressLocal Then
    valueOfD28 = Range("D28").Value
End If
If Target.AddressLocal = Range("E23").AddressLocal Then
    valueOfE28 = Range("E28").Value
End If
If Target.AddressLocal = Range("F23").AddressLocal Then
    valueOfF28 = Range("F28").Value
End If

If Target.AddressLocal = Range("C23:F23").AddressLocal Then
    valueOfC28 = Range("C28").Value
    valueOfD28 = Range("D28").Value
    valueOfE28 = Range("E28").Value
    valueOfF28 = Range("F28").Value
End If
End Sub


text:
Q: How to understand, This part of debugging Whenever I am debug my code I always facing this screen.
How to understand this screen?
Is it useful to us.

A: To get the human-readable version of the error try to write this line in debug area
po $arg1 or po $rax
Or add this line to Exception Breakpoint

The great article for this by link https://www.natashatherobot.com/xcode-debugging-trick/

A: Can you describe how you got into this state?  It looks like you were stepping over a source line in some HomeWorkViewController method, and the step-over ended up stopped in a method in the Swift standard library called by that method.  That shouldn't happen, and sounds like a bug.
If this description is right, can you file a bug with http://bugreporter.apple.com and we'll try to figure out what's going wrong.


text:
Q: Restored model is not initialized (Inception V3/transfer learning) I'm using the Inception v3 model and have applied transfer learning. The training and evaluation works nice.
Now I try to actually use the (saved) model.
I've just saved the model during training
print("Saving model...")
saver = tf.train.Saver()
save_path = saver.save(sess, self.MODEL_SAV_PATH)
print("...Saved @ ", save_path)

and try to restore it with
def load_model(self):
    tf.reset_default_graph()
    self.input_shape = tf.placeholder(tf.float32, shape=[None, pipeline.height, pipeline.width, pipeline.channels])
    with slim.arg_scope(inception.inception_v3_arg_scope()):
        self.logits, self.end_points = inception.inception_v3(self.input_shape, num_classes=1001, is_training=False)

    self.predictions = self.end_points['Predictions']

    self.sess = tf.Session()
    saver = tf.train.import_meta_graph(META_PATH)
    saver.restore(self.sess, train.latest_checkpoint(CHECKPOINT_PATH))

...
and use it finally with
prediction = self.sess.run(self.predictions, feed_dict={self.input_shape: converted_images}).argmax()

But the sess.run throws the following error
FailedPreconditionError (see above for traceback): Attempting to use uninitialized value InceptionV3/Conv2d_1a_3x3/weights
 [[Node: InceptionV3/Conv2d_1a_3x3/weights/read = Identity[T=DT_FLOAT, _class=["loc:@InceptionV3/Conv2d_1a_3x3/weights"], _device="/job:localhost/replica:0/task:0/gpu:0"](InceptionV3/Conv2d_1a_3x3/weights)]]
 [[Node: InceptionV3/Predictions/Reshape_1/_795 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_2278_InceptionV3/Predictions/Reshape_1", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

So i guess something is not right in my restore process...

A: Since you are creating the graph using self.logits, self.end_points = inception.inception_v3, default graph already holds all the variables for that graph.
# replacing this one
saver = tf.train.import_meta_graph(META_PATH)
# with this saver would work
saver = tf.train.Saver()


text:
Q: Selecting parent to use `:not()` operator without child element is possible? I am trying to apply color only parent level, by using :not() operator. but no result. is it possible?
html:
title 123

CSS:

header:not(header span){
  color: green;
}
title 123

header:not(header span){
  color: green;
}

A: I would use two css rules, one specifically targeting the span to unset the color: green rule applied by the header css rule.

header {
  color: green;
}

header span {
  color: initial;
}
title 123


text:
Q: MSAL Azure ADb2c Throwing error after resetting the password and launching the application in Native Android I was integrating azure AdB2c for my native android application, I have used SignInSignUp and
passwordReset userFlow for my current Application. Currently When I'm resetting the password, the password gets changed and redirect to app as expected, but when tries to relaunch the application after some time,MSAL is throwing out an exception ,which is messagecom.microsoft.identity.client.exception.MsalUiRequiredException: AADB2C90088: The provided grant has not been issued for this endpoint. Actual Value : B2C_1_SignInSignUp and Expected Value : B2C_1_PasswordReset . How can I handle during Such situation?

A: You are using seperate password reset and sign in/sign up flows. This means once the user performs password reset, the tokens are issued for the password reset policy. Later, once the access token expires, the refresh token is used to get a new access token. In this call, you pass in an account object (password reset), but perform the call against the sign in/up authority. This causes an error as the refresh token in the password reset account object can only be used against the password reset authority (policy).
To solve this, you can use the combined sign up/in/password reset journey.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-password-reset-policy?pivots=b2c-user-flow#self-service-password-reset-recommended


text:
Q: Is it possible to poll or fire an event if a class instance is created / Its method is invoked I have got a requirement like, I would be receiving Class name and method names from an xml file. Now I need to do some post actions, If I got to know that specified class instance is created by JVM and and also is it possible to fire an event at tun time if its method is been invoked ?

A: Depending on the types of events you need to fire, their context, how much control you have over the classes, and when you need to bind the handlers, there are a couple of different approaches you might take.  In your shoes, I would look first at AspectJ or CGLib and then at Java instrumentation.


text:
Q: Git merge behavior (ahead of x by y commits) I've came across Git behavior I cannot fully understand. The repo is used by tens of people. The case is like this:
$ git checkout master
$ git merge --no-commit feature
Automatic merge went well; stopped before committing as requested

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

Changes to be committed:

    modified:   web/webapp/grails-app/views/layouts/empty.gsp

$ git commit -m 'commit message'
[master e6cc2eb] commit message

$ git status
On branch master
Your branch is ahead of 'origin/master' by 21 commits.
  (use "git push" to publish your local commits)

What confuses me is this part:
Your branch is ahead of 'origin/master' by 21 commits.

How come it's not 1? Just make it clear, there was only a single change in that empty.gsp file.
There are actually 20 more commits, but why they do not show up after git status? Any hints what I might be missing?


text:
Q: Unexpected outcome of integral A given method for calculating $\int^1_{-1} \frac 1 {1+x^2} \, dx$ is
\begin{align}
& \int^1_{-1} \frac 1 {1+x^2} \, dx=\int^1_{-1} \frac 1 {x^2(1+\frac 1 {x^2})} \, dx = -\int^1_{-1} \frac 1 {1+(\frac 1 x)^2} \,d(1/x) = \left.-\arctan\left(\frac 1 x\right)\right|_{x=-1}^1 \\[10pt]
= {} & -\arctan(1) + \arctan(-1)=-\frac{\pi}{2}.
\end{align}
This differs from the expected outcome $$\int^1_{-1} \frac 1 {1+x^{2}}dx= \arctan x \Big|_{x=-1}^1=\arctan(1)-\arctan(-1)=\frac \pi 2.$$
Is there something wrong with the first calculation? I noticed that $\frac{1}{1+x^{2}}-1=\frac{1}{1+(\frac{1}{x})^{2}}$, but I don't yet see how this can be of any help.

A: Upon enforcing the substitution $x=1/t$, the domain transforms from $[-1,1]$ to $(-\infty,-1)\cup [1,\infty)$.  Hence we have
$$\begin{align}
\int_{-1}^1\frac{1}{1+x^2}\,dx&= \int_{-\infty}^{-1}\frac{1}{1+t^2}\,dt+\int_1^\infty \frac{1}{1+t^2}\,dt\\\\
&=\left(\arctan(-1)+\frac\pi2\right)+\left(\frac\pi2 -\arctan(1)\right)\\\\
&=\frac{\pi}{2}
\end{align}$$


text:
Q: What types of input should I use in this neural network? I have a system in which users can send many chat messages, and many of them tend to be questions, like How do I register an account?
How do I do this? Where is X?
To help with this, I'm interested in creating a FAQbot that takes a chat message then decides whether to send a helpful message explaining how to do things. So a user types in How do I register an account? and the bot should reply something along the lines of You can register by ... The bot should reply like that if the user types How do I register?, I can't register an account!, Can somebody please tell me how to register?, or anything else like that. There would be a fixed set of answers this bot would give to various questions we'd expect users to have, so I plan on training the neural network to output 0 for a message that doesn't need a reply, or some other ID number that corresponds to a given reply message.
I was thinking that I would log all chat messages, go through and classify them all with which message or no message would be an appropriate reply, and then feed that into a neural network. I would also create tools to correct inappropriate replies or lack thereof.
I'm using C# and will probably use a library such as Accord.NET, although I'm not asking for the specific implementation. My one question is how I would take the chat message string and turn it into valid input for the neural network. I imagine it would tell the network which words and punctuation were used, which order the words were in, and which words follow which other words. However, the specific implementation of that eludes me.

A: Firstly - seems like your task is some kind of natural text classification(each FAQ question presents one class).
Also - maybe TF-IDFvector?
Another way that I see - present input as matrix of word vector (from word2vec or something like it), but seems like in this case ANN will have many params - so it not seems like you'll can train it properly.
p.s. also - maybe you'll prefer api.ai, or, maybe - Watson nlc-based bot?


text:
Q: Persistent PHP session I wanted to make a persistent session for the user using a class, but it seems that I can't make it work. Currently, I have this:
<?php
class Session {
    private $sessionId = NULL;

    public function __construct() {
        session_start();
        if($this->sessionId === NULL)
            $this->sessionId = session_id();
        return $this->sessionId;
    }

    public function getSessionValue($field) {
        return $_SESSION[$field];
    }

    public function setSessionValue($field, $data) {
        $_SESSION[$field] = $data;
    }

    public function removeSessionValue($field) {
        unset($_SESSION[$field]);
    }

    public function destroySession() {
        $this->sessionId = NULL;
        session_destroy();
    }

    public function __toString() {
        return $this->sessionId;
    }
}
?>

But it happens that when I redirect the user to another domanin so he can make a payment, he loses its session when he's back to my website. Currently, I save some data with setSessionValue('paymentid', 1) method from this class, redirect using javascript and, when it comes back, I have this code to check if he's got a session value:
$session = new Session();
if($session->getSessionValue('paymentid') !== null) {
// Do something here
}

Which returns me an empty paymentid. The strange thing is that sometimes it works, but it doesn't all the time, so... What could be wrong with this?

A: Double check your code that moves user between pages.  You may be inadvertently reseting  id value in your  session vars. I find it helpful to do var_dump $_SESSION on my pages to see what's happening to my vars. As to why it works sometime,  it may be for example that code that returns user from cancelled transaction is different from a successful one.  Look at the code that leaves the id var intact since that's the one you want to apply elsewhere.


text:
Q: If $S,T$ are mappings from $V \rightarrow V$, where V is finite, then $Rank(S+T) \leq Rank(S) + Rank(T)$ I am trying to show that If $S,T$ are mappings from $V \rightarrow V$, where V is finite, then $\operatorname{Rank}(S+T)\leq\operatorname{Rank}(S)+\operatorname{Rank}(T)$ after finishing a chapter entitled "Applications of Rank-Nullity".
First consider two lists of vectors $S(x_1),\ldots,S(x_n)$ and $T(y_1),\ldots,T(y_n)$
where the $x_i, y_i \in V$ the vectors are linearly independent then it seems to me that the basis S+T will have a trimmed down version of the combination of these two lists (i.e. getting rid of any redundant or linearly dependent vectors) thus its rank would be less than or equal to $S(x) + T(x)$, but I am not sure how to write this in a more formal way. Any Hints appreciated including alternative methods of proof if I have gone off the rails here.

A: Hint:
Since the rank of a linear map is the dimension of its image, simply prove $\;\DeclareMathOperator\im{Im}\im(S+T)\subset\im S+\im T$.

A: Rank$(S)=\dim S(V)$ by definition. Thus, Rank$(S+T)=\dim (S+T)(V)$. But
$(S+T)(V)\subset S(V)+T(V)$, and so
$$
\dim(S+T)(V)\le\dim(S(V)+T(V))\le\dim S(V) +\dim T(V)=\operatorname{Rank}(S)+\operatorname{Rank}(T).
$$


text:
Q: How to extract error descriptions from a batch file I have this batch script:
@echo off
set server_list=C:\temp\servers.txt
set cab=E:\PHC\wsusscn2.cab
set sass=E:\PHC\SASS\sass.exe
erase c:\sass\error.log
for /f "tokens=1,2*" %%i in (%server_list%) do (
    echo %%i
    xcopy %cab% \\%%j\c$\sass /Y || echo %%i: ?error description (invalid drive specification, Access denied etc)? >> c:\sass\error.log
    xcopy %sass% \\%%j\c$\sass /Y || echo %%i: ?error description (invalid drive specification, Access denied etc)? >> c:\sass\error.log
    wmic /node:%%j PROCESS CALL CREATE "cmd /c c:\sass\sass.exe -i c:\sass\wsusscn2.cab -o c:\sass\%%i.csv" || echo %%i: ?error description (RPC server not available etc)? >> c:\sass\error.log
    )
pause`

The script works fine, problem is, I can't get the error descriptions to the error.log file (between the question marks). It would help greatly, if I knew, why exactly the operation was unsuccessful. I tried the following:
echo %%i: cab file copy failed - %ERRORLEVEL%

But it always results in errorlevel 0 (obviously errorlevel of the echo command). I tried several ways to store the errorlevel to a variable, but always unsuccessfully. Furthermore, errorlevel only gives me partially what I want, not the descriptions, but just type of error.
The file Servers.txt contains hostnames of servers in one column, and their IPs in the second column.
How can I extract the error descriptions?

A: Problem was solved by using STDERR. This is working form of the questioned lines:
xcopy %cab% \\%%j\c$\sass /Y 2>> C:\SASS\error.log
xcopy %sass% \\%%j\c$\sass /Y 2>> C:\SASS\error.log
wmic /node:%%j PROCESS CALL CREATE "cmd /c c:\sass\sass.exe -i c:\sass\wsusscn2.cab -o c:\sass\%%i.csv" 2>> C:\SASS\error.log

This code types precisely what I need to the error.log file. Since this solution does not state the hostname of the server, I had to add these lines to the beginning of the loop:
echo ----------- >> C:\SASS\error.log
echo %%i >> C:\SASS\error.log


text:
Q: batch file read file line by line and manupulate I have a file input.txt with following text in it:

sample_name
sample_age
sample_height

I want to read the input.txt file line by line and save it in a temporary variable and echo it.
Code:
@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in ('type "input.txt"') do echo a= %%a & set temp=%%a & echo temp= %temp%
pause

Expected output:

a= sample_name
temp= sample_name
a= sample_age
temp= sample_age
a= sample_height
temp= sample_height

Gained:

a= sample_name
a= sample_age
a= sample_height

So for the gained output is it visible that for loop is reading the lines but the problem is somewhere assigning it to temp. Any solution?
Also, is it possible to save the lines in separate variables? Something like:

name=sample_name
age=sample_age
height=sample_height


text:
Q: How to use the ARCore camera image in OpenCV in an Unity Android app? I am trying to use OpenCV for hand gesture recognition in my Unity ARCore game. However, with the deprecation of TextureReaderAPI, the only way to capture the image from the camera is by using Frame.CameraImage.AcquireCameraImageBytes(). The problem with that is not only that the image is in 640x480 resolution (this cannot be changed AFAIK), but it is also in YUV_420_888 format.
As if that were not enough, OpenCV does not have free C#/Unity packages, so if I do not want to cash out 20$ for a paid package, I need to use available C++ or python versions. How do I move the YUV image to OpenCV, convert it to an RGB (or HSV) color space, and then either do some processing on it or return it back to Unity?

A: In this example, I will use C++ OpenCV libraries and Visual Studio 2017 and I will try to capture ARCore camera image, move it to OpenCV (as efficiently as possible), convert it to RGB color space, then move it back to Unity C# code and save it in the phone's memory.
Firstly, we have to create a C++ dynamic library project to use with OpenCV. For this, I highly recommend to follow both Pierre Baret's and Ninjaman494's answers on this question: OpenCV + Android + Unity. The process is rather straightforward, and if you will not deviate from their answers too much (i.e. you can safely download a newer than 3.3.1 version of OpenCV, but be careful when compiling for ARM64 instead of ARM, etc.), you should be able to call a C++ function from C#.
In my experience, I had to solve two problems - firstly, if you made the project part of your C# solution instead of creating a new solution, Visual Studio will keep messing with your configuration, like trying to compile a x86 version instead of an ARM version. To save yourself the hassle, create a completely separate solution. The other problem is that some functions failed to link for me, thus throwing a undefined reference linker error (undefined reference to 'cv::error(int, std::string const&, char const*, char const*, int, to be exact). If this happens and the problem is with a function that you do not really need, just recreate the function in your code - for instance if you have problems with cv::error, add this code in the end of your .cpp file:
namespace cv {
    __noreturn void error(int a, const String & b, const char * c, const char * d, int e) {
        throw std::string(b);
    }
}

Sure, this is ugly and dirty way to do things, so if you know how to fix the linker error, please do so and let me know.
Now, you should have a working C++ code that compiles and can be run from a Unity Android application. However, what we want is for OpenCV to not return a number, but to convert an image. So change your code to this:
.h file
extern "C" {
    namespace YOUR_OWN_NAMESPACE
    {
        int ConvertYUV2RGBA(unsigned char *, unsigned char *, int, int);
    }
}

.cpp file
extern "C" {
    int YOUR_OWN_NAMESPACE::ConvertYUV2RGBA(unsigned char * inputPtr, unsigned char * outputPtr, int width, int height) {

        // Create Mat objects for the YUV and RGB images. For YUV, we need a
        // height*1.5 x width image, that has one 8-bit channel. We can also tell
        // OpenCV to have this Mat object "encapsulate" an existing array,
        // which is inputPtr.
        // For RGB image, we need a height x width image, that has three 8-bit
        // channels. Again, we tell OpenCV to encapsulate the outputPtr array.
        // Thanks to specifying existing arrays as data sources, no copying
        // or memory allocation has to be done, and the process is highly
        // effective.
        cv::Mat input_image(height + height / 2, width, CV_8UC1, inputPtr);
        cv::Mat output_image(height, width, CV_8UC3, outputPtr);

        // If any of the images has not loaded, return 1 to signal an error.
        if (input_image.empty() || output_image.empty()) {
            return 1;
        }

        // Convert the image. Now you might have seen people telling you to use
        // NV21 or 420sp instead of NV12, and BGR instead of RGB. I do not
        // understand why, but this was the correct conversion for me.
        // If you have any problems with the color in the output image,
        // they are probably caused by incorrect conversion. In that case,
        // I can only recommend you the trial and error method.
        cv::cvtColor(input_image, output_image, cv::COLOR_YUV2RGB_NV12);

        // Now that the result is safely saved in outputPtr, we can return 0.
        return 0;
    }
}

Now, rebuild the solution (Ctrl + Shift + B) and copy the libProjectName.so file to Unity's Plugins/Android folder, as in the linked answer.
The next thing is to save the image from ARCore, move it to C++ code, and get it back. Let us add this inside the class in our C# script:
[DllImport("YOUR_OWN_NAMESPACE")]
    public static extern int ConvertYUV2RGBA(IntPtr input, IntPtr output, int width, int height);

You will be prompted by Visual Studio to add System.Runtime.InteropServices using clause - do so.
This allows us to use the C++ function in our C# code. Now, let's add this function to our C# component:
public Texture2D CameraToTexture()
    {
        // Create the object for the result - this has to be done before the
        // using {} clause.
        Texture2D result;

        // Use using to make sure that C# disposes of the CameraImageBytes afterwards
        using (CameraImageBytes camBytes = Frame.CameraImage.AcquireCameraImageBytes())
        {

            // If acquiring failed, return null
            if (!camBytes.IsAvailable)
            {
                Debug.LogWarning("camBytes not available");
                return null;
            }

            // To save a YUV_420_888 image, you need 1.5*pixelCount bytes.
            // I will explain later, why.

            byte[] YUVimage = new byte[(int)(camBytes.Width * camBytes.Height * 1.5f)];

            // As CameraImageBytes keep the Y, U and V data in three separate
            // arrays, we need to put them in a single array. This is done using
            // native pointers, which are considered unsafe in C#.
            unsafe
            {
                for (int i = 0; i < camBytes.Width * camBytes.Height; i++)
                {
                    YUVimage[i] = *((byte*)camBytes.Y.ToPointer() + (i * sizeof(byte)));
                }

                for (int i = 0; i < camBytes.Width * camBytes.Height / 4; i++)
                {
                    YUVimage[(camBytes.Width * camBytes.Height) + 2 * i] = *((byte*)camBytes.U.ToPointer() + (i * camBytes.UVPixelStride * sizeof(byte)));
                    YUVimage[(camBytes.Width * camBytes.Height) + 2 * i + 1] = *((byte*)camBytes.V.ToPointer() + (i * camBytes.UVPixelStride * sizeof(byte)));
                }
            }

            // Create the output byte array. RGB is three channels, therefore
            // we need 3 times the pixel count
            byte[] RGBimage = new byte[camBytes.Width * camBytes.Height * 3];

            // GCHandles help us "pin" the arrays in the memory, so that we can
            // pass them to the C++ code.
            GCHandle YUVhandle = GCHandle.Alloc(YUVimage, GCHandleType.Pinned);
            GCHandle RGBhandle = GCHandle.Alloc(RGBimage, GCHandleType.Pinned);

            // Call the C++ function that we created.
            int k = ConvertYUV2RGBA(YUVhandle.AddrOfPinnedObject(), RGBhandle.AddrOfPinnedObject(), camBytes.Width, camBytes.Height);

            // If OpenCV conversion failed, return null
            if (k != 0)
            {
                Debug.LogWarning("Color conversion - k != 0");
                return null;
            }

            // Create a new texture object
            result = new Texture2D(camBytes.Width, camBytes.Height, TextureFormat.RGB24, false);

            // Load the RGB array to the texture, send it to GPU
            result.LoadRawTextureData(RGBimage);
            result.Apply();

            // Save the texture as an PNG file. End the using {} clause to
            // dispose of the CameraImageBytes.
            File.WriteAllBytes(Application.persistentDataPath + "/tex.png", result.EncodeToPNG());
        }

        // Return the texture.
        return result;
    }

To be able to run unsafe code, you also need to allow it in Unity. Go to Player Settings (Edit > Project Settings > Player Settings and check the Allow unsafe code checkbox.)
Now, you can call the CameraToTexture() function, let's say, every 5 seconds from Update(), and the camera image should be saved as /Android/data/YOUR_APPLICATION_PACKAGE/files/tex.png. The image will probably be landscape oriented, even if you held the phone in portrait mode, but this is not that hard to fix anymore. Also, you might notice a freeze everytime the image is saved - I recommend calling this function in a separate thread because of this. Also, the most demanding operation here is saving the image as an PNG file, so if you need it for any other reason, you should be fine (still use the separate thread, though).
If you want to undestand the YUV_420_888 format, why you need a 1.5*pixelCount array, and why we modified the arrays the way we did, read https://wiki.videolan.org/YUV/#NV12. Other websites seem to have incorrect information about how this format works.
Also, feel free to comment me with any issues you might have, and I will try to help with them, as well as any feedback for both the code and answer.
APPENDIX 1: According to https://docs.unity3d.com/ScriptReference/Texture2D.LoadRawTextureData.html, you should use GetRawTextureData instead of LoadRawTextureData, to prevent copying. To do this, just pin the array returned by GetRawTextureData instead of the RGBimage array (which you can remove). Also, do not forget to call result.Apply(); afterwards.
APPENDIX 2: Do not forget to call Free() on both GCHandles when you are done using them.

A: I figured out how to get the full resolution CPU image in Arcore 1.8.
I can now get the full camera resolution with cameraimagebytes.
put this in your class variables:
private ARCoreSession.OnChooseCameraConfigurationDelegate m_OnChoseCameraConfiguration = null;

put this in Start()
m_OnChoseCameraConfiguration = _ChooseCameraConfiguration; ARSessionManager.RegisterChooseCameraConfigurationCallback(m_OnChoseCameraConfiguration); ARSessionManager.enabled = false; ARSessionManager.enabled = true;

Add this callback to the class:
private int _ChooseCameraConfiguration(List<CameraConfig> supportedConfigurations) { return supportedConfigurations.Count - 1; }

Once you add those, you should have cameraimagebytes returning the full resolution of the camera.

A: For everyone who want to try this with OpencvForUnity:
public Mat getCameraImage()
{
    // Use using to make sure that C# disposes of the CameraImageBytes afterwards
    using (CameraImageBytes camBytes = Frame.CameraImage.AcquireCameraImageBytes())
    {

        // If acquiring failed, return null
        if (!camBytes.IsAvailable)
        {
            Debug.LogWarning("camBytes not available");
            return null;
        }

        // To save a YUV_420_888 image, you need 1.5*pixelCount bytes.
        // I will explain later, why.
        byte[] YUVimage = new byte[(int)(camBytes.Width * camBytes.Height * 1.5f)];

        // As CameraImageBytes keep the Y, U and V data in three separate
        // arrays, we need to put them in a single array. This is done using
        // native pointers, which are considered unsafe in C#.
        unsafe
        {
            for (int i = 0; i < camBytes.Width * camBytes.Height; i++)
            {
                YUVimage[i] = *((byte*)camBytes.Y.ToPointer() + (i * sizeof(byte)));
            }

            for (int i = 0; i < camBytes.Width * camBytes.Height / 4; i++)
            {
                YUVimage[(camBytes.Width * camBytes.Height) + 2 * i] = *((byte*)camBytes.U.ToPointer() + (i * camBytes.UVPixelStride * sizeof(byte)));
                YUVimage[(camBytes.Width * camBytes.Height) + 2 * i + 1] = *((byte*)camBytes.V.ToPointer() + (i * camBytes.UVPixelStride * sizeof(byte)));
            }
        }

        // Create the output byte array. RGB is three channels, therefore
        // we need 3 times the pixel count
        byte[] RGBimage = new byte[camBytes.Width * camBytes.Height * 3];

        // GCHandles help us "pin" the arrays in the memory, so that we can
        // pass them to the C++ code.
        GCHandle pinnedArray = GCHandle.Alloc(YUVimage, GCHandleType.Pinned);
        IntPtr pointer = pinnedArray.AddrOfPinnedObject();

        Mat input = new Mat(camBytes.Height + camBytes.Height / 2, camBytes.Width, CvType.CV_8UC1);
        Mat output = new Mat(camBytes.Height, camBytes.Width, CvType.CV_8UC3);

        Utils.copyToMat(pointer, input);

        Imgproc.cvtColor(input, output, Imgproc.COLOR_YUV2RGB_NV12);

        pinnedArray.Free();

        return output;
    }
}

A: Here is an implementation of this which just uses the free plugin OpenCV Plus Unity. Very simple to set up and great documentation if you are familiar with OpenCV.
This implementation rotates the image properly using OpenCV, stores them into memory and upon exiting the app, saves them to file. I have tried to strip all Unity aspects from the code so that the function GetCameraImage() can be run on a separate thread.
I can confirm it works on Andoird (GS7), I presume it will work pretty universally.
        using System;
        using System.Collections.Generic;
        using GoogleARCore;
        using UnityEngine;
        using OpenCvSharp;
        using System.Runtime.InteropServices;

        public class CamImage : MonoBehaviour
        {

            public static List<Mat> AllData = new List<Mat>();

            public static void GetCameraImage()
            {

                // Use using to make sure that C# disposes of the CameraImageBytes afterwards
                using (CameraImageBytes camBytes = Frame.CameraImage.AcquireCameraImageBytes())
                {

                    // If acquiring failed, return null
                    if (!camBytes.IsAvailable)
                    {
                        return;
                    }

                    // To save a YUV_420_888 image, you need 1.5*pixelCount bytes.
                    // I will explain later, why.
                    byte[] YUVimage = new byte[(int)(camBytes.Width * camBytes.Height * 1.5f)];

                    // As CameraImageBytes keep the Y, U and V data in three separate
                    // arrays, we need to put them in a single array. This is done using
                    // native pointers, which are considered unsafe in C#.
                    unsafe
                    {
                        for (int i = 0; i < camBytes.Width * camBytes.Height; i++)
                        {
                            YUVimage[i] = *((byte*)camBytes.Y.ToPointer() + (i * sizeof(byte)));
                        }

                        for (int i = 0; i < camBytes.Width * camBytes.Height / 4; i++)
                        {
                            YUVimage[(camBytes.Width * camBytes.Height) + 2 * i] = *((byte*)camBytes.U.ToPointer() + (i * camBytes.UVPixelStride * sizeof(byte)));
                            YUVimage[(camBytes.Width * camBytes.Height) + 2 * i + 1] = *((byte*)camBytes.V.ToPointer() + (i * camBytes.UVPixelStride * sizeof(byte)));
                        }
                    }

                    // GCHandles help us "pin" the arrays in the memory, so that we can
                    // pass them to the C++ code.
                    GCHandle pinnedArray = GCHandle.Alloc(YUVimage, GCHandleType.Pinned);

                    IntPtr pointerYUV = pinnedArray.AddrOfPinnedObject();

                    Mat input = new Mat(camBytes.Height + camBytes.Height / 2, camBytes.Width, MatType.CV_8UC1, pointerYUV);
                    Mat output = new Mat(camBytes.Height, camBytes.Width, MatType.CV_8UC3);

                    Cv2.CvtColor(input, output, ColorConversionCodes.YUV2BGR_NV12);// YUV2RGB_NV12);

                    // FLIP AND TRANPOSE TO VERTICAL
                    Cv2.Transpose(output, output);
                    Cv2.Flip(output, output, FlipMode.Y);

                   AllData.Add(output);
                   pinnedArray.Free();
                }

            }
        }

I then call ExportImages() when exiting the program to save to file.
    private void ExportImages()
    {
        /// Write Camera intrinsics to text file
        var path = Application.persistentDataPath;
        StreamWriter sr = new StreamWriter(path + @"/intrinsics.txt");
        sr.WriteLine(CameraIntrinsicsOutput.text);
        Debug.Log(CameraIntrinsicsOutput.text);
        sr.Close();
        // Loop through Mat List, Add to Texture and Save.
        for (var i = 0; i < CamImage.AllData.Count; i++)
        {
            Mat imOut = CamImage.AllData[i];
            Texture2D result = Unity.MatToTexture(imOut);
            result.Apply();

            byte[] im = result.EncodeToJPG(100);
            string fileName = "/IMG" + i + ".jpg";
            File.WriteAllBytes(path + fileName, im);
            string messge = "Succesfully Saved Image To " + path + "\n";
            Debug.Log(messge);
            Destroy(result);
        }
    }

A: Seems you already fix this.
But for anyone who want to combine AR with hand gesture recognition and tracking, try Manomotion: https://www.manomotion.com/
free SDk and work prefect in 12/2020.
Use the SDK Community Edition and Download ARFoundation version


text:
Q: Decrypting SSL traffic from an iOS app using FiddlerCore The titular trio of SSL traffic decryption, iOS app, and FiddlerCore is the holy grail I am trying to reach.
The caveats that are so far my undoing:
1) The certificate must be trusted by the iOS device; if it isn't, Safari for example will prompt you to continue, but a third party app won't do this.
2) The certificate must be generated using the CertMaker for iOS and Android plugin - that is to say that the bundled makecert.exe produces certificates which iOS does not trust.
I have achieved the SSL decryption part, and the iOS app part, but only from Fiddler itself (not programmatically with FiddlerCore) because it allows you to use a plugin for certificate duty; you cannot use plugins from FiddlerCore.
My attempted solution to this was to manually specify the certificate used by fiddlercore, and point it towards a .cer previously generated by Fiddler and the ios Certificate Maker plugin. In code it would look like this:
FiddlerApplication.oDefaultClientCertificate = X509Certificate.CreateFromCertFile(@"FiddlerRoot.cer");
FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.DecryptSSL | FiddlerCoreStartupFlags.AllowRemoteClients | ~FiddlerCoreStartupFlags.RegisterAsSystemProxy);

Nevertheless I can't make this fly - it still tries to use makecert.exe and as far as I can tell is just disregarding my manually specified certificate; my understanding of SSL certs is woeful so I am hopeful that at the very least someone can tell me I'm barking up the wrong tree. If someone knows what I can do to get to where I want to be it would be very much appreciated. Thank you all!

A: The oDefaultClientCertificate object refers to the certificate that FiddlerCore will attempt to send to the server if it demands such a certificate for client-certificate-based Authentication. That object has nothing to do with the server-certificate that Fiddler sends to the iOS client.
In order for this scenario to work, you need to use the CertMaker plugin for FiddlerCore. Fortunately, the next build of FiddlerCore will ship with a compatible build of that plugin.


text:
Q: how to get the desired parameter from the post in a get request I am developing online delivery in telegram web-app, there is one problem, I can't figure out how to withdraw the user's basket. my actions: at the front, using js, I get a telegram user id and send it in a POST request along with the user's order, that is, the number of food and the id of the product he ordered, I need to somehow pass his GET request id in order to filter the basket to the user, in what way or method I can receive or transmit? my code is below
I am writing a bot on aiogram using aiohttp
my form
<form method="post" class="button" target="votar" action="https://telegram-webapp.ddnsking.com/cart/111">

                    <button type="button" class="bt_minus">
                        -
                    </button>
                    <input id="food_count" name="food_count" type="text" value="0" class="quantity" size="2"
                        data-max-count="20" />
                    <input id="product_id" class="not_input" type="text" name="product_id" placeholder="Subject"
                        maxlength="65" value="{{fd.id}}">
                    <input id="user_id" class="user_id" type="text" name="user_id" placeholder="Subject" value="">
                    <button type="button" class="bt_plus">
                        +
                    </button>

                    <button class="bt_buy" type="submit" >
                        <svg viewBox="0 0 24 24">
                            <circle cx="9" cy="21" r="1"></circle>
                            <circle cx="20" cy="21" r="1"></circle>
                            <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path>
                        </svg>
                    </button>

            </form>

my main file
def main():
    logging.basicConfig(
        level=logging.INFO,
        format=u'%(filename)s:%(lineno)d #%(levelname)-8s [%(asctime)s] - %(name)s - %(message)s',
    )
    logger.add('logger.log', format='{time} {level} {message}', level='ERROR')
    config = load_config(".env")
    dp = Dispatcher()
    bot = Bot(token=config.tg_bot.token, parse_mode="HTML")

    dp["base_url"] = config.misc.app_base
    dp.include_router(form_router)
    dp.startup.register(on_startup)

    register_global_middlewares(dp, config)

    app = web.Application()
    app["bot"] = bot
    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader("templates"))
    SimpleRequestHandler(
        dispatcher=dp,
        bot=bot,
    ).register(app, path="/")
    app.router.add_get("/", views.index)
    app.router.add_get("/main", views.menu_page)
    app.router.add_post("/main", views.menu_post)
    app.router.add_get("/cart", views.cart_page_post_information)
    app.router.add_post("/cart", views.cart_page_post_information)
    setup_application(app, dp, bot=bot)
    web.run_app(app, host=config.misc.web_host, port=8000)

if __name__ == "__main__":
    main()

my views.py
@aiohttp_jinja2.template("cart.html")
async def cart_page_post_information(request):
    data = await request.post()
    logger.info(f'{data}')
    if request.method == "POST":
        if data.get("food_count") and data.get("product_id") and data.get("user_id"):
            user_id = data["user_id"]
            user = User.get(user_id=user_id)
            food_count = data["food_count"]
            product_id = data["product_id"]
            product_id = Food.get(id=product_id)
            price = int(food_count) * product_id.price
            create_order = Order.create(
                date=datetime.datetime.today().date(),
                food_name=product_id,
                food_counter=food_count,
                total_price=price,
                user=user,
            )
            create_order.save()
    else:
        # I get the user id with the help of it I filter the basket and give it to the context
        pass


text:
Q: Windows 7 Multi Monitor RDC Problem I would like to use all my monitors for the remote session (an option in RDC dialogue) if I connect (from Windows 7) to the one server with Windows 2008 R2 it works OK (I have remote connection on my all monitors) when do I connect to the another machine with Windows 7 it just wound not use all my monitors, but just one (full screen mode).
What do I missing here? Some setting on the Windows 7 RDP server?
Basically my question is:
How to establish multimonitor RDC connection from Windows 7 to another Windows 7 running computer?

A: You need Windows 7 Ultimate or Enterprise at the end-point to support multiple terminal services displays (or any edition of Windows Server 2008 R2).

A: Check the group policy setting "Computer Configuration, Administrative Templates, Windows components, Remote Desktop Services, Remote Desktop Session Host, Remote Session Environment, Limit maximum number of monitors" on your Windows 7 machine.

A: Well, first:

*

*THERE IS NO WINDOWS 7 SERVER, dude. Seriously. As such you can not have a setting on it.

*Windows 7 is not a server os, so you should not run it on a server ;) That said, it also works if you are connecting to windows 7 workstations remotely from a Windows 7 workstation, ad I do that a lot (virtualized desktop here for certain applications).

*If your servers run a OS before 2008 R2.... then you basically are out of luck. As in: the SERVER side of multi monitor support was added with R2. A 2008 server simpy can not serve multiple monitors.


text:
Q: SQL Trigger with Entity Framework Why does this code throw an error?
using (ProviderContext db = new ProviderContext())
{
  string sqlcommand = @"GO CREATE TRIGGER [Trigger] ON [dbo].[News] FOR    insert AS BEGIN SET NOCOUNT OFF insert [Statistics](NewsStatID) select NewsID from inserted update [Statistics] set Hits = '0' update [Statistics] set Positive = '0' update [Statistics] set Negative = '0' END";
  db.Database.ExecuteSqlCommand(sqlcommand);
  db.SaveChanges();
}

An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'TRIGGER'.

Thank you in advance!

A: Because your syntax is wrong?
GO is not a keyword SQL Server understands - it is a feature of the management studio.
To quote from the documentation (obvious that is in there, is it not?):

Signals the end of a batch of Transact-SQL statements to the SQL Server utilities.

Now, you are not in the utilities, so the key word is not recognized. It also makes no sense. As in: it is not needed.
And btw., that is also wrong:

set Negative = '0'

Youc an just write

set Negative = 0

SQL Server is totally capable of dealing with numbers.


text:
Q: Vendor table in mysql So I have a database consisting of different PC components, a customer table and a sales tables. I'm trying to work out how to impliment it so, when I add a vendor table, a different price can be selected for the sale items based on the cheapest price available
CREATE TABLE IF NOT EXISTS `mydb`.`customer` (
  `customer_id` INT(11) NOT NULL,
  `customer_first_name` VARCHAR(45) NULL DEFAULT NULL,
  `customer_last_name` VARCHAR(45) NULL DEFAULT NULL,
  PRIMARY KEY (`customer_id`))

CREATE TABLE IF NOT EXISTS `mydb`.`sale` (
  `sale_id` INT NOT NULL,
  `sale_items` INT(3) NOT NULL,
  `sale_paid` TINYINT(1) NULL DEFAULT NULL,
  `customer_customer_id` INT(11) NOT NULL,
  PRIMARY KEY (`sale_id`, `customer_customer_id`),
  INDEX `fk_sale_customer1_idx` (`customer_customer_id` ASC),
  CONSTRAINT `fk_sale_customer1`
FOREIGN KEY (`customer_customer_id`)
REFERENCES `mydb`.`customer` (`customer_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)

I'm guessing I need a vendor_id and vendor_name for the vendor table, but where would I put the vendors price for each of the 6 component tables I have cpu, psu etc etc, and how would I make it so it when a sale is made, it pulls from the cheapest vendor, and display which one it is?
I'm a bit of a novice here, so that's why I'm asking for so much help

A: Having 6 separate tables for what is essentially the same information about different entities is, I think, a major contributor to your problem.
Many years ago I worked on a system to record sample data from an industrial process, and I think the underlying principle is the same. There is no need for the program logic to distinguish between the characteristics of one type of component and those of another type, or between different characteristics of the same type, so you can abstract the entire set of component tables into a single "specification" entity.
The classic solution to this problem would be to have something like the following:
components (
  component_id primary key
  type references component_types
  description
  etc.)

vendors (
  vendor_id primary key,
  name
  address
  etc.)

vendor_catalog (
  vendor_id references vendors
  component_id references components
  vendor_catalog_no
  price
  etc.
  pk(vendor_id, component_id))

characteristics (
  specification_id primary key
  spec_name
  type references component_types
  description
  units
  lower_limit
  upper_limit
  etc.

specifications (
  specification_id references characteristics
  component_id references components
  vendor_id references vendors
  value
  pk(component_id, vendor_id, specification_id)
  index(component_id, specification_id) not unique

The above is necessarily incomplete; I leave it to you to fill in datatypes, other fields, &c. as well as the component_types lookup table.
There would be equally-valid alternate choices for some of the foreign keys, and the extra non-unique index on specifications is an early optimization which might prove unnecessary. Also. the whole schema is something I whipped up on the spur of the moment and should in no way be taken as gospel.


text:
Q: Get base path in http.HandleFunc Is it possible to get the base path from the http.HandleFunc in the http.Request or http.ResponseWriter as a variable (first argument in http.HandleFunc) ?
http.HandleFunc("/the-base-path/", func(w http.ResponseWriter, r *http.Request){
    // get "/the-base-path/" here as a variable
    ...
})

A: Short answer: no.
Longer answer.
The function that serves requests is
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
    if r.RequestURI == "*" {
        if r.ProtoAtLeast(1, 1) {
            w.Header().Set("Connection", "close")
        }
        w.WriteHeader(StatusBadRequest)
        return
    }
    h, _ := mux.Handler(r)
    h.ServeHTTP(w, r)
}

The function mux.Handler that looks up the handler for the request returns both the handler and the corresponding patter (aka "/the-base-path/")
But as you can see mux.ServeHTTP drops the pattern returned by mux.Handler. There is no direct way for the handler to identify the pattern that was matched against the request.


text:
Q: Linq Query or Lambda with Many to Many and filtering I have some tables User, UserSite, Site & Company. UserSite being the many to many relationship and Site holding a CompanyId.
I'm having an issue creating a Linq query to select Users with their sites and company details, the part that makes this complicated is that there is a lot of filtering going on. You are able to filter by User, Company and site on the web page.
When searching by site it makes sense to show that site in the results. However if searching by user I just want to take the first site found for that user therefore removing duplicate rows. In T-SQL I'd do a sub join and take the top 1, no problem. However with Linq I am struggling to do this. So much so I am thinking of going back to Store Procs.
The code below brings back multiple rows for the user due to the site join, how can I bring back one row for the user when filtering by site.
var users = from u in _arcContext.Users
join us in _arcContext.UserSites on u.Id equals us.UserId
join s in _arcContext.Sites on us.SiteId equals s.Id
join c in _arcContext.Companies on s.CompanyId equals c.Id
where
    (!userSearchParams.UserId.HasValue || u.Id == userSearchParams.UserId) &&
    ((String.IsNullOrEmpty(userSearchParams.UserText) || userSearchParams.UserId.HasValue) || // User Text
        (u.FirstName.StartsWith(userSearchParams.UserText, StringComparison.InvariantCultureIgnoreCase)
            || u.LastName.StartsWith(userSearchParams.UserText, StringComparison.InvariantCultureIgnoreCase)
            || u.Username.StartsWith(userSearchParams.UserText, StringComparison.InvariantCultureIgnoreCase))
        ) &&
    ((!userSearchParams.CompanyId.HasValue || c.Id == userSearchParams.CompanyId)) && // Company Id
    ((String.IsNullOrEmpty(userSearchParams.CompanyText) || userSearchParams.CompanyId.HasValue) || // Company Text
        (c.Name.StartsWith(userSearchParams.CompanyText, StringComparison.InvariantCultureIgnoreCase)
            || c.Country.StartsWith(userSearchParams.CompanyText, StringComparison.InvariantCultureIgnoreCase)
            || c.City.StartsWith(userSearchParams.CompanyText, StringComparison.InvariantCultureIgnoreCase))
        ) &&
    ((!userSearchParams.SiteId.HasValue || s.Id == userSearchParams.SiteId)) && // Site Id
    ((String.IsNullOrEmpty(userSearchParams.SiteText) || userSearchParams.SiteId.HasValue) || // Site Text
        (s.Name.StartsWith(userSearchParams.SiteText, StringComparison.InvariantCultureIgnoreCase)
            || s.Country.StartsWith(userSearchParams.SiteText, StringComparison.InvariantCultureIgnoreCase)
            || s.City.StartsWith(userSearchParams.SiteText, StringComparison.InvariantCultureIgnoreCase))
        )
select new UserToSiteAndCompany()
{
User = u,
Site = s,
Company = c
};

Update 1
 var site = (from u in _arcContext.Users
            join us in _arcContext.UserSites on u.Id equals us.UserId
            join s in _arcContext.Sites on us.SiteId equals s.Id
            where
                ((userSearchParams.SiteId.HasValue ? s.Id == userSearchParams.SiteId : true)) && // Site Id
                ((String.IsNullOrEmpty(userSearchParams.SiteText) || userSearchParams.SiteId.HasValue) || // Site Text
                    (s.Name.StartsWith(userSearchParams.SiteText, StringComparison.InvariantCultureIgnoreCase)
                        || s.Country.StartsWith(userSearchParams.SiteText, StringComparison.InvariantCultureIgnoreCase)
                        || s.City.StartsWith(userSearchParams.SiteText, StringComparison.InvariantCultureIgnoreCase))
                )
            select new { UserSite = us, Site = s}).Take(1);

            var users = from u in _arcContext.Users
            join us in _arcContext.UserSites on u.Id equals us.UserId
            join s in site on us.SiteId equals s.Site.Id
            join c in _arcContext.Companies on s.Site.CompanyId equals c.Id
            where
                (userSearchParams.UserId.HasValue ? u.Id == userSearchParams.UserId : true) &&
                ((String.IsNullOrEmpty(userSearchParams.UserText) || userSearchParams.UserId.HasValue) || // User Text
                    (u.FirstName.StartsWith(userSearchParams.UserText, StringComparison.InvariantCultureIgnoreCase)
                        || u.LastName.StartsWith(userSearchParams.UserText, StringComparison.InvariantCultureIgnoreCase)
                        || u.Username.StartsWith(userSearchParams.UserText, StringComparison.InvariantCultureIgnoreCase))
                    ) &&
                ((userSearchParams.CompanyId.HasValue ? c.Id == userSearchParams.CompanyId : true)) && // Company Id
                ((String.IsNullOrEmpty(userSearchParams.CompanyText) || userSearchParams.CompanyId.HasValue) || // Company Text
                    (c.Name.StartsWith(userSearchParams.CompanyText, StringComparison.InvariantCultureIgnoreCase)
                        || c.Country.StartsWith(userSearchParams.CompanyText, StringComparison.InvariantCultureIgnoreCase)
                        || c.City.StartsWith(userSearchParams.CompanyText, StringComparison.InvariantCultureIgnoreCase))
                    )
            select new UserToSiteAndCompany()
            {
            User = u,
            Site = s.Site,
            Company = c
            };


text:
Q: How to repair a laptop's screen hinges? I want to repair a laptop which has been heavily damaged by a fall.
The display is kept in place by two metal hinges, one by side, whose attach on the plastic underneath and on the motherboard.
The right one is good, but the screws on the left hinge ripped off from their place in plastic, and the laptop can't close anymore. My idea would be to attach them again using some kind of glue.
What glue or solution could I use?

A: There are some options you have to bond the pieces together but they will never be anywhere near as strong as a replacement casing would provide.  If you can get hold of a spares/repairs laptop of the same model I would personally do that.  Strip the interior from the spare one and replace with the interior of your broken laptop.
You could try 2-part resin glues as they will be stronger but there is of course Gorilla Glue or SuperGlue.

A: I agree with Chris Rogers that the best and right (and long-term reliable) way to fix it is to replace the shell.  There is a lot of stress on the hinges and it is tough to do a repair that will have the original strength and hold up long term.
That said, you may not have ready access to a replacement shell and may need at least a temporary repair to keep you operational.  Nothing in the way of glue or epoxy will hold up for long by itself, even if it bonds with the plastic.  Here's a more robust fix that will last for awhile.
Gorrila Glue or Super glue wouldn't be good for this. Something like JB Weld would have good strength and bond well, but still not close to the original strength. I would go farther. Where those brass insert were, drill a screw clearance hole through case. Get longer screws with matching threads. Glue the brass inserts back in place and use enough JB Weld to provide some support to the insert and the surrounding plastic. Then screw into and through the inserts and through the case. Use a large washer and nut on the outside of the case, with Loctite threadlocker to secure the nut.
That will look ugly, and will probably extend past any case bumpers, so it will have the potential to scratch your furniture.  You could cover it with a thin layer of silicone rubber to hide it and protect surfaces (there is black silicone adhesive or gray silicone caulk, or Sugru or Oogoo, if you want a "stylish" repair).  Be gentle with sliding the laptop around because that will likely tear off the silicone or erase it, and you would need to replace it.

A: There is a product called Plast-aid that I've used for years to repair all sorts of broken plastic pieces, including PVC that was under pressure, pool pumps, plastic housings, etc. Unlike glues, it creates a molecular bond with the existing plastic that makes it just as strong as the original. I've never had one repair I've made with it break. It works with most plastics, but not all, so it would be a good idea to try to find out the plastic the laptop shell is made out of. The plastics it's compatible with are in the product description.
https://www.amazon.com/Plast-aid-Multipurpose-Repair-Plastic-Pool/dp/B004DFHSM6

A: The attachment of the hinge to the lid is an area of fairly high mechanical stress, so weak adhesive-type repairs simply won't last.
When I faced this issue in resurrecting an HP laptop which had a metal-backed lid, what I ultimately ended up doing was drilling right through the lid and using small screws and nuts to re-attach the hinge.  The result is slightly ugly, but has been very sturdy.
I did make a mistake when the second hinge failed, of trying to use a slightly larger screw that required drilling out the hinge.  That did not work well, because the hinges are apparently stainless steel, which tends to work harden.  Because I did not make the initial attempt to drill it with enough power and pressure, the material became effectively impossible to drill with a conventional high speed steel bit and simply ruined the drill bit instead - I would have needed a carbide bit.  If I recall I eventually found a smaller screw and nut combination which would fit the existing hole.


text:
Q: MYSQL Sort by non alphanumeric I have a site that stores cooking tutorials. one of the columns in the mysql database holds either Novice, Intermediate, Advanced, Expert. I'd like to know if there was a way to write the MySQL query to order the results in the above fashion? Is this even possible?

A: You can sort by INSTR if its a small table:
ORDER BY INSTR('Novice, Intermediate, Advanced, Expert', `colname`)

But this will be slow on a large table. Better to just store a numeric value from 1 to 4 and add an index on it. Then translate the number to Novice, Intermediate, Advanced, or Expert when needed. Or perhaps two columns but that could lead to differences between the numeric and textual value.


text:
Q: How to open a new tab/page using ButtonField in GridView <asp:GridView ID ="FileGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="FileGrid_RowCommand">
    <Columns>
        <asp:BoundField DataField="OriginalFileName" HeaderText="OriginalFileName" SortExpression="OriginalFileName" />
        <asp:BoundField DataField="AttachmentGUID" HeaderText="AttachmentGUID" SortExpression="AttachmentGUID" />
        <asp:ButtonField Text="Generate PDF" runat="server" HeaderText="Convert To PDF" CommandName="GeneratePDF_Click" />
    </Columns>
</asp:GridView>

Code Behind:
protected void FileGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "GeneratePDF_Click")
    {
        int num = Convert.ToInt16(e.CommandArgument);
        string attachmentGuid = FileGrid.Rows[num].Cells[1].Text;
        Response.Redirect("DisplayImage.aspx?AttachmentGUID=" + attachmentGuid);
    }
}

I see a lot of solutions using OnClientClick with a asp:Button, but I'm unable to use a asp:Button within a column?

A: You can use ScriptManager.RegisterStartupScript to open up a new window:
var url = "DisplayImage.aspx?AttachmentGUID=" + attachmentGuid;
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + url + "','_blank')", true);

or you can also try:
var url = "DisplayImage.aspx?AttachmentGUID=" + attachmentGuid;
string redirect = "<script>window.open('" + url + "');</script>";
Response.Write(redirect);


text:
Q: Custom report, regex - filter for results only from specific websites/urls containing keywords I created a custom report in Google Analytics which I want to filter so that I see only the results/activities that come from predefined sub-websites including specific keywords e.g. I want to see results only from urls which include (/xy/abc) and (/xy/xyz) after the domain. I tried multiple ways but I am hopelessly stuck.
I have been working with "Hostname" and "Page" to then apply different exact paths and regex versions e.g. /xy/(abc|xyz)/.* or /xy/abc|xy/xyz but non worked. [abc] returned some interesting results. When I do [def] and [ghi] I get the same results for both when they should return different activities.
Please help.


text:
Q: How to connect to secure URLs with CakePHP's HttpSocket I'm trying to use CakePHP's HttpSocket to connect to Foursquare's API, particularly the venue search endpoint (https://developer.foursquare.com/docs/venues/explore). As you can see, Foursquare's API is accessed over HTTPS, so I added the following in my controller:
$httpSocket = new HttpSocket();
$results = $httpSocket->get('https://api.foursquare.com/v2/venues/search', array(
    'query' => $query
));

However, this throws the following error:

stream_socket_client(): Peer certificate CN='*.a.ssl.fastly.net' did not match expected CN='api.foursquare.com' stream_socket_client(): Failed to enable crypto stream_socket_client(): unable to connect to ssl://api.foursquare.com:443 (Unknown error)

How do I connect to secure URLs (and particularly Foursquare's) using CakePHP's HttpSocket?

A: The response indicates that the SSL certificate foursquare have is for another domain (their CDN), you either need to connect directly to the API using the CDN domain, or ignore the fact the certificates are for the wrong host.
The section on handling SSL certificates explains how to ignore incorrect hosts: http://book.cakephp.org/2.0/en/core-utility-libraries/httpsocket.html#handling-ssl-certificates (ssl_verify_host)


text:
Q: How to sort a matrix based on one index I have? t = [ 4 2
      2 6
      6 9];
c = [ 2
      3
      1];

Now, I want to arrange t according to c index; I need to get t new sorted based on c:
t = [ 2 6
      4 2
      6 9];

How to sort a matrix based on one index I have?
Here is what I tried:
h = cell(1,1);
h{1,1} = t;
h{1,1}(c)

A: this code makes use of the key:value mapping available in matlab. You could incorporate this into a function and tweak it for any arbitrary matrix t and c which I've relabeled keySet

t = [ 4 2;2 6; 6 9]; % original matrix
keySet = [ 2 3 1]; % original c indexing vector

valueSet= cell(1,size(t,1)); % create a cell matrix to hold the row elements of t
for i =1:size(t,1)
    valueSet{1,i} = t(i,:); % insert row elements into cell array
end
mapObj = containers.Map(keySet,valueSet); % map the keys to the values

keySet = sort(keySet,'descend'); % reorder the keys
for j=1:size(keySet,2)
    t(j,:) = mapObj(keySet(1,j)); % rebuild matrix t with new order
end


text:
Q: How to display BSSID from wifiManager.connectionInfo in textView or listView I am trying to display the network status from current connection similar to ipconfig in windows. I got to the point where I can access the information but I cannot get it to display in a textView or listView other than a toast.
I'm using the following code:
wifiManager = this.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

if (wifiManager.isWifiEnabled()) {
   val wifiInfo: WifiInfo! = wifiManager.connectionInfo;
   if (wifiManager.isWifiEnabled == true) {
      Toast.makeText(context: this, text: wifiInfo.bssid, Toast.LENGHT_LONG).show();
   }
}

I just cannot get it to display in a textView or listView, whichever is more feasible. Please help, I am new at this, but looking forward to becoming a full time freelance coder soon.

A: You should be able to add the bssid to a TextView by just doing something like:
myTextView.settext("Bssid: " + wifiInfo.bssid)

One of the first links when searchig for "Android TextView Tutorial":
https://abhiandroid.com/ui/textview