Making your actions properly repeatable

Question: Should be a simple question -
In Nethack often I've wanted to gain the telepathic intrinsic by eating a floating eye corpse.  Normally I'll try attacking it from a distance so as not to be frozen.
This time, I tried making things easier by readying a group of darts, and then trying to throw them all in a row.
So I typed in n20f and continually pressed the right button in order to aim my dart.
However, this caused me to freeze up and get killed by a random giant bat, which was able to easily kill me since I was helpless.
I'm playing the Windows port, so my arrow keys move me.  Is there something I did wrong here?
Answer: Once you throw one dart/dagger/etc., you can fire again in the same direction using CTRL-A.
This is IMO the best way to accomplish this.
Comment: So my method of 'firing' 20 times isn't valid?
Comment: @espais The problem is you won't stop firing once the target is dead. I'd repeat at most 5 times per attack
Answer: I believe that your method of firing 20 times was not valid.
Supplying a prefix to the f command actually tells it the number of projectiles you want to fire in that single action.  (This isn't normally useful, but daggers, arrows and some other ranged weapons can "multi-fire" at higher skill levels (i.e. in one action you fire two or three arrows).  Using the numeric prefix allows the player to place an upper limit on the number of projectiles released.  This is can be necessary, for example, if you're firing at a weak enemy with a peaceful creature behind it - n1f will guarantee that only one arrow is released, whereas simply f could fire multiple arrows, killing the enemy with the first and hitting the friendly with the rest.  And whenever you specify a quantity, the amount actually fired is the minimum of what you specified, and what would have been fired anyway.)
So anyway, that's what your command meant - "this turn, throw no more than 20 darts to the right".  Then after that action was done, you just went right, right, right - attacking the floating eye and being frozen.
MikeyB's right that Ctrl-A is the solution here; I just wanted to give some background on why your commands didn't do what you hoped.
Comment: thanks for the pointer...didn't realize that was the case!

Making your actions properly repeatable


How to appropriately include schemalocation to refer a xsd file in xml

Question: I am building a xml grammar file for speech recognition so for that I created a lexicon file and added lexicon elements as follows the schema location giving me errors

the schema referenced from this location in your document contains error
the operation has timed out

The bolded line is causing the error
xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
**http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"**
alphabet="x-microsoft-ups" xml:lang="en-IN"

What should I do?
Answer: The schema you're pointing at is valid. The thing is, schemas hosted on the W3C website are sometimes throttled; more so in your case since pls.xsd references xml.xsd (this one for sure is throttled).
W3C throttles responses to well know XSDs as means to protect itself against unnecessary traffic.
Download your local copy and reference those instead, and all should be fine (assuming everything else works for you).
This is how the XML file should look like based on your comments:
<?xml version="1.0" encoding="utf-8"?>
<lexicon version="1.0"
    xmlns="http://www.w3.org/2005/01/pronunciation-lexicon" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon file://C:/some/folder/where/your/xsd/file/is/pls.xsd"
    alphabet="x-microsoft-ups" xml:lang="en-IN">
    <lexeme>

    </lexeme>
</lexicon>

This is how the pls.xsd top part should look like (after changing the schema location for xml.xsd, assume they are in the same folder):
<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:p="http://www.w3.org/2005/01/pronunciation-lexicon" targetNamespace="http://www.w3.org/2005/01/pronunciation-lexicon" elementFormDefault="qualified" version="1.0">
    <xs:annotation>
        <xs:documentation>Importing dependent namespaces</xs:documentation>
    </xs:annotation>
    <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="xml.xsd" />

 ...
    </xs:schema>

It all works fine in VS2010 and up.
Comment: thank you sir...after changing xml as you shown it causes error saying An error has occurred while opening external DTD 'file:///C:/xsdforproject/XMLSchema.dtd': Could not find file 'C:\xsdforproject\XMLSchema.dtd
Comment: What tool are you using? The XSD files we're talking about don't reference the DTDs you're referring... your problems are most likely of a different nature.
Comment: Yah i know thatsy i am also confused about dtd error...i am working on VS2010
Comment: You're having unrelated problems... I've tried the files as posted in VS2010 and everything works fine (Intellisense, validation, etc.) You'll have to look elsewhere, ideally try a repro of some sort and post a different question...
Comment: Sir is there any problem in my c# code I mean that this problem has anything to do with in coding?
Comment: What C# code are you refering to? You did not post any.
Comment: I am using following c# code to read & use my XML file. string srgsDocumentFile=Path.Combine(@"Voice_Automator.xml"); XmlReader reader = XmlReader.Create(srgsDocumentFile); SrgsDocument t1 = new SrgsDocument(reader); Grammar g1 = new Grammar(t1); _recognizer.LoadGrammarAsync(g1);
Comment: It doesn't make sense... Loading an XML referencing an XSD doesn't trigger validation - there's something else you're not showing. Try to create your XmlReader using this [API](http://msdn.microsoft.com/en-us/library/ms162474(v=vs.110).aspx). On .NET 4.0 and above set [DtdProcessing](http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.dtdprocessing(v=vs.100).aspx) to Ignore; on earlier versions, set [ProhibitDtd](http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.prohibitdtd(v=vs.110).aspx) to false.
Comment: now see sir is it right?
string srgsDocumentFile = Path.Combine(@"Voice_Automator.xml");
XmlReaderSettings settings = new XmlReaderSettings();
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials =System.Net.CredentialCache.DefaultCredentials;
settings.XmlResolver = resolver;
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(srgsDocumentFile, settings);
SrgsDocument t1 = new SrgsDocument(reader);
Grammar g1 = new Grammar(t1);
_recognizer.LoadGrammarAsync(g1);
Comment: `settings.DtdProcessing = DtdProcessing.Parse` is wrong; as indicated, use Ignore instead.


Wordpress: Problems importing localhost database to live site

Question: I'm hoping someone can help me with this issue. I am trying to take a working wordpress site from WAMP and move it onto a live domain. I've already setup the hosting and everything and followed the instructions on exporting my current database to file and importing it through phpmyadmin on domain.com cpanel.
I am receiving the following error upon import: #1062 - Duplicate entry '1' for key 'PRIMARY'
I was receiving error #1064 before that, but after deleting a few lines of code at the top, It changed to this error. I'm assuming the problem might have to do with config.php, or perhaps having different versions?
Here is what I have in my .sql file I am trying to import at the top:
-- phpMyAdmin SQL Dump
-- version 4.1.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Sep 02, 2015 at 08:46 PM
-- Server version: 5.6.17
-- PHP Version: 5.5.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

I am very new to setting up wordpress sites as well as using databases so if there is other information you need to help me fix this, please ask and I will get it. If I have not provided enough info, I apologize, I'm just not sure where I should be looking and could really use some advice.
Thanks in advance to anyone who reads this.
- Barret
Edit: This might also be useful information
USE pubz_glass_db;

CREATE TABLE IF NOT EXISTS `1441208560942_wp_commentmeta` (
`meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',
`meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`meta_value` longtext COLLATE utf8mb4_unicode_ci,
 PRIMARY KEY (`meta_id`),
 KEY `comment_id` (`comment_id`),
 KEY `meta_key` (`meta_key`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci         AUTO_INCREMENT=1 ;

Answer: When you install new, fresh Wordpress it automatically create default article etc. so when you try to import old database there is conflict of id's. Before importing old database you should DROP or at least TRUNCATE all tables created by Wordpress after installation on your hosting.
Comment: Where would I delete them at? in phpmyadmin there is nothing in the database when I import. I've also tried creating a new database name entirely with no luck.
Comment: It's now reverted back to the original problem message: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 2 .

Is this not a version issue?
Comment: The error corresponds to the syntax error. You said, that you had deleted few lines of code. It may be the reason why you're getting this error. I suggest  to import `SQL` file without doing any changes to it.
Comment: The lines that I deleted were these:

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;

/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

/*!40101 SET NAMES utf8 */;

There were 3 or 4 errors before I deleted these and I read on several other posts they should be removed. If that is incorrect please let me know.
Comment: The SQL file i'm editing is the backup file from the export. Is this not the correct file to be editing? the error says near "?" on line 2, yet line 2 says: -- version 4.1.14 . I don't think I'm editing the right document? ugh this is frustrating


How do I use List.fold_left?

Question: I'm still trying to understand how fold_left exactly works. Does it iterate through the list like List.iter? Or is there just something else wrong with my code? I'm thinking that e is the element in the list (so it's a tuple) and fst e takes the first element of the tuple and snd e takes the second element in the tuple.
let rec pow x n =
    if n < 0 then
        0
    else if n = 0 then
        1
    else
        x * pow x (n - 1);;

let polynomial lst = function
    | x -> List.fold_left (fun e -> (fst e) * (pow x (snd e))) 1 lst;;

lst is a list of tuples where each tuple has two integers and makes a polynomial function, so polynomial is supposed to return a function. So an example of what should happen is this
# let f = polynomial [3, 3; -2, 1; 5, 0];;
val f : int -> int = <fun>
# f 2;; (* f is the polynomial function f(x) = 3x^3 + (-2)x + 5 *)
- : int = 25

But I get this error message

"Error: This expression has type int but an expression was expected of type 'a -> int * int".
Answer: List.fold_left indeed iterates over a list, passing the value from one call to another, which basically works like a bucket brigade, with only one bucket, where on each iteration you can look into the bucket, take whatever is there and put something new.
More formally, fold_left f init elements has type
val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b list -> 'a

and it takes three arguments, the function f, the initial value init, and a list of elements. The function f is called for each element x of elements as f acc x, where acc is either init if x is the first element of the list or a result returned by the previous invocation of f. Back to our analogy, it is either the initial empty bucket or a bucket passed from the previous call in the chain.
In your case, the role of the bucket is the final sum of all terms. Initially, it is empty, then each new term computes (fst e) * (pow x (snd e)) and adds it to the bucket so that at the end you will have the sum of all terms,
let polynomial coeffs x =
  List.fold_left (fun sum (k,r) -> sum + k * pow x r) 0 coeffs

Note, that instead of using fst and snd to access the elements of the pair, I deconstructed the tuple directly in the parameter list. This makes code easier to understand and shorter.
The function, that is applied on each step takes two arguments, sum is the bucket (it is often called the "accumulator") and the element of the list, which is a pair (k,r) in our case. We multiply k by the value of the x variable raised to the power r and then we add the result to the accumulator.
For people with an imperative mindset the following pseudocode1 might be more insightful than the bucket brigade analogy:
def fold_left(user_func, init, elements):
    acc = init
    for elt in elts:
       acc = user_func(acc, elt)
    return acc

1) Any resemblance to Python is purely coincidental :)
Comment: So the 0 is the starting value of the function and (fun sum (k,r) -> sum + k * pow x r) adds to it? If I'm getting it correctly.
Comment: you're welcome, I've added a detailed explanation of the `fold_left` function, as it looks like it is not thoroughly described in the official manual.

How do I use List.fold_left?


Mysql database copy for offline use

Question: My application reads data from an mysql database to a datagridview, some users want the ability to have a offline database option.
What is the best way to save the mysql database to a local file/database without the user needing to run a local mysql server.
The database contains only 2 tables.
Comment: Create another database in the same server and create a job that runs regularly to sync the tables by SSIS...
Comment: If you want to have a offline feature, i think the users must have mysql installed on their client. Or you make use of a ms access database, xml file or something that is dumped from the server while online that could be read as datasource when offline.
Answer: well since you want it offline without installing a database (which would be the easyest) i'd suggest storing it in an .xml file.
I take it you already have a piece of code to retrieve data from a database, so simply use that code and store all the data in a DataTable or custom Class, then with this peace of code save and load it
public static void Save(string FileName, object o)
{
    using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(o.GetType());
        serializer.Serialize(writer, o);
        writer.Flush();
    }
}

public static object Load(string FileName, Type t)
{
    using (var stream = System.IO.File.OpenRead(FileName))
    {
        var serializer = new XmlSerializer(t);
        return serializer.Deserialize(stream);
    }
}

assuming you want to sync the database and not completely select the entire database every time you could add a column to your tables such as DateTimeModified and select everything that has been modified/added after the last sync.
Comment: Will crash when the database grows up.

Mysql database copy for offline use


Add/Sub hours to my Calendar object

Question: I am using Calendar class in my project. In some cases, I need to subtract some hours to a date. I can face this easily.
The problem is when I subtract hours and it changes the day (one or more days later).
How can I manage it?
Thank you in advance,
Diego.
Comment: What specifically is the problem? Without more details, we can't really assist you.
Comment: Please post some code.
Comment: Why do you not want the days to be changed when adding or subtracting hours (or have I misunderstood you)? What is the use case?
Answer: The Calendar has the add() and roll() methods:

add(int field, in amount): Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
roll(int field, in amount): Adds the specified (signed) amount to the specified calendar field without changing larger fields.

So if you want to add 2 hours to Monday, 23:00 and get Tuesday, 01:00 do:
calendar.add(Calendar.HOUR_OF_DAY, 2);

If you want to get Monday 01:00 do:
calendar.roll(Calendar.HOUR_OF_DAY, 2);

Comment: Sorry for my late, @Nikos Paraskevopoulos
I have checked your answer and it doesn't work for me. My code is something like this:
Calendar now = Calendar.getInstance(t); int hours = 65;
now.add(Calendar.HOUR_OF_DAY, horas);

Now is a Calendar instance. Well, if you throw this code, you dont get 2 days in the future (because of 65 hours...), I just get 65 hours more... :(
Answer: I believe that using the normal add() method from Calendar you can be in control of the hours to be subtracted, considering the passing of one or more days. Please see this example that removes 5 days and 3 hours:
public void changeDate() {

    SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm aaa");
    Calendar calendar = new GregorianCalendar(2013, Calendar.MARCH, 12);
    String date1 = sdf.format(calendar.getTime());
    System.out.println("Date1: "+date1);

    //Remove 2 days and 2 hours
    calendar.add(Calendar.DAY_OF_MONTH, -2);
    calendar.add(Calendar.HOUR_OF_DAY, -2);

    String date2 = sdf.format(calendar.getTime());
    System.out.println("Date2: "+date2);

}

If you want to remove an hour but prevent the day to change then use the roll() method instead

Add/Sub hours to my Calendar object


ActiveMQ Artemis and multiple DLQs

Question: I have many queues, i.e
my.queue.no.1
my.queue.no.2
my.queue.no.3
my.queue.no.4

And I want to redirect unsuccessful messages to DLQ, but I don't want to mix messages from all queues to a one DLQ.
Is it possible to have multiple DLQs?
i.e
my.queue.no.1
my.queue.no.dlq.1
my.queue.no.2
my.queue.no.dlq.2
my.queue.no.3
my.queue.no.dlq.3
my.queue.no.4
my.queue.no.dlq.4

P.S I'm using Artemis 2.16.0
Answer: ActiveMQ Artemis can automatically create the defined dead-letter-address and a corresponding dead-letter queue when a message is undeliverable enabling the auto-create-dead-letter-resources address setting. The dead-letter-queue-prefix address setting can be used to define a prefix used for automatically created dead-letter queues, i.e. to create DLQ.my.queue.no.NNN queues under the DLA address:
<address-settings>
   <address-setting match="my.queue.no.#">
      <dead-letter-address>DLA</dead-letter-address>
      <auto-create-dead-letter-resources>true</auto-create-dead-letter-resources>
      <dead-letter-queue-prefix>DLQ.</dead-letter-queue-prefix>
      ...

Comment: @JustinBertram yes, you are right, `auto-create-dead-letter-resources` needs to be true, thanks, I have updated the answer.

ActiveMQ Artemis and multiple DLQs


Show $F_{n+1} \cdot F_{n-1} = F_n^2 + (-1)^n$ for all $n \in \mathbb{N}$

Question: By calculating for $n\in \{1,2,3,4,5,6,7\}$, I've formulated the rule
\begin{equation}
F_{n+1} \cdot F_{n-1} = F_n^2 + (-1)^n,
\end{equation}
where $F_n$ is the $n$th fibonacci number. I want to show that this is true for all $n \in \mathbb{N}$.
I tried using induction, with $n=1$ as the basis step, but didn't get very far:
For the induction step, we assume the formula holds for a $n = k$, and checks for $n=k+1$:
\begin{align*}
F_{k} \cdot F_{k+2} &= F_{k} \cdot (F_{k+1} + F_{k})  \\
&= F_k \cdot F_{k+1} + F_k^2 \\
\end{align*}
If somehow $F_k \cdot F_{k+1} = (-1)^k$, then I would be done. But I don't see how that's possible.
Is there a better way of proving this, maybe without using induction? Or am I just going about it the wrong way?
Comment: There must be many questions about this. When I try to [search for $F_{n+1} \cdot F_{n-1} = F_n^2 + (-1)^n$](https://approach0.xyz/search/?q=%24F_%7Bn%2B1%7D%20%5Ccdot%20F_%7Bn-1%7D%20%3D%20F_n%5E2%20%2B%20(-1)%5En%24&p=1) or
[for $F_{n+1} F_{n-1} - F_n^2 = (-1)^n$](https://approach0.xyz/search/?q=%24F_%7Bn%2B1%7D%20F_%7Bn-1%7D%20-%20F_n%5E2%20%3D%20(-1)%5En%24&p=1) in Approach0, I get some reasonably looking results. You can try a few more similar queries.
Answer: Use the induction hypothesis to replace $F_k^2$ by $F_{k-1} \cdot F_{k+1} - (-1)^k$.
Comment: Very good idea. +1
Answer: This is Cassini's identity. It has a nice proof using determinants:
$$
f_{n-1}f_{n+1} - f_n^2
=\det\left[\begin{matrix}f_{n+1}&f_n\\f_n&f_{n-1}\end{matrix}\right]
=\det\left[\begin{matrix}1&1\\1&0\end{matrix}\right]^n
=\left(\det\left[\begin{matrix}1&1\\1&0\end{matrix}\right]\right)^n
=(-1)^n
$$
This matrix formulation of Fibonacci numbers is well worth knowing and easily proved by induction:
$$
\left[\begin{matrix}f_{n+1}&f_n\\f_n&f_{n-1}\end{matrix}\right]
=
\left[\begin{matrix}1&1\\1&0\end{matrix}\right]^n
$$
Comment: Very nice proof, never thought using Q-matrix :o
Answer: We can prove the rule without induction using Binet's formula
$$F_n = \frac{\varphi^n - \psi^n}{\sqrt{5}}$$
where
$$\varphi = \frac{1 + \sqrt{5}}{2} \qquad \psi = \frac{1 - \sqrt{5}}{2} = -\frac{1}{\varphi}$$
so that
$$\varphi\psi = -1 \qquad \frac{\varphi}{\psi} + \frac{\psi}{\varphi} = -3 = 2 - 5$$
Then
\begin{align}
F_{n+1} F_{n-1} & = \frac{\varphi^{n+1} - \psi^{n+1}}{\sqrt{5}} \cdot \frac{\varphi^{n-1} - \psi^{n-1}}{\sqrt{5}}\\
& = \frac{1}{5}\left(\varphi^{2n} - \varphi^{n+1}\psi^{n-1} - \varphi^{n-1}\psi^{n+1} + \psi^{2n}\right)\\
& = \frac{1}{5}\left(\varphi^{2n} - \left(\frac{\varphi}{\psi} + \frac{\psi}{\varphi}\right)\varphi^n\psi^n + \psi^{2n}\right)\\
& = \frac{1}{5}\left(\varphi^{2n} - (2-5)\varphi^n\psi^n + \psi^{2n}\right)\\
& = \frac{1}{5}\left(\varphi^{2n} - 2\varphi^n\psi^n + \psi^{2n} + 5\varphi^n\psi^n\right)\\
& = \left(\frac{\varphi^n - \psi^n}{\sqrt{5}}\right)^2 + \frac{1}{5}\cdot5(\varphi\psi)^n\\
& = F_n^2 + (-1)^n
\end{align}
Answer: The Catalan's identity tell us that $$F_{n}^{2}-F_{n+r}F_{n-r}=\left(-1\right)^{n-r}F_{r}^{2}
 $$ so taking $r=1
 $ we have $$F_{n}^{2}-F_{n+1}F_{n-1}=\left(-1\right)^{n-1}
 $$ as wanted. It is also called the Cassini's identity.


Which bosses have an enrage timer and what are their effects?

Question: We already know that the Butcher sets the whole room on fire if you fail to kill him in 3 minutes.
Are just the end-of-act bosses that possess an enrage timer?
What are their effects? Is the timing the same for every one of them? Does the timer depend on the group size?
Comment: Here is a [timer](http://diablo3enrage.com).
Answer: Since patch 1.0.4 Elite packs no longer enrage, and all boss enrage timers only take effect on inferno difficulty.
Boss Enrage Timers
Boss enrage timers appear to be specific for Inferno difficulty only
The Butcher - will set fire to all of the platforms in his chamber simultaneously if you fail to kill him within three minutes.
Ghom - will begin spawning 'Gas Clouds' more frequently after four minutes.
Zoltun Kulle - will enrage, using his 'Ceiling Collapse' ability more frequently, and for more damage after three minutes.
Belial - Enrages after three minutes in phase 3, increasing the number of green pools spawned, which will be spawned across the entire platform.
Cydaea - will enrage after four minutes, causing spiderlings to spawn more frequently.
Rakanoth - will become more aggressive after three minutes.
Comment: @ThierryLam no, they're all difficulties I believe, certainly Nightmare, Hell and Inferno (the screenshot is of a level 55 in Hell)
Comment: @kalina Could you update your post with 2.0.1 (post Reaper) enrage timer information?
Comment: Does the enrage timer appear on all difficulties or just inferno? If the boss or elite mob is enraged, are there any visual indications that tell you so?
Comment: @ThierryLam elites that have enraged have a skull/crossed bones above their head with a red background to it as per [this picture](http://i.imgur.com/Xai1l.jpg)
Comment: @ThierryLam I have updated my answer detailing this more clearly, and added the incoming changes for the 1.0.3 patch.
Comment: What about enrage timer on champions and elite mobs? Are they on inferno only too?
Comment: I just have to add, Belial's enrage means he will constantly spam the exploding pools, and also at a far greater rate.  Making his fight almost impossible on inferno once he enrages.
Comment: Are there any details on what exactly "Out of Time" does?
Comment: @bwarner tooltip simply says "Combat against an Elite monster has grown more difficult, you are now taking damage over time". However, in this affect seems to ramp up over time, resulting in the initial ticks not hitting for a great amount but steadily growing the longer you stay alive against the enrage. [Video demonstration](http://www.youtube.com/watch?v=jSnkwiLalF0).
Comment: Sounds like the enrage timer for elites is going away in 1.04
Comment: once the patch is released I will update my answer
Comment: Belial's enrage is the fourth wave of pool spawns, for people wanting an in-game cue to track enrage timers.
Comment: Are you sure Cydaea has an enrage?  She's not listed on the [boss enrage list when they moved enrages to Torment 1+](http://us.battle.net/d3/en/blog/12671560/patch-201-now-live-2-25-2014##Bosses).
Answer: I've hit enrage timers on Blue and Yellow mobs before.
As soon as timer hits, the mobs did instant/constant AOE damage. I was playing on inferno, and the effect was hitting me for 5k dps
I'm not sure of the time it took for these mobs, but I do know it was at least 3 min. I would say it felt close to 10 min, but game time always seems longer. It was a mob of 3, for the record
I doubt these have to do with enrage, but I know that if you haven't killed Diablo within like 2 or 3 minutes he does that colorful purple blast that hits pretty hard. My friend said Azmodan's Hell's grasp type attack starts covering the entire map after 3 or 4 (reported for inferno).
Comment: The champions on inferno do enrage if you don't kill them fast enough. They get a red icon over their head, and just being in their presence will start doing damage to you every second. It starts off small (around 1k) and will rapidly increase in damage (One death of mine was due to 8k ticks)
Comment: @Twong Hell's grasp is the pool of blood?
Comment: @QAppei yes, Hell's Grasp is the 'defile' style effect, the growing pools.
Answer: All bosses in Inferno difficulty have soft enrage timers.
Most elites in hell, all in inferno, also have soft enrage timers.
Comment: This doesn't answer the question.  Indeed, all it does is acknowledge that bosses and perhaps elites, have enrage timers.
Comment: @fbueckert There have also been reports of Belial and Azmodan not having an enrage timer, so this answer, unless supported by further proofs, may be outright wrong.
Comment: @Kappei Just to add it took me 6 minutes to kill Belial and never noticed any enrage timer.


django model get field method

Question: I have a requirement, when a field say Price in a django model Lead is accessed I have to apply some business logic and update the price.
I can accomplish in Serializers / Views. However this object is accessed by several views and hence its not a viable design to have a code in several place.
So i'm looking for a way where i can get control like get_price(self).
class Lead(models.Model):
    price = models.IntegerField(_('price'), default=10)

    def get_price(self):
    ''' Looking for something like this '''
    .. Logic ...
    return self.price

get_price to be called when any serializers/ views access this model. The issue is get_price is not getting invoked when this model is accessed.
Comment: `return self.price` inside your `get_price()` ?
Comment: the issue is get_price is not getting invoked when this model is accessed ?
Comment: It won't. You have to call `get_price()` explicitly. I don't know if there's any method to be invoked whenever the model is accessed.
Comment: Yeah thats what i found. if its a serializer then we can have a method. so on access of serializer we can update. however in this way I have to update atleast 3 serialzier, which is not a great design. so looking for django models
Comment: So you want to update price field when access to Lead Object?
Comment: Yes, I want to update the price when some one get's the value. However will not change if someone set's it
Answer: you can use the property method of the class. Which will access through the objects. You can just include that fields in the serializer.
class Lead(models.Model):
    price = models.IntegerField(_('price'), default=10)

   @property
   def total_price(self):
      ''' Looking for something like this '''
      .. Logic ...
      return self.price

now you can include total_prcie field in serializer.
class LeadSerializer(serializers.ModelSerializer):
     class Meta:
          model = Lead
          fields = ('total_prize', )

Comment: I'm ok with this. but the only issue with this solution is we have to edit the serializers. What i'm looking for is a solution without touching serializers. This object will be accessed by several other objects, So would wish this logic to be in one place
Answer: I completed this task in a very different way,  I had to create another table known as TrackLead Table to track when changes where made.
Later in __init__ function i updated the price field when required. I didnt find anyother way to complete it. However its working now .

django model get field method


range.insertNode() is not inserting text node as expected

Question: I am creating a chrome extension. Basically, the if the user clicks a content menu option, I want to insert HTML format tags before and after the selected text.
The tags are being added in an event page which, after adding the format tags, fires off the new value to a content script in the 'paste' key of the message object.
The code for my content script is as follows:
chrome.runtime.onMessage.addListener(handleRequest)

function handleRequest(message, sender)
{
    if (message.paste!==undefined)
    {
        var newNode = document.createTextNode('');
        newNode.innerHTML=message.paste;

        var cursor = window.getSelection().getRangeAt(0);
        cursor.deleteContents();
        cursor.insertNode(newNode);
        alert(newNode.innerHTML);
    }
}

I thought I was doing this correctly, because according to this

If the new node is to be added to a text Node, that Node is split at the insertion point, and the insertion occurs between the two text nodes.

However, the result of clicking the context menu option is simply the deletion whatever text was selected. The new text is never added, but no errors are printed to console.
I am aware that this will not work for stuff in input elements or text areas, right now I am just trying to get it work on regular text on the page.
The contents of the alert popup are, as expected, the selected text surrounded in formatting tags.
Can someone explain what I am doing wrong? should I not be editing the HTML of a text node? Is there some last step that I am missing to make the text appear?
Demonstration of error:
If I highlight the title of this question, the following alert box appears(I clicked the strikethrough option). Notice that the title has disappeared from the page.
Comment: I don´t kwon if I understand you correctly. You put de message, deleting all. Maybe you need to do: `node.innerHTML = node.innerHTML + message.paste`. Putting all messages in the same node.
Comment: There is only a single message value. It  lies in the paste key.   For example, If I select  the text "fooBar" and click "bold" the paste key will contain "fooBar    this is being confirmed with the alert box
Answer: The object created by document.createTextNode('') doesn't have an innerHTML property. If you want to replace its content, you can do as follows:
var newNode = document.createTextNode('');
newNode.replaceWholeText(message.paste);

That looks like it will probably break the rendering if you're doing it with HTML content though, so either you'd have to get the parent container and edit its innerHTML directly, or wrap your new node in an element of some kind, if appropriate, as follows:
var newNode = document.createElement('b');
newNode.innerHTML = message.paste;

Comment: In javascript, you can easily append new properties to existing objects - which is what you've done. But it's not how the content of the node will be accessed when you add it to the DOM. To prove this, try setting an initial value in the constructor, like var newNode = document.createTextNode('FOO');
And then test it. When you add it, rather than the title being missing, I'm certain it will be replaced with FOO from the constructor.
Comment: Sure, now addressing your second comment - I would use the elements list here: http://www.w3schools.com/jsref/default.asp
Really the highlights for formatting are going to be: "i", "b", "u" for italic, bold, underline - respectively, "del" for strikethrough. I'm inclined to say "span" for either no formatting or if you want something with a style attribute so you can do colors, for example. The other thing is you could use createElement("span") and then use innerHTML on that to put in whatever you want, as long as you don't mind that in the markup the edited section will be inside a span tag.
Comment: if text nodes do not have the innerHTML property, then why is it that alert(newNode.innerHTML) returns the value of message.paste as expected?
Comment: Also, If I choose the latter route, where can I find a list of HTML tag names that correspond to the various elements I want to create? The fact that I can not find a list is what stopped me from doing that in the first place because I don't know what to use as a parameter to create a strike through element, for example


How can I 'know' where I am clicking in a D3 tree with several label per nodes

Question: I'm making an orgchart with D3 tree. In each node I have several ID. I'd like to click on my ID and get this ID in a pop-up. So far I can get ALL the node's IDs when I click on ONE ID of the node.
To be precise, I use a JSON where ALL my IDs are sotred, and the way I display ALL my node's IDs is :
<code>.on('click', function () {
    window.alert(d.data.id);
})
</code>
So I suppose I need an X variable to know on what ID I'm clicking and display with :
<code>.on('click', function () {
    window.alert(d.data.id[X]);
})
</code>
The Question is, how can I get this X, OR is there a better way to achieve that (I dont't really know js)
I'm really stuck on this, thank you for reading.
EDIT : I add more of my code for clarity :
<code>    nodeEnter.append('text').each(function (d) {
    var j = 0;
    while (d.data.id[j] && d.data.id[j] != "") {
        d3.select(this)
            .style("fill", "black")
            .style("text-anchor", "middle")
            .attr('cursor', 'pointer')
            .on('click', function () {
                alert(d.data.id[j]);
            })
            .append('tspan')
            .text(d.data.id[j])
            .append('tspan')
            .text(d.data.label[j]);
            j++;
    }
})
</code>
id is an array of ID in the JSON. Each node contain an array of id. So I need to bound "j" and the things I write (id and label).
Comment: don't use `while(cond) { ...; j++;}` Use a `for` loop. Do not add the click handler to the `text` but to the `tspan` elements, then you can get the `text()` of the clicked element.
Comment: Your question is about the data, so how is the json data looks like that you used for binding? i.e. If you have `.data(json)` somewhere in your code, what it is looks like?
Answer: There is a better way
Add hidden HTML field to each node and on click find that field and get its value
<code>.on('click', function () {
    alert($(this).find("[type=hidden]").val());
})
</code>
Comment: I tried this (maybe the wrong way) but it listed all the IDs of the node. In answer you say "Add hidden HTML field to each node" BUT I have severals IDs in ONE node. So adding a hidden value to each ID leads to same result.


"error: no matching function for call to 'std::priority_queue::priority_queue(int)' priority_queue pqueue(4); "

Question: I tried to allocate memory to the priority_queue using the constructor, but getting the below error:

No matching constructor for initialization of 'priority_queue pq(3)'

why this is not working in priority_queue but working correctly in vectors?
#include <iostream>
#include <queue>
using namespace std;

int main()
{

priority_queue<int> pqueue(4);
pqueue.push(3);
pqueue.push(5);
pqueue.push(1);
pqueue.push(2);

}

Comment: Even for `std::vector` this would not just allocate memory, but initialize it as well. Your example would yield a vector containing (0,0,0,0,3,5,1,2). Be aware of that.
Answer: related question
std::priority_queue doesn't have such constructor, but the below code implements what you want:
std::vector<int> temporary_container(4);

std::priority_queue<int, std::vector<int>> pqueue (comparator, std::move(container));

Also if you want not to change the size of queue and only reserve memory, you can do it like below:
std::vector<int> temporary_container;
temporary_container.reserve(4);

std::priority_queue<int, std::vector<int>> pqueue (comparator, std::move(container));

Using this ways, you should define your comparator and pass it to the constructor.
Comment: @HoseynHeydari `queue` has its own concept. It's not `vector` and we won't access randomly to each element or change their value, so maybe it's not useful generally to en-queue several elements with a value of `0` (which are all equivalent), at starting. Anyway, this constructor is not implemented for `std::queue` and that is the reason we can not use it.
Comment: You didn't mention any difference between priority_queue and vector which answer the question: "why this is not working in priority_queue but working correctly in vectors?".
Answer: A std::priority_queue has a restrictive interface, isn't the same thing as a std::vector and doesn't have that constructor.
See https://en.cppreference.com/w/cpp/container/priority_queue/priority_queue for constructor summary.
To fix the compile error, you may just do instead:
priority_queue<int> pqueue{};

Comment: Actually, you can use constructor (3) and pass in a preinitialized `std::vector`. Doesn't help for memory allocation though, as it just copy constructs the internal container.


js function for multiple variables

Question: So, I have two js variables that i use a lot:
var rhpp = jQuery(this).parents('.rhp');
var rhp_id = rhpp.data("pi");

For example:
function my_function_1 (){
   jQuery(document).on('click', '.button_1', function (e) {
      var rhpp_1= jQuery(this).parents('.rhp');
      var rhp_id_1 = rhpp_1.data("pi");
      //do something
   });
}
function my_function_2 (){
   jQuery(document).on('click', '.button_2', function (e) {
      var rhpp_2 = jQuery(this).parents('.rhp');
      var rhp_id_2 = rhpp_2.data("pi");
      //do something
   });
}
function my_function_3 (){
   jQuery(document).on('click', '.button_3', function (e) {
      var rhpp_3 = jQuery(this).parents('.rhp');
      var rhp_id_3 = rhpp_3.data("pi");
      //do something
   });
}

Because of it, i want to make this into a function that I can reuse:
function RHP_PARENT(a, b) {
    var a = jQuery(this).parents('.rhp');
    var b = a.data("pi");
}

Then, RHP_PARENT("rhpp", "rhp_id");
of course, it is not right. I am not too familiar with how to make a function for variables.
Could someone show me?
Thanks!
Comment: Could you elaborate what you're using this function for? What do you mean by "function for variables"?
Comment: Do you mean you frequently need to access the "pi" value?
Comment: The keyword `this` is scoped to the function. It might be helpful to create a jsbin of the working code so we can see the intent.
Comment: Sorry for the confusion. I added three functions to elaborate it more. Bottom line is that, I want to make these two variable as a function so I don't need to repeat it every single function.
Answer: You could create a function which returns both of those values.
function getRhpParent(element) {
  var rhpp = jQuery(element).parents('.rhp');
  return {
    rhpp: rhpp,
    rhpp_id: rhpp.data("pi")
  };
}

// Usage
var temp = getRhpParent(this);
var rhpp = temp.rhpp;
var rhp_id = temp.rhp_id;

Comment: This is something I didn't think about. Thanks for the help! =)
Comment: Looks a bit buggy. Pass jQuery(this), not this. and then use the element parameter in the function...
Answer: You could do something like this:
function RHP_PARENT(that) {
    var a = jQuery(that).parents('.rhp');
    var b = a.data("pi");
    return { parents: a, data: b };
}

This allows you to write:
var rhp_id_1 = RHP_PARENT(this).data;

Comment: Thank you! Learned something new =)
Answer: Do you intend to access those variables outside of RHP_PARENT?
If so you should instantiate a and b outside of the function.
Do you intend to access a and b as properties of RHP_PARENT?
In which case, you may want to do the following:
var RHP_PARENT = {
  'a': (function(){
    jQuery(this).parents('.rhp');
  })(),
  'b': (function(){
    this.a.data("pi");
  })()
}

It's not entirely clear based on your question what your use case is, so it's difficult to formulate a single answer.
EDIT:
It seems like you updated your question, here are two viable solutions to your problem.
The following code will loop over all elements which have classes that begin with "button". This solves for the homogenous use case:
$("[class^='button']").each(function(){
   $(this).click(function (e) {
        var rhpp = jQuery(this).parents('.rhp');
        var rhp_id = rhpp.data("pi");
        //do something
    });
})

The following solution solves for a more general use case and is a bit more flexible. The advantage here is that the business logic for getting rhhp and rhp_id is broken out into helper functions, allowing it to be more reusable. You may also reference other functions within the same object by using this:
var my_functions = {
  get_rhhp: function(el){
     return jQuery(el).parents('.rhp');
  },
  get_rhp_id: function(rhhp){
     return rhhp.data("pi");
  },
  "my_function_1": function(){
    jQuery(document).on('click', '.button_1', function (e) {
        var rhhp =  get_rhhp();
        var rhp_id = get_rhp_id(rhhp);
        //do something
    });
  },
  "my_function_2": function(){
    jQuery(document).on('click', '.button_2', function (e) {
        var rhhp =  get_rhhp();
        var rhp_id = get_rhp_id(rhhp);
        //do something
    });
  },
  "my_function_3": function(){
    jQuery(document).on('click', '.button_3', function (e) {
        var rhhp =  get_rhhp();
        var rhp_id = get_rhp_id(rhhp);
        //do something
    });
  }
}

Comment: Thank you for the help! =) I will give it a try for sure!

js function for multiple variables


TYPO3 Extbase sorting child object by another field as "sorting" (f.e. datetime)

Question: There's the way to sort childs via 'foreign_sortby' => 'sorting' which works perfectly. But it's not possible to use that in my case:
I don't wanna sort it via 'sorting' - I need to sort it via 'datetime' and that leads into problems if I set that as 'foreign_sortby', because it overwrites the field when I save the parent. I seams to fill that with sorting integers which makes totally sense, but destroys my entries.
There's as well a 'foreign_default_sortby' which seamed to be perfect for me, but that just sorts the backend, not the frontend. :/ Any Idea?
I need the first and the last child in my model, after sorting via dates - sometimes they are not created in the right order, that's why it's important to sort that first.
TCA:
    'events' => [
        'exclude' => false,
        'label' => 'LLL:EXT:database/Resources/Private/Language/locallang_db.xlf:tx_database_domain_model_production.events',
        'config' => [
            'type' => 'inline',
            'foreign_table' => 'tx_database_domain_model_event',
            'foreign_field' => 'production',
            'foreign_default_sortby' => 'date ASC',
            'maxitems' => 9999,
            'default' => 0,
            'appearance' => [
                'collapseAll' => 1,
                'levelLinksPosition' => 'bottom',
                'showSynchronizationLink' => 1,
                'showPossibleLocalizationRecords' => 1,
                'showAllLocalizationLink' => 1,
                'enabledControls' => [
                    'info' => true,
                    'new' => true,
                    'dragdrop' => true,
                    'sort' => true,
                    'hide' => true,
                    'delete' => true,
                    'localize' => false,
                ],

            ]
        ]
    ],

Comment: Can you please also add the full TCA of your field?
Comment: just added the tca ;) hope that helps. ;)
Answer: As you have noticed Extbase does not support foreign_default_sortby. (There is a feature request for this in the TYPO3 Forge.) And unfortunately also foreign_table_where is ignored even though this is actually added to the ColumnMap built by the DataMapFactory.
So your only options are to perform the sorting in your own code, e.g. in the getter of your ObjectStorage property. Then you can quite easily get the first and last object in your template or some custom getters like getFirstEvent() and getLastEvent() / getMostRecentEvent(). Notice that this requires loading all related objects which can impose a penalty on your memory usage depending on your usecase.
Aside from that you could also add custom methods to your EventRepository like findFirstByProduction() and findLastByProduction() given that Production is your local domain model with the events relation. This mostly makes sense for a detail view where you process a single Production instance anways.
Comment: yeah I thought about that, but that just makes sense in a single view as you say. it's more about a solution for list-views. But thx for your infos.
Answer:
This might be the ugly solution but working one..

Let's consider following scenario
$multiObjects = $blog->getPosts();

//first debug output in the screenshot
TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($multiObjects);

//Convert that into array (inner objects will remain the same)
$multiArray = [];
foreach ($multiObjects as $multiObject) {
    $multiArray[] = $multiObject;
}

//Second debug output in the screenshot
TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($multiArray);

//Now we can apply usort over it
usort($multiArray, function($first,$second){
    return strcmp($second->getUid(), $first->getUid());
});

//Here child objects within array will be sorted in descending order of their UIDs
TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($multiArray);

Note : This will be required in case where records are fetched with createQuery method of repository

The final output
Comment: Yeah sure. I always can do things manually. But it's a question of resources cause I add an additional sorting although you could already get a sorted query before.

In my case we're talking about thousands of entries. It would work, but it is much slower with a huge amount of data. Would be really nice if the core team would implement a working sorting for childs - out of the sort by mode that always wants to make an automatically sorting.
Comment: Now you can make childs sortable and sort them manually. You can sort childs in the backend tool as you want to, but you cannot tell the system what's the sorting for frontend, so you have to sort everything in fluid again. If you wanna have a first or last object then, but in the wanted sorting it becomes to get very tricky.
Comment: For my project I added now additional fields which have already the right objects as single-relation. That makes the system much faster. So I use an action to update all important relations with a click. That sets the first and last child as fixed field entries and adds some other fields as well.

I was just confused that typo3 doesn't have a nice way for that. I guess I'm not alone with this sort of needed features. And you have a getObject()->first() and getObject()->last() [or end()]. But that's senseless if I cannot tell the system how to sort the child's.  At least sometimes.


Problem in installing gimp-plugin-registry

Question: Using Ubuntu 11.04.. Updated gimp 2.6 to gimp 2.7. But have problem in installig gimp-plugin-registry
rajesh@rajesh-System-Product-Name:~$ sudo apt-get install gimp-plugin-registry -y

[sudo] password for rajesh:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies.
 gimp-plugin-registry : Depends: gimp (<= 2.7) but 2.7.3-2011052002~nn is to be installed
E: Broken packages

Answer: I suggest you to upgrade to Gimp 2.8
GIMP 2.8 stable installation
If you're upgrading from an older GIMP version please visit the link and pay attention to the 'dist-upgrade' command http://www.webupd8.org/2012/05/gimp-28-stable-finally-available-for.html (also if you want to revert to GIMP 2.6.x)
If you're just installing GIMP for the first time on your current system install:
sudo add-apt-repository ppa:otto-kesselgulasch/gimp
sudo apt-get update
sudo apt-get install gimp

GIMP Plugin Registry for GIMP 2.8 installation
sudo add-apt-repository ppa:otto-kesselgulasch/gimp
sudo apt-get update
sudo apt-get install gimp-plugin-registry


Where is the rubymine embedded Web Preview?

Question: Among the features the rubymine's page  mentions:
Context toolbar opening the page preview in a browser or in an embedded Web Preview.
I would like to have the web preview in the IDE, is it possible?
Answer: There used to be a web preview, but it was removed from the product a long time ago because it had a lot of problems. Right now you have to use an external browser.


Creating multiple objects using the same instance

Question: I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
    private String style;

    public Fighter() {}

    public String getStyle() {
        return style;
    }
    public void setStyle(String style) {
        this.style = style;
    }
}

FightersDAO.java
public class FightersDAO {
    public List<Fighter> getFighters(){

        List <Fighter> fighter = new ArrayList<>();
        String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };

        for(int i=0; i < styles.length; i++) {
            Fighter temp = new Fighter();;
            temp.setStyle(styles[i]);
            fighter.add(temp);
        }
        return fighter;
    }
}

Demo.java
public class Demo {
    private static FightersDAO fighterDAO;
    public static void main (String [] args) {
        List <Fighter> fighters = fighterDAO.getFighters();

        for(Fighter e: fighters) {
            System.out.println(e.getStyle()); //this should output the objects, but nothing shows
        }
    }
}

Why is it null? What part did went wrong
Answer: The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();

To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();

Comment: Great! Thank you very much
Answer: private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
Answer: In your code
private static FightersDAO fighterDAO;//  here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
 List  fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
    private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
    List <Fighter> fighters = fighterDAO.getFighters();

    for(Fighter e: fighters) {
        System.out.println(e.getStyle());
    }
}

}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();


Missing operations with Axis generated Stub

Question: I have an wsdl and I want to create a java stub-client by using Axis2 (WSDL2Java).
Because the generation is made at runtime and because of the structure of the system itself, I call the wsdl2java by using reflection:
<code>    Class<?> clzzOptionParser = classloader.loadClass("org.apache.axis2.util.CommandLineOptionParser");
            Class<?> clzzEngine = classloader.loadClass("org.apache.axis2.wsdl.codegen.CodeGenerationEngine");
            String[] args = new String[]{"-uri", wsdl.getAbsolutePath(),
                "-o", myJavaCompilerComponent.getOutputPath().getAbsolutePath(),
                "-p", packageName,
                "-ap"
                };

            Object optionParser = clzzOptionParser.getDeclaredConstructor(new Class<?>[]{String[].class}).newInstance(new Object[]{args});
            Object engine = clzzEngine.getDeclaredConstructor(new Class<?>[]{clzzOptionParser}).newInstance(optionParser);

            clzzEngine.getMethod("generate").invoke(engine);
</code>
I use "-ap" - Parameter to tell the generator to include all porttypes. And though the generated stub contains inner classes (incl. Request und response classes) for all types, only the method (to call the service) of the first type is generated.
How can I enable AXIS to create everything? I thought -ap would do the trick, but it didn't work.
Answer: It worked by splitting up the WSDL file into multiple files including one operation each.


Test two text in different activies

Question: On Activity A, I click on a button and call Activity B. And then I matches if addressNickNameView from Activity B is the same on itemAddressNickNameView
<code>     onView(withId(R.id.addressNickNameView))
            .check(matches(withId(R.id.itemAddressNickNameView)))`
</code>
But I facing this problem.

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with id: 2131363004' doesn't match the selected view.
  Expected: with id: br.com.fastshop.ecommerce.mock.teste:id/itemAddressNickNameView
  Got: "TextInputEditText{id=2131362631, res-name=component_fast_edittext_edit_text_cpf, visibility=VISIBLE, width=998, height=72, has-focus=false ....
Comment: are you looking to match the value of `addressNickNameView` with `itemAddressNickNameView` or are you looking to match the actual views?
Answer: I don't think the Matcher is able to work like that across activities.  You need to capture the value from the first activity before going to the second activity, something like:
<code>@Rule
public ActivityTestRule<ActivityA> mActivityTestRule = new ActivityTestRule<>(ActivityA.class);

@Test
public void test() {
    EditText editTextA = mActivityTestRule.getActivity().findViewById(R.id.itemAddressNickNameView);
    String textA = editTextA.getText().toString();

    // Move to Activity B
    onView(R.id.button).perform(click());

    onView(withId(R.id.addressNickNameView)).check(matches(withText(textA)));
}
</code>

Test two text in different activies


Ubuntu 18.04 - Dell XPS15 9570 - Impossible to reliably suspend/hibernate

Question: Sadly I decided to upgrade to 18.04. Now I pass half of my work hours fixing bugs.
Today specialty is: suspend the laptop.
Last time I tried to suspend my XPS15 9570 I almost burned up my new 2000$ because it was running for 3 hours in my backpack instead of being suspended.
As well documented in a lot of threads, out of the box 18.04 on a lot of laptop is unable to suspend the laptop. There are official bug reports 3 years old, no solution or fix whatsoever. It will simply wake up after 5 seconds or when you close the lid (very sneaky, very dangerous).
https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1574120
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1786094
I tried everything, the only solution that works for me is the one reported here:
Ubuntu 18.04 - Dell XPS13 9370 no longer suspends on lid close
that is changing the grub config to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash mem_sleep_default=deep"
With this change the system actually suspend properly, but when it wakes up wi-fi/bluetooth adapter are completely dead, not even a reboot is able to bring them back.
Something similar is reported here
https://bugzilla.kernel.org/show_bug.cgi?id=201469
and maybe here
https://bugzilla.redhat.com/show_bug.cgi?id=1514836
I also tried to hibernate, without any success (the system will simply shut down). This is probably my fault since I'm missing a swap partition.
After passing the whole day reading and trying solution I decide to open this thread. My question is simple:
how can I, end user in 2019, suspend my laptop without shutting down wifi or other key components of my HW?
I know that I sound arrogant but I lost one day of work on a standard feature that should not pose any problem.
Thank you for any assistance, I hop you had a better day than mine.
Comment: I bought a XPS13 with 18 preinstalled and am disgusted by 18. I used to work on 16, it worked fine, but Ubuntu 18 full of regressions. I hate it and wish I had known this in advance...
Answer: Edit /etc/default/grub with

sudo vim /etc/default/grub

make sure that the GRUB_CMDLINE_LINUX line has the following items:

GRUB_CMDLINE_LINUX="nouveau.blacklist=1 acpi_osi=! acpi_osi=\"Windows 2015\" acpi_backlight=vendor mem_sleep_default=deep"

or

GRUB_CMDLINE_LINUX="nouveau.blacklist=1 mem_sleep_default=deep"

Insert acpi_osi=! acpi_osi=\"Windows 2015\ will not change screen brightness.
update grub:

sudo update-grub

reboot
after computer has restarted, try suspending to see if the laptop wakes up normally
Comment: This worked for me.
Comment: Likewise adding `GRUB_CMDLINE_LINUX="nouveau.blacklist=1 mem_sleep_default=deep"` and rebooting seems to do the trick, this is ona 9570 running "bios" 1.11.2
Answer: First answer option 2
GRUB_CMDLINE_LINUX="nouveau.blacklist=1 mem_sleep_default=deep"
did it for me.   XPS 15 9570  Ubuntu 18.04
I did not need to edit that /lib/systemd/system-sleep script.
Answer:
I stumbled across OP's option a few days ago:

that is changing the grub config to GRUB_CMDLINE_LINUX_DEFAULT="quiet
  splash mem_sleep_default=deep"

but laptop would wake up instantly.
I reactivated this old script in /lib/systemd/system-sleep/custom-xhci_hcd and then it worked:
#!/bin/bash

# Original script was using /bin/sh but shellcheck reporting warnings.

# NAME: custom-xhci_hcd
# PATH: /lib/systemd/system-sleep
# CALL: Called from SystemD automatically
# DESC: Suspend broken for USB3.0 as of Oct 25/2018 various kernels all at once

# DATE: Oct 28 2018.

# NOTE: From comment #61 at: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/522998

TMPLIST=/tmp/xhci-dev-list

# Original script was: case "${1}" in hibernate|suspend)

case $1/$2 in
  pre/*)
    echo "$0: Going to $2..."
    echo -n '' > $TMPLIST
          for i in `ls /sys/bus/pci/drivers/xhci_hcd/ | egrep '[0-9a-z]+\:[0-9a-z]+\:.*$'`; do
              # Unbind xhci_hcd for first device XXXX:XX:XX.X:
               echo -n "$i" | tee /sys/bus/pci/drivers/xhci_hcd/unbind
           echo "$i" >> $TMPLIST
          done
        ;;
  post/*)
    echo "$0: Waking up from $2..."
    for i in `cat $TMPLIST`; do
              # Bind xhci_hcd for first device XXXX:XX:XX.X:
              echo -n "$i" | tee /sys/bus/pci/drivers/xhci_hcd/bind
    done
    rm $TMPLIST
        ;;
esac

The screen briefly flashes once while suspending but it's worked 100% since I activated kernel's deep sleep parameter.


HTML window.open causing port disappear from url

Question: I am using react and trying to open new windows with a function window.open but the url that I am opening has a port number let say https://example.com:9000/?params=abc123, but the window that newly opened doesn't have the port, just https://example.com/?params=abc123.
Is there something that I could do to keep the port?
Function sample
const handleButton = async () => {
        showLoading();

        try {
            let uniqueId;
            const url = "/getuniqueid";

            uniqueId = (await postNew(url, {}));

            const newUrl = 'https://example.com:9000/'

            if (uniqueId.data) {
                const top = (screen.height - 600) / 2;
                const left = (screen.width - 1200) / 2;

                window.open(
                    newUrl + `another-url?uniqueid=${uniqueId.data}`,
                    "popup",
                    "width=1200,height=600,scrollbars=no,resizable=no,top=" + top + ",left=" + left
                );
            } else {
                throw { message: "Something went wrong. Please try again!" };
            }
        } catch (error) {
            changeErrorMessage(error.message);
        } finally {
            hideLoading();
        }
    };

Comment: you must be doing something wrong, can't reproduce your problem, but then, you've shown no code
Comment: The port doesn't just disappear on it's own. Are you certain the target url doesn't redirect? Is the real code different? I assume it's not example.com
Answer: The port number is omitted from the URL if it is reserved by the protocol according to this documentation: https://developer.mozilla.org/en-US/docs/Web/API/URL/port
Port 9000 makes it to the list here https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
Try using a non well-known port number.
Comment: so far this is might be the correct answer.
I tried 8080, it's working. 443 not working. But 21 is working (based on the Docs, it is supposed to be not working either)
Comment: no port 9000 is not a disabled port it will not automatically remove
Comment: @ryanadhi Another clue as to what ports are available to use in your current computer is to go to your System32 folder through command prompt (run as administrator) and run "netstat -ab" without double quotes. The ones with LISTENING state should be usable.


What is the geometry of points inside a square, that are equally distant from the square

Question: Image:
A visual of the problem
For the square ABCD, what would be the geometry of points that are equally distant (distance r) from all points of the square?
How would the shape written out by r look like, and is it possible to define it with a function?
EDIT: "equidistant from all points of the square" means that any point on the vertices of the square ABCD is equally distant to the shape drawn by r on the inside. A more real-life example of the problem could be seen on this image, where the square represents the seats and the problem would be "what shape should the table be, so that all people sitting on the seats (all points on the ABCD square) are equally distant to the table?". If it's a square table, it's obviously not ideal, because the person at any of the edges of the square is much further away from the table than the person in the middle of the distance AB for example.
Comment: Welcome to MSE. I think this is a better modification of your question: for the square $ABCD$, what is the geometry of the set of the points in the square such that each point on the square is at distance $r$ from that set.
Comment: Welcome to stackexchange. I don't understand what :equidistant from all points of the square" means. Please [edit] the picture to show all the points you mean, not just one along with a single line segment. Nor is it clear what kind of function you mean. In what context do you need this information?
Comment: Thank you, I have added the explanation that I hopefully addresses all of your comments.
Answer: There is no point equally distant to all points of a square. Indeed, if $P$ were such a point, then the triangle $PAB$ is isoscele, as $PA=PB$. Therefore, the orthogonal projection of $P$ on the line $(A,B)$ (sorry if the notation is unusual) is the middle point of the segment $[A,B]$, call it $I$. Such a point belongs to the square, thus $PI=PA=PB$, however, $PAI$ is a square triangle, thus $PA>PI$, contradiction.
Comment: Maybe I have explained myself badly - I'm not looking for a point P which is equally distant from all points of the square, this is obviously not possible. I'm looking for a shape whose outline is, at all points, equally distant to the square. Here's a visualization of one proposal: https://imgur.com/a/rWRkxSI

As we "slide" the r from A to to A', then to B' and B, it draws a shape that it equally distant from all points of the square (just not minimally distant, because the y value of the r for the point B' is < r). However, all points can reach the shape with the distance r.
Comment: @praznin Oh I see. So it has to do with parametrized curves. Though your question is not precise enough as not only you didn't mention that, but looking at your picture you seem to have some requirements concerning the parametrization. Please re-write your question in a clear manner.
Comment: Sorry, I lack the mathematical foundation to rewrite it in such a way. In fact, this is the first time that I'm hearing about parametrized curves. Thanks anyway @Scientifica
Comment: @praznin No problem. I lack knowledge to give a very detailed or general answer, so I can't help you much about it. Your picture is definitly one example, and you can modify it making the shape less symmetric,
Answer: If the square $ABCD$ has dimension $s,$ then the locus you want is a smaller square contained in the finite region defined by the first, and concentric with it, so that it has dimension $s-2r.$
Comment: I don't think any square can be a solution to this because https://imgur.com/a/YNTOw0Q r' > r, and all points of the outer square need to be r distant from the inner shape
Comment: @praznin I answered based only on your verbal explanation above. I'll see the picture now, though.
Comment: @praznin I didn't see any image at the linked site. I suggest you enter the image directly into the body of OP. I also suggest editing the verbal parts to more correct mirror the problem.


Does Fingers of Frost cause frost specs to act as if the target is frozen?

Question: If Fingers of Frost is active on a target, will Frostbolt, Frostfire bolt, and other spells behave as if the target is frozen?
Comment: Has this question been answered or not? My answer's been around for a while and was posted less than an hour after you asked the question and you still have not shown any sign that the question has been answered.
Answer: Yes. If Fingers of frost is successful, the target is considered to be frozen without actually being frozen. Spells that have a particular effect when a target is frozen will still benefit from this.
Answer: Finger of Frost doesn't activate on a target, it activates on yourself. According to the talent tooltip it will affect only Ice Lance and Deep Freeze, treating those spells as if the target was frozen for validity/damage purposes (for example Ice Lance will do its bonus damage against frozen targets). In short, no, other spells will NOT be treated as if the target is frozen.


Dashboard for new users

Question: I would like to ask what is the best solution for onboarding users dashboard.
Scenario A

when user login i will show them a big image to tell them that must add subscribers.

when they add 2 subscribers show the sidebar column with the list with subscribers.

and replace the image with the next task.

Scenario B

when user login i will show them a big image to tell them that must add subscribers and lock the sidebar widgets (ex. list of subscribers)

Scenario C

when user login i will show a popup for the next task.

Scenario D

Show all my dashboard and at the top of sidebar a small box with next task

Task:

Add new subscribers
Add new event
Send new sms campaign.
Send new email campaign.

The application is for event scheduler, email and sms newsletters
Comment: Please tell us what is the app about?
Comment: Maybe also look at some of the questions relating to 'Blank State' design, one of which relates to dashboards: https://ux.stackexchange.com/questions/86710/is-there-a-difference-between-a-blank-state-as-a-new-user-and-an-existing-user-w
Answer: When I interact with an app I want to feel that I am in control.  I would go with Option D simply because locking out functionality makes an app feel "over guided". I would change the small box at the top with the next task to a noticeable top-of-page banner displaying the next required task to complete the current action.
Answer: since there is business logic between the tasks (#1 happens before #2, #3 and #4 cannot start before #2 is completed), and people expect this logic (they know why they use your solution), I'd go with "D", so that people feel that they're making progress in a wizard

Dashboard for new users


node:/usr/lib64/libstdc++.so.6:version GLIBCXX_3.4.14, GLIBCXX_3.4.18, CXXABI_1.3.5, GLIBCXX_3.4.15, GLIBC_2.17, GLIBC_2.16 and GLIBC_2.14 not found

Question: While running
node -v

it shows the below error:
node: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.14' not found (required by node)
node: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by node)
node: /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.5' not found (required by node)
node: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by node)
node: /lib64/libc.so.6: version `GLIBC_2.17' not found (required by node)
node: /lib64/libc.so.6: version `GLIBC_2.16' not found (required by node)
node: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by node)

Answer: My error now fixed, I have installed nvm from here and then when i run

nvm -v

Issue remains same as i said in my question
After that doing this from stack post it got fixed
But same error came when i gave exit and run same command...
So i followed some steps from here and i run below commands
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

Even though i got same error on some points while run version change commands.
So after taught version may be problem.
Then i ran to set default version to
nvm -ls # to list versions we installed(here also mention default and LTS versions)

nvm alias default 10.5.0

If no version 10.5.0, we should install.
nvm install 10.5.0

And then excute above export command... Then its working fine


I need to be able to press a button multiple times but only have one output

Question: I want a button that, when pressed five times, outputs a signal. What redstone device should I use?
Comment: a set of latches and some gates are sufficient
Answer: What you're describing is called a unidirectional ring counter. It's a circuit with (in your case) five outputs, with only one ever on at the same time. Each time the circuit receives a pulse, the output that is on moves over by one. When it gets to the end, it starts over at the beginning again. You'll only be using the fifth output, but you need the rest anyway just so that it can count your button presses.
The design in this video tutorial is fairly compact, easy to understand, and easily extensible (up to the limit that pistons can push). It uses a pair of pistons on either end to cycle blocks between them; most of the blocks are glass, with two being a block type that will pass a signal from a redstone torch below to a repeater beside them. Some people don't like using pistons since they're noisy, though, so that's a possible drawback of this design.

The pure-redstone alternative is chaining five T Flip-Flops, and connecting the output of the last one to both your final output and the input of the first T Flip-Flop (so that it will start over once you get past 5 presses). Any of the designs at that page will work, so you can choose whichever will fit the space you have to work with.
Answer: Another, maybe simpler, way to accomplish this is this simple piston line.
It is just the same loop repeated

Things to note about this method:

All pistons here are normal, non-sticky pistons
The redstone line moving towards the output must be repeated as shown. Otherwise, the redstone power will not be conducted through the block.
The redstone line going back must be delayed a total of at least 9 redstone ticks more than the repeater going towards the output.
The redstone lines going back must not interfere with one another. This is why they are staggered like so.
The redstone lamp on the far right is the output and can be replaced with anything. If the redstone current must be kept, a simple redstone loop or RS NOr latch may be implemented.
The stone block at the beginning just has a stone button on the end. If you are using a wooden button, just increase the minimum delays for the redstone lines going back to 14 ticks more than the repeater going towards the output. ( I think. Just experiment.)


UI Kitten - RangeCalendar component is not fitting with the mobile screen width. How to handle the width of the component?

Question: UI Kitten - RangeCalendar component is not fitting with the mobile screen width. I don't see the width property in the document https://akveo.github.io/react-native-ui-kitten/docs/components/calendar/api#rangecalendar.
How to handle the width of that component?
Answer: It is taking the parent element width. We need to provide 100% width to the parent element to make the calendar fit to that element.


OpenTK multiple GLControl with a single Context

Question: Im working on a program which should have multiple views of a model. I would like to use multipleGLControls` for that.
Is there any possibility to create multiple GLControl which use the same GraphicsContext?
I successfully created this on a multithreaded enviroment, but the contexts are not shared then. So I have to load the model for each context, which is bad.
My pseudocode for a single threaded enviroment looks something like this:
glControl1.MakeCurrent();
// Render here
glControl1.SwapBuffers();
glControl2.MakeCurrent();
// Render here too
glControl2.SwapBuffers();

I tried this by creating multiple contexts on the thread but it crashed with

Error: 170" at "MakeCurrent()

of glControl2. (Even glControl2.Context.MakeCurrent(null) before switching the context didn`t work)
Maybe you have some hints which can help me.
Answer: Right after I posted this question I found the solution.
I created a new GraphicsContext on the thread I want to render my stuff.
//Here does a new thread start->
IGraphicsContext control2Context = new GraphicsContext(GraphicsMode.Default,glControl2.WindowInfo);
while(true)
{
    glControl1.MakeCurrent()
    //render
    GL.Flush();
    glControl1.SwapBuffers();

    control2Context.MakeCurrent(glControl2.WindowInfo);
    //render
    GL.Flush();
    glControl2.SwapBuffers();
}

As you can see, I'm not using glControl2.MakeCurrent(). Instead I created this new context control2Context.
Maybe this can help someone who is facing the same problem.
Comment: can you please help me on this, I have already used above line of code. But still only one glcontrol is working at a time
Comment: Please comment my answer if there is something wrong. If everything is fine, I´ll mark it as the answer.


Why my code does outputs ? (Probable logic issue)

Question: Following problem is a problem from cs50 pset6. The goal here is to search for a .txt file that represent a DNA thread and check how many times a specific string occurs consecutively. If number of cons. string matches with an individual for each DNA example, print individuals name.
I am still a newbie with python, I wrote what I meant by the lines I hope all is right. Any help is appreciated. (At the moment code does not give any outputs)
python dna.py databases/small.csv sequences/2.txt (commend line arguments,1st is the csv and 2nd is txt file)
CSV files :
name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5

name,AGATC,TTTTTTCT,AATG,TCTAG,GATA,TATC,GAAA,TCTG
Albus,15,49,38,5,14,44,14,12
Cedric,31,21,41,28,30,9,36,44
Draco,9,13,8,26,15,25,41,39
Fred,37,40,10,6,5,10,28,8
Ginny,37,47,10,23,5,48,28,23
Hagrid,25,38,45,49,39,18,42,30
Harry,46,49,48,29,15,5,28,40
Hermione,43,31,18,25,26,47,31,36
James,46,41,38,29,15,5,48,22
Kingsley,7,11,18,33,39,31,23,14
Lavender,22,33,43,12,26,18,47,41
Lily,42,47,48,18,35,46,48,50
Lucius,9,13,33,26,45,11,36,39
Luna,18,23,35,13,11,19,14,24
Minerva,17,49,18,7,6,18,17,30
Neville,14,44,28,27,19,7,25,20
Petunia,29,29,40,31,45,20,40,35
Remus,6,18,5,42,39,28,44,22
Ron,37,47,13,25,17,6,13,35
Severus,29,27,32,41,6,27,8,34
Sirius,31,11,28,26,35,19,33,6
Vernon,26,45,34,50,44,30,32,28
Zacharias,29,50,18,23,38,24,22,9

.txt file example :
TGGTTTAGGGCCTATAATTGCAGGACCACTGGCCCTTGTCGAGGTGTACAGGTAGGGAGCTAAGTTCGAAACGCCCCTTGGTCGGGATTACCGCCATTCTAGTAGTCTAACCCCGAACGCGCTCAGGCTTTGAGTTCGCGCAGCATTAAGAAGTCCATGCCGGCACCGAATGTCCCGACGACAGGCAACCAGCACGGATACCCGCCTTGAAGGCGCAATCAGTAGGTCGAGTTACAGAGGCTCCCCCCGAGCTTGTGCTTCCATTGAGTAGGGGCTATAGATATGTAGCACTCAGGTTTAGTAGCGCCCTTTTAACAGCGAGAGCCCGCCTGGTCAGAACCGAACGGCTGATACGCGAGCTGATGGCTAGAGGATGAACACGGTCCTTCTCTTCGCTTCGATCCGGGGTAGTTTTGTAGCGAAGGATAACGCTCTGTGGATTCTCCGAGAATAATCATCAGTACGGTGTGCGTACCCTCTCTTTGATCCACGCCTGGGGCTGGACATAGTCAGGCGCATTTCATCTACTTAACCCCGGTAAGGGCCACGGGCGCGACATCTCCTTACCAGGGTTGTCTTATGCTCGCTTTTCCCAGATGATAAGCATCTCGTTGTAATGAACAGGTACCTAAGAAAACTGAGTTTCGACGACCCGTCGGCTCGTGTTCTTATCTATTGATCTAACCGAGGTGAAGCTCGCCAAAAATTTCGTAATGTAAGAGAGAAATTGAAGGGGTGAATTTTGCACTCTCGTGCATACGTCTTGCTACAATAGCAAGAGCTGTATGCGTGCGACCACTTCACTACCTCTATAGCATGCGATCTCGCAGCCCGGATTGTCGCCTCCTTTGGGCCGCAAAAACGGTATACGGACACACTGCATCTGTGAGCACGCACCAACTCGATGCGCGTAATAGGCATCTGCTCCACCCAGGGGGCAAGGGCACCTGAGGACGATCTGTTCCGAACAGTATATTTGAGCCAATGTTCTATTAGTGAAGGCAAGGTGAGGGCAACTCACACTGGTACCTCGAGGAGTAATCCGATCCATCTAAACTGGCATGCCCGTTCGAGCTCGGGGGGTTCTTGAATTTAGCTGCGTGTACCTCAGGTCTCCTGAAGGTGACACCAAAGTACAAGATAGATAGATAGATAGATAGGTAATATCTGACGTGAATTGCTTACCGCTAGTGAGCGATTTAGGTCACGTCCTCTGAAGATGTACCGTGATCATCGATGAAATGGCTCTGCAGAGCGTTGCTCTTAACTTAGTGGGAGTGTTCCTTTGCAGTCTGATGAAGTCGCTGCATGTTAACTTTGCACTAAGGGCGTTTCCGAACCCTATAGTCATCCTTATTGATTCGCCCTGTCTTACCCAGGATACACTACCGTTCGAGGCTCTTAACGTACCAACGCATGCAGTCAGAAGATGATTCACCATCCAAGCAAATCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTCTGTGGCTTTAAAGCACCGAATGTAGTTGGCCATCGGTCTCGGTCACCAATAAGACGGCCTCGTGGGTCACTCGGTCGATGATCTAGGGTCGGGTGCATAGTGTTTCAGGTCGGCGCTCAGGGTTCTTGTCAGGGAAATCTACGGGTGAGTTGGAAAGCGCCGCCAGCGAGATGCCTGTAGGCGATTAGTGTAGAGAGAGCAACATCGGAAAATTGTCCGTGGGGCGCTACGTAAGTGTTCCCAGTATTCTCGTCCAGAGTAAGTCATGCATACCAGTATCAGGCGTCTGTGTGTTACGTTGCAGTGTATCCCGGTAGCGGGAAGCGTATAGAGCGTAACAGACCTGTCCTACAGCACGCAGGATGTCGACCCTTTCTCAGGCACGATACTTCGTGTAACAGCAGTTCCGGTGTCATCTGTAACTGTTCTGTGTTCCATAGTGAAGATATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCTATCGGGCGACCCTGGCAATCAGGCGCCTGCTTATATGACAATTTGTCGCAATACGGGTCGCAGATGTATTGTCCGCATGAGTTTACGGTATCCGGAACTGTCACCGCCGATCCAATATGATCGCAAATCGGGGTGACACAATGGACCGCCGTAGATAAACCCTGCGATGCTGCAATAAGGATATGATATCGCGCGCGGGCCGTAAAACCGATCTTGGAAGGCGGGAAGTCTCCGGGAAAAACTCTCTGATAAAGCCTATTACAAGAAGAGCTCGAAGGCAAGATGGGCATGCCCCGTCGACCACACGGGCAAGCTCTGAGAATCGATGTGGTCGCTTAACCAACCCATACGGAGTGAACGAGACCACGCGGGCGGTTCTTGGTACGCATGATTCCTATTGGTTCTGCCGGGCGTGTGCAGGATTGTTCACTCCCCACCCTGTCGCTCACGAACGCGCTGGTTGCTTAAACCGACCGGAAATTCTGTAGCCGCCCCGTAAGTTTAACGCTTTGAAATACTCCACATGTGCGTACCGGGTCTGATCGCTTACGTGGCGCCACTATGTTAGGAGCTCATAGATATCGATGAATCAAATGTCTTTCATCGCTCCTTAAACAACCTGACGTATTCGCAAAATTGCGCGTATTGAGAAGGGAAAGTTAAAGGAACGATAACAATGAGTCTGCTTTCACCGGCTGCATAACGGGATCGCGCGCTATGGGATTTCCTAACTATAATTCGTGTCGATACTCAGACGCGTTGTACAGGTAAGAAGTCGGCGGGACAGTATTTGAGAAGGGGCTCTGCGGCACCAACGCCGAGCTGTATCAGGGGGGTTAATGTGTAGCGGGCATATAACACAATACAGCCCGCGGCGCGTCGTGGTTACCGTAGAATGAATGAATGAATGAATGAATGAATGAATGAATGAATGGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAAGAAACACCGGAGCTAGGATCCACGACTACCAGTGGGAAACTGTGAATTGTGCATGGTAATTAAAGGATGACTGGTCAACACCGGTCTCCACGGGCGTTAAACAACCTCGCTCCAGTCAATCTCTAGCGGTGGTTGTGGCAGCTTATTCCTGGAGGTAATACTCTTCCGGGCCCACTAAAAATGTAACGAAGTCGAGGTTGGGTCAGGGGATTGAGTGGGGGCGACTCACTGATTCCACCAGGAATTGTCGTCAATCGCGACGTACTTTGAGCCTTGTATCTTGGCGTTTCTTGTTGGTACGCGGCCGTGTTCGTGAATCACGACGTCGTTCATGATTCATCCGTCCAAGCCTAGACCTAGCGTAAAAACGGTGTCGATCTGTGCTCCAACCGATGGATGGTTTTTACACAAGTGAACTTCGAGGCTGTGGGACAAACAGCACAACTTGTTCACTGCTGACCGTGGTACTAAACCACGCTTGCTTTCAGCCCTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTTTTTTTCTCAGATGCGGATCAAGGGTTACTCGAGCCGTTCTGAGGTCCTAAAATTTTAGCCCTTGGTGTTAGCTTCGGTTTAAGAACGTAGGTGCGACGCGGGGGTCCTAGAGCTCCGCGATCTGCACTCCCCACCTGGCACCAAAACGAATCCTGCATAACGGCTCTCTGTGCATGGGGGATGGTCGCAACAACGAGCATAGCTGGCATCACTTCGTTTGCTGTGGATTGCTGTTTTATACAGAATACGGTGGTGATCATCAAAGGAAGCATAATCCACATCGGGCACCCCGGGCCATCGTGCGTTCCCTTATAGCCGGCTTGCATGTTGGGGGAGGAGTAAGGCCGGTAACGTCTCGCAGCACTGTCGCGTAACACAGGTACATCTTTATTTCCGGTGCTGTAGAAGTGGTTTTTCGAAGGCGTAACCCAGAACGACTGATATAATAGTCCACTATTCCCTGGTTTAAGACTTCTACAAAGTTTTACGCAAAGTTACATGCACACTCGGCGACGTAAATATTAGCCTTGCTAAATTGCCACGGATATTAATCCCGAGCCAACCTGTTCCCACTAGCGGTCTACGGTCATAGTCCTTTGTGTAGAGCGTCATTGCGGTTGGGGCCCGTCCGCGGAGGTTCCCCTTATGATCTAACCGCGGTGCAGGTTGACTGAATGCCATACACTATAGAGAAGACGTCTAAGTAGAAACGTTCTTTAAAAATCTTGAACTGACGGCCGAGTATTATCAAGAGAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCAGATCATGCACAATAAGGTTAGAAGCAGCAAGCATGTATTCTTTGCATAGAGGCGGTAAAGCCGCCTTGCATACCCAGCAGCAGCCGCGAAGGCCTTACTCCAGAGGACAGAACTTCTCACACAGCGTCCGCATACACCGCGGACGTGACAAGGTTAGATAGCTCTAGTTTGCGGCAACCCTCGCATCAGGCCGACTCACCCGCGCTTGCTACCCGGAGGATGGGTCAAGGGATAAACATAGCACGTTAGTTAAGCCTAACGTCAGTTTTTAGAGTTTACATGCACGACTAAGTGCATCGAAATACACGCCGTTGACAGACCAACAGCGTGTCAACTGGGCCTTGAGAATTGTATCATAATAGCCAAATACGAGGCCAAGTAGTCCGACGAGAGGCACGTAGAGACCACTTTCCCTAAACGATCTGTCGCATTACCCTTTGACTCGCACCCTATGCCTTATGTTCCAAGCAGCACCGAAGTTAGATTTAAGGGCGTATCTATCGGTACCTCGGTTGGGCCGGTCCACAGCTCCAGCTGAATTAGTGCTCACCCCGCTTCGAGGTTGAGTAAGGGTCACTTTTAAAAATATGCTTAAGGGTGATTCACATGACAGTAATCGAATAGTGAGATATAAGTAGGTGCGCCCCGCGCACACATCAAAACTGTGCAGACTGAAACTGAATGCTGGAGGCTGAGGAAAATGAAGATCAGAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGTCTAGAGAAGAGTGAATGAATAGATCTGCCGCTGAATCCCCGCGTGAGGTTTTTGCGAC

Code:
from sys import argv
import csv
from itertools import groupby
#first csv cma 2nd txt
# fread from CSV file first thing in a row is name then the number of strs
# fread from dna seq and read it into a memory
#find how many times each str censequetivel
# if number of strs == with a persons print the person

checkstr = [] #global array that tells us what str to read
def readtxt(csvfile,seq):
    with open(f'{csvfile}','r') as p:#finding which str to read from header line of the csv
        header = csv.reader(p) # Header contains which strs to look for
        for row in header:
            checkstr = row[1:]
            break
    with open(f'{seq}','r') as f:#searching the text for strs
        s = f.read()
        for c in checkstr:
            groups = groupby(s.split(c))
            try:
                return [sum(1 for _ in group)+1 for label, group in groups if label==''][0]
            except IndexError:
                return 0

def readcsv(n):
    with open(f'{n}','r') as f:
        readed = csv.DictReader(f)
        for row in readed:
            return row

def main():
    counter = 0
    if len(argv) != 3:
        print("Please start program with cmd arguments.")
        readtxt(argv[1], argv[2])#for fulling the checkstr
        for i in range(0,len(checkstr)): #Do this as much as the number of special strings
            for j in checkstr: #For each special string in the list
                if readtxt(argv[1], argv[2]) == readcsv(argv[1])[f'{checkstr[j]}']: #If dictionary value that returns for that spesific str is matches to the spesific str
                    counter += 1
        if counter == len(checkstr): # if all spesific strs matches, then we found our person!
            print(readcsv(argv[1])['name'])
        #readtxt(argv[1], argv[2])
        #readcsv(argv[1])

main()

Comment: When executing the line `for i in range(0,len(checkstr)):` , **checkstr** is empty. This is a problem for sure
Comment: could you also provide an example of the command line execution command? Like `python myscript.py arg1 arg2...`
Comment: I added a `readtxt(argv[1], argv[2])` before the loop know `checkstr` should be loaded but still no outputs.
Answer: I think the answer quite simple: you forgot an else-statement.
After you check the number arguments, you must place the else-statement.
def main():
    counter = 0
    if len(argv) != 3:
        print("Please use: program <csvfile> <textfile>")        # give usage and exit
    else:
        readtxt(argv[1], argv[2])#for fulling the checkstr
        for i in range(0,len(checkstr)): #Do this as much as the number of special strings
            for j in checkstr: #For each special string in the list
                if readtxt(argv[1], argv[2]) == readcsv(argv[1])[f'{checkstr[j]}']: #If dictionary value that returns for that spesific str is matches to the spesific str
                    counter += 1
        if counter == len(checkstr): # if all spesific strs matches, then we found our person!
            print(readcsv(argv[1])['name'])
        #readtxt(argv[1], argv[2])
        #readcsv(argv[1])

main()


How to determine whether a TransparentProxy points to a valid instance

Question: Is there a way to determine whether a TransparentProxy is pointing to a valid reference?
I have IPlugin. I create a new AppDomain, load the assembly with an implementation of IPlugin, and create an instance of that implemenation. I receive a IPlugin, but under the covers its TransparentProxy. If I unload the secondary AppDomain, the instance of IPlugin (the one that the proxy points to) is gone. But the proxy is still pointing there. My program crashes (with no exceptions) when I try to access the proxy.
Psudeocode:
var domain = CreateDomain("domain");
var assembly = domain.LoadAssembly("myAssembly");
var plugin = domain.CreateObject("MyPlugin") as IPlugin;
// plugin is really a TransparentProxy to a MyPlugin

if (plugin != null)
    plugin.DoSomething("123");

UnloadDomain(domain);

if (plugin != null) // Still evaluates to TRUE!
    plugin.DoSomething("123"); // Program crashes with no exceptions

Comment: You should get a RemotingException, not a crash. Still, I would like to know the answer to this question too.
Answer: Well, since no one has suggested a proper answer, you could try this:
public static bool IsValidReference(MarshalByRefObject obj)
{
    try {
        obj.Equals(null);
        return true;
    } catch (RemotingException e) {
        return false;
    }
}

Comment: i didn't receive any exceptions. my app just dies.


How to add variable to .py file from variable explorer

Question: New to Spyder IDE. If I use the variable explorer to import data from a .csv file and create a variable (numpy array), is there a simple way to add this variable to the .py file I'm coding in?
Answer: (Spyder maintainer here) There's no way to do what you're asking for in Spyder, sorry.
Comment: bummer, but thanks Carlos!


Solvable Lie algebras. derived algebras and ideals

Question: Let L be a vector subspace codimension $1$ in $g/ g'$, where g is a Lie algebra solvable and $g'=[g,g]$ derived algebra.
Have:

$g/g'$ is abelian

In fact, if $x, y \in g$
$$[x+g',y+g']=[x,y]+g'= g'=0+g'$$
because $[x,y]\in [g,g]=g'$.

Then L is a ideal in $g/g'$

I need help the second case.
Answer: Since $g/g'$ is abelian every vector subspace $I$ is an ideal. Since for every $x\in g/g', i\in I$ we have $[x,i]=0\in I$.
Comment: Thank's, Tsemo.


Vulnerabilities roundcube

Question: For almost four weeks, since October 18th, there is a vulnerability in roundcube, including CVE-2023-5631, and the status still is: needs triage.
When will this be solved and will it get a released status so this vulnerability issue will be resolved?
In Debian this is bug has been solved long ago. This is taking too long now for a medium priority.
Answer: You're generally addressing this in the wrong space. Nobody (or at least very few) here are involved in backporting packages for the Universe repositories.
You should instead contact the MOTU (Masters of the Universe) maintainers, as indicated on the Roundcube package page (perhaps through the mailing list or on Launchpad).
Also, since nobody can look into the future, this will probably be closed as "opinion based". And finally, complaining about the state of things won't really help anything at all.
Comment: Kick thyself first. The process for patching Universe packages is that a community member (like you!) does the patching and testing. Then they contact a MOTU "Hey I have this patched package that mitigates CVE-2023-5631", with a cc: to the Ubuntu Security Team. Alternately, paid Ubuntu Pro subscribers (not free tier) can reach out to their support contact for a Canonical engineer to do the work.
Comment: Thank you for your reply. I will kick someone there. Maybe that helps and they'll start doing their work.

Vulnerabilities roundcube


Error while installing Laravel Spatie Permission

Question: While installing Laravel Spatie using the following command:
composer require spatie/laravel-permission

the following error in displayed:
Click here to show the error
How can I solve my problem to install Laravel Spatie ?
I tried to install the package via composer as follows:
composer require spatie/laravel-permission

The steps of installation in the following page
https://spatie.be/docs/laravel-permission/v5/installation-laravel
And I can't expect how to solve it?
Answer: As the error says one thing to check for is any unexpected whitespace, for example:
Verify it from .env file
FIELD=some value
vs
FIELD="some value"


Group count results by month

Question: I am trying to obtain types of attendances per year/month in order to populate a bar chart.
These are my two tables ( I know the english is a bit off ):
**presences**
ID | Id_student | Id_class | Presence
3        2           27         1
4        4           28         2
...     ...         ...        ...

**class**
ID | Id_schedule | Date_class | State
27        6        2017-12-11     1
28        7        2018-01-13     1
...      ...          ...        ...

This is my current queries, which returns ALL results instead of the intended result, which is just the current year:
   SELECT
        DATE_FORMAT(Date_class, '%Y') as 'year', DATE_FORMAT(Date_class, '%M') as 'month',
        (SELECT COUNT(distinct ID) FROM presences WHERE Presence = 0) as Faltas,
        (SELECT COUNT(distinct ID) FROM presences WHERE Presence = 1) as Pre,
        (SELECT COUNT(distinct ID) FROM presences WHERE Presence = 2) as Temp,
        (SELECT COUNT(distinct ID) FROM presences WHERE Presence = 3) as Canc,
        (SELECT COUNT(distinct ID) FROM presences WHERE Presence = 4) as FaltasTemp
    FROM class, presences
    WHERE YEAR(Date_class) = YEAR(CURDATE())
    AND
    presences.Id_class = class.ID
    GROUP BY DATE_FORMAT(Date_class, '%Y%m')

This is the result, which is also displaying occurrences from last year:
year  month  Faltas Pre Temp Canc FaltasTemp
2018 January   2     6   5    0       1

Could anyone help me identify what is missing?
Comment: You do not have a where clause concerning the date in the queries which give you the counts, so why would you expect them to return only counts over the current year?
Answer: I think you want a much simpler query:
   SELECT YEAR(c.Date_class) as year, MONTH(c.Date_class) as month,
          SUM(p.Presence = 0) as Faltas,
          SUM(p.Presence = 1) as Pre,
          SUM(p.Presence = 2) as Temp,
          SUM(p.Presence = 3) as Canc,
          SUM(p.Presence = 4) as FaltasTemp
    FROM class c JOIN
         presences p
         ON p.Id_class = c.ID
    WHERE YEAR(c.Date_class) = YEAR(CURDATE())
    GROUP BY YEAR(c.Date_class), MONTH(c.Date_class);

Notes:

Use proper, explicit JOIN syntax. Never use commas in the FROM clause.
The tables have aliases, which make the queries easier to write and to read.
The columns are all qualified (with the table name) so you know where they come from.
You don't need a separate subquery for each column.
Comment: Thank you for the answer but most importantly, your notes which will hopefully help me write better queries.

Group count results by month


Doctrine QueryBuilder addSelect with user input

Question: I'm using the Doctrine QueryBuilder in my Silex project. I'm building a query, completely based on user input. The parameters are escaped with the setParameter() function. But how about the addSelect()?
I can't figure this out, is it save to do something like this:
$stmt = $this->conn->createQueryBuilder()
    ->addSelect("`".$userinputCol1."`")
    ->addSelect("`".$userinputCol2."`")
    ->from('`mytable`')
    ->where('id = :id')
    ->setParameter('id', $userinputId)
    ->execute();

Will this prevent SQL injection in the SELECT?
Comment: Can't you use a parameter? `addSelect(':userInputCol1')`
Comment: @Veve No. Then it will be escaped in single quotes
Answer: In general, I would not pass user input straight into a QueryBuilder method, even escaping it.  I would do something like this:
    $possibleSelectFields = ['name', 'dob', 'created', 'something'];
    if (!in_array($userInputCol1, $possibleSelectFields) || !in_array($userInputCol2, $possibleSelectFields)) {
        throw new \Exception("Throw an exception, or just silently ignore the user\'s input - depending on how bad this situation is for your application.");
    }

    //...Your code as before

It's a bit more verbose, but it's much more defensive - perhaps there might be a column that query could expose that you would never want a user to be able to see - this approach avoids that problem.
Comment: That is indeed true. I will fix that issue to.