text:
Q: Sort result texts in PyQt by key value I am trying to sort my output results from my program in PyQt using a sort of key value then print out the text that correspond to the order.
In other words I have this piece of code:
with open(compareResults, 'wb') as fdout:
            for index, tabName in enumerate(setNames):
                tabWidget = QtGui.QWidget()
                tabLabel = QtGui.QTextEdit()
                print "Tab Name is :{}".format(tabName)
                fdout.write('{}'.format(tabName) + '\r\n')

                nameData = lst[index]
                print 'name data = {}'.format(nameData)
                for k in nameData:
                    if k in correct_parameters:
                        if nameData[k] != correct_parameters[k]:
                            tabLabel.setTextColor(QtGui.QColor("Red"))
                            tabLabel.append('This Parameter is Incorrect: {} = {}'.format(k, nameData[k]))
                            fdout.write('\t' + '|' + 'This Parameter is Incorrect: {} = {}'.format(k, nameData[k]) + '\t' + '|' + '\r\n')
                            print ('{} = {}'.format(k, nameData[k]))
                            tabCounter+=1

                        elif nameData[k] == correct_parameters[k]:
                            tabLabel.setTextColor(QtGui.QColor("Black"))
                            tabLabel.append('{} = {}'.format(k, nameData[k]))
                            fdout.write('\t' + '|' + '{} = {}'.format(k, nameData[k]) + '\t' + '|' + '\r\n')

                            print ('{} = {}'.format(k, nameData[k]))
                    else:
                        tabLabel.setTextColor(QtGui.QColor("Blue"))
                        tabLabel.append('{} = {} does not appear in our default'.format(k, nameData[k]))
                        fdout.write('\t' + '|' + '{} = {} does not appear in our default'.format(k, nameData[k]) + '\t' + '|' + '\r\n')
                        print ('{} = {} does not appear in our default'.format(k, nameData[k]))
                        tabCounter += 1
                tabLayout = QtGui.QVBoxLayout()
                tabLayout.addWidget(tabLabel)
                tabWidget.setLayout(tabLayout)
                self.tabWidget.addTab(tabWidget, tabName)
                if tabCounter == 0:
                    print 'no change in tabs'

The program prints out line by line of the result in this case, what am aiming to do is print out the lines in order from nameData[k] != correct_parameters[k] then nameData[k] == correct_parameters[k] and then else
So my idea was to assign a key value to each one of these lines, so if the information is incorrect I can assign a key value of 0, then if the line is correct the key value is 1, and if the line doesn't appear it will have a key value of 2. Then I can sort those values in order numerically from 0-2. and print them out to the tabs im creating.
So far I understand how to assign the keyvalue to the three different situations I have here the issue is creating a tabLabel.append with the key values in order.
I was thinking of using something along the lines of this pseudo code:
for keyvalue in storedvalues:
for all keys equal to 0 print
then for all keys equal to 1 print
and then for all keys equal to 2 print.
Although I'm not sure if, rather than using a loop, I could instead store each result into a new dictionary then assign those keys to the value in the dictionary and just use a sort method like sorted(data.values()) in this case. Then after sorting print out the dictionary.


text:
Q: Fatal error cannot run 'mt.exe' at compiling VS 2012 C++ project I upgraded Visual Studio to VS Professional 2012.
Building old Visual C++ projects resulted in the error:
LINK : fatal error LNK1158: cannot run 'mt.exe'
Putting the folder with mt.exe into the path did not help.
Currently I am using mt.exe in the folder C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin\x64

A: Set "Generate manifest" as No in Linker.  This helped

A: As mentioned at fatal error LNK1158: cannot run 'mt.exe', there are times where turning off manifest generation is not an option, because one is actually using manifests.
At which point, one comes back to fixing the actual problem.
One cause of the actual problem is a bad executable search path.
I personally once had a setting for $(ExecutablePath) in the project file (VC++ Directories → Executable directories in the project settings) that was yielding an executable search path one of whose pathnames wasn't a valid directory name.
The pathname had a colon in one of its directory name components (caused by prefixing ..\..\ to another variable, which happened to contain an absolute pathname with a drive letter, rather than a relative pathname as expected).
In a sensible world, errors in path searches caused by merely bad/missing directories cause the pathname to just get skipped over, and the search to proceed to the next pathname in the search path.
link, in contrast, fails with this error (as indeed does midl when it tries to find cl.exe).
This is very confusing when one looks at the search path (with the build output level set to "detailed") and sees that the SDK directory containing mt.exe is right there in it, plain as day.
It seems that link does not live in a sensible world.  ☺
The fix was to correct the bad project setting, of course.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add support for fields to databound controls For example when using a gridview. When you specify the columns
BoundField for example won't work if you are binding it to a field instead of a property.
I guess this is so because when the gridview is looking for the DataField property it looks for a property and not a field. Now the question is how can i change this behavior to make it possible to use fields. I know i have to inherit from the gridview, but i don't know where to go from there.

A: Wrap the fields with Properties
    private string fieldA;

    public string FieldA
    {
      get { return fieldA; }
      set { fieldA = value; }
    }

A: This functionality is so wrapped into the framework and wasn't designed for extensibility so no you can't change this behavior; the only thing you can do is to create wrapper objects or wrap fields with properties.
Or render the UI in your own way, which then you lose the GridView in-built functionality.


text:
Q: Webpack et React 16: Failed to compile. ./node_modules/style-loader/lib/addStyles.js I'm building an App using React 16.4.2, unfortunately I've got this error message after installing Bootstrap 4 (via npm: np install bootstrap):
Failed to compile.

./node_modules/style-loader/lib/addStyles.js

Module build failed: Error: ENOENT: no such file or directory, open 'C:\Users\open\Desktop\react-app\contactmanager\node_modules\style-loader\lib\addStyles.js'

This is my App.js file (where I import bootstrap):
import React, { Component } from "react";
import Contact from "./component/Contact";
import Header from "./component/Header";

import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div className="App">
        <Header />
        <Contact name="My Name" email="XXX@gmail.com" phone="+XXX XXX XXX" />
      </div>
    );
  }
}

export default App;

By the way, I only have two components: Header and Contact.
Any Idea Please?
Thank You.

A: I ran into the same issue but deleting node_modules and reinstalling did not help.
'style-loader' was still missing and I have to manually install it via 'npm install style-loader', then stop and restart the React application.
I used create-react-app, with the following versions:
"bootstrap": "^4.1.3",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-scripts": "2.1.1"

A: It looks like your style-loader installation is corrupt. It will most likely be resolved if you just remove your dependencies and install them from scratch.
rm -rf ./node_modules && npm install


text:
Q: Does weight distribution affect angular velocity? If an equal torque of equal radius and size is produced on two bodies of the same weight and same center of gravity, but with different weight distribution (say one has a 1kg mass 1 meter above the center of mass, while the other has it 10 cm above). Will this affect the angular velocity of it?

A: Yes, it will affect angular velocity since different mass distribution have different moment of inertia $I$ in general. The effect of torque $\tau$ on the angular velocity $\omega$ of the object is given by $$\tau=\frac{d}{dt}(I\omega)$$
The moment of inertia of a point mass is given by $I=mr^2$, so in your case, the radius differ by 10 time so moment of inertia differ by 100 times and so does the angular velocity. Note that when you mention torque, you dont necessary need to specify which point it acts on.


text:
Q: Error : file is being used by another process I have a problem where it says that a file is already being used by another process
But I am pretty sure it's not being used anywhere else..
Imports System.IO
Public Class Browse
    Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
        Dim Files As New OpenFileDialog
        Dim Folder As New FolderBrowserDialog
        Dim Filelist As String = "C:\Program Files\FTP-Sync\Files.txt"
        Dim FileP As String = ""
        Dim list() As String = IO.File.ReadAllLines(Filelist)

        If fileb.Checked Then
            Try
                If System.IO.File.Exists(Filelist) = True And Files.ShowDialog = Windows.Forms.DialogResult.OK Then
                    FileP = Files.FileName
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If

        If folderb.Checked Then
            Try
                If System.IO.File.Exists(Filelist) = True And Folder.ShowDialog = Windows.Forms.DialogResult.OK Then
                    FileP = Folder.SelectedPath
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
        pathtxt.Text = FileP
    End Sub

    Private Sub ok_Click(sender As Object, e As EventArgs) Handles ok.Click
        Dim Filelist As String = "C:\Program Files\FTP-Sync\Files.txt"
        Dim writer As StreamWriter = New StreamWriter(Filelist)
        Dim FileP As String = ""
        Try
            If pathtxt.Text = "" Then
                MsgBox("No folder or file has been choosen")
            Else
                writer = File.AppendText(Filelist)
                writer.WriteLine(pathtxt.Text)
                pathtxt.Text = FileP
                writer.Close()
                Me.Hide()
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Private Sub cancel_Click(sender As Object, e As EventArgs) Handles cancel.Click
        Me.Hide()
    End Sub

    Private Sub Browse_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub
End Class

Thanks in advance!

A: It was because of this:
Dim writer As StreamWriter = New StreamWriter(Filelist)

i changed it to
Dim writer As StreamWriter

and it work like a charm.. dont know if it is the right way.. but it worked.


text:
Q: How to keep puppeteer browser running background without jumping to foreground? When use puppeteer to scrape a bunch of sites via a for-loop, whenever a new page is created, the browser would jump to the foreground, which hinders me from doing other things on my computer.
Even I set the following args, it still doesn't work, so how could I keep the browser running quietly without jumping to foreground and interupting me?
I need to run in headful mode, not headless mode.
headless: false,
args: [
                '--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
                '--disable-background-timer-throttling',
                '--disable-backgrounding-occluded-windows',
                '--disable-renderer-backgrounding',
            ]

A: Open Chromium's Info.plist (you may find it here node_modules/puppeteer/.local-chromium/mac-XXXXXX/chrome-mac/Chromium.app/Contents/Info.plist) in an editor and add the following piece after the first <dict> and before <key>:
<key>LSBackgroundOnly</key>
<string>True</string>

This works on any OS X application.
Source: Keep applications from stealing focus when opening in OS X


text:
Q: How to customize Ruby's Marshal load without changing format? I need to customize what happens to one of my class on Marshal.load(). I found that there are marshal_load and _load methods but so far I was unsuccessful to use either of them to what I need.
It's crucial for me that the resulting binary data are not changed compared to if those methods are not defined. This rules out _dump and _load as they're for defining custom serialization string format.
I tried to use marshal_load and marshal_dump but it changes the resulting binary format as well. This can't happen.
EDIT: To be a bit more specific about my usecase I have a marshalled binary file which contains strings in 8bit. I need to change these strings to utf8 in marshal_load and back to 8bit in marshal_dump.
I created this repository for testing, read the comments here:
https://github.com/enumag/marshal-test/blob/master/test.rb

A: I saw in your Github example you have the below comment, but I don't think you have the option not to do it manually before the dump and after the load.

in practice I'm Marshal loading a large structure with many nested objects so I can't do it manually

I would suggest one of the two following schemes.
Create wrapper around Marshal and use that to modify your object before and after marshaling.
class Foo
    def initialize(attr_1, attr_2)
        @attr_1 = attr_1
        @attr_2 = attr_2
    end
end

class MyMarshaler
    def load(file_name)
        source = File.new(file_name, "r")
        loaded = Marshal.load(source)
        source.close
        # do whatever you want with loaded object
        manipulated = loaded
    end

    def dump(obj, file_name)
        dest = File.new(file_name, "w")
        # do whatever you want with object before dumping it
        manipulated = obj
        Marshal.dump(manipulated, dest)
        dest.close
    end
end

foo = Foo.new("foo-thing-1", "foo-thing-2")
foo_file_name = "marshaled.ruby_object"
marshaler = MyMarshaler.new
p foo
marshaler.dump(foo, foo_file_name)
restored_foo = marshaler.load(foo_file_name)
p restored_foo

The other option would be to create a Module and extend your class to include methods that wrap the marshal load/dump methods.
module MyMarshalerModule
    def load(file_name)
        source = File.new(file_name, "r")
        loaded = Marshal.load(source)
        source.close
        # do whatever you want with loaded object
        manipulated = loaded
    end

    def dump(obj, file_name)
        dest = File.new(file_name, "w")
        # do whatever you want with object before dumping it
        manipulated = obj
        Marshal.dump(manipulated, dest)
        dest.close
    end
end

class Bar
    extend MyMarshalerModule
    def initialize(attr_1, attr_2)
        @attr_1 = attr_1
        @attr_2 = attr_2
    end
end

bar = Bar.new("bar-thing-1", "bar-thing-2")
bar_file_name = "marshaled2.ruby_object"
p bar
Bar.dump(bar, bar_file_name)
restored_bar = Bar.load(bar_file_name)
p restored_bar

A: I think my original answer addressed the question in your post, but in the comments you imply that you really have 2 questions.
This answer attempts to answer both questions.
Here is a TransMarshal class that allows you to pass a block to both the load and dump methods that recursively looks for instances of a class and transform those instances using a nested block.  The objects of the transformation are untouched.
class TransMarshal
    def self.load(file_name)
        source = File.new(file_name, "r")
        loaded = Marshal.load(source)
        source.close
        block_given? ? yield(loaded) : loaded
    end

    def self.dump(obj, file_name)
        dest = File.new(file_name, "w")
        manipulated = block_given? ? yield(obj) : obj
        Marshal.dump(manipulated, dest)
        dest.close
    end

    def self.transform(obj, klass, &block)
        cloned_obj = obj.clone
        return cloned_obj if obj.instance_variables.empty?
        cloned_obj.instance_variables.each do |o|
            cloned_inst_var = cloned_obj.instance_variable_get(o).clone
            cloned_obj.instance_variable_set(o, transform(cloned_inst_var, klass, &block))
            if cloned_inst_var.class == klass
                cloned_obj.instance_variable_set(o, yield(cloned_inst_var))
            end
        end
        cloned_obj
    end

end

Example usage.
class Foo
    def initialize(attr_1, attr_2)
        @attr_1 = attr_1
        @attr_2 = attr_2
    end
end

class Bar
    def initialize(attr_1, attr_2)
        @attr_1 = attr_1
        @attr_2 = attr_2
    end
end

class FooBar
    # extend MyMarshalerModule
    def initialize(foo, bar, string, number)
        @foo = foo
        @bar = bar
        @string = string
        @number = number
    end
end

foo = Foo.new("foo_attr_1", "foo_attr_2")
bar = Bar.new("bar_attr_1", "bar_attr_2")
foo_bar = FooBar.new(foo, bar, "foobar", 42)

TransMarshal.dump(foo_bar, "dumped") do |obj|
    TransMarshal.transform(obj, String) {|s| "#{s}-x"}
end

raw_restored_foo_bar = TransMarshal.load("dumped")
puts "raw_restored_foo_bar = #{raw_restored_foo_bar.inspect}"

transformed_restored_foo_bar = TransMarshal.load("dumped") do |obj|
     TransMarshal.transform(obj, String) { |o| o[0..-3] }
end
puts "transformed_restored_foo_bar = #{transformed_restored_foo_bar.inspect}"


text:
Q: Ejecutar exe Node js con parametros Estoy estancado en algo que simple que no puedo resolverlo, estoy haciendo en pequeño proyecto de lanzador de juegos con node y electron, por lo que requiero lanzar programas como steam, epic games, chrome con parametros
function RunExeFile(pathExe, arg){
    var child = require('child_process').execFile;
  var executablePath = pathExe;
  var parameters = arg;

  child(executablePath, parameters, function(err, data) {
       console.log(err)
       console.log(data.toString());
  });

      }

el caso es que si envio arg, no se ejecuta, tampoco tira error, si no envio arg ejecuta sin problemas
function createDomIconsleft(iconleft){

    const IconsleftHtml=`

`
  return IconsleftHtml;
}

${iconleft.link} ${iconleft.parameters} los traigo de un json
"link": "C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe",

    "parameters": "--incognito",

    "title": "Chrome",

    "image": "google.png"


text:
Q: Extra vertical line in table with overlayarea and wobbling table Problem 1: Extra vertical lines in the bottom of table with overlayarea. Tried solutions in Too long vertical lines in table, but changing |c|c| to cc is not okay for the looks of the table.
Problem 2: The table heading wobbles with overlayarea in slide 1 and 2.
MWE:
\documentclass{beamer}
\begin{document}
    \begin{frame}
    \frametitle{Title}
    \framesubtitle{Subtitle}
    \begin{overlayarea}{\textwidth}{2cm}
        \begin{table}
            \begin{tabular}{|c|c|c|}
                \hline
                \only<1-3>{
                    \textbf{Sl. No.}    &   \textbf{Heading1}   &   \textbf{Heading2}\\
                    \hline
                }
                \only<2-3>{
                    1                   &   Content1.1          &   Content1.2\\
                    \hline
                }
                \only<3>{
                    2                   &   Content2.1          &   Content2.2\\
                    \hline
                }
            \end{tabular}
        \end{table}
    \end{overlayarea}
\end{frame}
\end{document}

MWE (same as previous, but without any newline, tabs or space):
\documentclass{beamer}
\begin{document}
    \begin{frame}
    \frametitle{Title}
    \framesubtitle{Subtitle}
    \begin{overlayarea}{\textwidth}{2cm}
        \begin{table}\begin{tabular}{|c|c|c|}\hline\only<1-3>{\textbf{Sl. No.}&\textbf{Heading1}&\textbf{Heading2}\\\hline}\only<2-3>{1&Content1.1&Content1.2\\\hline}\only<3>{2&Content2.1&Content2.2\\\hline}\end{tabular}\end{table}
    \end{overlayarea}
\end{frame}
\end{document}

A: \documentclass{beamer}
\begin{document}
    \begin{frame}
    \frametitle{Title}
    \framesubtitle{Subtitle}
    \begin{overlayarea}{\textwidth}{2cm}
        \begin{table}
            \begin{tabular}{|c|c|c|}
                \hline
                \only<1-3>{%
                    \textbf{Sl. No.}    &   \textbf{\ Heading1\ }   &   \textbf{\ Heading2\ }%
                }%
                \only<2-3>{%
                    \\\hline
                    1                   &   Content1.1          &   Content1.2%
                }%
                \only<3>{%
                   \\\hline
                    2                   &   Content2.1          &   Content2.2%
                }%
                \only<1-3>{\\\hline}%
            \end{tabular}
        \end{table}
    \end{overlayarea}
\end{frame}
\end{document}


text:
Q: Loop where the condition for the first entry in a column is different from the remaining column entries? I have a dataframe named Exam that looks like
Col A      Col B      Col C     Col D     Col E     Col F
  1          1         Jan       2.5       2.5       Yes
  1          2         Jan       2.4       2.5       Yes
  2          3         Jan       2.4       2.5       Yes
  2          4         Feb       2.3       2.4       No
  2          5         Feb       2.5       2.6       No
  3          6         Mar       2.4       2.6       Yes
  3          7         Mar       2.5       2.5       Yes

I want to check the condition of Col F and store it in a new column called Col G but the condition for the first row of the dataframe/Col F is different from the remaining rows in the Col F.  I have the following script:
for i in Exam.index:
    def val(df):
        if i == 0:
            if df["Col F"] == "Yes":
                return "In"
            if df["Col F"] == "No":
                return "Out"
        if i != 0:
            if df["Col F"] == "Yes":
                return "In2"
            if df["Col F"] == "No":
                return "Out2"

Exam["Col G"] = Exam.apply(val, axis=1)

Exam
The script returns:
Col A      Col B      Col C     Col D     Col E     Col F     **Col G**
  1          1         Jan       2.5       2.5       Yes       **In2**
  1          2         Jan       2.4       2.5       Yes       **In2**
  2          3         Jan       2.4       2.5       Yes       **In2**
  2          4         Feb       2.3       2.4       No        **Out2**
  2          5         Feb       2.5       2.6       No        **Out2**
  3          6         Mar       2.4       2.6       Yes       **In2**
  3          7         Mar       2.5       2.5       Yes       **In2**

but I want it to return:
Col A      Col B      Col C     Col D     Col E     Col F     **Col G**
  1          1         Jan       2.5       2.5       Yes       **In**
  1          2         Jan       2.4       2.5       Yes       **In2**
  2          3         Jan       2.4       2.5       Yes       **In2**
  2          4         Feb       2.3       2.4       No        **Out2**
  2          5         Feb       2.5       2.6       No        **Out2**
  3          6         Mar       2.4       2.6       Yes       **In2**
  3          7         Mar       2.5       2.5       Yes       **In2**

The loop isn't executing the condition for the first row in Col F.  This seems like an easy thing but I'm not sure what I am doing wrong.  Thanks!

A: The simplest sulotion would probably be to modify the val function to take i and df['Col F'] as arguments, and use enumerate(df['Col F']) as inputs to val.
def val(i, f):
    if i == 0:
        if f == "Yes":
            return "In"
        if f == "No":
            return "Out"
    if i != 0:
        if f == "Yes":
            return "In2"
        if f == "No":
            return "Out2"

Exam["Col G"] = [val(i, f) for i, f in enumerate(df['Col F'])]

If you need to use more than one column in your calculation, you can use zip:
def val(i, e, f): ...

df['Col G'] = [val(i, e, f) for i, (e, f) in enumerate(zip(df['Col E'], df['Col F']))]


text:
Q: Query hierarchical data in SQL Server I have a table called SegmentCaller which saves a segment code (SegmentCaller) and the segment codes it calls (SegmentCalled), structured as below

SegmentCaller
SegmentCalled

SEG1
SEG2

SEG1
SEG3

SEG1
SEG4

SEG2
SEG5

SEG2
SEG6

SEG3
SEG7

SEG4
SEG8

SEG7
SEG9

SEG8
SEG1

SEG9
SEG7

Here is an graphical view of the data:
Node graph
I need a query that will start with a segment code, for example SEG1 and continue looking for all descendants until all paths end (as illustrated in the graph above). This can go on for hundreds of levels downwards, and there is the issue of circular references, where, for example, SEG8 could call SEG1 again.
Tried using a CTE, but I am not that familiar with it. Since SegmentCaller has repeated rows for each segment, couldn't figure out how to make it work.
WITH tmp AS (
SELECT
    [SegmentCaller],
    [SegmentCalled]
FROM
    [FOSAnalysis].[dbo].[FOSSegmentCaller]
WHERE SegmentCaller = 'SEG1'
UNION ALL
SELECT
    sc.[SegmentCaller],
    sc.[SegmentCalled]
FROM
    [FOSAnalysis].[dbo].[FOSSegmentCaller] sc
INNER JOIN tmp o
    ON o.SegmentCalled = sc.SegmentCaller
)
SELECT * FROM tmp

Using the sample code above, as seen in the table, some segments, as in the case of 2-9, are completely ignored instead of getting the descendants of each one. Also, the query above throws the following error.

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

SegmentCaller
SegmentCalled

SEG1
SEG2

SEG1
SEG3

SEG1
SEG4

SEG1
SEG5

SEG1
SEG6

SEG1
SEG7

SEG1
SEG8

SEG1
SEG9

SEG1
SEG10

SEG10
SEG11

SEG10
SEG12

SEG10
SEG13

SEG13
SEG14

SEG13
SEG15

SEG15
SEG16

SEG14
SEG16

A: You will need to figure out a means of preventing circular references from being traversed.  Otherwise a CTE structured similar to the below should work.  In this example, I adapted this answer and added a path to the traversal, and excluded any rows from traversal that contained a segment that had already been traversed.
CREATE TABLE Segments (
  SegmentCaller VARCHAR(4),
  SegmentCalled VARCHAR(4)
);

INSERT INTO Segments
  (SegmentCaller, SegmentCalled)
VALUES
  ('SEG1', 'SEG2'),
  ('SEG1', 'SEG3'),
  ('SEG1', 'SEG4'),
  ('SEG2', 'SEG5'),
  ('SEG2', 'SEG6'),
  ('SEG3', 'SEG7'),
  ('SEG4', 'SEG8'),
  ('SEG7', 'SEG9'),
  ('SEG9', 'SEG3');

  WITH items AS (
    SELECT SegmentCaller, SegmentCalled
    , 0 AS Level
    , CAST(CAST(SegmentCaller AS VARCHAR(255))  + '.' + CAST(SegmentCalled AS VARCHAR(255)) AS VARCHAR(255)) AS  Path
    FROM Segments
    WHERE SegmentCaller = 'SEG1'

    UNION ALL

    SELECT i.SegmentCaller, i.SegmentCalled
    , Level + 1
    , CAST(Path + '.' + CAST(i.SegmentCalled AS VARCHAR(255)) AS VARCHAR(255))
    FROM Segments i
    INNER JOIN items itms ON itms.SegmentCalled = i.SegmentCaller
    WHERE Path not like '%' + i.SegmentCalled + '%'
)

SELECT * FROM items ORDER BY Path

Result in:

SegmentCaller
SegmentCalled
Level
Path

SEG1
SEG2
0
SEG1.SEG2

SEG2
SEG5
1
SEG1.SEG2.SEG5

SEG2
SEG6
1
SEG1.SEG2.SEG6

SEG1
SEG3
0
SEG1.SEG3

SEG3
SEG7
1
SEG1.SEG3.SEG7

SEG7
SEG9
2
SEG1.SEG3.SEG7.SEG9

SEG1
SEG4
0
SEG1.SEG4

SEG4
SEG8
1
SEG1.SEG4.SEG8


text:
Q: Re encode JSON File Python I have a tough task, it is to download a json file from a format and re encode in other format to upload in a MongoDB. My json file is from Alpha Vantage (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo) and has the following format.
"Time Series (1min)": {
    "2018-07-13 16:00:00": {
        "1. open": "105.4550",
        "2. high": "105.5600",
        "3. low": "105.3900",
        "4. close": "105.4300",
        "5. volume": "2484606"
    },
    "2018-07-13 15:59:00": {
        "1. open": "105.5300",
        "2. high": "105.5300",
        "3. low": "105.4500",
        "4. close": "105.4600",
        "5. volume": "216617"
    }

I need to re encode the file according the following schema using Day, hour and minute as keys.
{
'2018-07-13': {
    '16': {
        '00': {'open': 105.4550,
              'high': 105.5600,
              'low': 105.3900,
              'close': 105.4300,
              'volume': 2484606,}
        }
    }
'2018-07-13': {
    '15': {
        '59': {'open': 105.53000,
              'high': 105.5300,
              'low': 105.4500,
              'close': 105.4600,
              'volume': 6484606,}
        }
    }
}

I've done a lot of research but I didn't figure it out how to construct a Dictionary with multiple keys using a loop, at the same time I read the json file I'd like to re enconde in the Dict.

A: I agree it can be a little confusing if you aren't used to working with nested data structures, but it's not that hard if you're careful. The trick is to create the inner dictionaries if they don't already exist. We can do that with the dict.setdefault method.
We also need to convert the inner data from strings to numbers. But we want the numbers to be integers if they don't contain a decimal point, otherwise we want floats. The usual way to do that is shown in my str_to_num function. First we try to convert to integer, and if that fails we convert to float. And if that fails due to bad data, the program will raise a ValueError exception and terminate. You may want to handle that differently, eg to ignore bad data.
I'll assume that you know how to extract the desired data from the outermost level using the "Time Series (1min)" key. The code below uses the standard json module simply to convert the data in the new format back to JSON so we can print it nicely.
import json

alpha_data = {
    "2018-07-13 16:00:00": {
        "1. open": "105.4550",
        "2. high": "105.5600",
        "3. low": "105.3900",
        "4. close": "105.4300",
        "5. volume": "2484606"
    },
    "2018-07-13 15:59:00": {
        "1. open": "105.5300",
        "2. high": "105.5300",
        "3. low": "105.4500",
        "4. close": "105.4600",
        "5. volume": "216617"
    }
}

def str_to_num(s):
    try:
        n = int(s)
    except ValueError:
        n = float(s)
    return n

# Where we'll store the output
out_data = {}

for timestamp, data in alpha_data.items():
    datestr, timestr = timestamp.split()
    hr, mn, _ = timestr.split(':')
    # Fetch inner dicts, creating them if they don't exist yet
    d = out_data.setdefault(datestr, {})
    d = d.setdefault(hr, {})
    d[mn] = {k.split()[1]: str_to_num(v) for k, v in data.items()}

print(json.dumps(out_data, indent=4))

output
{
    "2018-07-13": {
        "16": {
            "00": {
                "open": 105.455,
                "high": 105.56,
                "low": 105.39,
                "close": 105.43,
                "volume": 2484606
            }
        },
        "15": {
            "59": {
                "open": 105.53,
                "high": 105.53,
                "low": 105.45,
                "close": 105.46,
                "volume": 216617
            }
        }
    }
}

You will notice that my output isn't exactly the same as your desired output. That's because keys in Python dictionaries are unique: you can't have two items in the same dict with a key of "2018-07-13". So my code creates a dict in out_data with the key of "2018-07-13" and inside that dict it creates a dict for each hour, as necessary.


text:
Q: Areas of Surfaces and solids How can I merge the formula of volume for a sphere and the formula of area of a circle to create a new volume formula of a sphere that does not contain the symbol pi? It's not possible right ?
(Sorry if the title throws you off were learning about surfaces and solids)

A: Sure, it's possible. You could do:
$$
\text{volume of sphere}  = \frac{4}{3} A r,
$$
where $A$ is the area of the cross section of the sphere along its equator, and $r$ is the radius of the sphere.
This would be one way to "merge" the two formulas (since it uses the formula $\pi r^2$ for $A$), and the formula does not have $\pi$ in it.
Here is another one along similar lines:
$$
\text{volume}  = \frac{2}{3} C r^2,
$$
where $C$ is the length of the circumference of the sphere, and $r$ is again its radius.


text:
Q: How Can I display specific formats from ansible_facts using ansible playbook? I am new to Ansible, I got the task to display below format from host machine using ansible playbook.
output - RHEL 7.7 (x86_64)
I have written using shell script -
os_version=$(cat $RHAT_RELEASE 2>/dev/null | awk '{printf("%s ", $0)};END{printf("\n")}' | sed 's/Red Hat Enterprise Linux Server release/RHEL/g' | cut -f1 -d'(' | sed 's/ +$//g')
     RHEL_VERSION=$(echo $os_version | awk '{print $2}' | cut -f1 -d'.')

     RHEL_MINOR=$(echo $os_version | awk '{print $2}' | cut -f2 -d'.')

     RHEL_ARCH=$(uname -i)

But as per requirement, I should format the output using ansible_distribution or ansible_facts
Please help in writing ansible playbook

A: You can combine some of the ansible_facts variables, e.g.
---
- name: Print Distribution Info
  hosts: localhost
  tasks:

    - debug:
        msg: "{{ ansible_distribution }} {{ ansible_distribution_version }} ({{ ansible_architecture }})"


text:
Q: Ubuntu 20.04 when I tried to install RabbitMQ it showing this error I followed this website to install RabbitMQ https://attacomsian.com/blog/install-rabbitmq-macos-ubuntu
On the 5th step where it install RabbitMq, When I run the command I get this error
rabbitmq-server.service - RabbitMQ Messaging Server
     Loaded: loaded (/lib/systemd/system/rabbitmq-server.service; enabled; vendor preset: enabled)
     Active: activating (auto-restart) (Result: exit-code) since Fri 2021-08-20 10:11:27 IST; 5ms ago
    Process: 361473 ExecStart=/usr/sbin/rabbitmq-server (code=exited, status=1/FAILURE)
   Main PID: 361473 (code=exited, status=1/FAILURE)
dpkg: error processing package rabbitmq-server (--configure):
 installed rabbitmq-server package post-installation script subprocess returned error exit status 1
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for systemd (245.4-4ubuntu3.11) ...
Errors were encountered while processing:
 rabbitmq-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

when I run sudo apt update, this error is showing
    E: The repository 'http://www.rabbitmq.com/debian testing Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

A: Please follow the official documentation:
https://www.rabbitmq.com/install-debian.html#apt-quick-start-packagecloud
with a simple script, you can easily install rabbitmq on ubuntu.
for example:
#!/usr/bin/sh

sudo apt-get install curl gnupg apt-transport-https -y

## Team RabbitMQ's main signing key
curl -1sLf "https://keys.openpgp.org/vks/v1/by-fingerprint/0A9AF2115F4687BD29803A206B73A36E6026DFCA" | sudo gpg --dearmor > /usr/share/keyrings/com.rabbitmq.team.gpg
## Launchpad PPA that provides modern Erlang releases
curl -1sLf "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0xf77f1eda57ebb1cc" | sudo gpg --dearmor > /usr/share/keyrings/net.launchpad.ppa.rabbitmq.erlang.gpg
## PackageCloud RabbitMQ repository
curl -1sLf "https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey" | sudo gpg --dearmor > /usr/share/keyrings/io.packagecloud.rabbitmq.gpg

## Add apt repositories maintained by Team RabbitMQ
sudo tee /etc/apt/sources.list.d/rabbitmq.list <<EOF
## Provides modern Erlang/OTP releases
##
## "focal" as distribution name should work for any reasonably recent Ubuntu or Debian release.
## See the release to distribution mapping table in RabbitMQ doc guides to learn more.
deb [signed-by=/usr/share/keyrings/net.launchpad.ppa.rabbitmq.erlang.gpg] http://ppa.launchpad.net/rabbitmq/rabbitmq-erlang/ubuntu focal main
deb-src [signed-by=/usr/share/keyrings/net.launchpad.ppa.rabbitmq.erlang.gpg] http://ppa.launchpad.net/rabbitmq/rabbitmq-erlang/ubuntu focal main

## Provides RabbitMQ
##
## "focal" as distribution name should work for any reasonably recent Ubuntu or Debian release.
## See the release to distribution mapping table in RabbitMQ doc guides to learn more.
deb [signed-by=/usr/share/keyrings/io.packagecloud.rabbitmq.gpg] https://packagecloud.io/rabbitmq/rabbitmq-server/ubuntu/ focal main
deb-src [signed-by=/usr/share/keyrings/io.packagecloud.rabbitmq.gpg] https://packagecloud.io/rabbitmq/rabbitmq-server/ubuntu/ focal main
EOF

## Update package indices
sudo apt-get update -y

## Install Erlang packages
sudo apt-get install -y erlang-base \
                        erlang-asn1 erlang-crypto erlang-eldap erlang-ftp erlang-inets \
                        erlang-mnesia erlang-os-mon erlang-parsetools erlang-public-key \
                        erlang-runtime-tools erlang-snmp erlang-ssl \
                        erlang-syntax-tools erlang-tftp erlang-tools erlang-xmerl

## Install rabbitmq-server and its dependencies
sudo apt-get install rabbitmq-server -y --fix-missing

and ..
root@ubuntu-focal:/home/vagrant# rabbitmqctl status
Status of node rabbit@ubuntu-focal ...
Runtime

OS PID: 4038
OS: Linux
Uptime (seconds): 14
Is under maintenance?: false
RabbitMQ version: 3.9.4
Node name

A: This happens because of an environment variable reload, in file
/var/lib/dpkg/info/rabbitmq-server.postinst,
the line:
. /etc/profile

You could comment it out and do: apt install --fix-broken -y


text:
Q: ValueError Exception Handling in a while loop: Repeat only wrong input I would like the following code to ask the user -in a while loop- to input two integers, handle ValueError Exception, and if all well to print the sum.
My problem is that if the first number passes and the second doesn't, it asks to input the first one all over again.
How do I get it in this case to prompt the second input only?
while True:

try:
    number_1 = int(input("enter the first number: "))
    number_2 = int(input("enter the second number: "))
except ValueError:
    print("please enter numbers only!")

else:
    result = number_1 + number_2
    print(f" {number_1} + {number_2} = {result}")

Many thanks in advance!

A: Probably writing a small function to request user for input and handle the ValueError would come handy in here and would be a good practice to use.
Example:
def get_input(show_text:str):
    while True:
        try:
            number = int(input(show_text))
            break
        except ValueError:
            print('Enter number only!')
    return number

number_1 = get_input('enter the first number: ')
number_2 = get_input('enter the second number: ')
result = number_1 + number_2
print(f" {number_1} + {number_2} = {result}")

Example output
enter the first number: 1
enter the second number: a
Enter number only!
enter the second number: f
Enter number only!
enter the second number: 2
 1 + 2 = 3


text:
Q: Trying to show graph and other details in TensorBoard on google-colab by ngrok but failed I trained a model, got a log file and show graph and other details in TensorBoard on my computer.
It was successful and nothing wrong.
Then I tried to do it again on colab.
I install ngrok and tensorboard on colab, upload the log file and call tensorboard to show information.

# Install tensorboardcolab,download and unzeip ngrok
!pip install tensorboardcolab
!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip
print()

# Delete unuse file and folder
!rm ngrok-stable-linux-amd64.zip
!rm -f -r sample_data
!pwd
!ls
print()
# upload a log file from local
from google.colab import files
uploaded = files.upload()
!ls
print()

# start tensorboard on ngrok
get_ipython().system_raw('tensorboard --logdir /content --host 0.0.0.0 --port 6006 &')
get_ipython().system_raw('./ngrok http 6006 &')
!curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

Below is the output after I ran the above.
Requirement already satisfied: tensorboardcolab in /usr/local/lib/python3.6/dist-packages (0.0.22)
--2019-06-17 08:01:48--  https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
Resolving bin.equinox.io (bin.equinox.io)... 52.72.145.109, 52.203.66.95, 52.200.123.104, ...
Connecting to bin.equinox.io (bin.equinox.io)|52.72.145.109|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16648024 (16M) [application/octet-stream]
Saving to: 'ngrok-stable-linux-amd64.zip'

ngrok-stable-linux- 100%[===================>]  15.88M  17.0MB/s    in 0.9s

2019-06-17 08:01:49 (17.0 MB/s) - 'ngrok-stable-linux-amd64.zip' saved [16648024/16648024]

Archive:  ngrok-stable-linux-amd64.zip
  inflating: ngrok

/content
ngrok

events.out.tfevents.1560697268.DESKTOP-SMMCEHS(n/a) - 3431006 bytes, last modified: 6/16/2019 - 100% done
 Saving events.out.tfevents.1560697268.DESKTOP-SMMCEHS to events.out.tfevents.1560697268.DESKTOP-SMMCEHS
events.out.tfevents.1560697268.DESKTOP-SMMCEHS  ngrok

http://c9c33cc9.ngrok.io

I got this in the link. It said "No dashboards are active for the current data set".
Here is the notebook on colab.
I have no idea why this happened. There is a valid tensorboard link so I guess ngrok worked fine.
Checked TensorBoard tutorial but it focus on how to use in a local environment.
Can anyone help me with this? Any reply would be greatly appreciated.


text:
Q: Using prompt and if and spring to number together in javascript What I want to do is that if I type some text like Hello! in prompt I'll activate the first condition and if I write 5 in prompt I activate the second condition and anything else I activate the last condition. But It's not happening and I can't figure it out.

let fx = +prompt('?', '');
if (fx == null) {
  alert('f');
} else if (fx == 5) {
  alert('s');
} else {
  alert('gfgfg');
}

A: You could check for NaN with isNaN and display a text which reflects the input.
If you prompt a value which is not convertable to a number by using an unary plus +, you get NaN as value. For checking this value you need to use the above mentioned function which returns a boolean value.

let fx = +prompt('?', '');

if (isNaN(fx)) {
    console.log('not a number');
} else if (fx === 5) {
    console.log('five!');
} else {
    console.log('some other number not 5');
}


text:
Q: Add column in hive not allowed from scala/spark code I am trying to add a column in a Hive table if the source data has new columns. All the detection of new columns works well, however, when I try to add the column to the destination table, I receive this error:
for (f <- df.schema.fields) {
  if ("[" + f.name + "]"==chk) {
    spark.sqlContext.sql("alter table dbo_nwd_orders add columns (" + f.name + " " + f.dataType.typeName.replace("integer", "int") + ")")
  }
}

Error:
WARN HiveExternalCatalog: Could not alter schema of table  `default`.`dbo_nwd_orders` in a Hive compatible way. Updating Hive metastore in Spark SQL specific format
InvalidOperationException(message:partition keys can not be changed.)

However, if I catch the alter sentence generated and execute it from hive GUI (HUE), I can add it without issues.
alter table dbo_nwd_orders add columns (newCol int)

Why that sentence is valid from the GUI and not from spark code?
Thank you very much.

A: It has been said multiple times here, but just to reiterate - Spark is not Hive interface and is not designed for full Hive compatibility in terms of language (Spark targets SQL standard, Hive uses custom SQL-like query language) or capabilities (Spark is ETL solution, Hive is a Data Warehousing solution).
Even data layouts are not fully compatible between these two.
Spark with Hive support is Spark with access to Hive metastore, not Spark that behaves like Hive.
If you need to access full set of Hive's features connect to Hive directly with native client or native (not Spark) JDBC connection, and use interact with it from there.


text:
Q: Is it possible to record desktop screen with html5? Html5 can be used to record camera HTML5 solution to upload a webcam/camera video stream to server
What if instead of camera, I want to record user desktop screen ?

A: Check out this library: https://mgechev.github.io/jscapture/
Maybe you can implement this on your website.


text:
Q: Importing google app engine project from eclipse into intellij I'm trying out intellij to see what it is like to develop/maintain google app engine projects.  I've used the GAE plugin for eclipse for a couple of years and it usually worked flawlessly for me but I've heard a lot about intellij recently so I wanted to see what I was missing.
I've read many sites that describe step-by-step how to create new GAE projects in intellij but none that describe how to do so for existing projects.  I'm struggling with I imagine is some intellij 101 topics.  I have a few questions that I'm bundling together here:

*

*I added the Web/GAE facet to the project and specified the appropriate GAE SDK directory and appengine account info.  What's the right way to associate the right SDK jars with my project?

*IntelliJ recognized my maven imports and added them to my External Libraries, things like apache commons, slf4j, etc.  How do these jars make their way into the (exploded war) artifact I created for the project?  Are they automatically copied there after a successful compile?

*I'm using JDO so I downloaded the DataNucleus plugin.  How do I wire it up so it enhances my classes?
Thanks in advance.

A: *

*File - Project Structure - Modules - AppEngine: at the right side is "Path to AppEngine SDK install directory". Click button right to it to select dir via file selector. This is the right way - here Intellij will use all the needed jars in your project, no need to add GAE jars by hand .

*File - Project Structure - Artifacts: you should have a war artifact here. Create one if it's not there (+). Jars used in the project should be in "Available Elements" pane. You can add jars (if not added automatically) by drag-n-dropping them between panes. Yes, jars will be copied into war if they are in the left pane showing the contents of the package.

*File - Project Structure - Modules - AppEngine: check the "Run enhancer for the following classes.." and select your classes/packages.


text:
Q: Why am I getting this error? non-static variable randomNumbers cannot be referenced from a static context I know that there are many questions like this one but it didn't really help me out any. I have to Write a program that will help an elementary school student learn multiplication. Use a SecureRandom object to produce two positive one-digit integers. The program should then prompt the user with a question, such as "How much is 6 times 7?" I have done the hard part but I can not get my variables that is in my class to work for the other methods. i will "get non-static variable randomNumbers cannot be referenced from a static context" error! can someone help me please!!
import java.util.Random;
import java.util.Scanner;

public class computerAssistedInstruction {
    Random randomNumbers = new Random();
    int answer;// the right answer

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        int input;// the user answer
        newQuestion();
        input = scnr.nextInt();
        if (input != answer) {
            System.out.println("No. Please try again.");
        }// end of if
        else {
            System.out.print("Very Good!");
            newQuestion();
        }// end of else
    }// end of main

    public static void newQuestion() {
        int number1 = randomNumbers.nextInt(10);
        int number2 = randomNumbers.nextInt(10);
        answer = number1 * number2;
        System.out.printf("How much is %d times %d?", number1, number2);
    }// end of newQuestion
}// end of class

A: Problem
The error is

non-static variable randomNumbers cannot be referenced from a static context

which means that since you declared randomNumbers like this
public class computerAssistedInstruction {
     Random randomNumbers = new Random();
     int answer;
}

you cannot use it (or answer) in your static method
public static void newQuestion() {
    ...
}
Solution
Either make randomNumbers and answer static variables, or make newQuestion an instance method (i.e. not static) like so:
public class computerAssistedInstruction {
     Random randomNumbers = new Random();
     int answer;

     ...

     public void newQuestion() {
          ...
     }
}

Now, you need to edit your main method a little since you cannot call the non-static method without an instance of the class anymore. So, instead of
public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    int input;

    newQuestion();
    input = scnr.nextInt();

    if (input != answer) {
        System.out.println("No. Please try again.");
    }
    else {
        System.out.print("Very Good!");
        newQuestion();
    }
}

you would now need this:
public static void main(String[] args) {
    computerAssistedInstruction instance = new computerAssistedInstruction(); // Create an instance of the class here.
    Scanner scnr = new Scanner(System.in);
    int input;

    instance.newQuestion(); // Call newQuestion() on the instance.
    ^^^^^^^^^^^^^^^^^^^^^^^

    input = scnr.nextInt();

    if (input != answer) {
        System.out.println("No. Please try again.");
    }
    else {
        System.out.print("Very Good!");
        instance.newQuestion();
        ^^^^^^^^^^^^^^^^^^^^^^^
    }
}


text:
Q: Difference between "&lt" and "<" I saw people use some special characters like '&lt' instead of '<' in an enterprise project and write codes like this:
if (someting.length < 10000)

Is there any special reason for that?

A: < is < escaped (in a form of XML entity), so the code you posted is not valid, unless it's been encoded.
After decoding, code would look like:
if (someting.length < 10000)

so it makes sense now.
You can look here for a full list of XML/HTML entities.
Edit: as per comment by @Dan Goodspeed, note that trailing ; is mandatory.

A: Is the code per-chance in an XML file, or similar?
Obviously in XML files, the angular parenthesis have a special meaning - they create tags which start / end elements, for example:
<html></html>

Thus, if you use angular parenthesis as part of the text inside an element, this can confuse certain XML interpreters, for example:
<html>This is an angular parenthesis for less-than < </html>

To avoid the confusion that the parenthesis in the text block is not the start of a new element, it's best to "escape" it:
<html>This is an angular parenthesis for less-than < </html>

A: <, >, & etc are used in XML syntax. if you want use these in our text, to avoid confusion to parser we use < for <, > for >, & for & etc.
These are called XMl entity.
HTML is another markup language that supports entities.


text:
Q: How to resolve import and export error in reportWebVitals.js I am new to coding with React.js and monday.com. I am trying to create a weather app that works with monday.com. I want the app to use the location column on the monday.com board to display the weather data for a specific city. My api seems to work just fine and gives the weather results when I enter a city into my app. The below error occurred once I started to try and get the app to work with the monday.com board.
I have an import/export error. I have checked all my opening and closing brackets but they all seem correct. Please advise how I can fix this problem. Thanks!
Error:
Error in ./src/reportWebVitals.js
Syntax error: C:/Users/E7470/weather-app/src/reportWebVitals.js: 'import' and 'export' may only appear at the top level (3:4)

 1 |
const reportWebVitals = onPerfEntry => {
  2 |   if (onPerfEntry && onPerfEntry instanceof Function) {
> 3 |     import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
    |     ^
  4 |       getCLS(onPerfEntry);
  5 |       getFID(onPerfEntry);
  6 |       getFCP(onPerfEntry);

 @ ./src/index.js 19:23-51

App.js:
import React, { useState } from 'react';
import './App.css';
import mondaySdk from 'monday-sdk-js';
import 'monday-ui-react-core/dist/main.css';
//Explore more Monday React Components here: https://style.monday.com/
import AttentionBox from 'monday-ui-react-core/dist/AttentionBox.js';

const monday = mondaySdk();

function App() {
  const apiKey = 'API KEY'; //I inserted my api key here
  const [weatherData, setWeatherData] = useState([{}]);
  const [city, setCity] = useState('');

  const [context, setContext] = useState();
const [weatherArr, setWeatherArr] = useState();

useEffect(() => {
  const getContext = async () => {
    try {
      monday.listen('context', (res) => {
        console.log(res.data);
        getBoards(res.data);
        setContext(res.data);
      });

      monday.listen("settings", (res) => {
        console.log(res.data);
        setMeasurementUnit(res.data.dropdown)
      })

      //board id (Add board Id Here eg.328567743)
    } catch (err) {
      throw new Error(err);
    }
  };
  getContext();
}, []);

const getBoards = async (context) => {
  try {
    var arr = [];
    var boards = [];
    for( const boardId of context.boardIds){
      var res = await  monday.api(`query { boards(limit:1, ids:[${boardId}]) {
        name
        items {
          name
          column_values {
            id
            value
            text
          }
        }
        }
      }`);
    boards.push(res.data.boards);
    }

   for (const board of boards ){
    console.log(boards)
    console.log(board)
    for (const item of  board[0].items){
      var location = item.column_values[0].text;
      var latLng = item.column_values[0].value
      var itemObj = {
        location,
        latLng
      }

  const getWeather = (event) => {
    if (event.key == 'Enter') {
      fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=imperil&APPID=${apiKey}` //api given in video tutorial
      )
        .then((response) => response.json())
        .then((data) => {
          setWeatherData(data);
          setCity('');
        });
    }
  };

  setWeatherArr(arr);
} catch (err) {
  throw new Error(err);
}
};

  return (

      <input
        className="input"
        placeholder="Enter City..."
        onChange={(e) => setCity(e.target.value)}
        value={city}
        onKeyPress={getWeather}
      />

      {typeof weatherData.main === 'undefined' ? (

Welcome to weather app! Enter the city you want the weather of.

      ) : (

{weatherData.name}

{Math.round(weatherData.main.temp)}℉

{weatherData.weather[0].main}

      )}

      {weatherData.cod === '404' ?
City not found.
 : <></>}

  );
}

export default App;

App.css:
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 25px;
 }

 .input {
padding: 15px;
width: 80%;
margin: auto;
border: 1px solid lightgrey;
border-radius: 6px;
font-size: 16px;
 }

 .input:focus{
  outline: none;
 }

 .weather-data{
  margin-top: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
 }

 .city{
  font-size: 30px;
  font-weight: 200;
 }

 .temp{
  font-size: 90px;
  padding: 10px;
  border: 1px solid lightgray;
  border-radius: 12px;
 }

 .weather{
  font-size: 30px;
  font-weight: 200;
 }


text:
Q: What's the term for a word used in casual conversation that differs from its actual meaning, e.g. using "rim" to mean "wheel" It could be:
catachresis: A misuse of a word; an application of a term to something which it does not properly denote. e.g. Using 'rim' instead of 'wheel' is a catachresis, a misnomer used in casual conversation where 'rim' is understood to mean 'wheel' (the metal part, everything besides the tire).
solecism: An erroneous or improper usage.
Are there other terms to describe this?

A: This could also be an example of metonymy:

a figure of speech that consists of the use of the name of one object or concept for that of another to which it is related, or of which it is a part, as "scepter" for "sovereignty," or "the bottle" for "strong drink," or "count heads (or noses)" for "count people."

A: Well, both your words come close, in fact. However, you might want to consider howler. A bit old-fashioned, if you ask me, but still up to the task:

howler 3. a mistake, especially an embarrassing one in speech or writing, that evokes laughter; a very humorous mistake or a funny
blunder.

https://www.dictionary.com/browse/howler


text:
Q: Cryptology - Compare the amount of work the cryptanalyst is likely to require - Single vs. Double rotation "Suppose a cryptanalyst suspects that
SECEC SYHRI IRFET SSETE INLST AFNIA FSOAI HFSRT TEATE
was obtained by a succession of two rotations with different block lengths and rotation amounts. Compare the amount of work the cryptanalyst is likely to require under this assumption with what she is likely to require under the assumption of a single rotation. Try to do the cryptanalyst's work."
I am totally lost here regarding what they mean by "compare the work" and what a succession of two rotations entails. The book is very poorly written with lots of mistakes and just asked this question randomly without any mention of any such thing in the chapter. Any help is greatly appreciated!

A: One of the naive methods of encryption is to divide text into a few blocks of equal length, and to rotate letters inside each block.
Example:
Text : HELLOMYNEWWORLD (HELLO, MY NEW WORLD).
(We will ignore spaces, dots, etc)
Block length can be $3$, $5$ or $15$ (factors of $15$ - length of text).
Suppose Block length is $5$. Let rotation amount is $2$.
We'll denote this operation as $R(5,2)$.
Then we'll get
1) HELLO MYNEW WORLD
2) LOHEL EWMYN LDWOR
3) LOHELEWMYNLDWOR
To make encryption more complicated,
let's apply rotation for other block length (suppose for $3$).
Let rotation amount is $1$.
We'll denote this rotation as $R(3,1)$:
4) LOH ELE WMY NLD WOR
5) HLO EEL YWM DNL RWO
6) HLOEELYWMDNLRWO
So, applying sequentially $R(5,2), R(3,1)$, we get cipher text HLOEELYWMDNLRWO.
To decrypt, we need to apply inverse rotations in inverse order:
A) rotation R(3,2) as complementary/inverse rotation for R(3,1); (why?)
B) rotation R(5,3) as complementary/inverse rotation for R(5,2).

Your task:
When apply rotation $R(5,3)$ first, and rotation $R(3,2)$ after, we'll get:
1) SECEC SYHRI IRFET SSETE INLST AFNIA FSOAI HFSRT TEATE
2) ECSEC RISYH ETIRF TESSE STINL IAAFN AIFSO RTHFS TETEA
3) ECSECRISYHETIRFTESSESTINLIAAFNAIFSORTHFSTETEA
4) ECS ECR ISY HET IRF TES SES TIN LIA AFN AIF SOR THF STE TEA
5) SEC REC YIS THE FIR STE SSE NTI ALI NAF FAI RSO FTH EST ATE
6) SECRECYISTHEFIRSTESSENTIALINAFFAIRSOFTHESTATE
Can you read this???

To compare amount of work, you need to find factors of $45$ (text length): $3,5,9,15,45$.
If there was applied $1$ rotation, then amount of work is:
1) to check block length $3$ and amounts of rotation $1,2$;
2) to check block length $5$ and amounts of rotation $1,2,3,4$;
3) to check block length $9$ and amounts of rotation $1,2,...,8$;
4) to check block length $15$ and amounts of rotation $1,2,...,14$;
5) to check block length $45$ and amounts of rotation $1,2,...,44$.
Total amount of work is $2+4+8+14+44$ items.
If there were applied $2$ rotations, then amount of work is to check each pair of block lengths with their possible amounts of rotations.
Note, that rotations $R(15,2),R(3,1)$ and $R(3,1),R(15,2)$ are different rotations.


text:
Q: can I set the pointcut on the interfaces that extends MongoRepository When I set a pointcut on the interfaces that extends MongoRepository, but it works failed. Spring throws some exceptions. I have used @EnableAspectJAutoProxy in my MongoConfig.java file.
MongoConfig like this:
@Configuration
@EnableMongoRepositories(basePackages = {"com.nd.*.repository"})
@PropertySource("classpath:mongo.properties")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MongoConfig extends AbstractMongoConfiguration

If I remove the pointcut on repositories, it's OK. Stack info like this:
Caused by: org.springframework.beans.factory.BeanCreationException: Error  creating bean with name 'activityInvitationRespository': Post-processing of the FactoryBean's object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy54]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy54
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:167)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:103)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1514)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 58 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy54]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy54
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:212)
    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:494)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:379)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:339)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:421)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1698)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:164)
    ... 66 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy54
    at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
    at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
    at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
    at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
    at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57)
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
    ... 73 more


text:
Q: Getting the values in response body but web_reg_save_param is not capturing for some request I am encountering a problem in Load Runner where I can see the valid response in the Response body in snapshot view of request and approx 50% of times the value is captured in  a variable where correlation is done with web_reg_save_param_ex.
But for the same boundaries in web_reg_save_param the values are not captured in the variable in some of the case:

*

*I also checked the boundaries are not changing.

*Used web_set_max_html_param_len("999999") which is enough to capture response in my case.

What could be the other reason for this? Below are the error received in LR.
Action.c(181): Error -26377: No match found for the requested parameter "c_abcdef". Either the specified boundaries were not found in the response or the matched text is longer than current max html parameter size of 999999 bytes. The total length of the response is 50472 bytes. You can use "web_set_max_html_param_len" to increase the max parameter size.    [MsgId: MERR-26377]

Action.c(181): Error -26377: No match found for the requested parameter "c_trRef". Either the specified boundaries were not found in the response or the matched text is longer than current max html parameter size of 999999 bytes. The total length of the response is 50472 bytes. You can use "web_set_max_html_param_len" to increase the max parameter size.     [MsgId: MERR-26377]


text:
Q: Is there an easier way to disable all the buttons in matlab app designer? I wanted to know if there is an easier way to disable or enable all the buttons without calling each one separately. I was hoping to be able to press a start button which would then enable all the buttons in the app.
        app.Button_1.Enable = "off";
        app.Button_2.Enable = "off";
        app.Button_3.Enable = "off";
        app.Button_4.Enable = "off";
        app.Button_5.Enable = "off";
        app.Button_6.Enable = "off";
        app.Button_7.Enable = "off";
        app.Button_8.Enable = "off";
        app.Button_9.Enable = "off";

A: You need to create an array of handles to the components you want to affect, then loop through that array.  The example below works assuming that all of your buttons are placed directly onto the UIFigure and not in containers (no panels, grid layouts, tab groups).  If you do have any panels/etc. then you need to get the handles for their children also, and add them to your array of handles.
(The example below also skips disabling anything other than buttons, to show how you would do that.  If you want to disable all components (including edit fields, etc.), then just remove that if statement.
Edit: I should also point out that App Designer now has functions like uiconfirm() that are modal, and will therefore disable all other components until the user interacts with them.
    % Code that executes after component creation
    function startupFcn(app)
        allComponents = app.UIFigure.Children; % get a list of components that are direct children of the UIFigure

        for ii = 1:numel(allComponents) % loop through all the components
            thisComponent = allComponents(ii);
            if strcmpi(thisComponent.Type, 'uibutton') % disable buttons only
                thisComponent.Enable = 'off';
            end
        end
    end

    % Button pushed function: Button
    function ButtonPushed(app, event)
        allComponents = app.UIFigure.Children; % get a list of components that are direct children of the UIFigure

        for ii = 1:numel(allComponents) % loop through all the components
            thisComponent = allComponents(ii);
            if strcmpi(thisComponent.Type, 'uibutton') % enable buttons only
                thisComponent.Enable = 'on';
            end
        end
    end


text:
Q: how to create a deep link for FireStore content? In my android app, I have some user posts like in social media posts with some text, photo, and some additional details.
What I need is when user clicks on the share button it will create a dynamic or deep-link to that specific post.
I had stored some posts in Firestore and some in Realtime Database. How to create dynamic links to the specific posts?
I had seen the developer page, but not found how to achieve this. Any suggestions please...

A: You can use URL parameters in your Firebase Dynamic links and with that determine what post to show in the app when it's opened by a dynamic link.
For example such an URL:
Uri.parse('https://your.page.link/view_post/?postID=${post.uid}'


text:
Q: Jenkins exception : Run 'tf eula' to accept the End User License Agreement I'm trying to build a Visual Studio Solution(.sln) using Jenkins Plugin.
When I trigger the build I'm getting the below exception
Error: You must accept the End User License Agreement for this product
Run 'tf eula' to accept the End User License Agreement.
FATAL: Executable returned an unexpected result code [100]
ERROR: null
Finished: FAILURE

How can I run the tf eula to accept end user license agreement?
Any way to disable EULA by some configuration?

A: tf eula -accept

search for tf.exe on slave machine


text:
Q: Displaying an image via acf in the theme header I am using AFC Pro and created an options pafe so tjhat the user can upload a new header logo whenever he wants to.
The ACF field is called "headerlogo".
What I want now is that the Logo gets replaced by my theme automatically.
My Variables are:
$headerlogo = wp_get_attachment_image_src(get_field('headerlogo', 'option'), 'full');

$default_logo = '';

they get called in:
echo '
            ' . $default_logo . '
        ';

But the Output is:

What am I doing wrong here?
Thank in advance.

A: This should work:
<?php
$headerlogo = get_field('headerlogo');
if( !empty($headerlogo) ):
    $default_logo = '';
endif;

echo '' . $default_logo . '';
?>


text:
Q: Issue sending POST request from Swift Essentially I need to send a POST request to an API that is looking for the parameter value for "value" I have a variable in my Swift app that is called testPOST that contains the value the API is looking for:
I am having trouble understanding why the following code is not working?
fileprivate func fetchJSON(){
    var urlString =  URLRequest(url: URL(string: "https://example.com/example/example.php")!)
    guard let url = URL(string: urlString) else { return }
    urlString.httpMethod = "POST"
    let postString = "value=\(testPOST)"
    URLRequest.httpBody = postString.data(using: .utf8)
    URLSession.shared.dataTask(with: url) { (data, _, error) in
        DispatchQueue.main.async {
            if let error = error {
                print("Failed to fetch data from url", error)
                return
            }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                // Swift 4.1

                self.structure = try decoder.decode([ScheduleStructure].self, from: data)

                self.tableView.reloadData()

            } catch let jsonError {
                print("Failed to decode json", jsonError)
            }

        }
        }.resume()
}

UPDATE:
I don't get any error messages, but I also don't receive any JSON data back, ScheduleStructure is the codable struct I have but it doesn't seem to be read.
import UIKit
struct ScheduleStructure: Codable {
    let customer: String
    let PickedUpNUM: String
    let DeliveryNUM: String

}

I just need a way to POST a value to the API and have it return JSON data.  The only issue I am having is sending the data from the app and having it return data.

A: Change the beginning of your function to
guard let url = URL(string: "https://example.com/example/example.php") else {
    return
}
var request =  URLRequest(url: url)
request.httpMethod = "POST"
let postString = "value=\(testPOST)"
request.httpBody = postString.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, _, error) in

You created your url object twice and treated the request as a string

A: You should feel free to accept Joakim's answer which identified the syntactical issues, but I wanted to make another observation. Specifically your request will fail or not work properly if testPOST contains any reserved characters (e.g. space, &, +, etc.). Unless you know that testPOST can never contain any such characters, should percent-encode the value when building your request, e.g.:
func fetchJSON() {
    guard
        let url = URL(string: "https://example.com/example/example.php"),
        let value = testPOST.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
    else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "value=\(value)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, _, error in
        DispatchQueue.main.async {
            // ...
        }
    }.resume()
}

Where
extension CharacterSet {
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)
        return allowed
    }()
}

BTW, it's also best practice (though often not required) to set a few headers, specifically Content-Type (specifying how the request is encoded) and Accept (how the client expects the response to be encoded).
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

Your web service is obviously not considering these headers, but many web services do. Plus, it makes the intent of your code explicit.


text:
Q: Script install fonts powershell I have a script which installs a font, after checking whether the fonts exists or not. However, I'm having trouble validating the existence of the font.
$FONTS = 0x14;

$FromPath = "c:\fonts";

$ObjShell = New-Object -ComObject Shell.Application;
$ObjFolder = $ObjShell.Namespace($FONTS);

$CopyOptions = 4 + 16;
$CopyFlag = [String]::Format("{0:x}", $CopyOptions);

foreach($File in $(Get-ChildItem -Path $FromPath)){
    If ((Test-Path "c:\windows\fonts\$($File.name)") -eq $False)
    { }
    Else
    {
        $CopyFlag = [String]::Format("{0:x}", $CopyOptions);
        $ObjFolder.CopyHere($File.fullname, $CopyOptions);

        New-ItemProperty -Name $File.fullname -Path "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Fonts" -PropertyType string -Value $File
    }
}

A: Your if statement is wrong
If ((Test-Path "c:\windows\fonts\$($File.name)") -eq $False)

Test-Path returns true if the file exists and false if it doesnt. So in the case the file does not exist you have false -eq false = true so nothing is executed. Your code to copy the item only gets called if it already exists.
Solution:
If (Test-Path "c:\windows\fonts\$($File.name)")

A: Paul is correct. Basically your If condition was backwards.
If (Test-Path "c:\windows\fonts\$($File.name)")
 is equivalent to
If ((Test-Path "c:\windows\fonts\$($File.name)") -eq $True)
Either will work, though the second is unnecessarily more complex.


text:
Q: Error: (node:17060) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension I just started learning JavaScript by using Atom in order to create an online chart. Hence, I am quite unfamiliar with NPM, package.json and all that sort of things.
I want to import two modules by using the following code:
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";

Which gives the following error message:
(node:17060) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Users\PF1VMKH9_ADM\Documents\herverkaveling\test:4
import * as am4core from "@amcharts/amcharts4/core";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Object.newLoader [as .js] (C:\Users\PF1VMKH9_ADM\.atom\packages\script\node_modules\pirates\lib\index.js:104:7)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at Object.<anonymous> (C:\Users\PF1VMKH9_ADM\.atom\packages\script\node_modules\@babel\node\lib\_babel-node.js:176:21)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
[Finished in 0.522s]

I added "type": "module" to the package.json file but it did not solve the issue:
{
  "name": "packages",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type":"module",
  "dependencies": {
    "typescript": "^4.4.4"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

What am I doing wrong?


text:
Q: How to Sum from query search result I want to SUM from a query search result. I  have a table called Students. I created a Search form to list students with scores from Jan or Feb, by date range. The results are different (two rows, four rows, so on) based on how many months I search. I created a Sum row at the bottom to count the total from that column for Jan or Feb. However, it doesn't work at all.
Can anyone help?
Here is my code:

    Student Name
    Jan
    Feb

    <%=oRs("Name")%>
    <td <%=sRowStyle%>><%=oRs("Jan")%>
    <td <%=sRowStyle%>><%=oRs("Feb")%>

    <% total = total + CInt(oRs("Jan")) oRs.MoveNext WEND %>

A: It looks like you haven't defined where your recordset loop starts
Try this:
<% Dim CountJan, CountFeb
   Do while not oRS.eof %>

    <%=oRs("Name")%>
    <td <%=sRowStyle%>><%=oRs("Jan")%>
    <td <%=sRowStyle%>><%=oRs("Feb")%>

<% CountJan = CountJan + Cint(oRs("Jan"))
   CountFeb = CountFeb + Cint(oRs("Feb"))
   oRs.MoveNext
   Loop
 %>

    <%=CountJan%>
    <%=CountFeb%>

You can use while and wend instead of do while not and loop, its a matter of personal preference


text:
Q: Fitting data to the Poisson As a part of my mathematics research, I am trying to model the traffic in my city.
I have gathered traffic flow count data from highways and city roads. I am using the Poisson model for distribution. The data I gathered sometimes fails the chi-squared test. In this situation, which other model / addition would you suggest? I want to basically also state the limitations of a particular model in heavy traffic and conclude the best type of model for different traffic flows.

*

*my data has 13 degrees of freedom ; the chi-square value is coming too large - about 3000
what should i do in this case ?


text:
Q: How to allow maxDate and minDate to be equal on Bootstrap DateTimePicker? In order to create a report, I need to be able to choose the same starting and ending date.
I'm able to do that, but only on the first time that I pick the maxDate.
After that I can't pick the same value of the minDate as maxDate.
E.g:
Browser opens up.
I choose 01/01/2020 as starting date (minDate).
I choose 01/01/2020 as ending date (maxDate).
I change ending date to 02/01/2020.
Now I'm unable to pick '01/01/2020' as ending date again.
I need to be able to select the same moment for minDate and maxDate
I can't seem to find a solution for this in the DateTimePicker documentation
I've tried setting some values on the change event:
$(".datetimepickerTo").on("dp.change", function (e) {
    $('.datetimepickerFrom').data("DateTimePicker").maxDate(e.date);
});

And on the datetimepicker selector:
$('.datetimepickerTo').datetimepicker({
    useCurrent: false
});

A: Turns out it was a date format issue.
For some reason when selecting dates for the first time, the date output was:

'Wed Jan 01 2020 16:39:34 GMT-0300 (Horário Padrão de Brasília)'.

Where '16:39:34' was the actual time that I picked the date.
Although, on the second time selecting, the output was:

'Wed Jan 01 2020 00:00:00 GMT-0300 (Horário Padrão de Brasília)'

Making two different dates.
My approach was to format the date to the format that I needed. Using this function:
function formatDate(date) {
    var months = [
        "1", "2", "3",
        "4", "5", "6",
        "7", "8", "9",
        "10", "11", "12"
    ];

    var day = date.getDate();
    var monthIndex = date.getMonth();
    var year = date.getFullYear();

    return day + '/' + months[monthIndex] + '/' + year;
}

Where the output was:

01/01/2020

Then I just had to pass the formatted date to minDate() and maxDate() functions:
$(".datetimepickerFrom").datetimepicker().on("dp.change", function (e) {
    const formattedDate = formatDate(e.date.toDate())
    $('.datetimepickerTo').data("DateTimePicker").minDate(formattedDate);
});

$(".datetimepickerTo").datetimepicker().on("dp.change", function (e) {
    const formattedDate = formatDate(e.date.toDate())
    $('.datetimepickerFrom').data("DateTimePicker").maxDate(formattedDate);
});

A: I solved this problem by setting the default time zone before initializing the datetimepicker:
moment.tz.setDefault("Europe/Rome")

$('#multi_event_date').datetimepicker({
 ...
})


text:
Q: findAll returns empty list This is Repository interface
@Repository
    public interface MenuStructureTblService extends JpaRepository<MenuStructureTbl, Integer> {
}

MenuStructureTbl Table
@Data
@Entity(name = "menu_structure_tbl")
public class MenuStructureTbl {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Integer menuId;
    public String menuTitle;
    public String menuText;
    public Integer menuMotherId;
    public String createDate;
    public String updateDate;
}

I am banging my head on the wall, Returned list is empty.
This one returns null
@Repository
public interface MenuStructureTblService extends JpaRepository<MenuStructureTbl, Integer> {
    @Query(value="SELECT * FROM menu_structure_tbl", nativeQuery = true)
    Object justGetIT();
}

Returns null; I have checked the query, generates result. But, I do not know what is going on.
Let me know if you have any question.

A: My mistake, Conflict of Environment, i was checking against wrong environment.


text:
Q: Getting the value in jquery I have a problem in getting all of the values from the Total column and display it in the grand total field, but it doesn't show anything. Please help I am new to jquery. I am using this kind of script.

I have a snippet here.
<script>
  $(function() {

      $('.total').mask('#,###.##',{reverse : true});

      var grand_total = function() {
          var sum=0;
          $('.total').each(function(){
              var num = $(this).val().replace(',','');

              if(num != 0) {
                  sum +=parseFloat(num);
              }
          });
          $('#grand_total').val(sum.toFixed(2));
      }
       $('.total').keyup(function(){
          grand_total();
       });
  });
</script>

A: Based on the demo you have shared: Fiddle Demo
There are a few issues in your code:

*

*There is no element in your code having class .total. I am assuming the last column with header name as "Total" needs to have this class.

*Next, you are calling grand_total() function on keyup event on .total class elements, but as no element exists with this class thus grand total field is not showing anything.

*Also, "Total" column elements are readonly, so anyways keyup event will be never fired.

To resolve these issues, first add .total class to all the elements in "Total" column and then add grand_total() function inside all keyup events for classes .amount1, .amount2 and so on.. so that when any of the keyup event is fired grand total will be auto-calculated.
Here is the updated demo with all the above changes: Working Fiddle Demo


text:
Q: How do I insert primary id's from other tables into a new table I have a table called "artist" with three columns:
artist_id {PK} | artist_name | artist_url

There are around 500+ artists in this table.
I want to be able to copy all of the primary keys over to a table called "artist_to_store". This table will have two columns:
artist_id {PK} | store_id.

Store ID will always be equal to 0
I thought this query would work:
INSERT INTO artist_to_store SET artist_id = (SELECT artistr_id FROM artist) AND store_id = 0

Instead it reuturns with the error #1242 - Subquery returns more than 1 row.
I know what the error means so nobody needs to explain it. But could somebody please tell me how I get all of the artist_id's from the artist table to the other table?
Thanks,  and a Happy New Year when it arrives :)
Peter

A: Try this ::
INSERT INTO artist_to_store(artistId, storeId) SELECT artistr_id,0 FROM artist

A: INSERT INTO artist_to_store (SELECT artistr_id,0 FROM artist);

Try this


text:
Q: what would happen if I used a rheostat in series with a motor to drop my 230v ac supply to 110v ac? I realize that I would be running higher (a little more than double) current through the motor I'm just curious if it would damage my motor?
The motor is a 1 hp, 110V/60Hz driving a meat grinder.

A: It is very unlikely to be satisfactory. The reason is that the motor, as an electrical load, is variable depending on speed and mechanical load conditions on the motor. You would have to adjust the rheostat faster than humanly possible to get this to work the way you probably want it to. Maybe it could work in some very limited conditions. Also, note that you will dissipate a lot of power in the rheostat. Depending on motor size, the rheostat may need a fan to prevent it from overheating, and it will also be energized at a hazardous voltage. Talk about double-trouble.


text:
Q: sharepoint development concept issue -- about site and application I am developing on SharePoint Service 3.0/SharePoint Server 2007. I always read document says create an application or create a site (collection). The term application and site always make me confused. Could anyone help to clarify what is the relationship between a SharePoint application and a site (collection)?
For example, here is one of the case when I am confused,
http://weblog.vb-tech.com/nick/archive/2006/06/14/1617.aspx
"1, Create a new site – go to Office Server Central Administration -> Application Management -> Create or Extend Web Application -> Create a new Web Application Enter the settings to create a new SharePoint site." -- mixing site and application make me confused.
"Once the Application has been created choose to 'Create a new Windows SharePoint Services site collection'." -- seems application has 1:1 relationship with site collection?
thanks in advance,
George

A: Yes, that's a bit confusing. In the first instance he is using the term "site" to mean preparing the SharePoint installation to serve content, basically enabling it to become a web site; in the second instance he is talking about creating actual sites within SharePoint.
There are basically four different levels to think about in SharePoint:

*

*Farm - all the SharePoint servers (even the database server) taken as a whole. This is what you interact with via Central Administration

*Web Application - the software that serves SharePoint content via IIS

*site collection - a hierarchical collection of sites

*site - the actual site that the user interacts with within a site collection

If you find that confusing, wait until you program against it where you'll find a site is called SPWeb and a site collection is SPSite...

A: In real development terms - A SharePoint Application is an IIS site with nothing configured, while the site collection is the initial base configuration of the IIS App, sites in the site collections can be thought of as virtual directories.
This is not entirely accurate, but its a good way to generate a mental picture.
And you're right to be confused, welcome to the world of MOSS! Its gets even better.


text:
Q: What control to use to capture image from camera and show on ui as thumbnail with events xamarin ios I have created a view like this in my xamarin iOS mobile project.

User will be able to click on the capture images button to take a picture and set the image property of the image view.  I would like to know how can i allow the user longpress a image (after it has been captured) and popup a message box to delete the image.
I have tried what Sameer has suggested in his comment like so in my ViewDidLoad
    var gestureRecognizer = new UILongPressGestureRecognizer();
    gestureRecognizer.AddTarget(() => ButtonLongPressed(gestureRecognizer));
    img1.AddGestureRecognizer(gestureRecognizer);
    img2.AddGestureRecognizer(gestureRecognizer);

When i click and hold on the image nothing happens. I have added these image views via the designer.
After a little more research and using the comment from @Junior Jiang - MSFT. I have made a bit progress but i would like to know which UIImage view has been clicked.
Heres my current code:
 public JobImagesViewController(Job passedInCurrentJob) : base("JobImagesViewController", null)
        {
            currentJob = passedInCurrentJob;
            uIImageViews = new List<UIImageView>();
        }

    public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            uIImageViews.Add(img1);
            uIImageViews.Add(img2);
            uIImageViews.Add(img3);
            uIImageViews.Add(img4);
            uIImageViews.Add(img5);
            uIImageViews.Add(img6);
            uIImageViews.Add(img7);
            uIImageViews.Add(img8);
            uIImageViews.Add(img9);
            uIImageViews.Add(img10);

            InitialiseImageGrid();

            // Add a Save button to the navigation bar
            this.NavigationItem.SetRightBarButtonItem(
                new UIBarButtonItem("Save", UIBarButtonItemStyle.Done, (sender, args) =>
                {
                    //TODO if else block with all logic to check if there are images etc.
                    //TODO prompt user and ask if they would like to save images.
                    UIAlertView alert = new UIAlertView("Save Images?", "Save images against the Job?", null, "Yes", new string[] { "No" });
                    alert.Clicked += (s, e) =>
                    {
                        if (e.ButtonIndex == 0) // Yes clicked
                        {
                            SaveJobImages();
                        }
                    };
                    alert.Show();

                }), true);

        }

   [Export("ImageLongPressed:")]
        public void ImageLongPressed(UILongPressGestureRecognizer gestureRecognizer)
        {
            if (gestureRecognizer.State != UIGestureRecognizerState.Began)
            {
                return;
                // Needed because selector is executed twice, because Long-press gestures are continuous
            }
            // Perform action of opening the dialog to select/take a picture, replacing the ? image with the new image
            UIAlertView alert = new UIAlertView("Delete this image ?" , "Are you sure you want to delete this image?", null, "Yes", new string[] { "No" });
            alert.Clicked += (s, e) =>
            {
                if (e.ButtonIndex == 0) // 'Accept' clicked
                {
                    // TODO how to get the image which has been clicked??
                }
            };
            alert.Show();

        }

        private void InitialiseImageGrid()
        {
            _imageList = DataAccess.GetImages(currentJob.jobAddressID);
            var imageBytes = _imageList.Select(x => x.ImageBytes).ToList();

            var gestureRecognizer = new UILongPressGestureRecognizer(this, new ObjCRuntime.Selector("ImageLongPressed:"));
            gestureRecognizer.AddTarget(() => ImageLongPressed(gestureRecognizer));

            // Populate the image views.
            // TODO need to find a way to assign it to every imageview on the view without looping maybe linq???
            int i = 0;
            foreach (var item in imageBytes)
            {
                var imagedata = NSData.FromArray(item);
                var img = UIImage.LoadFromData(imagedata);

                if (uIImageViews != null && uIImageViews.Count > i)
                {
                    uIImageViews[i].UserInteractionEnabled = true;
                    uIImageViews[i].AddGestureRecognizer(gestureRecognizer);
                    uIImageViews[i].AddGestureRecognizer(gestureRecognizer);
                    uIImageViews[i].Image = img;
                }
                i++;

        }

A: It depends on how you are creating your view, are you using a XIB with all the images on there as buttons with images, and IBActions connected to those buttons. just make the sender a UILongPressGestureRecognizer.
If you are doing it through code, then in your ViewDidLoad you want to set your buttons to have an initial ? (or Image Needed) background image and then you add the UILongPress GestureRecognizer to each on of them. So if you had one button, you would do this:
public override void ViewDidLoad ()
{
    // Perform any additional setup after loading the view

    UIButton button = new UIButton (new System.Drawing.RectangleF(100, 100, 100, 30));
    button.SetBackgroundImage ("imageNeeded", UIControlState.Normal);
    var gestureRecognizer = new UILongPressGestureRecognizer ();
    gestureRecognizer.AddTarget(() => this.ButtonLongPressed(gestureRecognizer));
    button.AddGestureRecognizer(gestureRecognizer);
    this.View.Add (button);
}

public void ButtonLongPressed(UILongPressGestureRecognizer gestureRecognizer)
{
    if (gestureRecognizer.State != UIGestureRecognizerState.Began)
    {
          return;
          // Needed because selector is executed twice, because Long-press gestures are continuous
    }
    // Perform action of opening the dialog to select/take a picture, replacing the ? image with the new image
}

A: If want to use UILongPressGestureRecognizer in UIImage, should set ImageView's UserInteractionEnabled be true.
As follow:
List<UIImageView> imageViews = new List<UIImageView>();

UIImage image = UIImage.FromFile("off.png");
ImageViewOne.Image = image;
ImageViewOne.Tag = 1;
ImageViewTwo.Image = image;
ImageViewTwo.Tag = 2;

imageViews.Add(ImageViewOne);
imageViews.Add(ImageViewTwo);

foreach (var imageview in imageViews)
{
    imageview.UserInteractionEnabled = true;
    UILongPressGestureRecognizer uITapGestureRecognizer = new UILongPressGestureRecognizer();
    uITapGestureRecognizer.AddTarget(() => { Console.WriteLine("You choose View " + imageview.Tag); });
    imageview.AddGestureRecognizer(uITapGestureRecognizer);
}

Here is official document from Apple.


text:
Q: You roll 3 six-sided dice. What is the probability that the third is at least as high as the highest of the previous two? I know that the probability of the first two dice being different is $\frac56$, and the first/second being greater is $\frac56$, but am not sure how to calculate the prob of the 3rd being greatest.
(The answer key says $\frac{91}{216}$ or 42.13%)
Edit: Oops sorry I wrote the question wrong - it should be "at least as high as" the highest of the previous 2 instead of "higher than." Either way, thank you for the comprehensive responses! I think I got the answer now:)

A: One method: sum the following probabilities:

*

*Third die=6, first two dice are each between 1 and 5

*Third die=5, first two dice are each between 1 and 4

*Third die=4, first two dice are each between 1 and 3

*Third die=3, first two dice are each 1 or 2

*Third die=2, first two dice are each 1
(I get 55/216, not 91/216)

A: The total amount of possible throws with three dice is of course $6\cdot 6 \cdot 6 = 216$. If my third throw is a $6$, then I have $5\cdot5 = 25$ options with the other two dice such that the third throw is the higher than the other two.
In the same way, if the third is $5$, we have $4^2$ options, etc., etc.
This gives us $$5^2 + 4^2 + 3^2 + 2^2 + 1^1 = 55$$ possible options, instead of the $91$ the answer model gives, which difference is exactly $6^2$. We would include $6^2$ if the question had been that the third dice is the highest one, including equality. Is this the case?

A: For this to work according to the answer you were given, the problem should say "What is the probability that the third is higher than or equal to the highest of the previous two?" There are $6 * 6 * 6$ or $216$ possible throws. If you roll a $6$ with the third die, then you have to get $6-1$ with the other two, where there are $6 * 6$ or $36$ possibilities. Roll a $5$ and then you have to get $5-1$ with the other two which is $5 * 5$ or $25$. This same logic continues on and when you add all the possibilities you get $6^2+5^2+4^2+3^2+2^2+1^2=36+25+16+9+4+1$ which is $91$. Therefore, the probability is $91/216$.
However, if the problem is worded as you stated it, the answer is $55/216$ because the ranges the first and second dice can be will all be reduced by one so $5^2+4^2+3^2+2^2+1^2+0^2=25+16+9+4+1+0=55$


text:
Q: Exaggerating a sample to represent the whole Is there a word for when you exaggerate a limited sample to give a fact or opinion about a whole population, especially for the purposes of boasting.
e.g.
"All French wine is delicious!", said M Pompidou even though he had tasted only a few French wines.
What is he doing here, beyond just exaggerating? Would this be hyperbole?

A: Overgeneralize / overgeneralization


text:
Q: Throwing doubles in Computer Backgammon I am playing a computer game of Backgammon. I believe that the programme is biased towards the computer character.
Here is the basis for my suspicion:
I have played 223 games so far:
Here are my statistics: Thrown 877 doubles out of 5549 throws comprising
              Double ones 144
              Double twos 149
              Double threes 160
              Double fours 157
              Double fives 134
              Double sixes 133
The statistics for the computer character (Bill) are 966 doubles out of 5553 throws comprising
              Double ones 163
              Double twos 154
              Double threes 164
              Double fours 153
              Double fives 160
              Double sixes 172
Are my suspicions real in that the computer is favouring the character Bill?