text:
Q: How to set a proxy to run cypress in Github Actions? I have a proxy to set it on my Visual Studio by this command line on the terminal : export HTTP_PROXY=http://127.0.0.1:22548. I can run my script without issues. But I can not put this config on GitHub Actions?
Somme one can help me?

A: If you want to run cypress in github actions, you'll probably want to use the action they provide. https://docs.cypress.io/guides/continuous-integration/github-actions#Basic-Setup
EDIT: see this https://docs.github.com/en/actions/learn-github-actions/environment-variables#about-environment-variables
you can set an environment variable at the workflow, job or steps level
jobs:
  cypress_test:
    runs-on: ubuntu-latest
    steps:
      - name: "run cypress test"
        run: echo $HTTP_PROXY
        env:
          HTTP_PROXY: http://127.0.0.1:22548

A: I have solve this by adding this code on my main.yml file
jobs:
 cypress-ua-run:
   name: Cypress UA test
   runs-on: [ self-hosted, Companyname ]
   timeout-minutes: 20


text:
Q: Time complexity of Fleury's Algorithm Could you please help me find out the time complexity of the Fleury' algorithm (which is used to get the Eulerian circuit)?

A: Fleury's algorithm isn't really complete until you specify how the bridge edges are identified. Tarjan gave a linear-time algorithm for identifying all bridges (see http://en.wikipedia.org/wiki/Bridge_(graph_theory) ), so a naive implementation that reran Tarjan's algorithm after each deleted edge would be O(E^2). There are probably better ways to recompute the set of bridges, but there is also a better O(E) algorithm. (See http://www.algorithmist.com/index.php/Euler_tour#Fleury.27s_algorithm ; not my site :))

A: Here:
http://roticv.rantx.com/book/Eulerianpathandcircuit.pdf
you can read among other things, that it is O(E), linear edge count.

A: Fleury algorithm involves following steps :

*

*Make sure the graph has either 0 or 2 odd vertices.

*If there are 0 odd vertices, start anywhere. If there are 2 odd vertices, start at one of them.

*Follow edges one at a time. If you have a choice between a bridge and a non-bridge, always choose the non-bridge.

*Stop when you run out of edges.
If bridges are found out by Tarjan's algorithm and these bridges are stored in an adjacency matrix then we need not run tarjan's algorithm every time to check whether an edge is a bridge or not. We can check it in O(1) time for all other bridge queries. Thus Flury's algorithm time complexity can be reduced to O(V+E) {as this is a DFS} but this method needs O(V2) extra space to store bridges.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows phone Show/Hide textbox based on checkbox selection I would show/hide textbox based on checkbox selection (if checked, show the textbox filed).
I tried this way, but it does't work ( the textbox field is always hidden):
<CheckBox x:Name="chkpsw" IsChecked="{ Binding PasswordRequired, Mode=TwoWay}" />
<TextBox Text="{Binding Password,Mode=TwoWay}" Visibility="{Binding PasswordRequired, Converter={StaticResource VisibilityConverter}}"/>

PasswordRequired is a bool property, Password is a string property,
VisibilityConverter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    bool visibility = (bool)value;
    return visibility ? Visibility.Visible : Visibility.Collapsed;
}

My Model:
private bool _passwordRequired;
...
public bool PasswordRequired
{
    get { return _passwordRequired; }
    set
    {
        _passwordRequired = value;
        OnPropertyChanged("PasswordRequired");
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string name)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(name));
    }
}


text:
Q: Loading a JavaScript file using both defer and async What would be the loading order of these two JavaScripts?
<script src="a.js">
<script src="b.js" defer async>

What happens to b.js that has both defer and async?

A: As specified here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Async is a Boolean attribute indicating that the browser should, if possible, load the script asynchronously.
While Defer is a Boolean attribute that indicates to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
So in your case, b.js would load after a.js


text:
Q: identity and inverse/complement elements in a boolean algebra In a boolean algebra, $0$ (the lattice's bottom) is the identity element for the join operation $\lor$, and $1$ (the lattice's top) is the identity element for the meet operation $\land$. For an element in the boolean algebra, its inverse/complement element for $\lor$ is wrt $1$ and its inverse/complement element for $\land$ is wrt $0.$
A Boolean algebra can be defined to be a complemented lattice that is also distributive. For a distributive lattice, the complement of $x,$ when it exists, is unique. See Wikipedia (http://en.wikipedia.org/wiki/Lattice_(order)#Complements_and_pseudo-complements).
The power set of a set $S$ is an example of Boolean algebra. $S$ is the identity for union and $\emptyset$ is the identity for intersection. However, for union, the complement of a set wrt $S$ is not unique; For intersection, the complement of a set wrt $\emptyset$ is not unique either. So is this a contradiction?
Thanks and regards!

A: By definition, $\rm b\:$ is a complement of $\rm a\:$  if $\rm\ a\vee b = 1,\ a\wedge b = 0\:$. So a unique complement must be a unique solution to both$\ $ equations (involving both$\ $ operations), not just a single operation - as you consider above. So there is no contradiction.


text:
Q: SQL error in a MySQL query with alias (AS) I had problem while executing this SQL statement in MySQL workbench. Can anyone point out the problem for me?
SELECT concat(LocationName,' - ', StationName) AS LocationStation, EmpName AS '0000-0100', EmpName AS '0100-0200', EmpName AS '0200-0300', EmpName AS '0300-0400', EmpName AS '0400-0500', EmpName AS '0500-0600', EmpName AS '0600-0700', EmpName AS '0700-0800', EmpName AS '0800-0900', EmpName AS '0900-1000', EmpName AS '1000-1100', EmpName AS '1100-1200', FROM satsschema.employeeslot
WHERE LocationName = 'T2 PML'
and AllocationDate = '10-Aug'
and (EmpTime >= '00:00:00' and EmpTime <= '12:00:00')

The above statemnt prompted me this error, "You have an error in your SQL syntax, check the manual that corresponds to your MySQL server version for the right syntax to use neat 'FROM satsschema.employeeslot WHERE LocationName = 'T2 PML' and AllocationDate = ' at line 1."
Secondly, Is there any other ways that could make this line shorter besides typing everything out?
EmpName AS '0000-0100', EmpName AS '0100-0200', EmpName AS '0200-0300', EmpName AS '0300-0400', EmpName AS '0400-0500', EmpName AS '0500-0600', EmpName AS '0600-0700', EmpName AS '0700-0800', EmpName AS '0800-0900', EmpName AS '0900-1000', EmpName AS '1000-1100', EmpName AS '1100-1200', FROM satsschema.employeeslot

Help will be greatly appreciated.

A: Remove the comma before FROM. It causes the error.
SELECT concat(LocationName,' - ', StationName) AS LocationStation, EmpName AS '0000-0100', EmpName AS '0100-0200', EmpName AS '0200-0300', EmpName AS '0300-0400', EmpName AS '0400-0500', EmpName AS '0500-0600', EmpName AS '0600-0700', EmpName AS '0700-0800', EmpName AS '0800-0900', EmpName AS '0900-1000', EmpName AS '1000-1100', EmpName AS '1100-1200' FROM satsschema.employeeslot
WHERE LocationName = 'T2 PML'
and AllocationDate = '10-Aug'
and (EmpTime >= '00:00:00' and EmpTime <= '12:00:00')

Note that the error message said exactly where was the error.
In MySQL, the AS keyword is optional for column aliasing, so you may write EmpName '0000-0100' in place of EmpName AS '0000-0100'. I don't think there is a short solution to give more than one alias to one column as it's really not something that is often necessary.

A: Remove extra comma before from clause.
SELECT  concat(LocationName,' - ', StationName) AS LocationStation,
        EmpName AS '0000-0100',
        EmpName AS '0100-0200',
        EmpName AS '0200-0300',
        EmpName AS '0300-0400',
        EmpName AS '0400-0500',
        EmpName AS '0500-0600',
        EmpName AS '0600-0700',
        EmpName AS '0700-0800',
        EmpName AS '0800-0900',
        EmpName AS '0900-1000',
        EmpName AS '1000-1100',
        EmpName AS '1100-1200'   -- remove comma here
FROM satsschema.employeeslot
WHERE LocationName = 'T2 PML'
and AllocationDate = '10-Aug'
and (EmpTime >= '00:00:00' and EmpTime <= '12:00:00')


text:
Q: Looking for 2 types of file extension So I have this script that is suposed to run several commands on 2 specific types of files from various folders, the problem is:
The files I want to find file.fa or file.fasta
The files that exist among those file.fa.amb file.fa.ann file.fa.bwt file.fa.pac file.fa.sa file.fasta.amb file.fasta.ann file.fasta.bwt file.fasta.pac file.fasta.sa
Im doing a for loop something like this:
for i in path/path/file.fa*
do
   run command $i
done

How do I only pick up the files I want instead of all those files ?

A: Try:
for i in path/path/file.{fa,fasta}
do
   run command $i
done


text:
Q: Multiple Resource Cell Selection in FullCalendar I am using FullCalendar and I want to drag and select cells of multiple resources at the same time to perform some action. I couldn't find any solution to this in the documentation and right now I am able to drag and select only a single row/resource.
Looking forward for any help.
Thank You in advance :)
attachment


text:
Q: UIScrollView in landscape mode with Aspect Fill In a UIScrollView I have a UIImageView with the contentMode set to Aspect Fill. When I rotate the simulator to landscape mode the UIImageView shows the center of the image and I cannot scroll upwards to see the whole picture.
How do I fix this so that when I rotate the iPhone I instead see the top of the image (but still scaled with Aspect Fill).

A: Needed to set the size of the frame:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    CGFloat ratio = imageView.frame.size.width/imageView.image.size.width;
    CGRect rect = CGRectMake(0, 0, imageView.frame.size.width , ratio*imageView.image.size.height);
    [scrollView setContentSize:rect.size];
    [imageView setFrame:CGRectMake(0.0f, 0.0f, rect.size.width, rect.size.height)];
}


text:
Q: plotting a boxplot and a line plot in the same graph using ggplot I want to create a plot in ggplot for a box plot and a line plot in the same figure. I have a data frame which looks like the following:
    Lambda  |  means   | theorMean
1    0.1      10.07989       10
2    0.1      10.55681       10
3    0.1      10.26660       10
4    0.1      10.29234       10
5    0.1      10.07754       10
 ...

The means are sample means and the theoretical means are theorMeans. I want to plot the distribution of the sample means by box plots, while the theoretical means using a straight line.
This is what I have so far ...
library(ggplot2)
library(scales)

p <- ggplot(summ, aes(x=factor(Lambda), y=means)) +
     geom_boxplot() +
     geom_line(data=summ, aes(x=log10(Lambda), y=means))

The problem is that, for a box plot or a violin plot, I need to use the x axis as a factor. On the other hand, I need the x axis to be a number. I basically want to fit a theoretical line, to the box plots I generate. How can I possible do this?

A: This should do the trick:
library(ggplot2)

summ$Lambda <- log10(summ$Lambda)

ggplot(summ, aes(x=factor(Lambda), y=means)) +
  geom_boxplot() +
  geom_line(inheret.aes = FALSE, aes(x=factor(Lambda), y=means, group = 1), color = "blue") +
  ylab("Mean") +
  xlab("Lambda (Log10)") +
  scale_x_discrete(labels = round(summ$Lambda,2)) +
  theme(  axis.ticks.y = element_blank()
        , axis.text.x = element_text(angle = 45, hjust = 1)
  )

Yeilds:

Test data:
e <- 2.7182818284590452353602874713527
summ <- data.frame("Lambda" = seq(0.01, 0.9, by = 0.0287097))

list <- c()
for(x in 1:31){
  t <- e^-(x/10)*15
  list[x] <- t
}
summ$means <- list
summ$Lambda <- log10(summ$Lambda)

This was helpful here.


text:
Q: Variable column lines changed when ode45 function process? I wonder why when I run my code as below, the variable y will change from 2*2 to 4*1?
function testforleader()
    %tspan=[0 10];
    %y0=[[10 10];[3 3]];
    y = zeros(2)
    [t,y] = ode45('leadermove',[0 10],[10 10;3 3]);

function ydotr=leadermove(t,y)
    y
    ydotr = [y(2,:);[sin(t) cos(t)]];

The message in the command windows will show like this:

y =

 0     0
 0     0

y =

10
 3
10
 3

and then the function ode45 seems only receive the one column vector of variable y?

A: Your call to ode45 does not have y on the rhs:
[t,y]=ode45('leadermove',[0 10],[10 10;3 3]);

but on the lhs. If it exists before the call it will be overwritten by the call.  Perhaps you ought to rename the variable on the lhs to something like yout ?

A: Your leadermove function doesn't work for me, so I can't test this. I think the third argument to ode45 should be a vector, so maybe changing it to:
[t,y]=ode45('leadermove',[0 10],[10 10 3 3]);

will fix it. Also, as Mark says,
y = zeros(2);

doesn't do anything because ode45 will overwrite it when it returns an output. You might be able to fix this with:
y = zeros(2);
[t,y(:)]=ode45('leadermove',[0 10],[10 10 3 3]);

but I don't know if that would work, and I suspect that the way you are calling ode45 now is giving you the wrong answer anyway.


text:
Q: ordinal-isomorphisms The following theorem was stated in the notes I'm reading as "immediate" on the grounds that the composition of an order-isomorphism is an order-isomorphism, and the identity function is the only order isomorphism from (O, ∈ ) to itself.  For some reason I can't see how the theorem follows.  Could someone explain this?  Thanks.
Theorem: Let (L, ≤ ) be a well-order and O an ordinal.  Then there is at most one order-isomorphism, f:(L, ≤ ) --> (O, ∈ ).

A: The key point is, as you write correctly in your comment, the following: If $f,g \colon L \to O$ are isomorphisms, then $g^{-1} \circ f = \mathrm{id}_O$ implies, just by composing with $g$, that
$$ g = g \circ \mathrm{id}_O = g \circ g^{-1} \circ f = \mathrm{id}_O \circ f = f $$
To prove that $g^{-1} \circ f = \mathrm{id}_O$, note that $g^{-1} \circ f \colon O \to O$ is an isomorphism, hence the identity.


text:
Q: Techniques for solving recurrence relations using generating functions How does one extract coefficients from generating functions that involve exponents. Things like $A(z) = 1+A(z^2)$ or $A(z)= 1+A(z^2)+A(\sqrt z)$?

A: The general idea would be to expand both sides, and equate coefficients. In the first case cited, this won't work (you get $A(0) = 1 + A(0)$, which is inconsistent, on substituting $x = 0$ on both sides).
For the second one, take $B(z) = A(z^{1/2})$ and $B(z) = \sum_{n \ge 0} b_n z^n$:
$$
B(z^2) = 1 + B(z^4) + B(z)
$$
This is:
$$
\sum_{n \ge 0} b_n z^{2 n} = 1 + \sum_{n \ge 0} b_n z^{4 n} + \sum_{n \ge 0} b_n z^n
$$
This gives ($[\ldots]$ is Iverson bracket):
$$
b_{2 n} = [n = 0] + b_n + b_{4 n}
$$
This gives $b_0 = -1$, but we need $b_1$ and $b_2$ to get the recursion started. This means getting $B'(0)$ and $B''(0)$, but the equation gives $B'(0) = B''(0) = 0$. No solution possible.


text:
Q: Mac OS arrow keys not working properly when enabling paredit in Emacs I currently have this in my .emacs, which worked just fine in Linux:
;; paredit
;; this is from somewhere else on Stackoverflow
;; deals with curly brackets matching and stuff
;; I edited the answer a little bit

(defmacro setup-paredit (func-name mode-map)
  `(defun ,func-name ()
     (define-key ,mode-map
       (kbd "DEL") 'paredit-backward-delete)
     (define-key ,mode-map
       (kbd "{") 'paredit-open-curly)
     (define-key ,mode-map
       (kbd "}") 'paredit-close-curly)
     (modify-syntax-entry ?\{ "(}")
     (modify-syntax-entry ?\} "){")
     (modify-syntax-entry ?\[ "(]")
     (modify-syntax-entry ?\] ")[")
     (modify-syntax-entry ?~ "'   ")
     (modify-syntax-entry ?, "    ")
     (modify-syntax-entry ?^ "'")
     (modify-syntax-entry ?= "'")))

(defmacro setup-paredit-mode (func-name mode-map mode-hook)
  `(progn (setup-paredit ,func-name ,mode-map)
          (add-hook ',mode-hook ',func-name)
          (add-hook ',mode-hook 'enable-paredit-mode)))

;; probably doing lots of things wrong but at least this seems to work well
(setup-paredit-mode setup-c++-paredit c++-mode-map c++-mode-hook)
(setup-paredit-mode setup-slime-repl-paredit slime-repl-mode-map slime-repl-mod\
e-hook)
(setup-paredit-mode setup-slime-paredit slime-mode-map slime-mode-hook)
(setup-paredit-mode setup-clojure-paredit clojure-mode-map clojure-mode-hook)
(setup-paredit-mode setup-emacs-paredit emacs-lisp-mode-map emacs-lisp-mode-hoo\
k)
(setup-paredit-mode setup-css-paredit css-mode-map css-mode-hook)

But the last bit in Mac OS X makes arrow keys produce the following output:
[C [A [D [A [B [D [C [B [D [B [D]]]]]]]]]]]

Another weird thing when hitting C-x C-c:
Symbol's function definition is void: switch-to-buffer-in-tab

I finally killed it with C-x C-z.
These do not happen if I comment out the last part after ;; probably..., so the problem probably lies there. How should I go about fixing this problem?
EDIT:
I found this. Simply copy-pasting the code there didn't work. Hitting the arrow keys gave me this:
# ESC [ ⇧A ESC [ ⇧B ESC [ ⇧C ESC [ ⇧D #

Being the newb I am, I am not sure how to "adjust the code given above appropriately," though. (Also what is that up arrow doing?)
EDIT 2:
The C-c C-x problem, at least, seems to have been solved somehow with this .emacs code:
;; Fix Mac arrow keys
(if (not window-system);; Only use in tty-sessions.
     (progn
      (defvar arrow-keys-map (make-sparse-keymap) "Keymap for arrow keys")
      (define-key esc-map "[" arrow-keys-map)
      (define-key arrow-keys-map "⇧A" 'previous-line)
      (define-key arrow-keys-map "⇧B" 'next-line)
      (define-key arrow-keys-map "⇧C" 'forward-char)
      (define-key arrow-keys-map "⇧D" 'backward-char)))

Arrow keys still not working when paredit is active.
EDIT 3:
I should add that all this is happening inside the Terminal. I am not sure whether it still happens with the GUI, because somehow my .emacs is causing Aquamacs to not display any windows.
Arrow keys work fine in Emacs GUI, but not in -nw mode.

A: Finally got it working. In Terminal Preferences, under Settings > Advanced > Emulation, I set Declare terminal as: to vt100.
I did try this before, but it turns out that you need to close the Terminal window before starting Emacs up again, otherwise it will still use the current settings.
Now the downside is that Emacs is B&W. Will see if any other emulation settings work.
EDIT:
xterm-256color (the default) works just fine, with color. GRRRRR. All this because some tutorial (I forgot for what) told me to set the Terminal emulation to rxvt. Hahahaha.
At least I hope this helps somebody in the future.

A: Please try this and i assume you will be able to resolve the same
chsh -s /bin/bash


text:
Q: Entity Framework : Cannot evaluate expression because the code of the current method is optimized. I'm using Entity framework 6 ( DBContext ) and VB.net 2013
I have this code :
Partial Public Class Myentities
Inherits DbContext
Implements IObjectContextAdapter
Public ReadOnly Property ObjectContext() As ObjectContext Implements IObjectContextAdapter.ObjectContext
    Get
        Dim objectContext__1 = TryCast(Me, IObjectContextAdapter)
        If objectContext__1 IsNot Nothing Then
            Return TryCast(Me, IObjectContextAdapter).ObjectContext
        Else
            Return Nothing
        End If
    End Get
End Property

  Public Sub New(connectionString As String)
    MyBase.New("name=MyEntities")
    Database.Connection.ConnectionString = connectionString
End Sub
End class

.......
dim context as new Myentities

But I get this error :
Cannot evaluate expression because the code of the current method is optimized.

What's the problem ?
Thank you !


text:
Q: cx_oracle and sqlalchemy performance comparison I am working oracle database and wanted to know which toolkit (sqlalchemy or cx_Oracle) is better in performance as I can't see any comparisons online I hope someone can help me. I have listed the key performance indicators that I need to be addressed.
Bulk insertion and single line insertion
connections complexity
which one can be used for streaming more efficiently
Which one is better for OLTP connections (loading data from OLTP with that toolkit)

However more that these comparisons are highly appreciated
My Target and Source databases are Oracle
A comparison of the cx_oralce and sqlalchemy

A: SQLAlchemy is a layer on top of cx_Oracle so it will always have more overhead.
When looking for performance, you should evaluate the latest cx_Oracle release (now called python-oracledb) since the new Thin mode has some advantages (e.g with DB Object types).  See the release announcement for information about python-oracledb.  Also see this blog post about using SQLAlchemy 1.4 with python-oracledb.
Fundamentally, you need to decide which coding style (ORM or raw API calls) you want to use. You may also want to look at pandas, which uses SQLAlchemy. And you should benchmark in your own environment with your own code.


text:
Q: What does (?i) mean in a Python/pexpect regex? I'm trying to understand what the repeated (?i) syntax means in the following code:
i = self.expect([
  "(?i)are you sure you want to continue connecting",
  original_prompt,
  "(?i)(?:password)|(?:passphrase for key)",
  "(?i)permission denied",
  "(?i)terminal type",
  TIMEOUT,
  "(?i)connection closed by remote host"
], timeout=login_timeout)

A: This is documented under the heading for (?aiLmsux-imsx:...) in https://docs.python.org/3/library/re.html, as follows:

(?aiLmsux-imsx:...)
(Zero or more letters from the set a, i, L, m, s, u, x, optionally followed by - followed by one or more letters from the i, m, s, x.) The letters set or remove the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode matching), and re.X (verbose), for the part of the expression. (The flags are described in Module Contents.)

Thus, (?i) is an inline version of the flag that is otherwise set as re.I, or re.IGNORECASE; it makes the match case-insensitive, such that permission denied could also be written Permission Denied or PERMISSION DENIED but would still be matched.


text:
Q: How can I differentiate a plus operator from a positive sign in Lex? I am writing lex for a language almost like C and I need to differentiate these two signs. For example:
a+b -> plus sign
+a -> positive sign
Where a and b can be numbers or identifiers. I already have regex for numbers and identifiers but now I'm stuck in this question. How can I do that

A: It's not the lexer's job to distinguish between infix and prefix operators. A plus sign should produce the same token either way and then the parser can treat it differently depending on whether it occurs in prefix or infix position.


text:
Q: Ruby - How to extract public, rsa private and CA keys from .pfx file on ruby I have a certificate in .pfx format and I need to extract the Public, Private and CA certificates using ruby.
Using the shell I can make it this way:
# Extract Public Key (ask for password)
openssl pkcs12 -in file.pfx -out file_public.pem -clcerts -nokeys

# Extract Certificate Authority Key (ask for password)
openssl pkcs12 -in file.pfx -out file_ca.pem -cacerts -nokeys

# Extract Private Key (ask for password)
openssl pkcs12 -in file.pfx -out file_private.pem -nocerts -nodes

# Extract RSA Private Key from private .pem
openssl rsa -in file_private.pem -out file_private_rsa.key

# Create Combo file with Public and RSA Private Keys
cat file_private_rsa.key file_public.pem > file_combo.pem

On this post DMKE shows how to transform the keys to .PFX, but how to do the other way round?

A: pkcs = OpenSSL::PKCS12.new(File.read("xyz.p12"), "password_for_xyz.p12")
key = OpenSSL::PKey::RSA.new(pkcs.key.to_pem)
cert = OpenSSL::X509::Certificate.new(pkcs.certificate.to_pem)

A: pkcs = OpenSSL::PKCS12.new(File.read("file.pfx"), "password")

pkcs.key.to_pem

pkcs.certificate.to_pem


text:
Q: Zoom only horizontally UIView in UIScrollView I have tried some solutions from other posts but I haven't been able to solve the question I am going to post.
I have a custom UIView that draws a SoundWave and it contains a UIScrollView. The UIScrollView contains a main UIView that contains two other custom UIViews (marker left and right) and UIImage view where i render the sound wave.
private func initialize(){

    print("\(logClassName) initialize in Frame: \(frame)")

    //ScrollView
    addSubview(scrollView)
    scrollView.constraintToSuperViewEdges()

    //WaveView
    scrollView.addSubview(waveView)
    waveView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
    waveView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 0).isActive = true
    waveView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 0).isActive = true
    waveView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true

    waveViewWidthConstraint = waveView.widthAnchor.constraint(equalToConstant: 1000)
    NSLayoutConstraint.activate([waveViewWidthConstraint])
    scrollView.contentSize = CGSize(width: waveViewWidthConstraint.constant, height: 0)

    //SoundWaveImageView
    waveView.addSubview(soundWaveImageView)
    soundWaveImageView.constraintToSuperViewEdges()

    //WaveView markers
    //TimeMarker
    waveView.addSubview(timeMarkerView)
    timeMarkerView.topAnchor.constraint(equalTo: waveView.topAnchor).isActive = true
    timeMarkerView.bottomAnchor.constraint(equalTo: waveView.bottomAnchor).isActive = true
    timeMarkerView.widthAnchor.constraint(equalToConstant: 1).isActive = true
    timerMarkerViewLeadingContraint = timeMarkerView.leadingAnchor.constraint(equalTo: waveView.leadingAnchor, constant: 20)
    NSLayoutConstraint.activate([timerMarkerViewLeadingContraint])

    //LeftMarker
    waveView.addSubview(leftMarkerView)
    leftMarkerView.topAnchor.constraint(equalTo: waveView.topAnchor).isActive = true
    leftMarkerView.bottomAnchor.constraint(equalTo: waveView.bottomAnchor).isActive = true
    leftMarkerView.widthAnchor.constraint(equalToConstant: leftMarkerView.triangleWidth).isActive = true
    leftMarkerViewLeadingConstraint = leftMarkerView.leadingAnchor.constraint(equalTo: waveView.leadingAnchor, constant: 0)
    NSLayoutConstraint.activate([leftMarkerViewLeadingConstraint])

    //RightMarker
    waveView.addSubview(rightMarkerView)
    rightMarkerView.topAnchor.constraint(equalTo: waveView.topAnchor).isActive = true
    rightMarkerView.bottomAnchor.constraint(equalTo: waveView.bottomAnchor).isActive = true
    rightMarkerView.widthAnchor.constraint(equalToConstant: rightMarkerView.triangleWidth).isActive = true
    rightMarkerViewLeadingConstraint = rightMarkerView.trailingAnchor.constraint(equalTo: waveView.leadingAnchor, constant: 50)
    NSLayoutConstraint.activate([rightMarkerViewLeadingConstraint])

}

As seen, the main UIView is constraint to the edges of the UIScrollView and the width constraint is the total length which changes according the needs. The function responsible for that is the following:
private func updateWidthConstraintValue(_ newWidth:CGFloat){

    waveViewWidthConstraint.constant = newWidth
    scrollView.contentSize = CGSize(width: waveViewWidthConstraint.constant, height: 0)

}

When implementing the zoom for the UIScrollView it works but it zooms both vertically and horizontally (as expected) but I would like to implement only horizontally. I have this so far:
func scrollViewDidZoom(_ scrollView: UIScrollView) {

    print("\(logClassName) TEST -> scrollView did zoom \(scrollView.zoomScale)")
    expandHorizontally(withScale: scrollView.zoomScale)
    //scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0)
    //scrollView.contentSize = CGSize(width: scrollView.contentSize.width, height: scrollView.frame.height)
}

func viewForZooming(in scrollView: UIScrollView) -> UIView? {

    return waveView

}

private func expandHorizontally(withScale scale:CGFloat){

    let scaledWidth = currentWaveViewWidth * scale
    print("\(logClassName) TEST -> scaledWidth = \(scaledWidth)")

    updateWidthConstraintValue(scaledWidth)
    // Adjust content size and content offset
    scrollView.contentSize = CGSize(width: waveViewWidthConstraint.constant,
                                    height: 0);
    scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x,
                                       y: scrollView.contentOffset.y);

}

The UI Variables are declared like that:
lazy private (set) var scrollView:UIScrollView = {

    let rtView = UIScrollView()

    rtView.translatesAutoresizingMaskIntoConstraints = false
    rtView.backgroundColor = .clear

    rtView.bounces = false
    rtView.bouncesZoom = false

    rtView.minimumZoomScale = 1
    rtView.maximumZoomScale = 3

    rtView.delegate = self

    return rtView

}()

private (set) lazy var waveView:UIView = {

    let rtView = UIView()

    rtView.translatesAutoresizingMaskIntoConstraints = false
    rtView.backgroundColor = .clear
    rtView.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                       action: #selector(waveViewDidTouch)))

    return rtView

}()
private (set) var waveViewWidthConstraint = NSLayoutConstraint()

private (set) lazy var soundWaveImageView:UIImageView = {

    let rtView = UIImageView()

    rtView.translatesAutoresizingMaskIntoConstraints = false

    return rtView

}()

private (set) lazy var timeMarkerView:UIView = {
    let rtView = UIView()

    rtView.translatesAutoresizingMaskIntoConstraints = false
    rtView.backgroundColor = UIColor.AppColors.defaultTint

    return rtView
}()
private var timerMarkerViewLeadingContraint = NSLayoutConstraint()

private (set) lazy var leftMarkerView:MarkerView = {

    let rtView = MarkerView(title: AppHelper.printLocalized(withKey: "messages.start", targetSpecific: false), markerDirection: .right)

    rtView.translatesAutoresizingMaskIntoConstraints = false
    rtView.delegate = self

    return rtView

}()
private var leftMarkerViewLeadingConstraint = NSLayoutConstraint()

private (set) lazy var rightMarkerView:MarkerView = {

    let rtView = MarkerView(title: AppHelper.printLocalized(withKey: "messages.end", targetSpecific: false), markerDirection: .left)

    rtView.translatesAutoresizingMaskIntoConstraints = false
    rtView.delegate = self

    return rtView

}()
private var rightMarkerViewLeadingConstraint = NSLayoutConstraint()

I have tried to put all the relevant information as it is a big class.

A: I have figure out a temporary solution thank you to LaurentMaquet. At some point I will post the final soundWaveView as it is in development at the moment.
The changes made are:
1- Create a custom class for soundWave.
class WaveView:UIView{
    var unzoomedViewHeight: CGFloat = 0

    override var transform: CGAffineTransform{
        get{ return super.transform }
        set{
            var t = newValue
            t.d = 1.0
            t.ty = (1.0 - t.a) * unzoomedViewHeight/2
            super.transform = t
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        unzoomedViewHeight = frame.size.height
        print("\(logClassName) did layout to \(AppHelper.traitStatus) -> frame = \(frame)")

    }

}

2- Make my soundView var be a SoundView
private (set) lazy var waveView:WaveView = {

    let rtView = WaveView()

    rtView.translatesAutoresizingMaskIntoConstraints = false
    rtView.backgroundColor = .clear
    rtView.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                       action: #selector(waveViewDidTouch)))

    return rtView

}()

Result


text:
Q: jQuery: Uncaught TypeError: Failed to set the 'value' property on 'HTMLProgressElement': The provided double value is non-finite I know there are similar questions but nothing seems too work for my current issue. I have a simple audio player with progress bar:
$(document).ready(function() {
  $(".audio-clip .volume").on("input", function() {
    var audio = $(this)
      .closest("div")
      .find("audio")[0];
    audio.volume = this.value;
  });

  $(".audio-clip .position").on("input", function() {
    var audio = $(this)
      .closest("div")
      .find("audio")[0];
    audio.currentTime = (audio.duration / 100) * this.value;
  });

  $("audio").on("timeupdate", function() {
    var pc = (audio.currentTime / audio.duration) * 100;
    $(this)
      .closest("div")
      .find(".position")
      .val(pc);
  });

and in the html
   <label>
    Position:
    <input type="range" class="position" min="0" max="100" step="1" value="0" />

    <progress class="nes-progress is-pattern position" value="0" max="100"></progress>
  </label>

all works as expected but in the JS console I see
Uncaught TypeError: Failed to set the 'value' property on 'HTMLProgressElement': The provided double value is non-finite

A: Make sure pc is a valid number before trying to use it to set the value.
  $("audio").on("timeupdate", function() {
    var pc = (audio.currentTime / audio.duration) * 100;
    if (isNaN(pc)) {
      return;
    }
    $(this)
      .closest("div")
      .find(".position")
      .val(pc);
  });


text:
Q: PHP Array rearrange numeric key as parrent key i want to rearrange a simple multidimensional array.
Array
    (
        [pieces] => Array
            (
                [0] => 2
                [1] => 9
            )
        [start] => Array
            (
                [0] => 0001
                [1] => 9901
            )
        [end] => Array
            (
                [0] => 0002
                [1] => 9909
            )
        [group] => Array
            (
                [0] => 0001-0100
                [1] => 9901-9999
            )
    )

to
Array
(
    [tokens] => Array
        (
            [0] =>  Array
                (
                    [start] => 0001
                    [end] => 0002
                    [pieces] => 2
                    [group] => 0100
                )
            [1] =>  Array
                (
                    [start] => 9901
                    [end] => 9909
                    [pieces] => 9
                    [group] => 9901-9999
                )
        )
)

I have tried something similar this:
$keys = array_keys($array);
foreach ($keys as $key => $val) {
    foreach ($array as $k => $v){
        foreach($array[$v] as $tk => $tv){
            if($val == $k){
                $new['tokens'][][$val] = $tv;
            }
        }
    }
}

The numeric is the set of tokens which i prosted from my form,
Please can anyone explain me what i do wrong?
I am working some hours with different codes (i know the solution is very simple) but I am a little bit confused :/
Thank you very much!
BR KK

A: The Fourth Bird's solution is quite rigid in that it:

*

*Requires an explicitly-defined key in the loop condition.

*Enforces that the entire result has no more items than that one key has.

*Assumes and enforces that the input keys are sequential and zero-indexed.

The below will work no matter what:
foreach( $array as $y => $inner ) {
    foreach( $inner as $x => $value ) {
        $new['tokens'][$x][$y] = $value;
    }
}

Demo: https://3v4l.org/Rmdtd

Edit: I think it's worth preserving The Fourth Bird's explanation of the trouble with the posted code from his now-deleted answer:

You are trying to index into $array[$v], but $v in the case is one
  of the sub arrays. According to the array
  docs:
Arrays and objects can not be used as keys. Doing so will result in
  a warning: Illegal offset type.

Make sure that you have error_reporting turned up to E_ALL while you're developing code so that you can see non-critical messages that indicate current and/or future problems.


text:
Q: How to align text and images like the sample image provided in Qt?
I want to display the images and Texts in the PDF file generated in the manner shown in the image provided and I don't know how to go on about it.
At first I tried this:
for(int i=0; i<COVDATA.COV_ComponentName.size(); i++){
    //------------------------------------------------------------------------------------
    x = x + 550;
    y = y + 150;
    // ScreenShot_path = COVDATA.COV_ComponentScreenShot[i];
    // img = QImage(ScreenShot_path);
    // painter.drawImage(QRect(100,y,210,150),img.scaled( 800 , 800, Qt::KeepAspectRatio) );
    // painter.setPen(QPen(Qt::black, 5));
    // painter.setFont(OpenSans);
    // painter.setFont(QFont("Open Sans",10,QFont::Normal));
    // painter.drawText( QRect(0,y,PageWidth-210,150), Qt::AlignRight|Qt::AlignVCenter, COVDATA.COV_ComponentName[i]);
    if(i % 2 == 0 || i==0){
        painter.setPen(QPen(Qt::black, 5));
        painter.setFont(OpenSans);
        painter.setFont(QFont("Open Sans",10,QFont::Normal));
        painter.drawText( QRect(0,y,210,150), Qt::AlignLeft|Qt::AlignVCenter, COVDATA.COV_ComponentName[i]);

        ScreenShot_path = COVDATA.COV_ComponentScreenShot[i];
        img = QImage(ScreenShot_path);
        painter.drawImage(QRect(150,y+350,210,450),img.scaled( 800 , 800, Qt::KeepAspectRatio) );
    }else{
        painter.setPen(QPen(Qt::black, 5));
        painter.setFont(OpenSans);
        painter.setFont(QFont("Open Sans",10,QFont::Normal));
        painter.drawText( QRect(0,y,PageWidth-210,150), Qt::AlignRight|Qt::AlignVCenter, COVDATA.COV_ComponentName[i]);

        ScreenShot_path = COVDATA.COV_ComponentScreenShot[i];
        img = QImage(ScreenShot_path);
        painter.drawImage(QRect(0,y+350,210,350),img.scaled( 800 , 800, Qt::KeepAspectRatio) );
    }
}

But it didn't really work out for me and I honestly don't know how to go on about it. The COVDATA.COV_ComponentName is a list containing the texts I want to print while COVDATA.COV_ComponentScheenShot is a list containing the storage location of the images that are called in and store the image in the QImage object for them to be generated.
These are to be printed in my PDF file.

A: Your coordinate computation is not working as intended. I've put together a short example illustrating how you can go about implementing a layout as you wish:
QStringList Text;
Text << "String 1" << "String 2" << "String 3" << "String 4" << "String 5" << "String 6" << "String 7" << "String 8";
int TextHeight = painter.fontMetrics().height() * 1.5;
int Padding = 10;
int NumOfColumns = 2;
int RectWidth = (geometry().width() - (NumOfColumns+1) * Padding) / NumOfColumns;
int NumOfRows = std::ceil(Text.size() / static_cast<float>(NumOfColumns));    // std::ceil requires #include <cmath>

int RectHeight = (geometry().height() - NumOfRows * TextHeight - (NumOfRows + 1) * Padding) / NumOfRows;
for (int i = 0; i < Text.size(); i++)
{
    int x = Padding + (i % NumOfColumns) * (RectWidth + Padding);
    int y = Padding + (i / NumOfColumns) * (RectHeight + TextHeight + Padding);
    painter.setPen(QPen(Qt::black, 2));
    painter.drawText(QRect(x, y, RectWidth, TextHeight), Qt::AlignLeft | Qt::AlignVCenter, Text[i]);
    painter.drawRect(QRect(x, y + TextHeight, RectWidth, RectHeight));
}

I have replaced the COVDATA stuff and screenshots with a simple list of texts and rectangles.
With the above code, you can configure the number of columns (the number of rows will be computed from that such that all items in my list Text have place on the screen) as well as the padding between the rectangles.
But the principle should be clear:

*

*I compute the x and y component depending on the index i

*The coordinates are computed depending on a predefined with and height of the alloted spaces for the rectangles, in my case this is set to a fraction of the full space available to the widget (so it also adapts to resizing natively).

This is how the result looks like:


text:
Q: Survival model with unknown number of subjects exposed? Aka hurdle-survival model? I have data from a live-attenuated vaccine study and I want to estimate the distribution of shedding times after vaccination. I have samples collected at multiple time points for each subject, and I can classify the results at each time point as positive or negative for shedding vaccine. Subjects are observed to either never be positive at any time point, or transition from positive to negative at later time points (or never turn negative and thus are right-censored).
IFF I could assume each subject who received the vaccine does shed for some finite amount of time, I could model this as a standard interval-censored survival analysis.
But, biologically, there is zero-inflation at the start. If one were to do the study with many more time points, one would see that some subjects never shed at all and others shed for short times that end before our first time point. These are two different states--did the vaccine "take" or not, and if so, how long was it shed for?--and should be modeled as a hurdle-survival model.
This is a pretty common situation in infectious disease challenge studies, but I am unable to locate any papers that focus on this kind of mixture survival model (the opposite of a cure mixture model), let alone an R package.
Absent this "right way" to do it, I will do something easy enough that's worked before: model the mixture parametrically using the wrong score function. I know a priori that a lognormal survival model is a good one, and so I can fit that to the proportion data at each time point, assuming a binomial scoring function, and add a free parameter that the probability of shedding at the start is between 0 and 1.
Any tips?
Thanks!

A: The problem I see with your suggestion is that I don't think it can distinguish those for whom the vaccination didn't "take" at all from those who "took" quickly and stopped shedding before the first observation time. That seems to be an important distinction.
As you say about whether the vaccination takes at all and whether shedding then stops, "These are two different states." Consider a multi-state survival model. Your situation seems to be a simple version of the case illustrated in the top right of Figure 1 of the R vignette on Multi-state models and competing risks. You start by getting vaccinated (baseline state at time = 0), and then must go through the "shedding" state before you can enter the "stopped shedding" state. The vignette illustrates ways to model such multi-state models with the standard survival package, and provides links to other R software than can do such modeling.
Your point about what happens before your first observation times is well considered. State changes prior to the first observation time have left-truncated event times--you have no information about those events or event times whatsoever.* In principle, left truncation is taken directly into account in the Surv(startTime, stopTime, status) counting-process data format used to handle multi-state models: the startTime is treated as a left truncation. There can be practical problems if there are very few cases with the earliest left-truncation times. For parametric models, this page summarizes the forms of the likelihoods for exact, censored, and truncated observations.

*That's to be distinguished from left-censored event times, where you know that an event has already occurred but you don't know exactly when. For example, if someone is already shedding at the first observation time, then the time that shedding started is left-censored.


text:
Q: Count JSON values request(getuser, function(err, res, body) {
    let user = JSON.parse(body);
    let amount = // Show amount of groups
})

Basically user Has this part in the json:
"groups":[
    {
        "id":"001",
        "name":"Group 1",
    },
    {
        "id":"002",
        "name":"Group 2",
    }
],

This is only a small part, my question is how can I count how many "groups" there are? I could not find any similar questions to this on the internet, I would appreciate any code example.

A: If you want to count the number of elements inside the groups array, you can use the length function.
amount = user.groups.length;


text:
Q: Applescript error when trying to reference last paragraph of a string -1728 My code:
tell application "iTunes"
    set ofi to fixed indexing
    set fixed indexing to true
    set sel to selection
    repeat with i from 1 to (count sel)
        tell (item i of my sel)
            set fileLoc to the location as Unicode text
            set fileLoc to my findAndReplace(":", "
", fileLoc)
            --display dialog return & fileLoc buttons {"Ok"} default button 1      with icon 0

            --Show Name
            set showName to paragraph -3 of fileLoc
            set show to (showName as text)

            --Season #
            set seasonNum to the last word of paragraph -2 of fileLoc
            try
                set season number to (seasonNum as number)
            end try

            --Episode #
                    --*****ERROR HAPPENS HERE*****
            set test to the first word of the last paragraph
            set episodeNum to (the word 2 of paragraph -1)
            --set episode number to episodeNum as number

            --Episode name
            set episodeName to characters 4 thru -5 of paragraph -1 of fileLoc
            set name to episodeName as text

            --Video Kind
            set video kind to TV show
        end tell
    end repeat
    set fixed indexing to ofi
 end tell

on findAndReplace(tofind, toreplace, TheString)
    set ditd to text item delimiters
    set res to missing value
    set text item delimiters to tofind
    repeat with tis in text items of TheString
        if res is missing value then
            set res to tis
        else
            set res to res & toreplace & tis
        end if
    end repeat
    set text item delimiters to ditd
    return res
end findAndReplace

and I get:
error "iTunes got an error: Can't get word 1 of last paragraph of file track id 7141 of user playlist id 5157 of source id 69." number -1728 from word 1 of last paragraph of file track id 7141 of user playlist id 5157 of source id 69

The text I'm trying to parse looks like:
Users
christopher
TV Shows
How I Met Your Mother
Season 5
01 Definitions.m4v

A: Turns out I needed "of fileLoc" in there to make it work.


text:
Q: What is the Math.NET equivalent of numpy.where? I'm porting a piece of python code that currently uses numpy, to IronPython (the reasons for this have to do with the specifics of the platform I'm scripting in).
Due to incompatibilities of numpy and IronPython, I need to replace every numpy function with its Math.NET equivalent, which I have added as an external reference.
Being a total newbie in Math.NET, I have trouble finding the equivalent of the numpy.where() function.
Any help will be appreciated!


text:
Q: Update value every month using Javascript everyone!
I was looking for solution of this for a long time and didn't find anything.
I need to make element on page which will have +=2000 every month from ..let's say today's date.
And I am puzzled without any idea how to do this.
I easily wrote updating value every 10 seconds, but what about months that have different length and so on?
Should I compare difference between current date and today's date, than do +=2000*numberOfMonths? Then how often should I check if month has passed no to kill speedload?
Or is there any other convinient way to do it?
I know the solution might be easy, but I don't get it.
Will be gratefull for any suggestions.

A: You can do it like:
  const getMonthsPassed = () => {
    const startDate = new Date(2018, 10, 22); // month start at 0
    const currentDate = new Date();
    const monthDifference =
      (currentDate.getFullYear() - startDate.getFullYear()) * 12 +
      (currentDate.getMonth() - startDate.getMonth());
    return monthDifference;
  };


text:
Q: Как сгруппировать массив по дате для цикла? Мне нужно найти подходящий период в каждом году, вычислить его продолжительность и сумму температур. У меня есть срез массива за несколько лет, он выглядит так:
Табл.1

Начало
Конец
Продолжительность
Сумма температур
Полугодие

2018-01-01
2018-03-19
78
-1631.8
1

2018-03-20
2018-03-20
1
0.0
1

2018-03-21
2018-04-05
16
-157.6
1

2018-04-06
2018-04-06
1
0.9
1

2018-04-07
2018-04-11
5
-16.8
1

2018-04-12
2018-04-12
1
1.3
1

2018-04-13
2018-04-20
8
-34.6
1

2018-04-21
2018-04-21
1
1.0
1

2018-04-22
2018-04-24
3
-11.2
1

2018-04-25
2018-05-01
7
23.7
1

2018-05-02
2018-05-09
8
-32.8
1

2018-05-10
2018-05-16
7
21.1
1

2018-05-17
2018-05-18
2
-4.8
1

2018-05-19
2018-10-15
150
1839.0
1

2018-10-16
2018-10-18
3
-2.8
2

2018-10-19
2018-10-23
5
5.4
2

2018-10-24
2018-10-24
1
-1.8
2

2018-10-25
2018-10-29
5
13.9
2

2018-10-30
2019-03-13
134
-2558.3
2

2019-03-14
2019-03-14
1
0.8
1

2019-03-15
2019-03-29
15
-66.6
1

2019-03-30
2019-04-01
3
3.9
1

2019-04-02
2019-04-05
4
-5.8
1

2019-04-06
2019-04-06
1
0.0
1

2019-04-07
2019-04-07
1
-2.0
1

2019-04-08
2019-04-09
2
2.4
1

2019-04-10
2019-04-17
8
-58.2
1

2019-04-18
2019-04-18
1
0.6
1

2019-04-19
2019-04-22
4
-19.7
1

2019-04-23
2019-04-23
1
3.6
1

2019-04-24
2019-05-02
9
-27.7
1

2019-05-03
2019-05-08
6
29.4
1

2019-05-09
2019-05-10
2
-1.2
1

2019-05-11
2019-10-09
153
1929.1
1

2019-10-10
2019-10-12
3
-6.9
2

2019-10-13
2019-10-17
5
20.7
2

2019-10-18
2020-03-15
150
-2154.3
2

2020-01-01
2020-03-15
75
-961.4
1

2020-03-16
2020-03-16
1
0.2
1

2020-03-17
2020-03-29
13
-86.1
1

2020-03-30
2020-03-30
1
1.0
1

2020-03-31
2020-04-01
2
-6.8
1

2020-04-02
2020-10-06
188
2287.6
1

2020-10-07
2020-10-13
7
-18.9
2

2020-10-14
2020-10-18
5
4.2
2

2020-10-19
2020-10-21
3
-3.8
2

2020-10-22
2020-10-22
1
1.9
2

2020-10-23
2020-11-07
16
-114.3
2

2020-11-08
2020-11-10
3
3.5
2

2020-11-11
2020-12-31
51
-962.4
2

Я разбиваю этот массив на года. Каждый год прогоняю через код.
За дату устойчивого перехода весной принимается первый день периода, сумма положительных отклонений которого превышает сумму отрицательных отклонений любого из последующих периодов с отрицательными отклонениями. Осенью наоборот - концом периода будет считаться первый день того периода, сумма отрицательных отклонений которого превышает сумму положительных отклонений любого из последующих периодов с такими отклонениями.
Чтобы найти самый большой период с температурой выше 0 я написал такие условия:
# переменные для условий
a_max = 1
a = 0 # сюда записывается искомая сумма из начального периода
b = 0
c = 0
d = 0 # сюда записывается искомая сумма из конечного периода
d_max = 0

# условие для нахождения начала периода
for i in sort_df.loc[sort_df['Полугодие'] == 1]['Сумма температур']:
    if i >= 0:
        if i > a > abs(b):
            a = a
        if i > a and abs(b) > a:
            a = i
        if a > i > abs(b):
            a = a
        if i > a_max:
            a_max = i
        if a < abs(b) < a_max:
            a = a_max
    if i < 0:
        if abs(i) > a:
            b = i
            a = 0
        if abs(i) < a:
            b = i

# условие для нахождения конца периода
for i in sort_df.loc[sort_df['Полугодие'] == 2]['Сумма температур']:
    if i >= 0:
        if i >= abs(d):
            c = i
            d = d_max
        if i < abs(d):
            d = d
            c = i
    if i < 0:
        if i < d_max:
            d_max = i
        if c == 0:
            d = i
        if abs(i) > abs(d) and c > abs(d):
            d = i
        if abs(i) > abs(d) and c < abs(d):
            d = d

Возможно они написаны некрасиво и громоздко, но ничего лучше я пока не придумал и они работают для всех возможных случаев.
Далее находим индексы значений в a и d:
idx_a = sort_df[sort_df['Сумма температур'] == a].index[0]  # индекс начальной даты
idx_d = sort_df[sort_df['Сумма температур'] == d].index[0]  # индекс конечной даты

Потом находим начальную и конечную дату, продолжительность и сумму периода для положительных значений:
start = sort_df.at[idx_a, 'Начало']  # начальная дата
end = sort_df.at[idx_d, 'Начало']  # конечная дата
delta = end - start  # продолжительность периода
summa = sort_df[idx_a:(idx_d+1)].loc[sort_df['Сумма температур'] >= 0, 'Сумма температур'].sum()  # сумма температур

После этого записываем эти переменные в уже созданный фрейм с заголовками:
warm_tot.loc[len(warm_tot)] = [start, end, delta, summa]  # записываем строку во врейм

Результатом должно быть:
Табл. 2

Начало
Конец
Продолжительность
Сумма

2018-05-19
2018-10-30
164 days
1858.3

2019-05-03
2019-10-18
168 days
1979.2

2020-04-02
2020-10-07
188 days
2287.6

Всю эту процедуру неудобно делать отдельно для каждого года. Я пытался проверить код на массиве, содержащий данные за 50 лет, в итоге он записал мне одну строку с периодом с 1971 по 2006 год (хотя что-то подобное стоило ожидать). Как можно вписать этот код в один цикл так, чтобы он отдельно проходил по каждому году массива как показан в Табл. 1, а итог записывал в новый массив, где будет один период для каждого года?

A: Получилось так, возможно у кого-то будут идеи получше...
# переменные для условий
a_max = 0
a = 0  # сюда записывается искомая сумма из начального периода
b = 0
c = 0
d = 0  # сюда записывается искомая сумма из конечного периода
d_max = 0

for i, g in sort_warm.groupby('Year'):
    # условие для нахождения начала периода
    for n in g.loc[g['Half'] == 1]['Sum']:
        if n >= 0:
            if n > a > abs(b):
                a = a
            if n > a and abs(b) > a:
                a = n
            if a > n > abs(b):
                a = a
            if n > a_max:
                a_max = n
        if n < 0:
            if abs(n) > a and abs(n) > a_max:
                b = n
                a = 0
                a_max = 0
            if a < abs(n) < a_max:
                b = n
                a = a_max
            if abs(n) < a:
                b = n
    # условие для нахождения конца периода
    for n in g.loc[g['Half'] == 2]['Sum']:
        if n >= 0:
            if n > abs(d) and n > abs(d_max):
                c = n
                d = 0
                d_max = 0
            if abs(d) < n < abs(d_max):
                c = n
                d = d_max
            if n < abs(d):
                d = d
                c = n
        if n < 0:
            if n < d_max:
                d_max = n
            if c == 0 and d == 0:
                d = n
            if c == 0 and d != 0:
                d = d
            if abs(n) > abs(d) and c > abs(d):
                d = n
            if abs(n) > abs(d) > c:
                d = d
            if abs(n) < abs(d):
                d = d
    idx_a = g.loc[(g.Sum == a) & (g.Half == 1)].index[0]  # индекс начальной даты
    idx_d = g.loc[(g.Sum == d) & (g.Half == 2)].index[0]  # индекс конечной даты
    start = sort_warm.at[idx_a, 'Start']  # начальная дата
    end = sort_warm.at[idx_d, 'Start']  # конечная дата
    delta = end - start  # Period периода
    summa = sort_warm[idx_a:(idx_d + 1)].loc[sort_warm['Sum'] >= 0, 'Sum'].sum()  # сумма температур
    warm_tot.loc[len(warm_tot)] = [start, end, delta, summa]  # записываем строку во фрейм
    a_max = 0
    a = 0
    b = 0
    c = 0
    d = 0
    d_max = 0


text:
Q: VBA - getting sub or function not defined error with error handling active I've got a mystery. In a project I made a while back, there is a check when you activate a different sheet ("Worksheet_Activate" event). The check is to see if there is anything in the "UnsaVedList()" string array, meaning there are unsaved changes. That variable is redimmed early on, but I suppose it's possible somehow that it can disappear and no longer be dimensioned - I don't get that part, but that's not even the issue here.
The issue is that when at least one user's computer hits this line of code where it checks the first bank of that variable, the user is getting an error breaking the code because the variable is not defined. That is only 2 lines after an "On Error GoTo label" line, which is still active at the time of the error popup.
Any idea how this could happen or how to fix it? I'll post the whole sub below

Private Sub Worksheet_Activate()
Dim dontSave As Integer, unsavedDay As Date, backSheet As Worksheet
Set backSheet = ActiveSheet
On Error GoTo noUnsaved
Application.EnableEvents = False
    If Not UnsaVedList(0) = Empty Then
        unsavedDay = DateSerial(Int(Left(UnsaVedList(0), 4)),Int(Mid(UnsaVedList(0), 5, 2)), Int(Mid(UnsaVedList(0), 7, 2)))
        Sheets(18 - DateDiff("d", unsavedDay, Sheets(5).Cells(2, 1).Value)).Activate
        dontSave = MsgBox("You have unsaved changes on " & Format(unsavedDay, "ddd d mmm") & ". Click Yes to review the changes or No to abandon the changes on this day", vbYesNo, "Review changes?")
        Select Case dontSave
            Case 6 'yes
                dontSave = ActiveSheet.Columns("A:A").Find(What:=Int(Right(UnsaVedList(0), 2)), After:=Cells(1, 1), LookIn:=xlFormulas, LookAt _
                :=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
                False, SearchFormat:=False).Row
                ActiveSheet.Range(ActiveSheet.Cells(dontSave, 3), ActiveSheet.Cells(ActiveSheet.Cells(dontSave, 1).End(xlDown).Row, 14)).Select
            Case 7 'no
                ReDim UnsaVedList(0)
                backSheet.Activate
        End Select
    End If
noUnsaved: '''<< this is where it's supposed to jump to!
On Error GoTo 0
Application.EnableEvents = True
End Sub


text:
Q: How to format a local time object in Go with correct minutes? Edit: I have updated the question with code that highlights why the alleged duplicate's solution doesn't work for me
I am trying to take UTC (+0000) times and format them into local times (eastern time in my case) without hard coding any timezone offsets (as to avoid implementing dst correction).
I have the following code which demonstrates the problem I am having
package main

import (
    "fmt"
    "time"
)

func main() {
    // Here I load the timezone
    timezone, _ := time.LoadLocation("America/New_York")

    // I parse the time
    t, _ := time.Parse("Mon Jan 2 15:04:05 +0000 2006", "Tue Jul 07 10:38:18 +0000 2015")

    // This looks correct, it's still a utc time
    fmt.Println(t)
    // 2015-07-07 10:38:18 +0000 UTC

    // This seems to be fine - -4 hours to convert to est
    t = t.In(timezone)
    fmt.Println(t)
    // 2015-07-07 06:38:18 -0400 EDT

    // This prints 6:07am, completely incorrect as it should be 6:38am
    fmt.Println(t.Format("Monday Jan 2, 3:01pm"))
    // Tuesday Jul 7, 6:07am
}

(https://play.golang.org/p/e57slFhWFk)
So to me it seems that it parses and converts timezones fine, but when I output it using format, it gets rid of the minutes and uses 07. It doesn't matter what I set the minutes to, it always comes out as 07.

A: Your layout (format) strings are incorrect. As noted in the doc of the time package, the layout string must denote this time:
Mon Jan 2 15:04:05 MST 2006

When parsing, use the following format string:
t, _ := time.Parse("Mon Jan 02 15:04:05 -0700 2006", "Tue Jul 07 10:38:18 +0000 2015")

And when printing, use this format string:
fmt.Println(t.Format("Monday Jan 2, 3:04pm"))

This will result in your expected output:
Tuesday Jul 7, 6:38am

Try it on the Go Playground.


text:
Q: iOS drawing over UIImage I need to draw over an image graffiti style, as below.  My problem is that I need to have the capability to erase the lines I've drawn without erasing sections of the UIImage.  At the moment I'm considering using one image for the background image and another image, with a transparent background, for the graffiti drawing, then combining the two once the drawing is complete.  Is there a better way?
- (void)drawRect:(CGRect)rect
{
    //Get drawing context
    CGContextRef context = UIGraphicsGetCurrentContext();

    //Create drawing layer if required
    if(drawingLayer == nil)
    {
        drawingLayer = CGLayerCreateWithContext(context, bounds.size, NULL);
        CGContextRef layerContext = CGLayerGetContext(drawingLayer);
        CGContextScaleCTM(layerContext, scale, scale);
        self.viewRect = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.width);

        NSLog(@"%f %f",self.viewRect.size.width,self.viewRect.size.width);
    }

    //Draw paths from array
    int arrayCount = [pathArray count];
    for(int i = 0; i < arrayCount; i++)
    {
        path = [pathArray objectAtIndex:i];
        UIBezierPath *bezierPath = path.bezierPath;
        CGContextRef layerContext = CGLayerGetContext(drawingLayer);
        CGContextAddPath(layerContext, bezierPath.CGPath);
        CGContextSetLineWidth(layerContext, path.width);
        CGContextSetStrokeColorWithColor(layerContext, path.color.CGColor);
        CGContextSetLineCap(layerContext, kCGLineCapRound);

        if(activeColor == 4)
        {
            CGContextSetBlendMode(layerContext, kCGBlendModeClear);
        }
        else
        {
            CGContextSetBlendMode(layerContext, kCGBlendModeNormal);
        }

        CGContextStrokePath(layerContext);
    }

    if (loadedImage == NO)
    {
        loadedImage = YES;
    CGContextRef layerContext = CGLayerGetContext(drawingLayer);
    CGContextSaveGState(layerContext);
    UIGraphicsBeginImageContext (self.viewRect.size);
    CGContextTranslateCTM(layerContext, 0, self.viewRect.size.height);
    CGContextScaleCTM(layerContext, 1.0, -1.0);
    CGContextDrawImage(layerContext, self.viewRect, self.image.CGImage);
    UIGraphicsEndImageContext();
    CGContextRestoreGState(layerContext);
    }

    [pathArray removeAllObjects];

    CGContextDrawLayerInRect(context, self.viewRect, drawingLayer);
}


text:
Q: Throwing exceptions to wcf service Can any one please explain me on how to throw a exception from a class library to a wcf service.
  Actually i have three layers
    1. Data Acess layer(Contails DB).
    2. BI Layer(WCF Class library)
    3. Asp.NET UI
Now my question is how to throw if some exception accurs in DAL to WCF BI Component.And How to throw that FaultException to UI.
Thanks in Advance,
Jane

A: There is a very interesting article in codeproject about exception handling in 3-Tier architecture:
http://www.codeproject.com/KB/exception/expceptionhandling-3-tier.aspx
Basically every tier should be responsible for catching its own exceptions, logging the error/exception and providing just the necessary information to the next tier. For example: the UI should have just a user-friendly message without technical information.
The same idea can be adapted to the model you have implemented. Any error in DAL should be handled and propagated to the business tier. In your case the business service layer should throw a fault exception across the network with a custom user-friendly message that will be caught in the UI and probably displayed as a message.
Hope it helps.


text:
Q: Sharing individual PHPStorm workspace settings through GIT In the .idea/workspace.xml file, there's loads of settings I'd like to share with colleagues. Most xml files in .idea/ can be committed as is, but the .idea/workspace.xml should not be committed, per Jetbrains' documentation -- as there's a lot of user-specific config in there as well..
In my case I'm interested in the following config-snippet:
<component name="ComposerSettings" doNotAsk="true">
    <pharConfigPath>$PROJECT_DIR$/composer.json</pharConfigPath>
    <execution />
  </component>

(and others alike ) which is in .idea/workspace.xml
Is there a way to share these settings through Git, in another way? The mechanisms of the idea folder and its files is not that well documented in the IDEA/Phpstorm documentation.
So for example, conceptually I hope there's something like a .idea/global.xml which can set a default without the user having to set the settings which would otherwise go in workspace.xml.


text:
Q: Distributing JavaFX Applications that use automodules I have created a JavaFX application. It runs perfectly in my Intellij IDE. Now I want to distribute the application - i.e. I want to obtain an installer that users could download and then it would install the application for them.
I found a very interesting article about this here. This blog article basically describes what I want to achieve. There are two differences though:

*

*I am using Maven and not Gradle

*I have dependencies which use automodules such as iText7 and apache.commons.lang3
The usage of automodules is making things very complicated. There is a GitHub project called ModiTect (here) that has been written to solve these issues. I have no experience in using ModiTect though and even my Maven knowledge is barely existent (meaning: I don't really know what I am doing in the pom.xml).
What I am looking for is an explanation (step-by-step) as on how to integrate ModiTect (and if necessary jpackage) into my pom.xml in order to obtain an installer for my JavaFX application that uses automodules (and also a sqlite database, which shouldn't be a problem though).
Can somebody provide this explanation or refer me to a tutorial?
I provide a MWE at the end of this question. The MWE ist a TestApp. To illustrate the problem, run the application and press the "Print PDF" button. A pdf is created in resources --> pdf
The MWE will compile and run when executing javafx:run
There will be an error related to the usage of automodules when executing javafx:jlink
I don't know how to fix this. ModiTect appears to be a promising addon. Another possible way can be found in this GitHub repo. But as I said before: My Maven knowledge is not sufficient to really grasp what is going on here. Any help would mean a lot to me!
MWE:

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.company</groupId>
    <artifactId>TestApp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>15</maven.compiler.source>
        <maven.compiler.target>15</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>15.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>15.0.1</version>
        </dependency>

        <dependency>
            <groupId>de.jensd</groupId>
            <artifactId>fontawesomefx-fontawesome</artifactId>
            <version>4.7.0-9.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.34.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.1.14</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>7.1.14</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>io</artifactId>
            <version>7.1.14</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-jdk14</artifactId>
            <version>1.7.30</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>15</release>
                    <source>15</source>
                    <target>15</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.5</version>
                <configuration>
                    <mainClass>com.company.TestApp</mainClass>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>

module-info.java:
module com.company {
    requires javafx.controls;
    requires javafx.fxml;
    requires java.sql;
    requires org.apache.commons.lang3;
    requires kernel;
    requires layout;
    requires io;
    requires sqlite.jdbc;
    requires javafx.graphics;

    opens com.company to javafx.fxml;
    opens com.company.controllers to javafx.fxml;

    exports com.company;
    exports com.company.controllers;
}

TestAppController.java:
package com.company.controllers;

import javafx.event.ActionEvent;

import javafx.fxml.FXML;

import javafx.scene.control.Button;
import javafx.scene.control.TextArea;

import org.apache.commons.lang3.StringUtils;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;

import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.Document;

import java.io.FileNotFoundException;

public class TestAppController {

    @FXML
    private TextArea taText;

    @FXML
    private Button btnPrint;

    public void handleButtonAction(ActionEvent event) {
        if (event.getSource() == btnPrint) {
            setTaText();
            printPdf();
        }
    }

    public void setTaText() {
        taText.setText(StringUtils.leftPad("Random Text left padded by 50", 50));
    }

    public void printPdf() {
        String directoryString = "src/main/resources/com/company/pdf";

        try {
            String filepath = directoryString + "/" + "pdf_1" + ".pdf";
            PdfWriter writer = new PdfWriter(filepath);
            PdfDocument pdf = new PdfDocument(writer);
            Document document = new Document(pdf);
            document.add(new Paragraph(taText.getText()));
            document.close();
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
            return;
        }

    }
}

TestApp.java:
package com.company;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class TestApp extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("testApp.fxml"));
        Scene scene = new Scene(root);

        primaryStage.setScene(scene);
        primaryStage.setTitle("Test");

        primaryStage.show();
    }
}

testApp.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.company.controllers.TestAppController">
   <top>
      <AnchorPane prefHeight="60.0" prefWidth="600.0" style="-fx-background-color: #337DFF;" BorderPane.alignment="CENTER" />
   </top>

      <AnchorPane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
         <children>
            <Button fx:id="btnPrint" layoutX="240.0" layoutY="155.0" mnemonicParsing="false" onAction="#handleButtonAction" prefHeight="25.0" prefWidth="120.0" style="-fx-background-color: #337DFF;" text="Print PDF" textFill="WHITE">

            </Button>
            <TextArea fx:id="taText" layoutX="125.0" layoutY="44.0" prefHeight="82.0" prefWidth="350.0" />
         </children>
      </AnchorPane>

</BorderPane>

A: Instead of the javafx maven plugin you could use the moditect plugin to create missing module-info to auto module dependencies and then build the image with moditect.
Such a pom for you could be something like:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.company</groupId>
<artifactId>TestApp</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <appName>TestApp</appName>
    <launcherName>testapp</launcherName>
    <moduleName>com.company</moduleName>
    <mainClass>com.company.LoginApp</mainClass>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>15</maven.compiler.source>
    <maven.compiler.target>15</maven.compiler.target>
    <version.java>15</version.java>
</properties>

<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>15.0.1</version>
    </dependency>

    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>15.0.1</version>
    </dependency>

    <dependency>
        <groupId>de.jensd</groupId>
        <artifactId>fontawesomefx-fontawesome</artifactId>
        <version>4.7.0-9.1.2</version>
    </dependency>

    <dependency>
        <groupId>org.xerial</groupId>
        <artifactId>sqlite-jdbc</artifactId>
        <version>3.34.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>kernel</artifactId>
        <version>7.1.14</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>layout</artifactId>
        <version>7.1.14</version>
    </dependency>

    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>io</artifactId>
        <version>7.1.14</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.30</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <release>${version.java}</release>
            </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.1.2</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/modules</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.moditect</groupId>
            <artifactId>moditect-maven-plugin</artifactId>
            <version>1.0.0.RC1</version>
            <executions>
                <execution>
                    <id>add-module-info-to-dependencies</id>
                    <phase>package</phase>
                    <configuration>
                        <outputDirectory>${project.build.directory}/modules</outputDirectory>
                        <overwriteExistingFiles>true</overwriteExistingFiles>
                        <modules>
                            <module>
                                <artifact>
                                    <groupId>com.itextpdf</groupId>
                                    <artifactId>kernel</artifactId>
                                </artifact>
                                <moduleInfo>
                                    <name>kernel</name>
                                </moduleInfo>
                            </module>
                            <module>
                                <artifact>
                                    <groupId>com.itextpdf</groupId>
                                    <artifactId>layout</artifactId>
                                </artifact>
                                <moduleInfo>
                                    <name>layout</name>
                                </moduleInfo>
                            </module>
                            <module>
                                <artifact>
                                    <groupId>com.itextpdf</groupId>
                                    <artifactId>io</artifactId>
                                </artifact>
                                <moduleInfo>
                                    <name>io</name>
                                </moduleInfo>
                            </module>
                            <module>
                                <artifact>
                                    <groupId>org.xerial</groupId>
                                    <artifactId>sqlite-jdbc</artifactId>
                                </artifact>
                                <moduleInfo>
                                    <name>sqlite.jdbc</name>
                                </moduleInfo>
                            </module>
                            <module>
                                <artifact>
                                    <groupId>org.apache.commons</groupId>
                                    <artifactId>commons-lang3</artifactId>
                                </artifact>
                                <moduleInfo>
                                    <name>org.apache.commons.lang3</name>
                                </moduleInfo>
                            </module>
                            <module>
                                <artifact>
                                    <groupId>org.slf4j</groupId>
                                    <artifactId>slf4j-api</artifactId>
                                </artifact>
                                <moduleInfo>
                                    <name>org.slf4j</name>
                                </moduleInfo>
                            </module>
                        </modules>
                        <module>
                            <mainClass>${mainClass}</mainClass>
                            <moduleInfoFile>${project.build.sourceDirectory}/module-info.java</moduleInfoFile>
                        </module>
                        <jdepsExtraArgs>
                            <args>--multi-release</args> <args>15</args>
                            <args>--ignore-missing-deps</args>
                        </jdepsExtraArgs>
                    </configuration>
                    <goals>
                        <goal>add-module-info</goal>
                    </goals>
                </execution>
                <execution>
                    <id>create-runtime-image</id>
                    <phase>package</phase>
                    <goals>
                        <goal>create-runtime-image</goal>
                    </goals>
                    <configuration>
                        <modulePath>
                            <path>${project.build.directory}/modules</path>
                        </modulePath>
                        <modules>
                            <module>${moduleName}</module>
                        </modules>
                        <launcher>
                            <name>${launcherName}</name>
                            <module>${moduleName}</module>
                        </launcher>
                        <compression>2</compression>
                        <stripDebug>true</stripDebug>
                        <outputDirectory>${project.build.directory}/jlink-image</outputDirectory>
                        <ignoreSigningInformation>true</ignoreSigningInformation>
                    </configuration>
                </execution>

            </executions>
        </plugin>
        <plugin>
            <groupId>com.github.akman</groupId>
            <artifactId>jpackage-maven-plugin</artifactId>
            <version>0.1.2</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>jpackage</goal>
                    </goals>
                    <configuration>
                        <name>${appName}</name>
                        <type>IMAGE</type>
                        <runtimeimage>${project.build.directory}/jlink-image</runtimeimage>
                        <module>${moduleName}/${mainClass}</module>
                    </configuration>
                </execution>
            </executions>
        </plugin>

    </plugins>
</build>

</project>

My first tests seems to be successful but a few items might need more work (e.g. I do not like to have the --ignore-missing-deps argument)
Maybe this helps a little to get you forward.


text:
Q: Editing default functions: Changing the default color of plot function in kernlab in R Per the example in the kernlab documentation, plot makes a nice figure of the decision weights and boundary of an SVM model.
require(kernlab)
x<- rbind(matrix(rnorm(n=120,mean=-1,sd=2),,2),matrix(rnorm(120,mean=3,sd=2),,2))
y <- matrix(c(rep(1,60),rep(-1,60)))
svp <- ksvm(x,y,type="C-svc",kernel="vanilladot")
plot(svp,data=x)

However, I'd like to change the default colors of the background gradient.  Any suggestions how to do this?  I've looked into edit(plot), but am not comfortable enough with generic functions to know what to change.   Thanks!

A: If you check with showMethods("plot") and then getMethod("plot", c("ksvm", "missing")), you'll see that the plotting function creates its own colors:
[...]
mycols <- c(hcl(0, 100 * (nl:0/nl)^1.3, 90 - 40 *
   (nl:0/nl)^1.3), rev(hcl(260, 100 * (nl:0/nl)^1.3,
   90 - 40 * (nl:0/nl)^1.3)))
[...]

and uses them for plotting:
[...]
filled.contour(xr, yr, matrix(as.numeric(preds),
    nrow = length(xr), byrow = TRUE), col = mycols,
[...]

which means that you cannot change the colors easily, they are hardcoded into the ksvm plot().
What you can do is

*

*Making a copy of the plot() function, and rewrite it, such that you can overwrite the default colors.

*Write an email to the maintainer of the package, and tell him to add this feature. Possibly send him
a patch, if you already rewrote the plotting function.

*"Edit the function in place. See What ways are there to edit a function in R?.


text:
Q: Trying to use ColdFusion to create HMAC-SHA1 hash for API authentication I am at my wit's end on this one, I just can't find the right combination of code to make this work.  I'm trying to create an authentication digest for an API query.  I've tried many CFML functions (for example:  Coldfusion HMAC-SHA1 encryption and HMAC SHA1 ColdFusion), but I'm not coming up with the same results that are cited in the API documentation.  Here's that example (basically elements of the request header with line breaks as delimiters.):
application/xml\nTue, 30 Jun 2009 12:10:24 GMT\napi.summon.serialssolutions.com\n/2.0.0/search\ns.ff=ContentType,or,1,15&s.q=forest\n

and here's the key:
ed2ee2e0-65c1-11de-8a39-0800200c9a66

which according to the documentation should result in:
3a4+j0Wrrx6LF8X4iwOLDetVOu4=

when the HMAC hash is converted to Base64. Any ideas would be most appreciated!

A: The problem is your input string, not the functions.  The first one works fine. Though I would change the charset to UTF-8, or make it an argument. Otherwise, the results are dependent on the jvm default, which may not always be correct, and can change which would break the code.
Verify you are constructing the sample string correctly. Are you using chr(10) for new lines? Note: It must also end with a new line.
Code:
<cfscript>
    headers = [ "application/xml"
                    , "Tue, 30 Jun 2009 12:10:24 GMT"
                    , "api.summon.serialssolutions.com"
                    , "/2.0.0/search"
                    , "s.ff=ContentType,or,1,15&s.q=forest"
                ];
    theText = arrayToList(headers, chr(10)) & chr(10);
    theKey = "ed2ee2e0-65c1-11de-8a39-0800200c9a66";
    theHash = binaryEncode( hmacEncrypt(theKey, theText), "base64");
    writeDump(theHash);
</cfscript>

Result:
3a4+j0Wrrx6LF8X4iwOLDetVOu4=


text:
Q: How can I use a relative path in my toml file? I want to use a relative directory in toml file.
I heard that I should use "\" instead of "" in toml file,
but I don't know how to use relative path in toml file.
HatMode = "Custom"
HorizontalSize = 1.5
HatPosition = 0.600000023841858
CustomHatPath = "C:\\Users\\Desktop\\kane_goose\\DesktopGoose_v0.3_Extractor\\Assets\\Mods\\HatGoos\\kane.png"

This is codes inside of toml file.
I should enter a relative path in
CustomHatPath = "C:\\Users\\Desktop\\kane_goose\\DesktopGoose_v0.3_Extractor\\Assets\\Mods\\HatGoos\\kane.png"
this part.
Below, directory of the first image is C:\Users\username\Desktop\kane_goose\DesktopGoose_v0.3_Extractor\Assets\Mods\HatGoos
, and directory of the second image is C:\Users\username\Desktop\kane_goose\DesktopGoose_v0.3_Extractor\Assets\Mods\HatGoos\hat
The toml file is on the first image, and I must add the kane.png of the second image to the toml file.
Can you teach me how to use relative path in this situation? in toml file?


text:
Q: JS 2D массив loop Суть задачи такова: через Math.random создаем 6 массивов из 3 элементов. Затем эти массивы нужно поместить в массив a так, чтобы они не повторялись. Применить indexOf к 2D массиву, насколько я понял, нельзя. А если использовать if (a[i] != b) {a.push(b)} приведет к тому, что массив будет добавляться после каждого цикла.
var a = [];

for (let i=0; i<6; i++) {
  var b = [];
for (let j=0; b.length<3; j++) {
  var rnd = Math.floor(Math.random()*3+1);
  if (b.indexOf(rnd) === -1) {
    b.push(rnd)
  }
 }
 //здесь нужно дописать для a
}

A:

var a = [];
var lookup = [];
while (a.length < 6) {
  var b = [];
  while (b.length < 3) {
    var rnd = Math.floor(Math.random()*3+1);
    if (b.indexOf(rnd) === -1) {
      b.push(rnd);
    }
  }
  if (lookup.indexOf(b + "") == -1) {
    lookup.push(b + "");
    a.push(b);
  }
}
console.log(JSON.stringify(a));


text:
Q: ST-LINK/V2 repairing issue My original ST-LINK/V2 has been broken. There was the Short circuit between VDD and GND pins. I changed the MCU(STM32F103C8T6) and the voltage regulator(LD3985M33R) with new ones. Short Circuit problem gone, but when I plugged ST-LINK to USB port, the indicator LED is on very lightly. USB Device not recognized window shown at PC screen.
I measured VDD pin as 3.29V. Power is OK.
ST-LINK/V2 is not open source and I couldnt reach its schematic.
What should I do to fix the issue? Thanks your helps...

A: You need to upload ST Link firmware onto the MCU. It might be possible with some soldering/desoldering involved.
I am not sure if the original firmware is available freely, but there is STSW-LINK007 firmware update package on ST site and I suspect it contains entire firmware ready to upload.
The first problem is that the MCU must be in DFU mode for this. It is done by selecting system memory boot mode (boot0 = 1, boot1 = 0). So, you have to find a way to temporarily connect boot0 pin to VCC and then power reset. Preferably without making another short on board.
The second problem is that STSW-LINK007 requires USB DFU bootloader, and there is a chance the one installed on your MCU uses UART protocol. See AN2606 for details. If this is the case you'd have to connect USB-Serial adapter board to UART port pins and install USB bootloader first, then try firmware update again.
But frankly, I agree with the comments left on your question - unless you are doing this for fun and education, it is not worth the time spent.
Finally, it might be a bad photo angle, but it seems you have a lot of bridging on the MCU chip. You might want to check that out first.

A: Considering that you changed the MCU with an empty part and the original MCU contains the software required for that whole thing it's now probably finally gone. You'll need to get a new one.

A: At last, I solved the issue in the help of Maple's advises. The steps I followed below:

*

*Pull the BOOT0 pin up to VDD in order to flash bootloader firmware (R1 desoldered and connected the BOOT0 side of R1 to VDD).

*Soldered CN1 headers and connected the SWDIO,SWCLK,GND and VDD pins.

*

*Flashed the STLinkV2.J16.S4.hex file with another ST-Link programmer.(while flashing the firmware, the st-link should powered on by USB. )

*Resoldered R1.
Now it is ready.:)

*Update the firmware with STLink Utility to latest version.
thanks to everyone who left a comment..


text:
Q: Serializable issue with List with Session stored in SQL Server We are using .Net 4.0 and SQL Server for our Session Store.
We have marked all our objects as [Serializable] but we are still getting the error:
System.Web.HttpException (0x80004005): Unable to serialize the session state.

In turns out the issue is with a call to a ToList method we have implemented
if (licenseHoldings != null && licenseHoldings.**ToList()**.Any())

And the implementation of LicenseHoldings.cs :
[Serializable]
public class LicenseHoldings
{

    public MyEnum myEnum{ get; set; }

    public MySerializableObject mySerializableObject { get; set; }

    public List<MySerializableObjectBaseClass> ToList()
    {
        var list = new List<MySerializableObjectBaseClass>();

        if (mySerializableObject != null)
            list.Add(mySerializableObject  );

...
        return list;
    }
}

Why is a List of a serializable objects not serializable to a SQL Server session?

A: The issue in this case was that the object MySerializableObjectBaseClass had a reference to an IEnumerable, ie. an interface which is not serializable.
We replaced IEnumerable with a List and all was well in the world..


text:
Q: pybarcode add not setted digits I try to generate barcode EAN13 (1234567890123)
ean = barcode.get('ean13', '1234567890123')
return render(request, 'index.html', {'date':now, 'data': listing, 'auth': auth, 'barcode': ean})

in template add
{{ barcode }}

and receive result as:

1234567890128

Why this strings is different (1234567890128 must have 1234567890123)?

A: 1234567890123 is not a valid EAN code; even if you had managed to output that barcode, nothing would have been able to scan it, because its check digit is incorrect.  The barcode software you're using helpfully corrected the check digit, rather than producing a useless barcode (although generating an error might arguably have been a better thing for it to do).


text:
Q: uninstall using registry uninstall string powershell I'm trying to create a powershell script that will uninstall all versions of a program in our studio.
I had a look at the registry and can see that we have 3 strings of the program installed in our studio computers
{D4BE10F2-3E2D-4120-863A-765623D53264}
{77067FD9-800C-48B4-803D-569642ADABC5}
{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}

I created a test script:
msiexec.exe /x{D4BE10F2-3E2D-4120-863A-765623D53264} /q

and used it on a machine, this worked and that version of the program was uninstalled.
I want to create a script that cycle all 3 strings and Success on the correct one, as I don't know what machine has what version without doing a scan.
so I created a `powershell script:
foreach ($guid in '{D4BE10F2-3E2D-4120-863A-765623D53264}',
                  '{77067FD9-800C-48B4-803D-569642ADABC5}',
                  '{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}') {

  $exe = 'C:\Windows\System32\msiexec.exe'

  $ps = Start-Process -PassThru -Wait $exe "/x /q"

  if ($ps.ExitCode -eq 0) { "Success"; exit 0 }

}

Write-Warning "Uninstallation failed."
exit $ps.ExitCode

This is not working for me as it keeps returning with Uninstallation failed, I'm not sure whats going on.
Any advice?

A: This will work even if there are all three versions installed:
foreach ($guid in '{D4BE10F2-3E2D-4120-863A-765623D53264}',
                  '{77067FD9-800C-48B4-803D-569642ADABC5}',
                  '{1DB1AEB7-EDBD-4BB1-87DB-26C72576DA42}') {

    $exe = 'C:\Windows\System32\msiexec.exe'
    $ps = Start-Process $exe -ArgumentList "/x$guid /q" -PassThru -Wait
    if ($ps.ExitCode -eq 0) {
        Write-Host "$($guid): Success"
    } else {
        Write-Host "$($guid): Failed"
    }
}


text:
Q: SetTimeout And SetImmediate with console.log Can anyone please explain why i am getting this below two types of output for adding and removing console.log between setTimeout and setImmediate.
Why I am getting different output while executing example 1 and Why I am getting same output for example 2. Please tell me difference between setTimeout and setImmediate
Example 1:
setTimeout(function(){
        console.log("inside timeout")
});

setImmediate(function(){
        console.log("inside immediate")
});

Output:
inside immediate
inside timeout

Example 2:
console.log(1)

setTimeout(function(){
        console.log("inside timeout")
});
console.log(2)
setImmediate(function(){
        console.log("inside immediate")
});
console.log(3)

Output:
1
2
3
inside timeout
inside immediate

A: Let's talk about the situation in nodeJs. Actually the order of the below code is can not be guarantee.
 setTimeout(function(){
            console.log("inside timeout")
    });

    setImmediate(function(){
            console.log("inside immediate")
    });

If you run it many times, you will found that, in high probability it is
inside immediate
inside timeout,

but sometimes it's in reverse. You second demo is same.
In nodeJs there one thing call event loop, For the asynchronous function, the  event loop forward it to libuv and then it be forward to the OS. For eg. When the time in setTimeout is coming, the callback function be set into a queue, it will be invoked after the synchronous thread is done. For different asynchronous task there are four different queue, the setTimeout's queue is run before the setImmediate's queue.But the setTimeout's cut down return depend on the CPU's time slice, even the setTimeout(0), so it is not stable.

A: Edit
Following your edit I'll add the answer given by Mark Meyer in the comments:

the docs are clear: the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process

Original answer
setTimeout and setImmediate are asynchronous methods relying on the asynchronous stack.
Even if you are using setTimeout with no timer (which is the same as setImmediate), you would still put the callback on the asynchronous stack.
This stack is being executed as the main JS thread is freed.
So in your case this is what is happening:

*

*Execute console.log(1)

*Place the first callback on the stack

*Execute console.log(2)

*Place the second callback on the stack

*Execute console.log(3)

*Main thread is freed

*Execute first callback

*Execute console.log('inside timeout')

*Main thread is freed

*Execute second callback

*Execute console.log('inside immediate')

If you had a timer on the first timeout, it would take some time before actually going on the stack, and would end up behind the inside immediate output.