text:
Q: Python: why these two assignments cause different results? I tried two different cases below. I hope the testcase is different from the testset. However, only by sencond method, the assertion returns warning.
In [95]: from random import shuffle

In [96]: testset = list(range(100))

In [97]: testcase = testset

In [98]: shuffle(testcase)

In [99]: assert testcase == testset

In [100]: testset2 = list(range(100))

In [101]: testcase2 = testset2[:]

In [102]: shuffle(testcase2)

In [103]: assert testcase2 == testset2
------------------------------------------------------
----------------
AssertionError                       Traceback (most
recent call last)
<ipython-input-103-268525dbf253> in <module>()
----> 1 assert testcase2 == testset2

AssertionError:

A: With testcase = testset, testcase is literally the same list as testset. They are referring to the same list. If you do anything to one of them (like shuffle one), since both variables are pointing to the same list, both will be shuffled.
With testcase2 = testset2[:] however, [:] creates a copy of testset2 and puts it in testcase2. They now point to different lists, so doing something to one will not effect the other. This is why assert testcase2 == testset2 fails. One was shuffled. One was not.


text:
Q: How to take arbitrary number of parentheses from user for add function add(5)(10)(20)

How can I to supply an arbitrary number of parentheses to add numbers?

A: You could create a class like so:
class add(object):
    def __init__(self, value):
        self.value= value

    def __call__(self, value):
        self.value+= value
        return self

    def __repr__(self):
        return str(self.value)

print add(5)(10)(20)
# output: 35

A: It's impossible, or at least it should be if the language you're using is worth anything. You're asking for a function to return two different types, which is inviting a a disaster.

*

*sometimes it should return a function that takes the next number to add

*other times it should return the sum of the previous inputs.

What? Take a step back and ask yourself what kind of design that is. You would need need some way to notify the function that you're done giving inputs and now you want the computed value.
Think about it, the function might look like this
def add (sum):
  print(sum)
  return lambda x: add(sum + x)

add(1)(3)(4)(5)(10)(20)

# 1
# 4
# 8
# 13
# 23
# 43
# => None

But there's no way to let the function know to return a final value unless you change the api somehow.

You could change the api to return the computed value when the users enters a 0 or something. Great idea right? Very clever.
def add (x):
  def loop(sum, x):
    if x == 0:
      return sum
    else:
      return lambda x: loop(sum + x, x)
  return loop(0, x)

print(add(1)(3)(4)(5)(10)(20)(0))
# 42

Hey look, it works where @Rawling's clever code fails. All without adding a bunch of tricks to a class
print(add(5)(10)(20)(0) + add(5)(10)(20)(0))
# 70

But still, this is garbage code. No well-designed function should ever behave like this.
Or if your content with being insane, create a class like @Rawing's answer suggests.

A: What you could do is this:
class add(object):
    def __init__(self, val):
        self.val= val

    def __call__(self, val=None):
        if not val:
            return self.val
        self.val += val
        return self

add(5)(10)()
>>> 15

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the ambience space of the Lp spaces and what topology does it have? When we say that the $L^p$ space is complete and hence closed, what ambience space is it closed in, and what is the topology of that ambience space? I think it's the space of measurable functions, but is there a natural norm/topology on the space of measurable functions?
An Update After Reading the Comments:
I realized that this might just be a simple topology question rather than $L^p$ spaces. This is what I have gathered: If we view $L^p$ itself as the ambience space with the $L^p$ norm topology, then of course it is closed (closed and open at the same time) in itself. Completeness has nothing to do with closedness of the space in this case. On the other hand, if we can embed $L^p$ into any topological space $(X, \mathcal{T})$ and if we can show the $L^p$ norm topology is the same as the induced subspace topology of $L^p \subseteq X$, then $(L^p, \| \cdot \|_{L^p}) \subseteq (X, \mathcal{T})$ must be closed in $(X, \mathcal{T})$ as it is complete.
I suppose a question that I have not been able to figure out still is : We know $L^p$ must be embedded in the space of measurable functions. Is there a natural topology that we can put on the space of measurable functions, so that the induced subspace topology of $L^p$ is exactly the same topology as the $L^p$ norm, without knowing if the function domain is finite measure or not?


text:
Q: ANTLR Nested Functions Is ANTLR right for this project?
I'm looking to process and transform a string entered in by a user which may include custom functions. For example, the user might write something like $CAPITALIZE('word') in a string and I want to perform
the actual transformation in the background using StringUtils.
I would imagine the users will sometimes write nested functions like:
$RIGHT_PAD($RIGHT($CAPITALIZE('a123456789'),6),3,'0')
Where the expected output would be a string value of 'A12345000'.
I tried using regex to split the functions apart, but once nested, it wasn't so easy. I figured I might try writing my own parser, and while doing research I came across an article that suggested using ANTLR instead.
Is this something ANTLR would be right for? If so, are there any similar examples already available for me to look at? Or would someone be kind enough to give me an example of how I might write this out in ANTLR so that I can have both custom functions that can be processable individually and in a nested fashion.
Functions:

*

*$CAPITALIZE(String str)

*$INDEX_OF(String seq, String searchSeq)

*$LEFT(String str, int len)

*$LEFT_PAD(String str, int size,char padChar)

*$LOWERCASE(String str)

*$RIGHT(String str, int len)

*$RIGHT_PAD(String str, int size, char padChar)

*$STRIP(String str)

*$STRIP_ACCENTS(String input)

*$SUBSTRING(String str, int start)

*$SUBSTRING(String str, int start, int end)

*$TRIM(String str)

*$TRUNCATE(String str, int maxWidth)

*$UPPERCASE(String str)

Basic Examples:

*

*$CAPITALIZE('word') → 'Word'

*$INDEX_OF('word', 'r') → 2

*$LEFT('0123456789',6) → '012345'

*$LEFT_PAD('0123456789',3, '0') → '0000123456789'

*$LOWERCASE('WoRd') → 'word'

*$RIGHT('0123456789',6) → '456789'

*$RIGHT_PAD('0123456789',3, '0') → '0123456789000'

*$STRIP(' word ') → 'word'

*$STRIP_ACCENTS('wórd') → 'word'

*$SUBSTRING('word', 1) → 'ord'

*$SUBSTRING('word', 0, 2) → 'wor'

*$TRIM('word ') → 'word'

*$TRUNCATE('more words', 3) → 'more'

*$UPPERCASE('word') → 'WORD'

Nested Examples

*

*$LEFT_PAD($LEFT('123456789',6),3,'0') → '000123456'

*$RIGHT_PAD($RIGHT($CAPITALIZE('a123456789'),6),3,'0') → 'A12345000'

Actual Example:
What I mean by actual example is that this is what I expect a string value might look like. You will notice that there are variables written like ${var}. These variables will be replaced with actual string values using Apache Commons StringSubstitutor prior to passing the String into ANTLR (if it turns out I should use it)
Initial String Written By User
\HomeDir\Students\$RIGHT(${graduation.year},2)\$LEFT_PAD($LEFT(${state.id},6),3,'0')
String After Being Processed By StringSubstitutor
\HomeDir\Students\$RIGHT('2020',2)\$LEFT_PAD($LEFT('123456789',6),3,'0')
String After Being Processed By ANTLR (And my final output)
\HomeDir\Students\20\000123456
Does ANTLR seem like something I should use for this project, or would something else be better suited?

A: Yes, ANTLR would be a good choice. Keep in mind that ANTLR only does the parsing for you, and provides you with a mechanism to traverse the generated parse tree. You will have to write code to evaluate the expressions.
In your case, your lexer would need to be triggered when it stumbles upon a '$' by pushing the lexical state as being "in-a-function-mode". And when it sees a ')', one such "in-a-function-mode" should be popped off the lexical stack.
Read all about lexical modes/stack on the ANTLR wiki: https://github.com/antlr/antlr4/blob/master/doc/lexer-rules.md
Here's a quick demo of how that could work for ANTLR4 (ANTLR3 doesn't support lexical modes):
file: TLexer.g4
lexer grammar TLexer;

TEXT
 : ~[$]
 ;

FUNCTION_START
 : '$' -> pushMode(IN_FUNCTION), skip
 ;

mode IN_FUNCTION;
  FUNTION_NESTED : '$' -> pushMode(IN_FUNCTION), skip;
  ID             : [a-zA-Z_]+;
  PAR_OPEN       : '(';
  PAR_CLOSE      : ')' -> popMode;
  NUMBER         : [0-9]+;
  STRING         : '\'' ( ~'\'' | '\'\'' )* '\'';
  COMMA          : ',';
  SPACE          : [ \t\r\n]-> skip;

file: TParser.g4
parser grammar TParser;

options {
  tokenVocab=TLexer;
}

parse
 : atom* EOF
 ;

atom
 : text
 | function
 ;

text
 : TEXT+
 ;

function
 : ID params
 ;

params
 : PAR_OPEN ( param ( COMMA param )* )? PAR_CLOSE
 ;

param
 : NUMBER
 | STRING
 | function
 ;

With the ANTLR4 plugin from IntelliJ, you can easily test the parse method from the parser and feed it the following input: foo $RIGHT_PAD($RIGHT($CAPITALIZE('a123456789'), 6), 3, '0') bar, which will generate the following image of the parse tree:


text:
Q: Is energy conserved in a Van der Pol oscillator? The Van der Pol Oscillator is governed by a 2nd order ODE with nonlinear damping. The 'position' of the oscillator is the solution to
$$x''(t) = \mu (1 - x^2(t)) x'(t) - x(t)$$
Here $\mu$ controls how much nonlinear damping there is. When $\mu = 0$ the ODE reduces to
$$x''(t) = - x(t)$$
which is simply the equation of the simple harmonic oscillator ('a spring') with spring constant $k = 1$.
It's well-known that the Van der Pol oscillator has a non-trivial limit cycle for most initial conditions in the $x - x'$ plane. However, this is actually surprising to me!
I am a little surprised because the damped harmonic oscillator governed by
$$x''(t) = - \mu x'(t) - x(t)$$
(with $\mu > 0$, I think)
doesn't have a limit cycle. Instead, the oscillator is damped until $x, x' = 0, 0$ in the limit as $t \rightarrow \infty$. In elementary physics textbooks people like to explain this as the oscillator losing energy due to friction.
This seems to imply that in the limit as $t \rightarrow \infty$, the damped harmonic oscillator 'loses all its energy'.
On the other hand, since the Van der Pol oscillator has a non-trivial limit cycle, with non-zero speed, does that mean that the oscillator has some non-zero amount of (kinetic?) energy in its steady state?
How is the Van der Pol oscillator different from the damped harmonic oscillator?
How can/should I quantify the energy in these oscillators?
Context: I've been playing around with simulations of oscillators in using numpy/scipy.

A: $\def\half{{\textstyle {1 \over 2}}}$
Multiply your first equation by $x'(t)$ and integrate between $t_1$ and $t_2$:
$$x' x'' = \mu\,(1 - x^2)\,{x'}^2 - x\,x'$$
$$\eqalign{
&\half\,{x'}^2(t_2) - \half\,{x'}^2(t_1) = {}\cr
&\qquad -\half\,x^2(t_2) + \half\,x^2(t_1) +
\mu\!\int_{t_1}^{t_2}\! [1 - x^2(t')]\,{x'}^2(t')\>dt'.\cr}$$
Reordering
$$\eqalign{
&\Bigl[\half\,{x'}^2(t_2) + \half x^2(t_2)\Bigr] -
\Bigl[\half\,{x'}^2(t_1) + \half\,x^2(t_1)\Bigr] = {}\cr
&\qquad\qquad \mu\!\int_{t_1}^{t_2}\![1 - x^2(t')]\,{x'}^2(t')\>dt'.\cr}$$
At left side you read variation of kinetic energy plus potential energy between $t_1$ and $t_2$. At right side, were it not for the $x^2$, you'd have energy "creation": a positive term, showing that energy increases so that oscillation is enhanced.
But there is the $x^2$ term, which has the opposite sign, showing a dissipation of energy, i.e. a damped oscillation. It's negligible for small $x$ whereas it becomes important for large $x$. You may then expect that for some intermediate oscillation amplitude dissipation and creation might balance, thus giving rise to a sustained (stable) oscillation.  This the limit cycle.
A better understanding is possible trying an explicit form for $x(t)$:
$$x(t) = a\,\sin \omega t.$$
Although you can't expect this is the right form of the limit cycle, it may give a semiquantitative idea of what will happen. I leave for you to compute the integral and to show that for $a>2$ dissipation prevails whereas for $a<2$ there is a net energy creation. A balance is obtained for $a=2$.
Therefore if you start from rest or in general from an amplitude $<2$ the oscillation will grow larger, until balance is reached. The opposite happens if you start from $a>2$: amplitude decreases until the limit cycle is reached from above. This shows stability of the limit cycle.


text:
Q: How to initialize an application's java object from command line I have an ear application (myApp) that runs on a Websphere Application Server (WAS). I have a jar (myJar) that is loaded into the classpath of myApp when the WAS server is started.  myJar has a class (MyInitClass) that reads from a db and loads a set of data (myData) into memory.  This data gets read many times by myApp.  The point is to get myData into memory to prevent doing a db call every time this data is used.  This part works great!
The solution I am trying to provide is a manual initialization of MyInitClass. myData gets changed from time to time and I would like to be able to reinitialize MyInitClass from a command line so I don't have to restart the application.  Is this possible?
myApp calls a class (MyClass) that has something like this:
public static MyInitClass initClass;

public boolean doStuff()
{
    if (initClass == null)
    {
        // this method loads the data into initClass.myData array
        initClass.dataInitializer();
    }
    else
        // no need to reload initClass.myData
}

I have created code similar to this in another class (MyManualInit):
public static void main(String[] args)
{
    MyClass.initClass = new MyInitClass();
    MyClass.initClass.dataInitializer();
}

When I run MyManualInit from command line it prints all the same debug info that gets printed during the initialization from myApp.  But myApp does not recognize that MyInitClass has been reinitialized.  I have printed System.out.println(System.getProperty("java.home")) from both processes to validate that I am using the same JRE to run both.  Am I doing something obviously wrong here or does it just not work like that?  I assumed if I ran MyManualInit on the same JRE it would work.  MyClass, MyInitClass and MyManualInit are all in myJar.
Please let me know if you need more info.

A: You are mixing things.  Websphere runs in an instance of the JVM and your command line program instantiates a new one, and objects do not communicate between different JVMs (at least without some effort, bringing up sockets, etc.)
Actually your code does a lazy initialization of your initClass object, and it should be enough without any command line interaction.  Why is it not enough for you?


text:
Q: Wrong page numbering in the Table of contents, of figures and of tables my problem is related to the number of pages in the table of contents, list of figures and list of contents. Everything in my .pdf works well except that! I don't understand why!
Could you help me?
In the following my main:
\begin{document}
\hyphenation{Com-po-si-to-ri}
\hyphenation{Giu-sep-pe}
\hyphenation{Ba-lu-stra-des}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{\thesection\ #1}}
\fancyhf{}
\fancyhead[LE,RO]{\bfseries\thepage}
\fancyhead[LO]{\bfseries\rightmark}
\fancyhead[RE]{\bfseries\leftmark}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\addtolength{\headheight}{0.5pt}
\fancypagestyle{plain}{
\fancyhead{}
\renewcommand{\headrulewidth}{0pt} % e la linea
}

\includepdf[pages={1}]{Frontespizio.pdf}

\newpage
\thispagestyle{empty}
\clearpage{\pagestyle{empty}\cleardoublepage}
\selectlanguage{english}
\tableofcontents
\clearpage{\pagestyle{empty}\cleardoublepage}
\listoffigures
\clearpage{\pagestyle{empty}\cleardoublepage}
\listoftables
\clearpage{\pagestyle{empty}\cleardoublepage}

\large
\setcounter{secnumdepth}{-1}
\selectlanguage{italian}
\input{Sommario}
\clearpage{\pagestyle{empty}\cleardoublepage}
\selectlanguage{english}
\input{Acronym.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Abstract}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Introduction.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\clearpage
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{4}
\onehalfspacing
\input{Iso.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Literature.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Storia.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{IRMeasurement.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{ComputerModelling.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Discussion.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Conclusions.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Bibliografia.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}
\input{Ringraziamenti.tex}
\clearpage{\pagestyle{empty}\cleardoublepage}

\end{document}

A: You need at least two up to three (or more) LaTeX runs to get the table of
contents right:
During one LaTeX run the following happens:

*

*\begin{document}: The .aux files are read, entries for the table of contents or list of figures/tables are ignored (because of \let\@writefile\@gobbletwo).

*\tableofcontents/\listoffigures/\listoftables call \@startoc{<ext>} (<ext> = toc, lof, or lot).

*

*It reads the file \jobname.<ext>, the table of contents (or list of ...) is set.

*The \jobname.<ext> is cleared and opened for writing.

*\chapter, \section, \caption, ... internally call \addcontentsline{}{...}{...}and\addtocontents{}{...}. These write\@writefile{}{...}commands into the.auxfile. This can also
happen before\tableofcontents` and friends are called.

*\end{document}. After the last page is shipped out, the .aux file is closed and read in again. Now the \@writefile{<ext>}{<contents>} commands are executed and the <contents> is written to the correspondent \jobname.<ext> file or ignored, if \jobname.<ext> is not opened. For example, if there are figure captions, but \listoffigures is not called, then \jobname.lof is not written.
That means the printed table of contents (list of figures, ...) has the status of the previous LaTeX run. In the first LaTeX run, the \jobname.<ext> files are not yet written and the table of contents and the lists are empty. Thus the minimal requirement are two LaTeX runs.
If the table of contents and the lists are not numbered independently, then it can happen, that there are so many entries, that there are more pages than an empty list would need. Then the following page number after the lists increases as all following entries for the lists. Then another LaTeX run is needed.
For example, two side setting with \cleardoublepage:
\begin{document}
\tableofcontents
\cleardoublepage
\chapter{...}
...

An empty table of contents needs one page for the title (Contents) and an empty page (because of \cleardoublepage). The table of contents is three pages long:

*

*First LaTeX run:
1. Page: Contents <otherwise empty>
2. Page: <empty>
3. Page: Chapter 1 ...

*Second LaTeX run:
1. Page: Contents, Chapter 1 -> page 3, <other entries>
2. Page: <other entries>
3. Page: <other entries>
4. Page: <empty>
5. Page: Chapter 1 ...

Thus the page number is wrong, but LaTeX does not warn.

*Third LaTeX run:
1. Page: Contents, Chapter 1 -> page 5, <other entries>
2. Page: <other entries>
3. Page: <other entries>
4. Page: <empty>
5. Page: Chapter 1 ...

Now, the table of contents is correct.
Rerun warnings
LaTeX does not warn, if another LaTeX run is needed for the table of contents and the other lists. There is a package rerunfilecheck that uses \pdfmdfivesum of pdfTeX (both DVI or PDF mode) to calculate a MD5 checksum over an auxiliary file at the beginning and the end of the job. If something has changed, then the package prints a rerun warning:
\documentclass{book}

\usepackage[starttoc]{rerunfilecheck}

\newcommand*{\cleardoubleemptypage}{%
  \clearpage
  \begingroup
    \pagestyle{empty}%
    \cleardoublepage
  \endgroup
}

\begin{document}
Title page
\cleardoubleemptypage
\tableofcontents
\cleardoubleemptypage
\listoffigures
\cleardoubleemptypage
\listoftables
\cleardoubleemptypage
\chapter{First chapter}
\begin{figure}
\caption{First figure}
\end{figure}
\addtocontents{toc}{\protect\clearpage}% short for many \chapter/\section/... entries
\chapter{Second chapter}
\addtocontents{toc}{\protect\clearpage}% short for many \chapter/\section/... entries
\chapter{Third chapter}
\end{document}

The first and second run generates the warnings:
Package rerunfilecheck Warning: File `test.toc' has changed. Rerun.
Package rerunfilecheck Warning: File `test.lof' has changed. Rerun.

The third run is successful without warnings.


text:
Q: Linking and extracting records in MySQL I have a table in my MySQL database which contains records of activity.  It looks like:
Action_______________Date_________________User________________Location___________Ref Number
Action 1........1/1/2012.........J Jones.......Home.............00123
Action 2........2/1/2012.........K Smith.......Work.............00234
Action 2........2/1/2012.........J Jones.......Home.............00123
Action 1........4/1/2012.........B Smith.......Home.............00345
Action 3........5/1/2012.........J Jones.......Mobile...........00123
ETC

What I am looking for is a query that will go through the table, find the first occurrence of Action 1and then go and find Action 2 for the same Ref Number and the Action 3 etc.
It would do this for each occurrence of the Ref Number in the table.
These would need to be presented in PHP as a single data line ie:
Ref No._____________Act1date_____________Act1User_____________Act1location_____________Act2date_____________Act2User__etc
00123..........1/1/2012..........J Jones............Home....................2/1/2012..........J Jones
00234..........1/1/2012..........J Jones............Work....................2/1/2012..........J Jones  00345..........1/1/2012..........J Jones............Home....................2/1/2012..........B Smith

There will also be some calculations to be done ie time differences between Action1_date and Action2_date etc.
I can't think how to write a query to do this – can anyone help?
Thanks in advance,

A: Just use an order by statement to sort the results.
select
    action,
    Date,
    User,
    Location,
    refNumber
from
    yourTable
order by
    refNumber,
    action


text:
Q: Tinymce 4 in orchard cms cannot upload images I use Orchard cms.I had installed tinymce 4 module.I upload a photo,my photo is shown in editor but when I refresh the website the path of image is change and I cant see the photo.
the image url changed to
../../../../../Media/Default/pic/7-23-2016-10-10-03-PM-300x200.jpg

A: Since the default TinyMCE module has all tiny plugins, by default it will load some of them,then the best way is to extend it and add more plugins as you want.
To do this, you have to replace the default orchard-tinymce.js file in your module, and register it in your ResourceManifest, to tell Orchard to load your script instead of the default one:
ResourceManifest.cs:
public class ResourceManifest : IResourceManifestProvider {
    public void BuildManifests(ResourceManifestBuilder builder) {
        var manifest = builder.Add();
        manifest.DefineScript("OrchardTinyMce").SetUrl("orchard-tinymce.js").SetDependencies("TinyMce");
    }
}

orchard-tinymce.js: (You can copy it from \Modules\TinyMce\Scripts\orchard-tinymce.js)
var mediaPlugins = "";

if (mediaPickerEnabled) {
    mediaPlugins += " mediapicker";
}

if (mediaLibraryEnabled) {
    mediaPlugins += " medialibrary";
}

tinyMCE.init({
    selector: "textarea.tinymce",
    theme: "modern",
    schema: "html5",
    // Here you can add your plugins
    plugins: [
        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars code fullscreen",
        "insertdatetime media nonbreaking table contextmenu directionality",
        "emoticons template paste textcolor colorpicker textpattern",
        "fullscreen autoresize" + mediaPlugins
    ],
    // Here you can customize your toolbar
    toolbar: "undo redo cut copy paste | bold italic | bullist numlist outdent indent formatselect | alignleft aligncenter alignright alignjustify ltr rtl | " + mediaPlugins + " link unlink charmap | code fullscreen",
    convert_urls: false,
    valid_elements: "*[*]",
    // Shouldn't be needed due to the valid_elements setting, but TinyMCE would strip script.src without it.
    extended_valid_elements: "script[type|defer|src|language]",
    //menubar: false,
    //statusbar: false,
    skin: "orchardlightgray",
    language: language,
    auto_focus: autofocus,
    directionality: directionality,
    setup: function (editor) {
        $(document).bind("localization.ui.directionalitychanged", function(event, directionality) {
            editor.getBody().dir = directionality;
        });
    }
});

You can customize TinyMCE initialize configuration as you need.


text:
Q: Using csname with \addto\captions[language]{} The method to change the name of the contents while using the babel package
is described here.
Per the answer included in the link, the following code may be used:
\documentclass{article}

\usepackage[american]{babel}

\addto\captionsamerican{%
  \renewcommand{\contentsname}%
    {newContentsName}%
}

\begin{document}

\tableofcontents

\section{Section}
\subsection{Subsection}

\end{document}

If I wanted to use a variable for the language, I thought I could make the following adjustment:
\documentclass{article}

\newcommand{\xLanguage}{american}          % <-- Added this command

\usepackage[\xLanguage]{babel}             % <-- Implemented here

\addto\csname captions\xLanguage\endcsname{% <-- and here
  \renewcommand{\contentsname}%
    {newContentsName}%
}

\begin{document}

\tableofcontents

\section{Section}
\subsection{Subsection}

\end{document}

But this does not work.
Am I approaching this correctly?

A: \csname captions\xLanguage\encsname must be expanded first, before \addto can work with the 'real' command sequence name, i.e. an \expandafter is needed before \addto.
I.e.  captions\xLanguage must be expanded first to yield the content of \xLanguage, american in the O.P. example, such that captionsamerican is usable for `\csname ...\endcsname.
Only after that \addto\captionsamerican{...} is finally available.
This is the same code needed for constructing \newcommand macros etc. from macronames or parameters etc., i.e.  \expandafter\newcommand\csname foo\otherfoobar\endcsname{My foo content}, where \otherfoobar contains 'any' token being allowed as a \newcommand - defined macro name.
\documentclass{article}

\newcommand{\xLanguage}{ngerman}          % <-- Added this command

\usepackage[\xLanguage]{babel}             % <-- Implemented here

\expandafter\addto\csname captions\xLanguage\endcsname{% <-- and here
  \renewcommand{\contentsname}%
    {Verzeichnisse der tollen Inhalte}%
}

\begin{document}

\tableofcontents

\section{Section}
\subsection{Subsection}

\end{document}

A: I'm not sure about the usefulness of this approach, but you can use etoolbox:
\documentclass{article}
\usepackage{etoolbox}

\newcommand{\xLanguage}{american}          % <-- Added this command

\usepackage[\xLanguage]{babel}             % <-- Implemented here

\csappto{captions\xLanguage}{% <-- and here
  \renewcommand{\contentsname}%
    {newContentsName}%
}

\begin{document}

\tableofcontents

\section{Section}
\subsection{Subsection}

\end{document}


text:
Q: get/check inner kernel32 state for process win32 (for safe usage of TerminateThread ) I've written a threadpool with a terminate option for threads available to the user. As described in
Documentation of API terminateThread(),

If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.

I could verify this problem myself: Terminating a thread in that condition caused memory allocation  problems (amongst others), but fixing that condition fixed the problems at the same time.
Questions

*

*So, I want to check this inner state after every time terminateThread() has been used. If terminateThread() has caused problem for the inner state of a process in kernel32.dll, I want to raise an exception - and terminate the process after logging to user (unless fixing the inner state is still possible).
Is this feasible? Maybe by finding the address of the relevant state variable (or anything like that - by matching the pdb file of kernel32 or another way)? The situation is bad for me - if I cannot solve it, I either have to omit the terminate option for the threapool or just leave the thread for itself. Any hints would be appreciated!

*Is there any other win32 function that causes similar problems?

*a. Is it safe to leave a thread for itself when it has called a blocking kernel32 function that will definitely never return?
b. What happens if the win32 function returns and the lambda function has been destroyed?
Why am I asking this? (Supplementary information)
I have a custom threadpool in my project where I call some win32 APIs that may sometimes block forever. Hence, I call them using a timeout. When that timeout is reached, I call terminateThread() and have my threadpool return "unsucessfull call state".
Sometimes, my current app reaches a deadlock. I found out that this deadlock is happening in the threadpool, so I'm looking for alternatives to terminateThread() (such as leaving the thread as I described in the question) or trying to fix the inner state, or at least to verify whether terminateThread() is the root of my deadlock.
I'd like to reuse this threadpool in other projects, too, so I should make it safe.
Update: Problem fixed.
I found the bug in my app:
It was actually a call to terminateThread() when the timeout in my threadpool was already low (about 200 ms).
The thread was killed in a moment when it wasn't blocking (i.e., if a longer timeout period had remained, it would have worked and returned correctly).
From the kernel stack trace I found out that in kernel mode, a mutex was being locked while the thread was terminated, and while the thread was exiting, other threads were already waiting for that mutex.
The problem first appeared to go away by increasing the minimum timeout to 1000 ms, but I wasn't content with that:
My solution was to create lambda on heap when timeout reached, to leave the lambda and the thread for itself without terminating, and to add it to a list of _ToTerminateThreads.
The list gets terminated once in 10 minutes (waits 10 min., copies the list, waits another minute, and then terminates the threads and deletes the lambdas).
Still, after testing and hours of debugging I was getting heap corruptions.
Finally I found out the following:
The threads that I had left for deletion
wrote to the memory that had been used by the user function (which was passed to threadpool)
- and they were freed because threadpool had returned.
This had caused the ultimate problems, so the final solution was to increase the timeout to a safe amount.
I recommend to everyone who needs such a feature to deploy it to a child process, and to terminate that process instead of using a thread.
I keep this question open because the main 4 questions haven't been answered  yet. For my problem, I don't need their answer anymore, but they may be interesting for other members of stackoverflow.

A: My issue resolved although it has nothing to do with 3 questions in post.
I try to answer them in reverse order:

*

*ad 3.b.) If an external function returns and your local lambda has been deleted, the cpu won't know this and will try to process the bytes at that offset as CPU instructions. This surely will mess you up, so never do that!

*ad 3.a.) Yes, it is safe to leave if you're 100% sure the external function will never return (otherwise it'll mess your app when return

*

*if you deleted the rest of the code with the same way explained in b.

*if you haven't deleted the lambda or it's a gobal function, it'll run the rest of function which may be editing dynamic allocated memories (heap, not stack) which has been deallocated and cause heap corruption or simply just edit some global variables).

*ad 2.) I googled for dangerous winapi functions and didn't find any result other than TerminateThread().
If you know about one, please add a comment or write another answer.

*ad 1.) I don't have any solution for checking/fixing the inner kernel32 state for the process that Microsoft refers to.
I think a guy at Microsoft who has read kernel32.dll source code should answer this.
Apart from this kernel32 state, TerminateThread() will cause lots of other problems (like resource/heap allocations, mutex locks, leaks and so on) so never use it unless you 100% sure what you are doing.
Read the article @RichardCritten linked in the comments: TerminateThread()
What was the bug in my code?
I was calling TerminateThread() with a low timeout (300 ms).
Randomly when a machine had low resources, the function was still operating (I mean non-blocking call!).
I terminated that function and thereby caused a kernel mutex to be locked.
This locked mutex made all other threads wait - and not exit when they returned.
Remarks
I answered my own question from what I found after I didn't receive any answer. Hence, it may contain some wrong information. Please correct me if anything is wrong in this.


text:
Q: Combine wins and losses in same row I'm struggling to nail down a SQL Server 2012 query I'm trying to write and hoping somebody can help me out. This is what I currently have as my query:
 --home wins
 select NULL as roadlosses, Count(t1.TeamName) as homewins, t1.TeamName from scores s
 inner join games g
 on g.GameID=s.GameID
 inner join teams t1
 on t1.TeamID=g.HomeTeam
 inner join teams t2
 on t2.Teamid=g.AwayTeam
 where (s.hometotalruns - s.awaytotalruns) > 0 and t1.TeamName = 'Pirates'
 group by t1.teamname

 UNION
 --road losses

 select Count(t2.TeamName) as roadlosses, NULL, t2.TeamName from scores s
 inner join games g
 on g.GameID=s.GameID
 inner join teams t1
 on t1.TeamID=g.HomeTeam
 inner join teams t2
 on t2.Teamid=g.AwayTeam
 where (s.hometotalruns - s.awaytotalruns) > 0 and t2.TeamName = 'Pirates'
 group by t2.TeamName

This gets me close with the results being:
 roadlosses    homewins     teamname
 NULL            41          Pirates
 26             NULL         Pirates

I want this to return only 1 row, eliminating the NULLs, but I just can't seem to get it.
I tried looking at this but it's not quite exactly what I need.

A: Since you know the team name you're after, I think it makes sense to pull that out instead of referring to it throughout the query continuously, and not having to join to the teams table at all in the main query. If the team name is unique (I certainly hope it is!), this should be a very inexpensive seek.
-- this would be your input parameter:
DECLARE @TeamName VARCHAR(32) = 'Pirates';

-- the rest would be the code:
DECLARE @TeamID INT;
SELECT @TeamID = TeamID FROM dbo.Teams WHERE TeamName = @TeamName;

;WITH x AS
(
   SELECT
     location = CASE g.HomeTeam WHEN @TeamID THEN 'H' ELSE 'A' END,
     run_diff = s.hometotalruns - s.awaytotalruns
   FROM dbo.Scores AS s
   INNER JOIN dbo.Games AS g
   ON s.GameID = g.GameID
   WHERE @TeamID IN (g.HomeTeam, g.AwayTeam)
)
SELECT
 RoadLosses = COUNT(CASE WHEN location = 'A' AND run_diff > 0 THEN 1 END),
 HomeWins   = COUNT(CASE WHEN location = 'H' AND run_diff > 0 THEN 1 END),
 TeamName   = @TeamName
FROM x;

A: Do this as a single query, with conditional aggregation.  I think this is the query:
 select sum(case when (s.hometotalruns - s.awaytotalruns) > 0 and t2.TeamName = 'Pirates'
                 then 1 else 0
            end) as roadlosses,
        sum(case when (s.hometotalruns - s.awaytotalruns) > 0 and t1.TeamName = 'Pirates'
                 then 1 else 0
            end) as homewins,
        'Pirates' as TeamName
 from scores s
 inner join games g
 on g.GameID=s.GameID
 inner join teams t1
 on t1.TeamID=g.HomeTeam
 inner join teams t2
 on t2.Teamid=g.AwayTeam
 where 'Pirates' in (t1.TeamName, t2.teamName);


text:
Q: activate an automatically archived chatter group(because of inactivity of 90days)by apex code Can you activate a chatter group which has been archived for inactivity by apex code?
If so what are the permissions required to do this?
Is it that only owner of group/modify all data users can do this?

A: The ConnectApi functionality supports this.
...need some code to retrieve group id and optionally community id...
ConnectApi.ChatterGroupInput groupInput = new ConnectApi.ChatterGroupInput();
groupInput.isArchived = false;

ConnectApi.ChatterGroups.updateGroup(communityId, groupId, groupInput);

This example is almost identical to the example shown in the Apex Code developer guide for the ConnectApi.ChatterGroups.updateGroup() method.
The downside to ConnectApi, however is that you only get access to the Chatter functionality according to the access of the context user. So if this were done by a trigger, say, and the user invoking it did not have manager access to the group, it would fail. The advantage is this update to the group lives outside of the normal Apex governor limits and is instead governed by the ConnectApi limits, which are typically a bit more generous.
If you need access no matter what, you would query for the chatter group needed, retrieve it, then update the group. The short version of this would look like this:
CollaborationGroup cg = [select Id from CollaborationGroup where Id = : someGroupId];
cg.IsArchived = false;
update cg;

To be certain this would work no matter from where, you would want to then declare the class as without sharing ignoring sharing restrictions and ensuring any Apex invoked from anywhere else would successfully execute this code.


text:
Q: what is $\cos(2^k\cos^{-1}(x))$? For $\cos(2\cos^{-1}(x))$ we can say it is equal to $2\cos^2(\cos^{-1}(x))-1$ which is $2x^2-1$ but for $\cos(2^k\cos^{-1}(x))$ is there any way to simplify ?
I have tried to use the double angle Cosine for multiple times, but I don't think this is going to work !

A: These are the $2^k$th Chebyshev polynomials of the first kind. The $n$th Chebyshev polynomial can be written as:
$$T_n(x)=\cos(n\arccos x)), x\in [-1,1]$$
You can easily show that:
$$T_{2n}(x)=2T_n^2(x) -1$$
so you can compute $T_{2^k}(x)$ recursively.
You can also see it as:
$$T_{2^k}(x)=\sum_{j=0}^{2^{k-1}} \binom{2^k}{2j}(x^2-1)^jx^{2^k-2j}$$

A: What you are looking for are called the Chebyshev Polynomials.  Here is a table.
Much more to read at the link, but there is a recurrence relation for these:
$$\cos(nx)=2\cos(x)\cos[(n–1)x]–\cos[(n – 2)x].$$
Applying this formula to your expression, we have
$$\cos(2^k\arccos x)=2\cos(\arccos x)\cos[(2^k–1)\arccos x]–\cos[2^k-2\arccos x].$$
So $\cos(2^k\arccos x)=T_{2^k}(x),$ where $T_n(x)$ is the $n$th Chebyshev Polynomial of the first kind.


text:
Q: Why are Serre functors always exact? Let $k$ be a field and $\mathcal{T}$ be a $k$-linear triangulated category with finite dimensional spaces of morphisms. Bondal and Kapranov proved that every Serre functor on $\mathcal{T}$ is exact (Proposition 3.3 here). A different proof was given by Huybrechts in his Fourier-Mukai book (Proposition 1.46). The proof by Bondal and Kapranov is a bit technical and relies on the notion of a mattress. For now, I decided not to read it thoroughly. Concerning the one given by Huybrechts, I could not convince myself that it is complete. Could someone please shed a light on this, possibly providing a simple proof or explaining how the desired linear form in Huybrechts' proof is constructed?

A: (Notations as in Huybrechts' book.) Consider the maps $\mathrm{Hom}(C,S(B))\rightarrow\mathrm{Hom}(C,C_0)$ and $\mathrm{Hom}(A[1],C_0)\rightarrow\mathrm{Hom}(C,C_0)$, and let $I$ and $J$ be their images. Huybrechts tells you how to define linear forms $\Xi_I:I\rightarrow k$ ("condition $\mathrm{i}')$") and $\Xi_J:J\rightarrow k$ ("condition $\mathrm{ii}')$"), and shows that $\Xi_I|_{I\cap J}=\Xi_J|_{I\cap J}$. The latter condition says exactly that there is a linear form on $I+J$ restricting to $\Xi_I$ on $I$ and $\Xi_J$ on $J$; extending this form to all of $\mathrm{Hom}(C,C_0)$ gives the desired form $\Xi$ Serre dual to $\xi$.


text:
Q: Ubuntu Server DNS server I need to configure DNS server for my private cloud which is based only on LAN, do i need internet providers dns for forwarder?
forwarders {
      # Replace the address below with the address of your provider's DNS server
      123.123.123.123;
};

A: Not sure I understand your question...
You don't need to use forwarders, but it can speed things up (your ISP probably caches lookups for thousands of clients). It will however work without them.
If you mean that your private cloud is 100% offline (should not communicate with the internet) then there is no point in having them.
EDIT: Do -> Don't (sorry about that)


text:
Q: Use an image file link to display a random banner Not sure if this is even appropriate here, but I'm trying to work out how a banner rotator website is using standard html image code, to return a random banner?

In the example above, that html will display a random image from that campaign.
This started as a bit of a whim to see if I could set up something similar to work with different image sizes, but now it's driving me nuts... trying to figure out how to go from a image url to a database call to send back a different image!?
No lucky searching for ideas or examples, probably because I don't know what sort of processes or functions I should actually be looking for?
I'm thinking there must be some sort of url rewrite for all image calls, that redirects to a handler script...
That script makes the database call, grabs a random image from the nominated campaign, updates stats etc...
And possibly a php header response returns the corresponding image file?
But most of that is new to me and I'm not sure where/how to search for guidance or examples to get me started.
If anyone has any ideas on this, or even the kind of phrasing/functions I need that might help me get there in my own searching, it would be much appreciated!
(I've also installed and tested about 12 different rotator scripts hoping to find one that works the same, but no luck there either).
Thanks!
Matt

A: I wrote a php script that assumes to exist the wanted folders in the root of your website. Then you can invoke it in a simple way in any location of your website. Here is my script:
rotate.php
<?php
  ##########################################################
  # Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
  # Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
  ##########################################################
  function rotate($folder) {
    if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
      $list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
      $fileList = array();
      $img = '';
      foreach ($list as $file) {
        if ((file_exists($_SERVER['DOCUMENT_ROOT']  . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT']  . "/$folder/$file"))) {
          $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
          if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
            $fileList[] = $file;
          }
        }
      }
      if (count($fileList) > 0) {
        $imageNumber = time() % count($fileList);
        $img = $folder . '/' . $fileList[$imageNumber];
      }
      return $img;
    } else {
      mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
    }
  }
?>

Now you can create a index.php file where you want and put this line:
<?php include("your_path/rotate.php"); ?>

    <img border="0" src="/<?php echo rotate('campaign1'); ?>">

other like this:

    <img border="0" src="/<?php echo rotate('campaign2'); ?>">

and so that...
You have only to create the wished folders in the root called campaign1, campaign2...etc...
then in each folder put the banner images of the current campaign...
for example: in the folder campaign1 put image like 001.png, 002,png, 003.png, 004.jpg, 005.jpg... (where these filenames match your campaign banners).
for example: in the folder campaign2 put image like 001.png, 002,png, 003.png, 004.jpg, 005.jpg, 006.gif, 007.png, 008.jpg... (where these filenames match your campaign banners).
Please note that if you don't want rename your banner images you can take the original names, my script will work in any way.
My script will turn all in wished output like this:
campaign1:

campaign2:

See you and test all into your localhost website... for me works fine on PHP 7.4.5 and Apache 2.4.43.
The script will do the rest!
Hope this helps you!


text:
Q: How to print lines from nth line to nth line between two strings using powershell I am struggling to print lines from nth line to nth line between two strings using powershell.
From the below sample data I want to print lines between '--------' to 'Jammer' except first line after '---------' to output.txt
This is my sample data sample.txt
--------
C:\test\1528372320775.xml
C:\test\fail\1528372320775_877291.xml
C:\test\outgoing\1528372320775_xexAx2111.xml
   Jammer: 2C339A2A:138814
--------
C:\test\244124414.xml
C:\test\fail\244124414_232423.xml
C:\test\outgoing\244124414_xexAx21333.xml
   Jammer: 8373SDF4:138814
--------
C:\test\832492892387.xml
C:\test\fail\832492892387_2SU2932.xml
C:\test\outgoing\832492892387_xexAx23232.xml
   Jammer: 3G380DD2A:338783
--------
C:\test\23234923427.xml
C:\test\fail\23234923427_2SLLE.xml
C:\test\outgoing\23234923427_xexAx2233.xml
C:\test\exeption\23234923427_xexAx2233.xml
   Jammer: 3883BB3SC:311314
--------

Expected output: output.txt
C:\test\fail\1528372320775_877291.xml
C:\test\outgoing\1528372320775_xexAx2111.xml
C:\test\fail\244124414_232423.xml
C:\test\outgoing\244124414_xexAx21333.xml
C:\test\fail\832492892387_2SU2932.xml
C:\test\outgoing\832492892387_xexAx23232.xml
C:\test\fail\23234923427_2SLLE.xml
C:\test\outgoing\23234923427_xexAx2233.xml
C:\test\exeption\23234923427_xexAx2233.xml

This is what I have tried so far and I was able to get number of lines between strings but not able to print the desired output. Can someone please suggest how can I achieve this. Thanks in advance.
$file = "C:\Sample.txt"
$start="--------"
$end="Jammer"

$lines = (Select-String -Path $file -Pattern $start).LineNumber
$endlines = (Select-String -Path $file -Pattern $end).LineNumber

#Write-Host $endlines
#$lines.Count
#$endlines.Count

$i=0;
foreach($endline in $endlines)
{
   $numberoflines = ($endline - $lines[$i] -1)
   $linetoprint = $lines[$i]+1

  for($j=1; $j-eq$j+$numberoflines; $j++)
  {
     Get-Content $file | Select -Index $linetoprint
  }
  Write-Host $numberoflines
  $i++;
}

A: You can try using regex but a simpler solution would be to use a simple state machine while processing each line to determine if

*

*you have just read a '-------' and need to skip the next line

*and if the line starts with C:\test, you should output the line

Example
@'
--------
C:\test\1528372320775.xml
C:\test\fail\1528372320775_877291.xml
C:\test\outgoing\1528372320775_xexAx2111.xml
   Jammer: 2C339A2A:138814
--------
C:\test\244124414.xml
C:\test\fail\244124414_232423.xml
C:\test\outgoing\244124414_xexAx21333.xml
   Jammer: 8373SDF4:138814
--------
C:\test\832492892387.xml
C:\test\fail\832492892387_2SU2932.xml
C:\test\outgoing\832492892387_xexAx23232.xml
   Jammer: 3G380DD2A:338783
--------
C:\test\23234923427.xml
C:\test\fail\23234923427_2SLLE.xml
C:\test\outgoing\23234923427_xexAx2233.xml
C:\test\exeption\23234923427_xexAx2233.xml
   Jammer: 3883BB3SC:311314
--------
'@ -split "`r`n" | % {
    switch -Regex ($_) {
        '--------' {$skipnext=$true}
        '^C:\\test' {if ($skipnext) {$skipnext = $false} else {$_}}
    }
}

Applied to your file
switch -File (gc <yourfile>) -Regex {
    '--------' {$skipnext=$true}
    '^C:\\test' {if ($skipnext) {$skipnext = $false} else {$_}}
    }
}


text:
Q: Do I need to use a "=" in the scope to pass a function to my directive? I have:
<admin-retrieve-button ctrl="ctrl">

app.directive('adminRetrieveButton', ['stateService', function (stateService) {
    return {
        scope: {
            ctrl: '='
        },
        restrict: 'E',
        template: "<button ng-click='ctrl.abc()'>Retrieve</button>",
        link: function (scope, element, attrs) {
            scope.stateService = stateService;
            scope.entity = attrs["entity"];
        }
    };
}]);

I am unsure what is meant by binding when it comes to a function. Do I need to specify ctrl: '=' for this directive when the only thing that happens is the call to the abc() function.  Also are there any other options for the scope that would allow me to not even need to specify ctrl ?

A: You're not passing a function. You're passing the ctrl object and in that case you need the '=' binding. You can bind a function to the directive scope by using the '&' binding.


text:
Q: Google Vision not always including pagesWithMatchingImages in web detection responses I'm sending web detection requests like this to the Google Vision API.
{
  "requests": [
    {
      "image": {
        "content": "<base 64 encoded image>"
      },
      "features": [
        {
          "maxResults": 50,
          "type": "WEB_DETECTION"
        }
      ]
    }
  ]
}

The requests are being sent to https://vision.googleapis.com/v1/images:annotate?key=<my key>.
The part of the response I need is pagesWithMatchingImages, so I can see which pages have the given image.  This works for most of the images I've tried, but not for images that contain text.  If the image is a common logo that includes text, for example, then the API doesn't include pagesWithMatchingImages in the response.
How can I get a list of pages with matching images for images that include text?
Here's are some samples of images that are used on a lot of web pages, but don't have pagesWithMatchingImages in the API response:

A: The issue you are facing with the Google Vision API WEB_DETECTION feature seems to be an issue detected by the  Google Vision API team, they seem to be investigating more about it and they will post the updates within the Public Issue Tracker post.
One of the reasons the WEB_DETECTION feature does not responds with the pagesWithMatchingImages seems to be related to the transparency in PNG images, adding a white background might help the WEB_DETECTION feature according to the post, but does not warranty the accuracy in the response
The Public Issue Tracker is used for reporting bugs and feature requests of the Google Cloud products, by indicating that you are affected by the same issue it can help to bring more visibility on it and expedite the resolution.

A: You can try to add the LOGO_DETECTION type under features.
{
  "requests": [
    {
      "image": {
        "content": "<base 64 encoded image>"
      },
      "features": [
        {
          "maxResults": 50,
          "type": "WEB_DETECTION"
        }
        {
          "type": "LOGO_DETECTION"
        }
      ]
    }
  ]
}


text:
Q: Adding each value in an RDD to its partition number
Quite new to PySpark so this might be simple. I have an RDD that ranges from 1 to 100 and has 4 partitions.
A = sc.parallelize(range(100), 4)

And I have to find a way to return another RDD where each value in the RDD is added to its partition number. The ideal example would be:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
99, 100, 101, 102]

Would like to know how I could amend the following code to get the desired results.
A = sc.parallelize(range(100), 4)

B =

print(B.collect())


text:
Q: Redirect stdout from a runing script In C, you can redirect stdout somewhere when a program is running, for example:
int fd = open("some_file", O_RDWR);
dup2(fd, STDOUT_FILENO);
printf("write to some_file\n");

Can I achieve this in bash without redirecting stdout when running a bash script (./script.sh > some_file)?

A: You can use a redirection around any command, including compound commands. For example:
some_function () {
  echo "This also $1 to the file"
}

{
  echo "This goes to the file"
  some_function "goes"
} >some_file
echo "This does not go to the file"
some_function "does not go"

You can do a permanent redirection (which applies until the end of the script or until overridden by another redirection) by calling the exec builtin with a redirection, but no command. For example:
foo () {
  echo "This does not go to the file"
  exec >some_file
  echo "This goes to the file"
}
foo
echo "This still goes to the file"

These features are available in all Bourne/POSIX-style shells including bash.


text:
Q: Display limited repeat values in one pdf page Is there any way of limiting the displayed repeat values in one page?
Ex: Display first two values in first page, next two values in the next page etc ?
I tried to find a way of doing this but I could not find anything helpful.

A: What you want to do requires a creating a controller that prepares pages for pagination based on the number of lines that are generated for each page (before sending them to the page for output) as described in Creating Professional PDF Documents with CSS.


text:
Q: A question on the resolution of parabolic Verma module $M_I(\lambda)$ in BGG category O I am reading Humphrey's book "Representations of semisimple Lie algebras in the BGG Category O" on Page 189, Proposition 9.6, where he remarked that "Note that if we had developed the full BGG resolution of $L_I(\lambda)$, this would correspond to an exact sequence completing the one in Theorem 9.4(b)."
I am interested in this idea because this would prove directly that $$
ch M_I(\lambda)=\sum_{w\in W_I}(-1)^{\ell(w)}ch M(w\cdot\lambda)
$$
I wonder if it is clear that we do have a full BGG resolution of $L_I(\lambda)$ or it is still an open question for some reason. Why can't we just get the full BGG resolution of
$L_I(\lambda)$ by applying Corollary 6.5 (Page 114) in that book to the Levi subalgebra? Did I  miss some important points here?


text:
Q: Зачем создавать програмно, если есть дизайнер форм? Прошу внести ясность. Я начал изучение с# с консоли что не удивительно.
И вот я хочу создать приложение, с неким функционалом в WinForm. Я создаю проект и поехали... Перетащил нужные элементы, заполнил нужные события,  Ну и там реализовал какую-то логику. Все работает, все здорово.
Это вообще нормальная практика? Или нужно учится писать все элементы програмно, и если да, то в чем прелести этого подхода? Чувствую, что я чего-то сильно не понял.

A: Если у вас проект с динамическим выводом элементов (не просто скрыть/показать, а именно добавлять разное число элементов в зависимости от полученных данных из базы, аккуратно их распределять по форме - то может пригодиться создание из кода.
В простых проектах обычно достаточно один раз расставить в дизайнере элементы.
Как программист вы должны уметь оба подхода. Начать изучение лучше с визуального.

A: Я считаю, что это вполне нормальная практика. Главное понимать, как весь этот UI, который Вы используете, транслирует всё это в код. В программной реализации нужда возникает только в каких-то особенных случаях, а так UI всё сделает лучше и красивее, чем человек.


text:
Q: Цвет не меняется с помощью функции setColor() function love.draw ()
  love.graphics.setColor ( .255, .0, .0 )
  love.graphics.rectangle ( "fill", Rect.x, Rect.y, Rect.width, Rect.height )
  love.graphics.setColor ( .51, .255, .51 )
  love.graphics.rectangle ("fill", 1, 750, 600, Rect.height)
end

сейчас стоит белый цвет, а в фоне устанавленный в setBackgroundColor() цвет стоит. Фоновый цвет работает. а для земли зеленый цвет и для обьекта который будет прыгать  не работает цвет... где может быть ошибка ? цвета вроде пишутся в love.draw() ?


text:
Q: VSCode Typescript with NextJS debugging I can't get any debug config to work with breakpoints and nextJS using typescript… Does anyone have one to share with me ?
Thanks

A: This is my .vscode/launch.json:
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/node_modules/next/dist/bin/next"
    }
  ]
}

Working for me with Next.js v9.4.4 in June 2020.


text:
Q: spring boot start up error I get the below error when i start up spring boot.
The application is able to start up fine even if this error is reported in the logs.
Has anybody faced this issue ? Will this impact the hibernate operations during run time ?
2017-06-14 10:04:26.186  INFO 8376 --- [           main] j.LocalContainerEntityM
anagerFactoryBean : Building JPA container EntityManagerFactory for persistence
unit 'default'
2017-06-14 10:04:26.246  INFO 8376 --- [           main] o.hibernate.jpa.interna
l.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
2017-06-14 10:04:27.562  INFO 8376 --- [           main] org.hibernate.Version
                  : HHH000412: Hibernate Core {5.2.2.Final}
2017-06-14 10:04:27.566  INFO 8376 --- [           main] org.hibernate.cfg.Envir
onment            : HHH000206: hibernate.properties not found
2017-06-14 10:04:27.569  INFO 8376 --- [           main] org.hibernate.cfg.Envir
onment            : HHH000021: Bytecode provider name : javassist
2017-06-14 10:04:27.763  INFO 8376 --- [           main] o.hibernate.annotations
.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-06-14 10:04:27.828  WARN 8376 --- [           main] org.hibernate.orm.url
                  : HHH10000002: File or directory named by URL [file:/D:/MRO/QA
MS/sourcecode/10_04_2017/mro/distribution/qams/microservices/qam-rsk-prediction/
build/libs/my-jar-1.0.0.jar!/BOOT-INF/classes] could not be found.  URL will be
ignored

java.io.FileNotFoundException: D:\myproject\build\libs\my-jar-1.0.0.jar!\BOOT-INF\cl
asses (The system cannot find the path specified)
        at java.util.zip.ZipFile.open(Native Method) ~[na:1.8.0_73]
        at java.util.zip.ZipFile.<init>(Unknown Source) ~[na:1.8.0_73]
        at java.util.zip.ZipFile.<init>(Unknown Source) ~[na:1.8.0_73]
        at java.util.jar.JarFile.<init>(Unknown Source) ~[na:1.8.0_73]
        at java.util.jar.JarFile.<init>(Unknown Source) ~[na:1.8.0_73]
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.res
olveJarFileReference(JarFileBasedArchiveDescriptor.java:165) ~[hibernate-core-5.
2.2.Final.jar!/:5.2.2.Final]
        at org.hibernate.boot.archive.internal.JarFileBasedArchiveDescriptor.vis
itArchive(JarFileBasedArchiveDescriptor.java:51) ~[hibernate-core-5.2.2.Final.ja
r!/:5.2.2.Final]
        at org.hibernate.boot.archive.internal.JarProtocolArchiveDescriptor.visi
tArchive(JarProtocolArchiveDescriptor.java:59) ~[hibernate-core-5.2.2.Final.jar!
/:5.2.2.Final]
        at org.hibernate.boot.archive.scan.spi.AbstractScannerImpl.scan(Abstract
ScannerImpl.java:47) ~[hibernate-core-5.2.2.Final.jar!/:5.2.2.Final]
        at org.hibernate.boot.model.process.internal.ScanningCoordinator.coordin
ateScan(ScanningCoordinator.java:75) ~[hibernate-core-5.2.2.Final.jar!/:5.2.2.Fi
nal]
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(
MetadataBuildingProcess.java:98) [hibernate-core-5.2.2.Final.jar!/:5.2.2.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init
>(EntityManagerFactoryBuilderImpl.java:226) [hibernate-core-5.2.2.Final.jar!/:5.
2.2.Final]
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init
>(EntityManagerFactoryBuilderImpl.java:161) [hibernate-core-5.2.2.Final.jar!/:5.
2.2.Final]
        at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvi
der.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.ja
va:54) [spring-orm-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.cr
eateNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:338)
[spring-orm-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNat
iveEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373) [spring-orm-4
.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPro
pertiesSet(AbstractEntityManagerFactoryBean.java:362) [spring-orm-4.3.2.RELEASE.
jar!/:4.3.2.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) [spring-
beans-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) [spring-bea
ns-4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) [spring-beans-
4.3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBean
Factory.createBean(AbstractAutowireCapableBeanFactory.java:482) [spring-beans-4.
3.2.RELEASE.jar!/:4.3.2.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getOb
ject(AbstractBeanFactory.java:306) [spring-beans-4.3.2.RELEASE.jar!/:4.3.2.RELEA
SE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistr
y.getSingleton(DefaultSingletonBeanRegistry.java:230) [spring-beans-4.3.2.RELEAS
E.jar!/:4.3.2.RELEASE]


text:
Q: How to get password failure count of crypto token (Smartcard) using PKCS11Interop I have .Net application to interact with the crypto token (Smartcard) using PKCS11Interop library where users can login to the token and generate keypair and sign.
If users enter the wrong password multiple time token will be locked, how can I get the remaining number of attempt to login to the token.
while searching on the internet I came across Net.Pkcs11Interop.HighLevelAPI.TokenInfo.TokenFlags which contains this information
CKF_USER_PIN_COUNT_LOW 0x00010000 True if an incorrect user login
PIN has been entered at least
once since the last successful
authentication.
CKF_USER_PIN_FINAL_TRY 0x00020000 True if supplying an incorrect
user PIN will cause it to
become locked.
CKF_USER_PIN_LOCKED 0x00040000 True if the user PIN has been locked. User login to the token
is not possible

but these are boolean values, I need the exact number of retry left.

A: PKCS#11 API does not provide exact number of retries left. As you have correctly found out it does provide similar information via TokenFlags:
// Get token info
TokenInfo tokenInfo = slot.GetTokenInfo();

if (tokenInfo.TokenFlags.UserPinCountLow)
{
    // An incorrect user login PIN has been entered at least once since the last successful authentication
}

if (tokenInfo.TokenFlags.UserPinFinalTry)
{
    // Supplying an incorrect user PIN will make it to become locked
}

if (tokenInfo.TokenFlags.UserPinLocked)
{
    // User PIN has been locked. User login to the token is not possible.
}


text:
Q: Phabricator doesnt map user to svn commiter I have a problem that phabricator doesnt map user to svn commit in Diffusion, if the commits are commited before the user is created in phabricator. So the user will not receipt any notification related to that commit. Is there a way to map those commits to the user too. Thanks.

A: You can request a reparse of the commits from the command line.
bin/repository reparse --all REPO --message

The reparsing will happen in background, so don't expect instant results after the command is run.


text:
Q: Question about specific arclength over an ellipse problem to see an image of what I'm talking about click this link:
https://i.gyazo.com/909ccf0113fd26d21797f411a756ba1e.png
In this image, arclength A is what we desire to be calculated. Point P is given and chord length C is given.
Given a point P and Chord length C, how do I calculate the arclength A in either side to create a chord of length C when a chord is created between the points both an arclength A away from point P are connected.
To do this I can take an iterative approach, trying arclengths until a chord of the desired length can be produced. However, I was wondering if a mathematical approach was possible.
In my specific problem, I define a point P along the circumference of an ellipse as the arclength distance from the point at theta=0. In other words, I evaluate the arclength from theta=0 to the theta characteristic of the point P to get the arclength parameter using the method described here: How to determine the arc length of ellipse?
This is fairly easily doable on a circle, but on an ellipse the arclength is not as easily as s=r*theta, but instead involves elliptic integrals, which I am not familiar with.
Thanks in advance for your help!

A: http://www.ijsrp.org/research-paper-0813/ijsrp-p20103.pdf
Solves it!
The factor PI/(2root(2))[which I must write F (farooque) factor], which when
multiplied to the chord length between any two points on curve gives the length of corresponding arc.)


text:
Q: Updating multiple versions of JPA entity Background-> I have an employee table that is represented by many JPA entities in the code - EmployeeBasic and EmployeeDetails.
Each of these JPA entities have different levels of details - the basic entity has only the employee name and id. The detailed entity has other details such as startdate, department etc, in addition to the name and id.
Now coming to the issue -> I have a place in the code which updates the name of the entity using the EmployeeBasic entity. In another part of the code, the EmployeeDetails entity is being used. But, it is not synched with the updated name automatically. Is there a way to handle it in JPA so that both versions of the entity are in sync?

A: No, there is no such a behavior in JPA/Hibernate.
Synching automatically is not possible, because Hibernate is not aware of object modifications until flush-time. So when you change EmployeeBasic's name, Hibernate will not notice it before dirty-check.
However, I think that it would not be a good design to make something like this anyway. The best approach is to unify all of your different entities mapped to the same table (rows) into one entity, so that persistence context is never in an inconsistent state regarding to DB and other entities.

A: JPA allows caching at different layers, so that even if all processes were using the same Employee entity, it would require careful design to make sure that all processes were synched with the updated name automatically.  The reason for this is that an EntityManager is meant to be treated transactionally; reading from it will give you managed instance of entities that then are isolated from changes made in other EntityManagers.  The data in the database is only a concern when it comes time to write.  This allows you to work on them without worrying about data changing out from under you, and manage any problems yourself (some form of optimistic locking is recommended).
Your case is also complicated by the fact that although EmployeeBasic and EmployeeDetails may reuse the same database table, JPA allows for a shared cache as well.  So making changes to EmployeeBasic will update its cache and shared cache, but the EmployeeDetails cache will be stale.  This is similar to having multiple persistence units accessing the same tables.
The way this is handled is that the application is responsible and can control when they want to refresh their entities, the level of caching and invalidation of the caches.   JPA allows turning off the shared cache (using isolated caches), so that when you read from a new EntityManager, it will always go to the database for the data, and see changes in any of the entities.  It also has refresh api (and most providers have refresh hints) that allow you to force a query to the database when you know something might need to be checked, though care must be taken as it wipes out changes.
EclipseLink (I'm not familiar with Hibernate) has cache invalidation options and cache coordination that could be used together with events, so that you can take advantage of shared caches; you could use update events to trigger all Employee** caches related to that updated to become invalidated.


text:
Q: Connecting to Apache files remotely when using different port So I'm working on a class project involving setting up a LAMP server using the instructions here. I was able to get everything setup and running fine... on my LAN. But nothing outside my LAN could connect to the sites. I did some research, and, based on what I found, changed the port Apache was listening to. Now devices could connect to the front page of my Apache server by adding the port to the end of the URI.
Unfortunately, the test.php page and the phpmyadmin page still can't be accessed remotely. I'm not sure what to do to correct the issue.


text:
Q: XAML Binding to a CollectionViewSource property on a ViewModel I have a simple ViewModel like:
public class MainViewModel {
    ObservableCollection<Project> _projects;
    public MainViewModel() {
        // Fill _projects from DB here...
        ProjectList.Source = _projects;
        ProjectList.Filter = ...;
    }

    public CollectionViewSource ProjectList { get; set; }
}

I set the window's DataContext to a new instance of that ViewModel in the constructor:
public MainWindow() {
    this.DataContext = new MainViewModel();
}

Then in the Xaml I am attempting to bind the ItemsSource of a ListBox to that ProjectList property.
Binding just ItemsSource like so doesn't work:
<ListBox ItemsSource="{Binding ProjectList}" ItemTemplate="..." />

But if I first rebase the DataContext this works:
<ListBox DataContext="{Binding ProjectList}" ItemsSource="{Binding}" ItemTemplate="..." />

Shouldn't the first method work properly? What might I be doing wrong?

A: If you are using CollectionViewSource you need to bind ItemsSource to ProjectList.View instead of ProjectList. That should solve your problem.

A: From what you provided the first method should perfectly work. Devil lurks somewhere in details.
PS: Maybe you didn't specify implementation of INotifyPropertyChanged interface in sake of post size, but be careful in production. It's very easy to get a memory leak if you don't implement it.


text:
Q: Async/Await on Callback not waiting I am querying AMPS SOW using javascript API. My functions look like this:
sow_query = async(topic, filter, options) => {
await this.connection
await this.client.sow(this.onMessage, topic, filter, options)
return this.message
}

onMessage = (message)=>{
this.message.push(message.data)
}

//Calling functions
const getData = async(date) =>{
let data = await getAmpsData(date)
}

async getAmpsData(date){
const filter = "some filter"
const data = await ampsClient.sow_query(topic, filter)
data.forEach((element) => console.log(element))
}

It looks like my call to ampsClient.sow_query doesnt wait for the callback to finish so returns an empty list. Therefore, I cannot loop through the data in my calling function getAmpsData.
I know it has to do with async/await because if I simply do console.log(data) in getAmpsData i can see the data (perhaps after 2 seconds) when the promise is resolved. Is there anyway i can get this working?

A: If I understand you correctly, data in getAmpsData is an array as expected, but data in getData is undefined. It's not an async/await problem, you just forgot to add return data; to getAmpsData.

A: I not sure about what package you are using. But, maybe, it using a callback function to get the result of .sow function - message.data.
With your logic, onMessage function will be called after data.forEach done, you can try adding a console.log line to onMessage function.
Maybe, the package has an important reason to do that. But, to fix this issue, you can wrap .sow function into a promise.
sow_query = async (topic, filter, options) => {
  await this.connection // ???
  return new Promise((resolve) => { // wrap in a promise
    this.client.sow( // no need to wait .sow
      (message) => {
        resolve(message.data); // just resolve when we get the message's data
      },
      topic, filter, options)
  });
}

//Calling functions
const getData = async (date) => {
  let data = await getAmpsData(date)
}

async getAmpsData(date) {
  const filter = "some filter"
  const data = await ampsClient.sow_query(topic, filter)
  data.forEach((element) => console.log(element))
}


text:
Q: Setting transparency color in Expression Builder Using QGIS 3.16, I am trying to set color through expression builder, using #RRGGBBAA format.
The problem, I was using the same color, let's say '#94AFDCff', it should return the same color as '#94AFDC' in #RRGGBB format, yet the color that is rendered is fully different. I cannot seem to find out why.
Could anyone help?
The code is simple, it is used in symbol, as a condition of fill colors of circles.
CASE
    WHEN   "Cat_Num" = 1 THEN '#94AFDC66'
    WHEN  "Cat_Num"  = 2 THEN '#FFFF0066'
    WHEN  "Cat_Num"  =  3 THEN '#ffc40366'
    WHEN  "Cat_Num"  =  4 THEN '#54823566'
    WHEN  "Cat_Num"  =  5 THEN '#7030a066'
    WHEN  "Cat_Num"  =  6 THEN '#843c0c66'
    WHEN  "Cat_Num"  =  7 THEN '#38c0f666'
    WHEN  "Cat_Num"  =  8 THEN '#CCCC0066'
    WHEN  "Cat_Num"  =  9 THEN '#C55A1166'
    WHEN  "Cat_Num"  =  10 THEN '#8d5a9966'
    ELSE 'pink'
END

but this code resulted in (notice that the 2 circles are "Cat_Num" = 8 THEN '#CCCC0066' and "Cat_Num" = 10 THEN '#8d5a9966')

In the end, I did change the code to rgba format, so that "Cat_Num" = 8 THEN '204, 204, 0, 90' and "Cat_Num" = 10 THEN '141, 90, 153, 90'
with this result:

How are these 2 so different?? The hex color returns pink result for "Cat_Num" = 8 THEN '#CCCC0066' (the bigger circle). The smaller circle, which should return purplish, became greenish... Did I make a mistake?
As a reference, in QGIS' own color picker, inputting '#CCCC0066'  will have the same color as '141, 90, 153, 90', only different transparency value (90 is about 0.65% for RRGGBBAA and 66 in hex is 40% )


text:
Q: Reactjs dropdown setState being set on second value change In the following component, the handleDropdownChange function does not set the state for "data" on the first change, it only sets it after the second change. For example, when I select 'Electronics', nothing happens. I then select 'Produce', and the page loads all 'Electronics' products.
export default class ProductList extends Component {

    constructor(props){
        super(props);
        this.handleDropdownChange= this.handleDropdownChange.bind(this);
        this.state = {
             data: fulldata
            };
    }

    handleDropdownChange(e){

        e.preventDefault();
        var filtered_data = fulldata.filter(prod => prod.category == e.target.value);
        this.setState({ data:filtered_data })

    }

   render(){

    return(

Category

                        <select id="filter-cat" onChange={this.handleDropdownChange}>
                            <option value="Apparel">Apparel</option>
                            <option value="Electronics">Electronics</option>
                            <option value="Produce">Produce</option>
                        </select>

              {this.state.data}
     );
    }
}

A: Your code looks okay, although I'm not entirely sure how you're rendering this.state.data because by the looks of it it is an array. You can modify your handleDropdownChange to store the selected item instead.
Your state:
    this.state = {
      data: fulldata[0]
    };

Your onChange handler:
handleDropdownChange(e) {
  const filtered_data = fulldata.find(
    (prod) => prod.category === e.target.value
  );
  this.setState({ data: filtered_data });
}

Here's the working codesandbox example

A: The only thing that worked for me was found here:
setState doesn't update the state immediately
My updated method looks like this:
async handleDropdownChange(e){

        e.preventDefault();
        var filtered_data = fulldata.filter(prod => prod.category == e.target.value);
        await this.setState({ data:filtered_data })

    }

This feels hacky and I wish there was a better way, but for now this is only solution that works me.


text:
Q: Swift, fetch TableView from JSON and save it into array i'm trying to do some simple things here, but i'm struggling a bit as i'm a beginner.
So basically i have a JSON file link to use to populate my tableview with 2 sections. Each cell have a "Favourite button".
i've tried many way to save my array with UserDefault with no luck.
What i wish to achieve:

*

*When the "Favourite button" is pressed, i wish to move the cell to the other section

*Save and retrieve those 2 array using UserDefault

I'm open to hear any suggestion also any other differs approach, as i'm sure there is some better one.
I will upload here some code, but also the link for the full project in Git so you can check better (https://github.com/Passeric/UserTableview.git)
I really appreciate any help.
The JSON i'm using:
    {
  "User": [
    {
      "Name": "John",
      "Age": "34"
    },{
      "Name": "Sara",
      "Age": "19"
    }.......]}

My Struct:
class User: Codable {
    let user: [UserDetails]

    enum CodingKeys: String, CodingKey {
        case user = "User"
    }
    init(user: [UserDetails]) {
        self.user = user
    }
}

class UserDetails: Codable {
    let name: String
    let age: String

    enum CodingKeys: String, CodingKey {
        case name = "Name"
        case age = "Age"
    }

    init(name: String, age: String) {
        self.name = name
        self.age = age
    }
}

And my ViewController:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var arrayDefault = [UserDetails]()
    var arrayFavourite = [UserDetails]()
    var sec: [Int:[UserDetails]] = [:]
    var Default = UserDefaults.standard

    @IBOutlet weak var myTableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.myTableview.dataSource = self
        self.myTableview.delegate = self

        DownloadJSON()

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        sec = [0 : arrayFavourite, 1 : arrayDefault]
        return (sec[section]?.count)!
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dataRef = arrayDefault[indexPath.row]
        let cel: MyCell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyCell
        cel.NameLabel.text = dataRef.name
        cel.AgeLabel.text = dataRef.age

        let imgFav = UIImage(systemName: "star")
        let b = imgFav?.withRenderingMode(.alwaysOriginal)
        cel.FavButton.setImage(b, for: .normal)

        return cel
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }

    func DownloadJSON() {
            let urlll = URL(string: "https://pastebin.com/raw/Wufivqmq")
            guard let downloadURL = urlll else { return }
            URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
                guard let data = data, error == nil, urlResponse != nil else {
                    print("something is wrong")
                    return
                }
                print("downloaded")
                do
                {
                    let decoder = JSONDecoder()
                    let downloadeduser = try decoder.decode(User.self, from: data)
                    self.arrayDefault.removeAll()
                    self.arrayDefault.append(contentsOf: downloadeduser.user)
                    DispatchQueue.main.async {
                        print("data saved")
                        self.myTableview.reloadData()
                    }
                } catch {
                    print(error)
                }
            }.resume()
    }

    @IBAction func RefreshButton(_ sender: Any) {
        // Here i wish to refresh the table view (so the current saved array) with the updated JSON
        // For example if i update the "Age" in the original JSON
        // But i don't want to lose the user preference for the "Favourite"
    }

}

As you can see is not a big deal thing, but i can't figure out how to properly save and retrive the array, and then move the cell (by the index path) to the other array.
This is the link for the full project: https://github.com/Passeric/UserTableview.git
Thanks again to anyone who will help.❤

A: I would make a few changes:

*

*Clean up your data model.  Currently you are storing the data as both two arrays and a dictionary.  There are minor pros and cons to each approach, but in the grand scheme of things it doesn't really matter which one you use, just pick one.  Personally, as a beginner, I would go with two arrays.

*Don't change your data model in the data source.  Currently you are creating the sec dictionary in the tableView:numberOfRowsInSection function.  If you want to keep using sec then create it as the same time you load the data initially. Or, as mentioned above, just remove sec completely.

*Assuming you've made the above changes, moving a user to the favorites section is as simple as removing the user from the default list, adding it to the favorites list, and telling the list that the data has changed:

func makeFavorite(index:IndexPath) {
    let user = arrayDefault[index.row]
    arrayDefault.remove(at: index.row)
    arrayFavourite.append(user)

    //This updates the entire list.  You might want to use moveRow(at:to:) in order to animate the change
    tableView.reloadData()
}

*When it comes to converting your data model to/from json, you're already most of the way there by conforming to Codable.  To load from json:

if let jsonData = UserDefaults.standard.string(forKey: "userKey").data(using: .utf8) {
    let decoder = JSONDecoder()
    if let user = try? decoder.decode(User.self, from: jsonData) {
        //Do something with user here...
    }
}

And to output to json:
let encoder = JSONEncoder()
if let data = try? encoder.encode(user),
    let jsonString = String(decoding: data, as: .utf8) {
    UserDefaults.standard.setValue(jsonString, forKey: "userKey")
}

Do the same thing with the list of favorites (using a different key).


text:
Q: Расширенный патч в git Если тебе необходимо перенести изменения из репозитория в репозиторий, то ты используешь git diff -> git apply.
Но в случае, если репозитории отличаются слишком сильно, ты получишь гору ошибок.
Есть ли возможность в гите создать расширенный патч, который будет содержать не изменения данного коммита в сравнении с прошлым коммитом, а сами файлы, задетые этим коммитом?
Ну, чтобы даже применив такой патч на абсолютно пустой репозиторий, там бы появились все файлы, задетые в коммите в репозитории-доноре. (Но не весь репозиторий-донор! Только файлы задетые в одном коммите!)

A:
Есть ли возможность в гите создать расширенный патч, который будет содержать не изменения данного коммита в сравнении с прошлым коммитом, а сами файлы, задетые этим коммитом?

то, что вы описали, называется не «патч», а «непосредственно содержимое файлов». ведь «патч» — это разница между двумя конкретными состояниями файла(-ов), а если одно из состояний неизвестно, как в вашем случае, то и получить «патч» (разницу) становится методологически невозможно.
я уже давал ответ на подобный вопрос (ваш вопрос фактически является его под-вопросом). привожу только команду, подробности смотрите в том ответе:
$ tar -czf /tmp/archive.tgz $(git log --name-only \
 --pretty="format:" коммит1..коммит2 | grep -v '^$' | sort -u)


text:
Q: Pulling values from list's I have this list.
[NormalizedReference(book=<Book.MATTHEW: 40>, start_chapter=18, start_verse=12, end_chapter=18, end_verse=14, end_book=None), NormalizedReference(book=<Book.LUKE: 42>, start_chapter=15, start_verse=3, end_chapter=15, end_verse=7, end_book=None)]

How can I get the book value or end book value??
Python3

A: More details here -> https://pypi.org/project/pythonbible/
STEP 1 : Converting a normalized scripture reference into a list of integer verse ids
STEP 2 : Get the verse text
import pythonbible as bible

verse_text = bible.get_verse_text(1001001, version=bible.Version.KING_JAMES)

Output :
'In the beginning God created the heaven and the earth.'

To get verse id -
Consider reference for Genesis 1:1-4:
import pythonbible as bible

reference = bible.NormalizedReference(bible.Book.GENESIS, 1, 1, 1, 4)
verse_ids = bible.convert_reference_to_verse_ids(reference)

The conversion functionality would return the following list of verse id integers:
[1001001, 1001002, 1001003, 1001004]


text:
Q: Java input input decimals and deal with imaginary numbers I want to make a quadratic formula program. I succeeded with the basics but have 2 major errors. One when I try to input decimal values as a,b or, c and the other when I have to deal with i(imaginary numbers). How do I fix these issues? I also appreciate ways to simplify the code here is my code:
import java.util.Scanner;

public class Calculator {
    public static void main (String args[]){
    System.out.println("Input a");
    Scanner ai = new Scanner(System.in);
    double a = ai.nextInt();
    System.out.println("Input b");
    Scanner bi = new Scanner(System.in);
    double b = bi.nextInt();
    System.out.println("Input c");
    Scanner ci = new Scanner(System.in);
    double c = ci.nextInt();
    double Square1 = Math.pow(b, 2);
    double Square2 = -4*a*c;
    double Square3 = Square1 + Square2;
    double Square = Math.sqrt(Square3);
    double Bottom = 2*a;
    double Top1 = -b + Square;
    double x1 = Top1/Bottom;
    double Top2 = -b - Square;
    double x2 = Top2/Bottom;
    System.out.printf("X = %s", x1);
    System.out.printf("X = %s", x2);

    }
}

A: First error you got because you have used method nextInt(). It throws InputMismatchException when you try read double - Method nextInt
Instead nextInt() you should use method nextDouble.
Second error: Java does not have support for imaginary numbers :(
If you want use imaginary numbers you have to write your class ImaginaryNumber.
This is your code refactored:
import java.util.Scanner;

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

        System.out.println("Input a");
        double a = input.nextDouble();

        System.out.println("Input b");
        double b = input.nextDouble();

        System.out.println("Input c");
        double c = input.nextDouble();

        double square1 = Math.pow(b, 2);
        double square2 = -4 * a * c;
        double square3 = square1 + square2;

        if (square3 < 0) {
            double square = Math.sqrt(square3);

            double bottom = 2 * a;
            double top1 = -b + square;
            double x1 = top1 / bottom;
            double top2 = -b - square;
            double x2 = top2 / bottom;

            System.out.printf("X = %s", x1);
            System.out.println();
            System.out.printf("X = %s", x2);
        } else {
            System.out
                    .println("Can not calculate square root for negative number");
        }

        input.close();

    }
}

You can notice that I added
if (square3 < 0) {

that is because method Math.square can only take positive.
If you pass negative number it will return NaN - Not a number:
Math.sqrt


text:
Q: Unity3D Character Customization Здравствуйте!
Решаю задачу уже несколько дней и никак не могу найти решение. Надеюсь найдутся компетентные люди и помогут.
Из названия понятно что требуется. Есть персонаж. Есть одежда. Ну и, собственно, нужно одевать персонажа в одежду. Все бы ничего, но персонаж, анимированный, понятное дело. Следовательно при анимации персонажа и одежда должна тоже анимироваться. Поясню: одели куртку на персонажа - рукава куртки двигаются вместе с руками. Со штанами аналогично.
Теоретически, да и практически, понятно как это делать. Вот только не работает так как надо. Явно что-то где-то упущено.
Сейчас расскажу как строится процесс. Делаю я это все в первый раз так что весь код, который будет приведен, создан исключительно для тестирования и для того чтобы понять как это работает.
Мне 3D-модельер дает модельку с костями, материалами, текстурами и анимацией в fbx. Я импортирую ее в Unity. Выкидываю модель на сцену. Пишу код для управления, настраиваю анимацию и так далее. В итоге на сцене стоит рабочая моделька. Она ходит, машет и так далее.
Дальше я пытаюсь повесить на нее, допустим штаны. Штаны вроде как встают куда надо, но сам меш становится в исходное положение расставленными в сторону руками. как на картинке.
Но притом она продолжает анимироваться, но, понятное дело, криво. То есть веса и кости вроде как встали в новый скомбинированный меш.
Дальше интересней. Пытаюсь накинуть на него куртку.

Тут она уже с каким-то смещением. И меш в исходное положение встал. Тоже кривая анимация.
Теперь я приведу код.
void Generate ()
{
    SkinnedMeshRenderer smr = GetComponent<SkinnedMeshRenderer>();

    List<CombineInstance> combineInstances = new List<CombineInstance>();

    boneWeightsList = new List<BoneWeight>();

    CombineInstance ci1 = new CombineInstance();
    ci1.mesh = smr.sharedMesh;
    ci1.transform = smr.transform.localToWorldMatrix;
    ci1.subMeshIndex = 0;
    combineInstances.Add(ci1);

    boneWeightsList.AddRange(smr.sharedMesh.boneWeights);

    /*materialList = new List<Material>();
    materialList.Add(smr.material);*/
    Transform[] bones = smr.bones;//bones.GetComponentsInChildren<Transform>();

    foreach(Transform bone in bones)
        Debug.Log(bone.name);

    //Debug.Log("Elements length : " + elements.Length.ToString() + "config length : " + config.Length.ToString());

    for (int i = 0; i < 1; i++ )
    {
        //Debug.Log("i = " + i + ", config[i] = " + config[i] + ".");
        SkinnedMeshRenderer smr1 = (SkinnedMeshRenderer)Object.Instantiate(element);
        Debug.Log(element);
        Debug.Log(smr1.sharedMesh.subMeshCount);

        // Add meshes to combineinstances
        for (int sub = 0; sub < smr1.sharedMesh.subMeshCount; sub++)
        {
            CombineInstance ci = new CombineInstance();
            ci.mesh = smr1.sharedMesh;
            ci.transform = smr1.transform.localToWorldMatrix;
            ci.subMeshIndex = 0;
            combineInstances.Add(ci);
        }

        boneWeightsList.AddRange(smr1.sharedMesh.boneWeights);

        Object.Destroy(smr1.gameObject);
    }

    // Combine meshes
    smr.sharedMesh = new Mesh();
    smr.sharedMesh.CombineMeshes(combineInstances.ToArray(), true, false);
    smr.sharedMesh.boneWeights = boneWeightsList.ToArray();

    smr.bones = bones;

    // Update bindposes
    List<Matrix4x4> bindposes = new List<Matrix4x4>();
    for (int i = 0; i < bones.Length; i++)
    {
        bindposes.Add(bones[i].worldToLocalMatrix * transform.localToWorldMatrix);
    }
    smr.sharedMesh.bindposes = bindposes.ToArray();

    //smr.sharedMesh.RecalculateBounds();

    transform.Rotate(Vector3.right, -90);

    //GetComponent<Animation>().Play();
}

Собственно вот. Комментировать не стал так как там все просто. Тем более, если вы компетентный в этом вопросе человек.
Собственно, мой вопрос. Что не так? И где? Проблема в том, что может быть что-то не так делает моделлер? Или он все делает так, а вот этот вот код работает не так? Или может быть что-то где-то упущено? Я хз. Честно. Почти неделя на это убита.
В инете все перерыл. Адекватного почти ничего нет. Готовых рабочих сцен не нашел. Пример от самого  Unity под оптимистичным названием "Character Customization" тоже не работает. Но я от туда и взял в общем-то часть кода которую привел здесь. И все исходники, которые я находил, были основаны на этом коде.
Спасибо!

A: Попробуйте прочитать про Ragdoll. Дальше уже, нужно попользоваться фантазией и воображением.
http://docs.unity3d.com/ru/current/Manual/wizard-RagdollWizard.html


text:
Q: Arrow type \Rightarrow in tikz-cd displayed not correctly I'm currently trying to draw commutative diagrams of natural transformations, to represent these I use the arrow type \Rightarrow of tikz-cd. I unfortunately incurred in the following problem: sometimes when I use this command the arrows are not displayed in the correct way.
Here's a concrete example: I wrote the following simple diagram

and this is the associated code
\begin{center}
\begin{tikzcd}
u^* \phi_B \arrow[Rightarrow, dd,"u^* \eta_B" left] \arrow[rr, Rightarrow,"\gamma^{\phi}_u" above]
&  & \phi_A u^* \arrow[Rightarrow, dd,  "\eta_A u^*" right]  \\
&    & \\
u^*\nu_B \gamma_B \arrow[Rightarrow, rr,  "\gamma^{\gamma}_u  \odot \gamma^{\nu}_u" above] & & \nu_A \gamma_A u^*
\end{tikzcd}
\end{center}

I don't know the package tikz-cd very well so I don't understand why the upper arrow is drawn in this way: my guess is that the label interferes in some way with the drawing of one of the lines of the arrow but I'm not sure.
This happened non just to this particular diagram but to others as well: I write the command \Rightarrow but some arrows are drawn as intended while others not. This occurred to both vertical and horizontal arrows and I cannot see any pattern indicating the trouble.
So could you please let me understand what is the problem and provide a solution to it?
If you find more examples of this problem helpful just ask me to post other codes with the associated image.


text:
Q: Problem with image and transparent filter for IE I'm coding a simple bands that goes on at the bottom of the browser on my website. I had everything under control using a semi transparent PNG as my background, but for more flexibility I was asked to do it purely in CSS. So I used an background with a RGBa with a fallback to solid color and, using a conditionnal style sheet, the Microsoft filter for IE 8 and earlier. This works fine, my background looks like I want it to be. The problem I have is that this banner contains an image that is taller than it. Since I've added the filter, it now gets crop in IE... If a switch to a solid background, everything works fine.
Is this a known issue? Is there any workaround?
Here's my IE css:
/* This is the banner taking the whole browser width */
#bottompub {
    position:fixed;
    bottom:0px;
    left:0px;
    width:100%;
    height:50px;
    text-align: center;
    background: transparent;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#B289BAE4,endColorstr=#B289BAE4)"; /* IE8 */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#B289BAE4,endColorstr=#B289BAE4);   /* IE6 & 7 */
    zoom: 1;
    margin:0;
    padding:0;
    overflow:visible; /* Just to make sure no parent change that to hidden */
}

/* This is the image in the banner */
#bottompub .pubimage {
    position:relative;
    margin-left:220px;
    height:75px;
}

/* This is to fit my content web site width the image is in there */
#bottompub .insidebottompub {
    width:1031px;
    margin-left:auto;
    margin-right: auto;
}

Here is the simple HTML:

Thanks!
Edit to not use negative margin

A: it's a known issue - click the link marked flaws for some things to try
I tried a bit and can get it to work for IE8, but not 7, here's the code with some notes to show what I tried for IE7 (ignore the colors they were there to help visualise)
CSS:
/* This is the banner taking the whole browser width */
#bottompub {
    position:fixed;
    bottom:0px;
    left:0px;
    width:100%;
    height:50px;
    background: transparent;
    background: #cfc;

    zoom: 1;
    /*-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#B289BAE4,endColorstr=#B289BAE4)"; /* IE8 */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#B289BAE4,endColorstr=#B289BAE4);   /* IE6 & 7 */

}

/* This is the image in the banner */
#bottompub .pubimage {
    height:75px;
    position: relative;
    top: -25px;
    /*z-index: 1;*/
}

/* This is to fit my content web site width the image is in there */
#bottompub .insidebottompub {
    width:1031px;
    margin: 0 auto;
    text-align: center;
    background: #0f0;
    position: relative;
    /*z-index: 1;*/
}

.insidebottompub a {
position: relative; /* important*/
/* applying hasLyout here doesn't work for IE7 */
}

#bottompub {
/* no z-index or IE8 breaks */
/*z-index: -1;*/
}

applying position: relative; to the link holding the image seemed to be the main thing but there are other changes

A: First of all you should try the CSS3 as well as other vendor prefixes for gradient and opacity to be sure it's consistent.
Secondly, try not setting the negative margins for the image and instead setting a hidden overflow for the parent div. That is to say:
#bottompub
{
    overflow:hidden;
}
EDIT:
This works on IE9:
/* For Internet Explorer 5.5 - 7 */
filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#FF0000FF,endColorstr=#FFFFFFFF);
/* For Internet Explorer 8+ */
-ms-filter:"progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#FF0000FF,endColorstr=#FFFFFFFF)";

Also, take a look at this for all the vendor prefixes, it's a short and good read:http://css-tricks.com/css3-gradients/

A: It is not a fix for the filter problem, but a workaround that works on IE7 and Firefox without needing conditional stylesheet and getting the same effect. I used a separated div for my backgound color and my content. For some reason, I had to put the background after the content, otherwise the transparency was still inherit and the image was cropped. I used the z-index to show elements in the proper order. I kept the main div bottompub mainly to keep thing organized and have a distinct id for all elements in that section.
CSS:
#bottompub {
    position:fixed;
    bottom:0px;
    left:0px;
    width:100%;
    height:50px;
    margin:0;
    padding:0;
}

#bottompub .background {
    position:fixed;
    bottom:0px;
    left:0px;
    width:100%;
    height:50px;
    background-color:#89BAE4;
    opacity: .80;
    filter: alpha(opacity="80");
    z-index: 50;
}

#bottompub .insidebottompub {
    position:relative;
    width:1031px;
    margin-left:auto;
    margin-right: auto;
    z-index: 100;
}

#bottompub .pubimage {
    position:relative;
    float:left;
    left:220px;
    top:-25px;
}

HTML