text:
Q: How users are verified when passwords are NOT stored as plain text in the database? I know it is bad to store password as plain text in DB, because if hackers gain access to the server's DB, all usernames and passwords will be completely exposed? Therefore, original passwords are passed through hash functions, afterward they are stored in DB as series of incomprehensible characters of the same length. That is a good thing for security.
But...how can the server verify if the users enter correct passwords or not? Since the users enter their passwords in their original forms (eg: whoami, ilovecomputer...), but the server store them under "hashed" forms (eg: 234203409803249580980gfdg41cdvd4, jknegnergiuhiuhdni4584234dfgbn4j....). How can the user-entered password and the sever-stored password be matched?

A: Let H be a password hashing function. One simple property of these functions is that they a deterministic, i.e. same input outputs the same value.
First time: When users register onto the website, they require the users' password, usually two fields. Now the password is hashed h = H(passwd) and stored in the database for the user.
Later time: User enters the user name and password, then the server gets the h from the database by using the user name. Hashes the currently entered password pwd, too. if H(pwd) = h then entered password is correct. Your server lets the user continue to the system.
The above are the basics of the password system, however, that is not enough. a little gist of the password hashing;

*

*For password hashing we don't use the cryptographic hashes at least directly. Cryptographic hashes are required to be fast, however, password hashing is required to be slow even controllably slow with adjustable iteration. This helps to systems to fit to desired security.

*We use salt against the rainbow attack; random salt per user will prevent the rainbow attacks. We also use pepper as server salt for domain separations.

*We require memory-hard password hashing to prevent massive GPU/ASIC/FPGA password search. See hashcat for some comparison of password hashings.

*Require threads against parallelization, too.

*We used specially designed password hashing like PBKDF2, Scrypt, Argon2. Argon2 was the winner of the latest password hashing competition. It is advised for everybody to use Argon2id in their new system.

The Final, and most important point is to educate the user about passwords. Firstly, introduce then the dicewire or similar password generation methods, and secondly, introduce them to password managers like 1passwords.

A: Here is how you authenticate users without storing their password in clear text.
You will need TWO database columns to do this. Column 1 - Password Hash, Column 2 - Salt
Column 2 - Salt is a randomly generated value that your code/system generates for each user and it is random without it ever being exposed to any UI or backend system. (I'll explain the use below)
Column 1 - Will be the HASHED value of the user's password + (concatenate) salt.
You can read more about hashing here Common Hashing Algorithms
How this whole thing works:
Hashing: Hashing is a way to create a UNIQUE value for each string based on an algorithm. The uniqueness varies based on the algorithm but unless you have a gazillion records, you should be fine. Also, the HASH value of each string is unique. Meaning the Hash of a string "test" will always be the same, lets say "123"
Salt: Salt is just a random string that is added to each password. This way the HASH value is calculated as user's PASSWORD + SALT. This ensures that even if multiple users use the same password, their Password Hash (HASH(Password+Salt)) will be unique.
Setting the password

*

*When the user set's their password, they will provide a password.

*Your code will randomly generate a "salt" value.

*A third variable PasswordAndSalt = password + salt will be created.

*Then a fourth variable hashValue = HASH(PasswordAndSalt) will be generated.

*You would then save the hashValue in Password Hash (column 1) and Salt in Salt (column 2).

Adding SALT is a counter measure so if two users use the same password, the HASH value will still be different.
Validating User
When the user enters their username and password, this is how your code will execute.
Check if the username exists.

*

*If the username exists, get its SALT value.

*Take the password user provided and concatenate the SALT value you got from DB.

*Calculate HASH value for password + SALT

*If the calcualted HASH value matches the SALT value in your DB, authenticate the user.

*Else, tell the user authentication failed.


text:
Q: Get 404 error when accessing a public file's meta data on Google Drive I have a file which is shared public.
https://drive.google.com/file/d/1SuYrjwWJKlNmSEr6CpcOVFUT1MpGqLe3/view

But when I use Google API to access the file's meta data, the result is 404 not found.
https://www.googleapis.com/drive/v3/files/1SuYrjwWJKlNmSEr6CpcOVFUT1MpGqLe3

Can someone tell me the reason of this behavior?

A: If you want to access via Drive API a file that is not located on your Drive, you need to set
supportsAllDrives to true:
https://developers.google.com/drive/api/v3/reference/files/get?apix_params=%7B%22fileId%22%3A%221SuYrjwWJKlNmSEr6CpcOVFUT1MpGqLe3%22%2C%22supportsAllDrives%22%3Atrue%7D

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to make prettier not split this code? whenever I use the querySelector element in javascript prettier split the line into multiple lines, how can I prevent that from happening
e.g
what I want:
document.querySelector('#current--' + activePlayer).textContent = roundScore;
what prettier do:
    document.querySelector(`

        '#current--' + activePlayer

       ).textContent = roundScore;


text:
Q: Twilio chat client is coming nil for iOS after getting token from twilio function I am trying to integrate Twilio chat (message, voice, and video) in my application.
I am not able to get chat client in the below code
 // Set up Twilio Chat client after getting token
    TwilioChatClient.chatClient(withToken: token, properties: nil, delegate: self) {(result, chatClient) in

    // Here chatClient is coming nil all the time and the result is not successful.

       self.client = chatClient

      }
  }

A: Twilio developer evangelist here.
There seems to be something wrong with your token generation as you get an error when trying to instantiate the Chat client.
The code you're using to generate the token is mostly right, though a little out of date. We can use a ChatGrant now, rather than the IpMessagingGrant and there's no need to include an endpointId any more. I would update your function to:
exports.handler = function(context, event, callback) {
  let identity = event.identity;
  let AccessToken = Twilio.jwt.AccessToken;
  let ChatGrant = AccessToken.ChatGrant;
  let chatGrant = new ChatGrant({
    serviceSid: context.CHAT_SERVICE_SID,
    pushCredentialSid: context.CHAT_PUSH_CREDENTIAL_SID
  });
  const accessToken = new AccessToken(
    context.ACCOUNT_SID,
    context.CHAT_TWILIO_API_KEY,
    context.CHAT_TWILIO_API_SECRET
  );
  accessToken.addGrant(chatGrant);
  accessToken.identity = identity;
  callback(null, { token: accessToken.toJwt() });
};

Also, I would confirm that you have correctly set the following environment variables in the function configuration: CHAT_SERVICE_SID, CHAT_PUSH_CREDENTIAL_SID, ACCOUNT_SID, CHAT_TWILIO_API_KEY and CHAT_TWILIO_API_SECRET.
If any of those are missing or incorrect then your token will be invalid.
Let me know how that goes.


text:
Q: Find is a business is open: MySQL hours calculation I have a list of business stored in a locations table, and stored in that table are hours the business opens and closes:
location
`mon_1_open`
`mon_1_closed`
`tue_1_open`
`tue_1_closed`
`wed_1_open`
`wed_1_closed`

ect...
I store the times in full hours and minutes, so say a business is open from 9:00AM to 5:30PM on monday.. mon_1_open = '900' AND mon_1_closed = '1730'.
I can't seem to figure out a way to find the day of week and output if the business is else open or closed based on the time of day.
Any suggestions?

A: This does not necessarily answer your question, but it may in the long run.
Your database scheme seems flawed. It definitely is not normalized. I would address that before it becomes a big issue, as you have noticed that it makes it hard to locate certain businesses hours. Here is a draft scheme that might be better suiting.
TABLE: locations
    id INT AUTO_INCREMENT PRIMARY KEY
    name VARCHAR(50)

TABLE: location_hours
    id INT AUTO_INCREMENT PRIMARY KEY
    location_id INT  -  Foreign Key references locations table
    day CHAR(3) - (examples: mon, tue, wed, thu, fri, sat, sun)
    hours VARCHAR(4) - (could also be int)

Then to get todays date, this can be done in MySQL with DATE_FORMAT %a, an example query:
SELECT locations.name, location_hours.hours
FROM locations
    JOIN location_hours ON locations.id = location_hours.location_id
WHERE location_hours.day = DATE_FORMAT(NOW(), '%a')
    AND location.name = 'Someway Business'
ORDER BY location_hours.hour

You should not need an open / close given that the the ORDER BY knows that 0900 < 1430 since it is a VARCHAR (although INT should know how to sort it as well), but your code when adding businesses will either need to update this record or you will need another field active to signify if that row should be used in the query. Just remember to use 24 hour time. Again this is a mock up, I just created it on the spot so it probably could use some improvements, but that would be better then doing a hack like you would have to with your current code.
UPDATE
Addressing the comment about finding if it is open or close:
Just use the PHP date function and call date('Hi') this will pull out the current time in 24-hour time, then you just do a simple if statement to see if it is between that, if it is, it is opened.
IE:
$sql = "SELECT locations.name, location_hours.hours
FROM locations
    JOIN location_hours ON locations.id = location_hours.location_id
WHERE location_hours.day = DATE_FORMAT(NOW(), '%a')
    AND location.name = 'Someway Business'
ORDER BY location_hours.hour";

$result = mysql_query($sql) or trigger_error("SQL Failed with Error: " . mysql_error());

$times = array();
while ($row = mysql_fetch_assoc($result)) {
    if (empty($times['open'])) {
        $times['open'] = $row['hours'];
    }else {
        $times['closed'] = $row['hours'];
    }
}

$currentTime = date('Hi');

if ($times['open'] <= $currentTime
        && $times['closed'] > $currentTime) {
    echo "Open";
}else {
    echo "Closed";
}

Given that my logic is correct. Again, this is just pseudo code an example of usage. Given I just wrote it up on the spot. The above assumes you are only querying one business at a time.

A: $dayOfWeek = strtolower(date('D'));

$query = '
    SELECT
        location,
        '.$dayOfWeek.'_1_open <= '.date('Gi').' AND
        '.$dayOfWeek.'_1_closed >= '.date('Gi').' as is_open';

That should work.
However, you really should use a proper time datatype for the open/closed columns.


text:
Q: Why is string literal faster than a static char array? I ran a following test.
charspeed.c
#include <stdio.h>
#include <time.h>

#define CHAR_COUNT 26
#define CHAR_LIST "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
static const char *CHAR_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

#define RUN_COUNT 1000000000

#define GET_CLOCK (float)clock() / CLOCKS_PER_SEC

int main()
{
    long long int sum = 0;
    float start, end;

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++)
    {
        char test = CHAR_LIST[i % CHAR_COUNT];
        sum += test; // Force the loop to run!
    }
    end = GET_CLOCK;
    printf("#define Time: %f\n", end - start);

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++)
    {
        char test = CHAR_ARRAY[i % CHAR_COUNT];
        sum += test; // Must be the same as fist loop!
    }
    end = GET_CLOCK;
    printf("static const *CHAR_ARRAY Time: %f\n", end - start);
    printf("sum = %lld\n", sum); // Must access "sum" after loops!
    return 0;
}

Its outputs
#define Time: 1.741000
static const *CHAR_ARRAY Time: 1.868000
Why the string literal using #define directive faster than a pre-initialised static char array? Where exactly the string literal is stored and why it is faster to access them within a block scop?
The compiler option used is gcc -o charspeed charspeed.c

A: Just an additional answer to complete the others.
A string literal is not a const char *.
The reason is that a const char * can be reassigned. In your case that means that you could do CHAR_ARRAY = "foo";.
Practically it means that the compiler cannot optimize as much the code dealing with a const char * than the code dealing with a string literal.
To solve this you could use one of the following:
const char *const CHAR_ARRAY = "...";
const char CHAR_ARRAY[] = "...";

This should guarantee the same performance as a string literal.
However, in you case, since you declared CHAR_ARRAY as static, that means that the compiler can see, only looking at the current source file, if CHAR_ARRAY can be  reassigned to.
In practice that means that, assuming optimization are enabled:

*

*for a string literal, a const char *const or a const char[], the same assembly code (A) will be generated.

*for a non static const char * a different assembly code (B) will be generated, possibly slower since their is an added indirection and the result cannot be known at compile time.

*for a static const char *, it will use either the assembly code (A) or (B) depending if the compiler can prove or not that the pointer might be reassigned. For instance if you add a function void f() { CHAR_ARRAY = "foo"; } at any place in your code you prohibit the compiler to use the assembly (A) and (B) will be used.

A: Note: Edited to 'synchronize' with OP's changes:
Maybe the problem is that you aren't giving a good enough test. A decent compiler will run both loops in zero time, because nothing of consequence happens inside them. I tried on MSVC, and your code gave 0 for both times.
However, increasing the loop counts ten-fold and putting in something that can't be optimized away, I get pretty much equal times for both:
#include <stdio.h>
#include <time.h>

#define CHAR_COUNT 26
#define CHAR_LIST "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
static const char* CHAR_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

#define RUN_COUNT 1000000000 // Increased by factor of 10!
#define GET_CLOCK (double)clock() / CLOCKS_PER_SEC

int main()
{
    long long int sum = 0;
    double start, end;

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++) {
        char test = CHAR_LIST[i % CHAR_COUNT];
        sum += test; // Force the loop to run!
    }
    end = GET_CLOCK;
    printf("#define Time: %lf\n", end - start);

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++) {
        char test = CHAR_ARRAY[i % CHAR_COUNT];
        sum += test; // Must be the same as fist loop!
    }
    end = GET_CLOCK;
    printf("static const *CHAR_ARRAY Time: %lf\n", end - start);
    printf("sum = %lld\n", sum); // Must access "sum" after loops!
    return 0;
}

Try doing something like this on your compiler/machine, to see if it makes a difference.

A: First, I am almost certain you did not compile your code with full optimisation turned on.
If you did so, both loops would have totally disappeared (no side effect).
Considering that optimisation is turned off, and that the generated code matches exactly every step of your source code, in your first loop it's like if you did
int test=5;

while in the second it's more like
int something=5;
...
int *addr=&something;
int test=*addr;

In the first case you directly access the interesting value but in the second you reach the interesting value through an indirection.
But I insist, it should not be relevant in an optimised code.


text:
Q: How to supply a string literal value as a binding in WPF EDIT:
My former question also referred to commands, but as pointed out in a comment below, it was unnecessary and added noise.

This is more a XAML syntax question, so it is probably trivial.
I would like to know how to pass a string literal as a value for a binding in WPF.
If the value is already known from the context in XAML, may its value simply be directly assigned to the binding, instead of using paths and other means?
If so, what would the syntax be in that case?
<MultiBinding.Bindings>
    <!-- First binding, a textbox  -->
    <Binding  RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type TextBox}}"/>
    <!-- Second binding, I want to pass a string as is, for instance, "Description" -->
    <!-- The proper syntax for the line below is what I am after -->
    <Binding Value="Description"/>
</MultiBinding.Bindings>

A: It's
<Binding Source="Description"/>

Source can be any type, so in attribute syntax that is interpreted as a string, if no Path is specified a binding's value is the source.
Also that is a multi-binding, i would not talk about command parameters as that is irrelevant to the matter...


text:
Q: Eclipse shortcut "debug last debug configuration" (not F11) I'm looking for a shortcut to debug the last debug configuration. I know about the existence of F11, but the problem is, that I want to start debugging the last configuration. F11 runs the debugging of the class currently opened.
I thought it would be easy to find that shortcut on the net, but no luck...

A: Check the prefs, namely "Run/Debug" -> "Launching" -> "Launch Operation". There you can select what F11 does: Run/Debug the file open in the current editor or use the last launch config again (first option in the last block in the page).


text:
Q: Code new variable based on grep return in R I have a variable actor which is a string and contains values like "military forces of guinea-bissau (1989-1992)" and a large range of other different values that are fairly complex. I have been using grep() to find character patterns that match different types of actors. For example I would like to code a new variable actor_type as 1 when actor contains "military forces of", doesn't contain "mutiny of", and the string variable country is also contained in the variable actor.
I am at a loss as to how to conditionally create this new variable without resorting to some type of horrible for loop. Help me!
Data looks roughly like this:
|   | actor                                              | country         |
|---+----------------------------------------------------+-----------------|
| 1 | "military forces of guinea-bissau"                 | "guinea-bissau" |
| 2 | "mutiny of military forces of guinea-bissau"       | "guinea-bissau" |
| 3 | "unidentified armed group (guinea-bissau)"         | "guinea-bissau" |
| 4 | "mfdc: movement of democratic forces of casamance" | "guinea-bissau" |

A: if your data is in a data.frame df:
> ifelse(!grepl('mutiny of' , df$actor) & grepl('military forces of',df$actor) & apply(df,1,function(x) grepl(x[2],x[1])),1,0)
[1] 1 0 0 0

grepl returns a logical vector and this can be assigned to whatever, e.g. df$actor_type.
breaking that appart:
!grepl('mutiny of', df$actor) and grepl('military forces of', df$actor) satisfy your first two requirements.  the last piece, apply(df,1,function(x) grepl(x[2],x[1])) goes row by row and greps for country in actor.


text:
Q: Is there a way to eliminate duplicate margin notes in LaTeX? I'm working on a game manual and I'd like to put page references in the margins for key concepts, for example something like this (from Justin Alexander's Legends and Labyrinths):

I can use \marginpar to produce the margin notes.  But I would like only one margin note per key concept per page.  For example, the word class is used several times in the above example, but there is only one margin note.  But when writing my LaTeX source, I don't know what the output pagination will be.  So, for example, I might use the word class in two different paragraphs.  If they end up on the same page, I only want one note.  If they end up on different pages, I want one note on each page.
One solution would be to wait until I've completed the main body of text, then manually go back and add margin notes making sure I don't add duplicates on any given page.  But that's a lot of work, and if I need to edit the document after adding the notes I may need to redo it all.  So I'm wondering if there's an automated way to do this in LaTeX itself.
I've searched for any package that provides this sort of functionality, but have not found any.  I figure there's a not simple solution, but I am willing to try programming my own solution.  That said, I'm not very knowledgeable about LaTeX/TeX programming, so any details or references would be greatly appreciated.  Thank you,

A: The solution is not perfect, as it can overwrite the existing counters, so one should avoid names like chapter, section, enumi, and so on.
The first parameter is the name of counter (our label), the second is the text of the margin note.
\documentclass{article}%

%The two following commands are only for smaller pages -  PS
\textwidth6cm
\textheight4cm
\begin{document}
\makeatletter
\def\mparr#1#2{\@ifundefined{c@#1}
    {\newcounter{#1}[page]
    }
    {}
\stepcounter{#1} \ifnum\value{#1}<2\marginpar{#2}
\fi
}
\makeatother

Bla  bla bla \mparr{aaa}{aaa}

Bla  bla bla \mparr{aaa}{aaa}

Bla  bla bla \mparr{aab}{bbb}

Bla  bla bla \mparr{aab}{bbb}

\newpage

Bla  bla bla \mparr{aaa}{aaa}

Bla  bla bla \mparr{aaa}{aaa}

\end{document}

It needs e-tex, as we need many counters. But about 500 is less than over 30k. If your TeX installation is not too old, it is accessible without additional actions.


text:
Q: Apostol Calculus Vol 2 Exercise 8.17 Q No. 3 Evaluate the directional derivative of $f$ for the points and directions specified
$f(x,y,z)=x^2+y^2-z^2$ at $(3,4,5)$ along the curve of intersection of the two surfaces $2x^2+2y^2-z^2=25$ and $x^2+y^2=z^2.$
The answer is supposed to be $0.$ I am not getting the right answer maybe because I don't know how to get the curve of intersection or I don't really understand the directional derivative enough. This is what I did though:
\begin{align}
2x^2+2y^2-z^2&=25\\
\implies 2(x^2+y^2)-z^2&=25\\
\implies z^2&=25
\end{align}
Thus the curve of intersection is $x^2+y^2=25.$ which is a circle centred at orgin with radius $5.$ Hence if $(x,y)$ is any point of the circle, then the unit direction towards that point is $\frac{1}{5}(x,y).$ Also $\nabla f=(2x,2y,-2z)$ and hence we have $\nabla f(3,4,5)=(6,8,-10)$.
Thus the directional derivative at the point $(3,4,5)$ is $\nabla f(3,4,5)\cdot \big(\frac{3}{5},\frac{4}{5}\big)=\frac{58}{5}.$(a wrong answer)

A: I think your unit direction vector should be  : $\left(
\begin{array}{c}
-\frac{4}{5}\\
\frac{3}{5}\\
0\\
\end{array}
\right)$
 (maybe I'll include picture later).
And that the answer should be : $0$ accordingly : $\left(0=\left(
\begin{array}{c}
-\frac{4}{5}\\
\frac{3}{5}\\
0\\
\end{array}
\right) \cdot \left(
\begin{array}{c}
6\\
8\\
-10\\
\end{array}
\right)\right)$.
Here a picture of the tangent line in $(3,4)$   :


text:
Q: Selecting listbox items from a previously selected listbox I have two list boxes, I am trying to automatically select the second list from from the first one. The trouble is, I get stuck in the second Foreach loop, and the first one doesn't run insync with it. Can someone take a look, thanks.
        foreach (ListItem item in this.clb_Departments.Items)
        {
            foreach (ListItem it in this.cbl_fDepartments.Items)
            {
                    if (item.Value == "2")
                    {
                        if (it.Value == "2")
                        {
                            if (item.Selected == true)
                            {
                                it.Selected = true;
                                break;
                            }
                        }
                    }
                    if (item.Value == "3")
                    {
                        if (it.Value == "3")
                        {
                            if (item.Selected == true)
                            {
                                it.Selected = true;
                            }
                        }
                    }
            }

A: If both ListBoxes have the same items:
for(int i=0; i<cbl_fDepartments.Items.Count; i++)
    cbl_fDepartments.Items[i].Selected = clb_Departments.Items[i].Selected;

A: I don't think this is the right approach. Once you capture the data from the first list box on the first page, you stash it somewhere. Then when you render the review page, you set the SelectedValue of the second list box with the value you stashed previously.
There is no need to synchronize anything.

A: I'm still a bit confused on what you are trying to do but this might get you started?
    foreach (ListItem item in this.clb_Departments.Items)
    {
        this.cbl_fDepartments.Items[this.cbl_fDepartments.IndexOf(item)].Selected = item.Selected;
    }

If that doesn't work you can try this inside of your foreach instead:
this.cbl_fDepartments.Items.Cast<ListItem>().Where(t=>t.Value == item.Value).Selected = item.Selected;


text:
Q: POST /api/Messaging/ 405 (Method Not Allowed) I have some angular attempting to post to a web API.
I have got this working before but keep getting issues with CORS.
I have put this in global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

this is the API Controller action signature:
 public void Post([FromBody]Message message)

both [FromUri] and [FromBody] do not work
I have tried:
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

in the WebApiConfig.cs while removing Application_BeginRequest code in asax file and I get the same message which is:
405 (Method Not Allowed)
And the Controller:
 public class MessagingController : ApiController
    {
        private IMessagingRepository DataRepository;

        public MessagingController()
        {
            DataRepository = new DataRepositoryFactory().GetMessagingInstance();
        }

        public List<Message> Get([FromUri]MessageGetModel model)
        {
            var result = DataRepository.GetMessages(model.FromId, model.ToId);

            return result;
        }

        public Message Get(string messageId)
        {
            var result = DataRepository.GetMessage(messageId);

            return result;
        }

        public void Post([FromUri]Message message)
        {
            message.Id = ObjectId.GenerateNewId().ToString();
            DataRepository.GetDataRepository().Save(message);

            DataRepository.PostOrUpdateThread(message);

        }
}

A: 1- Change [FromUri] to [FromBody] because you normally post the data through the message body not through the query string, normally the query string is for Get requests.
2- Remove your code from Application_BeginRequest because EnableCors is enough, and it will add the Allow headers, and by adding them again through the code of Application_BeginRequest, you get problems of duplication for the same header in your response.
3- You can add the Route Attribute or RoutePrefix to your method/controller so for your Post method, replace it to be something like this:
[Route("api/Messaging")]
public void Post([FromBody]Message message)
{
    message.Id = ObjectId.GenerateNewId().ToString();
    DataRepository.GetDataRepository().Save(message);

    DataRepository.PostOrUpdateThread(message);
}

4- Test with Fiddler or postman and make sure that you add your message into the request body either in a JSON format or url encoded.
5- Make sure that use set the "content-type" header to "application/json" if you set the message in the previous point to be in a JSON format, or set the content-type header to "application/x-www-form-urlencoded" if you encoded the message object in the previous point.
6- Finally, you need to make sure that your request url is posting to yourapilocatio/api/Messaging url.
Also, you can see my answer here.
Hope this helps.


text:
Q: How to inspect "multi-object" return type Is there a common reflection approach to find out whether java method returns a set of objects like array, list, set, collection and other iterable subinterfaces?
The story behind is that I need to inspect third-party method's return type and say two things:

*

*Does method return set of objects (in
human sense)?

*If yes - what is the component type?

For example if method's return type is Vector<A>, A[], Set<A>, etc, I want that A to be returned by my code.
I'm new to reflection/generics, don't want to re-invent the wheel and not sure my approach is correct. Here's what I've done so far:
  private boolean isMultiple(Class clazz) {
    return clazz.isArray() || Iterable.class.isAssignableFrom(clazz);
  }

  private Class getReturnComponentType(Method m) {
    Class clazz = m.getReturnType();
    if(!isMultiple(clazz)) return clazz; // Not a collection
    // Collection
    if(clazz.isArray()) {
      // How do I get Array's component type?
      // return null;
    } else {
      // How do I get Iterable component type?
      // return null;
    }
  }

Please help.

A: *

*To get Iterable component type: Besides getReturnType() also use getGenericReturnType() to get generic types. Then compare it to Type subinterfaces: GenericArrayType, ParameterizedType.

*To get Array component type use clazz.getComponentType().


text:
Q: How can I grab the 2nd set of the price variable in this array? I'm grabbing info from an API and the API kicks back 2 different prices in the array, one in CAD and one in USD. The current API call only grabs the CAD price but I'm trying to get it to grab the prices in USD.
Here is the API call and how it sets the data
            global $resultCount;
            global $arrXml;
            $stringA = "msg";
            $stringB = "value";
            $product = "product";
            $measure = "measure";
            $title = "title";
            $a001 = "a001";
            $contributor = "contributor";
            $mediafile = "mediafile";
            $supplydetail = "supplydetail";
            $price = "price";
            $publisher = "publisher";
            $c094 = "c094";
            $resultCount = $arrXml[$stringA][0][$stringB];

            global $Book_Array;
            global $arrXml;
            global $resultAmount;
            $Book_Array[$resultAmount]['ISBN'] = $arrXml[$product]["a001"];
            $Book_Array[$resultAmount]['TITLE'] = $arrXml[$product][$title]["b030"]." ".$arrXml[$product][$title]["b031"]." ".$arrXml[$product][$title]["b203"]." ".$arrXml[$product][$title]["b029"];
            $Book_Array[$resultAmount]['PUB'] = $arrXml[$product][$publisher]["b081"];
            $Book_Array[$resultAmount]['YOP'] = $arrXml[$product]["b003"];
            $Book_Array[$resultAmount]['BOOK_SIZE'] = $arrXml[$product][$measure][0][$c094]." ".$arrXml[$product][$measure][0][$c095]." by ".$arrXml[$product][$measure][1][$c094]." ".$arrXml[$product][$measure][1][$c095]." by ".$arrXml[$product][$measure][2][$c094]." ".$arrXml[$product][$measure][2][$c095];
            $Book_Array[$resultAmount]['AUTH'] = $arrXml[$product][$contributor]["b037"]." ".$arrXml[$product][$contributor][0]["b037"]." ".$arrXml[$product][$contributor][1]["b037"];
            $Book_Array[$resultAmount]['PRICE'] = $arrXml[$product][$supplydetail][$price]["j151"];
            $Book_Array[$resultAmount]['THUMB'] = $arrXml[$product][$mediafile][0]["f117"];
            $Book_Array[$resultAmount]['IMG'] = $arrXml[$product][$mediafile][1]["f117"];

And here's the info it shoots back, I used Rich dad poor dad as an example:
<data>
    <msg>
        <num>2001</num>
        <txt>results: 1</txt>
        <value>1</value>
    </msg>
    <product>
        <a001>9781978691704</a001>
        <b012>AC</b012>
        <productidentifier>
            <b221>02</b221>
            <b244>197869170X</b244>
        </productidentifier>
        <productidentifier>
            <b221>03</b221>
            <b244>9781978691704</b244>
        </productidentifier>
        <title>
            <b203>Rich Dad Poor Dad</b203>
            <b029>20th Anniversary Edition: What the Rich Teach Their Kids About Money That the Poor and Middle Class Do Not!</b029>
        </title>
        <publisher>
            <b081>Brilliance Audio</b081>
        </publisher>
        <b003>20190514</b003>
        <b064>_AV010010</b064>
        <subject>
            <b067>10</b067>
            <b069>BUS050000</b069>
        </subject>
        <subject>
            <b067>10</b067>
            <b069>FAM034000</b069>
        </subject>
        <b056>UBR</b056>
        <measure>
            <c093>01</c093>
            <c095>in</c095>
            <c094>5.50</c094>
        </measure>
        <measure>
            <c093>02</c093>
            <c095>in</c095>
            <c094>6.50</c094>
        </measure>
        <measure>
            <c093>03</c093>
            <c095>in</c095>
            <c094>1.13</c094>
        </measure>
        <contributor>
            <b035>A01</b035>
            <b037>Kiyosaki, Robert T</b037>
            <b034>1</b034>
        </contributor>
        <contributor>
            <b035>A01</b035>
            <b037>Parks, Tom</b037>
            <b034>2</b034>
        </contributor>
        <supplydetail>
            <j137>TBM</j137>
            <price>
                <j148>01</j148>
                <j151>81.99</j151>
                <j152>CAD</j152>
            </price>
            <price>
                <j148>01</j148>
                <j151>54.97</j151>
                <j152>USD</j152>
            </price>
        </supplydetail>
        <mediafile>
            <f114>07</f114>
            <f115>03</f115>
            <f116>01</f116>
            <f117>http://bookmanager.com/i/b.php?b=BMOGSzFyXVkasX4SnRYa_w</f117>
        </mediafile>
        <mediafile>
            <f114>04</f114>
            <f115>03</f115>
            <f116>01</f116>
            <f117>http://bookmanager.com/i/m.php?b=BMOGSzFyXVkasX4SnRYa_w</f117>
        </mediafile>
    </product>
    <msg>
        <num>2003</num>
        <txt>XMLISBN_ENHAN queries remaining: 10021</txt>
        <value>10021</value>
    </msg>
</data>

A: var_export() of supply detail will look like the following
 'supplydetail' =>
    array (
      'j137' => 'TBM',
      'price' =>
      array (
        0 =>
        array (
          'j148' => '01',
          'j151' => '81.99',
          'j152' => 'CAD',
        ),
        1 =>
        array (
          'j148' => '01',
          'j151' => '54.97',
          'j152' => 'USD',
        ),
      ),
    ),

USD price is in a 2nd element of price array, So to access the USD price, you need to call it using index which is 1 in given case
echo  $arrXml[$product][$supplydetail][$price][1]["j151"];


text:
Q: Casting for Lambda: BiConsumer I get a compiler failure like this:
 The method accept (Integer, Integer) in the type BiConsumer is not applicable for the arguments (Object, Object). How can I cast two Integer-inputs, so the compiler accepts them as <Integer, Integer>?
I'm getting the failure in the following code:
import java.util.function.BiConsumer;

public class ExceptionHandlingExample {

    public static void main(String[] args) {
        int[] numberArray = { 1, 2, 3, 4 };
        int key = 2;
        calc(numberArray, key, wrapperForLambda( (a, b) -> System.out.println(a / b) ));
        // Type Safety: The expression of Type BiConsumer needs unchecked conversion to conform to unchecked BiConsumer<Integer, Integer>
    }

    private static void calc(int[] numberArray, int key, BiConsumer<Integer, Integer> consumer) {
        for (int i : numberArray) {
            consumer.accept(i, key);
        }
    }

    private static BiConsumer wrapperForLambda(BiConsumer<Integer, Integer> consumer) {
    // BiConsumer is a raw type. References to generic type BiConsumer<T, U> should be parameterized
        return (a, b) -> consumer.accept(a, b) ;
    // [Compilier-error] The method accept (Integer, Integer) in the type BiConsumer<Integer, Integer> is not applicable for the arguments (Object, Object)
    }
}

I want to get rid of the compiler-error:
The method accept (Integer, Integer) in the type BiConsumer is not applicable for the arguments (Object, Object)
Thank you for your help in advance!

A: Don't use the raw type BiConsumer. Declare the method as
private static BiConsumer<Integer, Integer>
        wrapperForLambda(BiConsumer<Integer, Integer> consumer) {
    return (a, b) -> consumer.accept(a, b);
}

When you use the raw BiConsumer, Java uses it as the target type for the lambda expression (a, b) -> consumer.accept(a, b). The consequence of that is that the parameters a and b are assumed to be of type Object (raw types, remember!), which won't work with your consumer BiConsumer which expects Integers.
If this is supposed to be a general-purpose method, you can make the method generic:
private static <T, U> BiConsumer<T, U>
        wrapperForLambda(BiConsumer<T, U> consumer) {
    return (a, b) -> consumer.accept(a, b);
}

A: I don't know what's the purpose of wrapperForLambda. You don't need it. Simply call calc as follows:
calc(numberArray, key, (a, b) -> System.out.println(a / b));

And the error in wrapperForLambda can be eliminated with:
private static BiConsumer wrapperForLambda(BiConsumer<Integer, Integer> consumer) {
     return consumer;
}

but I still think this method is pointless.
P.S. I'm assuming the loop in calc method should iterate on the someNumbers array, not numberArray (which is a local variable of your main method).

A: You can use as
    return (a, b) -> consumer.accept((Integer) a, (Integer) b);

Before Java 1.5, you couldn't even do this:
    int a;

    Object x = (Integer) a;

The compiler would complain that a is of a primitive data type, and therefore cannot be cast to an object.
Starting with Java 1.5, Java introduced the concept of automatic boxing. So, the following became OK:
    int a;

    Object x = (Integer) a;

Because the compiler knows how to convert from a primitive int to the boxed type Integer automatically; and from Integer to an Object it's, well, not a problem.
However, what you're trying to do:
    int a;

    Object x = (int) a;

Is basically telling the compiler to avoid boxing. You explicitly tell the compiler to leave a as an int, and put a reference to that int into an Object. The compiler isn't designed to deal with such a case.

A: You don't need the method wrappedForLambda, as @Eran correctly mentions.
Just use the lambda expression directly.
public static void main(String[] args) {
    int[] numberArray = { 1, 2, 3, 4 };
    int key = 2;
    calc(numberArray, key, (a, b) -> System.out.println(a / b) );
    // Type Safety: The expression of Type BiConsumer needs unchecked conversion to conform to unchecked BiConsumer<Integer, Integer>
}

private static void calc(int[] someNumbers, int key, BiConsumer<Integer, Integer> consumer) {
    for (int i : numberArray) {
        consumer.accept(i, key);
    }
}

If this does not compile for some reason (old JDK or old eclipse), cast to Integer explicitly:
calc(numberArray, key, (Integer a, Integer b) -> System.out.println(a / b) );


text:
Q: Interacting with cPanel via PHP I used to use 000WebHost and found that they have a custom version of cPanel written via PHP which interacts with cPanel.
Could anyone explain how this works?
Thanks,
Connor

A: By using the cPanel / WHM API.


text:
Q: How to add and save entry in dropdown listbox using coldfusion Id like to make a drop down list box where in at the end of the list, an option "Enter New housing", that if selected there will be a message box then it will automatically saves on the database and refreshes the object.
Im a beginner and this is what ive started:
<cfquery name="housingsel" datasource=" " dbtype=" ">
    select rtrim(housing_name) as housing, housingid as housingid from housing order by housing
</cfquery>

Housing

    <cfform action="de_housing.cfm" method="POST">

Housing
            <select name="housingcat">
                <CFOUTPUT QUERY="housingsel">
                    <OPTION VALUE="#housingid#">#housing#</OPTION>
                </CFOUTPUT>
                <option value="new">Enter New Housing</option>
                </select>

    </cfform>

Please help!
Thanks!

A: First off, avoid cfform at all costs. It will not help you. See https://github.com/cfjedimaster/ColdFusion-UI-the-Right-Way for reasons why and examples of how to do stuff the right way.
That being said, what you want to do isn't difficult. Let's break it down.
> "Id like to make a drop down list box where in at the end of the list, an option "Enter New housing", that if selected "
Using jQuery, you would add a change handler to your dropdown. In that change handler, you can get the selected index of the drop down. If that index is equal to the length of the options, then the user has picked the last one.
> "there will be a message box"
You have a few choices here. One simple, but not pretty way, is to use the built in confirm option. It has a simple modal box API that the user can type in. There are pretty options, like jQuery UI dialogs, but the confirm option is super simple. I'd recommend starting there.
> "automatically saves on the database"
So, you will know when a user enters a value into the confirm. Take that and use jQuery to do an XHR (Ajax) hit to your code. You will need to write CF code to respond to this request and insert it into the db. Not too difficult and it has been shown many places elsewhere.  I'd also add logic to check for dupes.
> "refreshes the object"
When you do a XHR in jQuery, you know when the server is done doing crap, so in the response handler, you can add a new option to the drop down. This too has been done many times before, just Google for adding an option to a drop down. (You will probably end up back here.)


text:
Q: Return value from http request using Volley I try to get the altitude of a location using an http request to Google Maps. Unfortunately, I receive a response but I cannot use it. In this piece of code, I try to set the altitude of a Location but it does not work. The altitude is correct in my OnResponse method but it is wrong elsewhere. Do you have any idea why?
public class MainActivity extends AppCompatActivity {
Location location = new Location("");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    location.setLatitude(39.7391536);
    location.setLongitude(-104.9847034);
    getElevation();
    Log.d("OnCreate", ""+location.getAltitude()); //print OnCreate: 0.0

}

public void getElevation(){
    String urlName = "https://maps.googleapis.com/maps/api/elevation/json?locations="
            +location.getLatitude()+","+location.getLongitude()
            +"&key=mykey";

    RequestQueue queue = Volley.newRequestQueue(this);

    JsonObjectRequest requester = new JsonObjectRequest(urlName, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
                TextView mTxtDisplay = (TextView) findViewById(R.id.elevation);
                double altitude;

            try {
                altitude = response.getJSONArray("results").getJSONObject(0).getDouble("elevation");
                mTxtDisplay.setText("Elevation : " + altitude);
                location.setAltitude(altitude);
                Log.d("OnResponse", ""+location.getAltitude()); //print OnResponse: 1608.637939453125
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //TODO
        }
    });
    queue.add(requester);
    }
}

A:
I try to set the altitude of a Location but it does not work.

Yes it does work, because you say yourself.

The altitude is correct in my OnResponse method

So, when you say

it is wrong elsewhere.

It isn't wrong, it is unitialized. Volley doesn't just immediately return the result of the elevation. So, the log statement that prints 0 happens before the onResponse that prints the value.
So, to answer "how to return values from volley", you already are doing that - obtain that value within the onResponse and delay execution of anything that relies on that value until then


text:
Q: Can I get access to Amazon's AWS API? Has anyone tried accessing the Amazon web services (AWS) API from Mathematica? I'm assuming the HTTP WebService module of Mathematica would be a starting point. Any suggestions on getting started would be welcome. The following example from the documentation is not working:
Needs /@ {"WebServices`", "JLink`"};
InstallService[
  "http://soap.amazon.com/schemas3/AmazonWebServices.wsdl"];

  InvokeServiceOperation::httpcode: 404 (HTTP/1.1 404 Not Found) >>

A: You can get started using the following code.  It currently connects to the AWS SES service but should be easily extended.Git Hub


text:
Q: Match string with vowels at the end using Regex I'm trying to return items in a list that has any four or more characters in the string at the end of the item (could be repeated).
The string is = "iaeou"
I wrote
"[iaeou]+{4,}$"

This is not returning what I want, I'd like to know what is wrong with it.
I get error 'multiple repeat'.
>>> example = ['ti','tii','ta','tae','taeguu','fy']
>>> import re
>>> for item in example:
...  if re.search("[iaeou]+{4,}$",item):
...   print(item)
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 183, in search
    return _compile(pattern, flags).search(string)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 286, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 930, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 426, in _parse_sub
    not nested and not items))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/sre_parse.py", line 654, in _parse
    source.tell() - here + len(this))
re.error: multiple repeat at position 8

A: You need to write it like this,
[iaeou]{4,}$

This part '+{4,}' in your regex is not valid, because + itself is a quantifier and {4,} also is a quantifier and you can't quantify a quantifier for the regex to be valid, due to which you must be getting some pattern error. In case you literally want to quantify a + sign, you will need to escape that like this,
\+{1,4}

but that is not what you wanted as per your question. Hope that clarifies.


text:
Q: Passing optional arguments inside a wrapper function to a sub-function I have a wrapper function, where I need to pass optional arguments to the sub-function specified. But there are so many different possible sub-functions that I can't pre-specify them.
For reference, the sub-functions exist in the environment etc...
Consider:
funInFun<- function (x, method, ...) {

  method.out <- function(this.x, FUN, ...) {
    FUN <- match.fun(FUN)
    c <- FUN(this.x, ...)
    return(c)
  }

  d <- method.out(x, method)
  return(d)
}

data<-seq(1,10)
funInFun(data, mean) #  Works

data<-c(NA,seq(1,10))
funInFun(data, mean, na.rm=TRUE) # Should remove the NA

funInFun(c(seq(1,10)), quantile, probs=c(.3, .6))  # Shoudl respect the probs option.

A: You need to pass the ... to method.out. Then it works fine:
funInFun<- function (x, method, ...) {

  method.out <- function(this.x, FUN, ...) {
    FUN <- match.fun(FUN)
    c <- FUN(this.x, ...)
    return(c)
  }

  d <- method.out(x, method, ...)  # <<--- PASS `...` HERE
  return(d)
}

data<-seq(1,10)
funInFun(data, mean) #  Works
# [1] 5.5

data<-c(NA,seq(1,10))
funInFun(data, mean, na.rm=TRUE) # Should remove the NA
# [1] 5.5

funInFun(c(seq(1,10)), quantile, probs=c(.3, .6))
# 30% 60%
# 3.7 6.4

A: In addition to Thomas' answer to the OP's question you might have to forward an optional argument that is an explicit argument of the wrapper function.
In this case, instead of repeating the default value of the wrapped function in the wrapper definition you can use missing to construct a call with a missing argument.
f <- function(s = "world!") cat("Hello", s)
f()
# Hello world!
g <-  function(s = NULL) eval(substitute(
  f(s = sub_me),
  list(sub_me = if(missing(s)) quote(expr =) else s)))
g()
# Hello world!
g("you!")
# Hello you!


text:
Q: Failure to download "ttf-mscorefonts-installer". Not even reinstall works! I get this message everytime I log in:

Failure to download extra data files
The following packages requested additional data downloads after
  package installation, but the data could not be downloaded or could
  not be processed.
ttf-mscorefonts-installer
The download will be attempted again later, or you can try the
  download again now.  Running this command requires an active Internet
  connection.

When I try to reinstall the package, I get this error:
$ sudo apt-get install --reinstall ttf-mscorefonts-installer

Reading package lists... Done
Building dependency tree
Reading state information... Done
0 upgraded, 0 newly installed, 1 reinstalled, 0 to remove and 0 not upgraded.
Need to get 0 B/29,5 kB of archives.
After this operation, 0 B of additional disk space will be used.
Preconfiguring packages ...
(Reading database ... 322478 files and directories currently installed.)
Preparing to unpack .../ttf-mscorefonts-installer_3.4+nmu1ubuntu2_all.deb ...
mscorefonts-eula license has already been accepted
Unpacking ttf-mscorefonts-installer (3.4+nmu1ubuntu2) over (3.4+nmu1ubuntu2) ...
Processing triggers for fontconfig (2.11.94-0ubuntu1.1) ...
Processing triggers for update-notifier-common (3.168.2) ...
ttf-mscorefonts-installer: processing...
ttf-mscorefonts-installer: downloading http://downloads.sourceforge.net/corefonts/andale32.exe
Err:1 http://downloads.sourceforge.net/corefonts/andale32.exe
  The HTTP server sent an invalid Content-Range header Bad header data [IP: 78.35.24.46 80]
W: Can't drop privileges for downloading as file '/var/lib/update-notifier/package-data-downloads/partial/andale32.exe' couldn't be accessed by user '_apt'. - pkgAcquire::Run (13: Permission denied)
E: Failed to fetch http://netcologne.dl.sourceforge.net/project/corefonts/the fonts/final/andale32.exe  The HTTP server sent an invalid Content-Range header Bad header data [IP: 78.35.24.46 80]

E: Download Failed
Setting up ttf-mscorefonts-installer (3.4+nmu1ubuntu2) ...

What could I do?
UPDATE
Seems like there is a bug about this topic:
https://bugs.launchpad.net/ubuntu/+source/msttcorefonts/+bug/1645253

A: There is an issue with the sourceforge downloads (mirrors and redirects being slow and/or failing).
To workaround this you can grab the files manually from here for example:
https://sourceforge.net/projects/corefonts/files/the%20fonts/final/
and save them in the same directory (say mscorefonts).
The files are (from the installer):
Those files are in the Microsoft Windows self-installing format, and are named
andale32.exe, arial32.exe, arialb32.exe, comic32.exe, courie32.exe, georgi32.exe, impact32.exe, times32.exe, trebuc32.exe, verdan32.exe and webdin32.exe.

Make sure the package is purged and no remaining setup triggers are remaining:
sudo apt-get remove --purge ttf-mscorefonts-installer

Then in a terminal run:
sudo apt-get install ttf-mscorefonts-installer #(this will fail again most likely)
sudo dpkg-reconfigure ttf-mscorefonts-installer

That should give you a "graphical" interface in the terminal.
Then point to the directory with downloaded files like /home//Downloads/mscorefonts.
Make sure no deb files are in there, the seem to be picked up too and then it fails.
That fixed it for me.
I got a popup later for a post install action, I just let it run and it did not come back.
Please register at launchpad and mark yourself as affected to the bug:
https://bugs.launchpad.net/ubuntu/+source/msttcorefonts/+bug/1645253
so it will get more priority.
Thank you.


text:
Q: Django user password hash, oracle db, and java im developing and ecommerce site on django for a Sushi Restaurant, and i have to create a CRUD for users in java and edit info from the database in oracle, the database are generated with django, so my questions are.
how can i deal with the django hash for password? change password from the java crud app would be nice, if can i disable the hash from django would be nice to, its just a institute project, so doesn't matter the security.


text:
Q: Cache task in AzDO is timing out My cache task fails with a timeout exception, wasn't able to find any information on the web
2021-11-19T13:12:49.5440178Z ##[section]Starting: Cache Maven local repo
2021-11-19T13:12:49.5444463Z ==============================================================================
2021-11-19T13:12:49.5444700Z Task         : Cache
2021-11-19T13:12:49.5444880Z Description  : Cache files between runs
2021-11-19T13:12:49.5445073Z Version      : 2.0.1
2021-11-19T13:12:49.5445247Z Author       : Microsoft Corporation
2021-11-19T13:12:49.5445454Z Help         : https://aka.ms/pipeline-caching-docs
2021-11-19T13:12:49.5445913Z ==============================================================================
2021-11-19T13:12:50.3859003Z Resolving key:
2021-11-19T13:12:50.3867990Z  - maven      [string]
2021-11-19T13:12:50.3868628Z  - "Linux"    [string]
2021-11-19T13:12:50.3869252Z  - **/pom.xml [file pattern; matches: 1]
2021-11-19T13:12:50.3870147Z    - s/pom.xml --> 425BE14263A590554133E4A4AE3B095D0207EE19CADB68111111A8623073C9
2021-11-19T13:12:50.3870747Z Resolved to: maven|"Linux"|6BG0VLzocHR1ABXQNLQ+q7oxXHj2Ln9xNBME=
2021-11-19T13:12:50.3872532Z Resolving restore key:
2021-11-19T13:12:50.3873112Z  - maven   [string]
2021-11-19T13:12:50.3873653Z  - "Linux" [string]
2021-11-19T13:12:50.3874064Z Resolved to: maven|"Linux"|**
2021-11-19T13:12:50.3874469Z Resolving restore key:
2021-11-19T13:12:50.3874998Z  - maven [string]
2021-11-19T13:12:50.3875403Z Resolved to: maven|**
2021-11-19T13:12:50.4071086Z ApplicationInsightsTelemetrySender will correlate events with X-TFS-Session 018d9b8b-7e2e-4eb4-9081-60a8aac6ca19
2021-11-19T13:12:50.4271999Z Getting a pipeline cache artifact with one of the following fingerprints:
2021-11-19T13:12:50.4272751Z Fingerprint: `maven|"Linux"|6BG0VLzocHR1ABXQNLQ+CkcxTTgq7oxXHj2Ln9xNBME=`
2021-11-19T13:12:50.4273230Z Fingerprint: `maven|"Linux"|**`
2021-11-19T13:12:50.4273649Z Fingerprint: `maven|**`
2021-11-19T13:12:51.4866539Z There is a cache hit: `maven|"Linux"|6BG0VLzocHR1ABXQNLQ+CkcxTTgq7oxXHj2Ln9xNBME=`
2021-11-19T13:12:51.4878034Z Used scope: 1506;0fc5062f-55dd-476b-baba-8952a15401e7;refs/heads/EOD_STORES;52820a17-3ace-4f9e-ba77-2330a6eccacb
2021-11-19T13:12:51.5808454Z Entry found at fingerprint: `maven|"Linux"|6BG0VLzocHR1ABXQNLQ+CkcxTTgq7oxXHj2Ln9xNBME=`
2021-11-19T13:13:51.9289494Z [https://vb8vsblobprodsu6weus46.blob.core.windows.net/db908636dc538642c896c6b0557076a854/1F68E25AD7A9B91792F6DE976146515E90F7488470FD5DB9D2166AEB7C2451A201?sv=2019-07-07&sr=b&spr=https&se=2021-11-20T14:07:21Z&sp=r&rscl=x-e2eid-7f1caaa0-030b4341-adf321f6-8515e4e2-session-018d9b8b-7e2e4eb4-908160a8-aac6ca19] Try 1/5, Task was requested to be canceled.
2021-11-19T13:45:52.9504822Z ApplicationInsightsTelemetrySender correlated 3 events with X-TFS-Session 018d9b8b-7e2e-4eb4-9081-60a8aac6ca19
2021-11-19T13:45:52.9581543Z ##[error]Attempt timed out after 00:01:00.
2021-11-19T13:45:52.9618987Z ##[section]Finishing: Cache Maven local repo


text:
Q: Let $J$ be a closed ideal in a $C^*$-algebra $A$. Prove that $A/J$ is a $C^*$-algebra. Let $A$ be a $C^*$-algebra and $J$ a closed two-sided ideal of $A$. I want to show that $A/J$ with the quotient norm is a $C^*$-algebra as well, for the $*$-operation $(a+J)^*:= a^*+J$.
In the book I'm reading, the author provides a proof in the case that $A$ has a unit, so I can assume my algebra is non-unital.
Attempt:
Consider the unitalisation $A_I$. We have that $J$ is a norm-closed twosided ideal in $A_I$ and consequently, we see that $A_I/J$ is a $C^*$-algebra. Since $A \subseteq A_I$, we see that
$$A/J \subseteq A_I/J$$
and thus the $C^*$-identity in $A_I/J$ is inherited by $A/J$, which ends the proof.
Is this correct?

A: One small detail you may want to mention is that the inclusion $A/J\hookrightarrow A_I/J$ is isometric.  Other than that, everything seems fine.


text:
Q: There is no "Hosting Content with Apple" section on iTunes Connect for my iTunes account I create a new IAP item this way:
click "Manage In-App Purchases"
click "Create New"
Select "Free-Subscription"

The section "Hosting Content with Apple" is not present for that app, or any of my apps for that matter.
If I log-in with a different developer account and follow exactly the same steps, there is a section "Hosting Content with Apple" Yes [] No [] for any/all apps.
Does Apple have yet a special policy I am not aware of?

A: Did you check "Contracts, Tax, and Banking" in iTunes connect?
Maybe, Some you don't agree Contracts exist.


text:
Q: you should require 'minitest/autorun' instead. in ruby on rails I am creating an application on ruby on rails:
After creating users, for validating users I am running below commands:
$ bundle exec rake db:migrate
$ bundle exec rake test:prepare

Both command are run properly on the rails commandLine, but when I run the below command:
$ bundle exec rspec spec/models/user_spec.rb

I am getting error below:
Warning: you should require 'minitest/autorun' instead.
Warning: or add 'gem "minitest"' before 'require "minitest/autorun"'

And I am using 4.1.1 version of rails.
I don't understand why it comes.
Kindly suggest me, waiting for your reply.
Thanks.

A: Include minitest gem in your 'Gemfile' and run bundle install
gem install 'minitest'

and then bundle install

A: More a note for posterity than anything, but this issue can also happen if you're using an older version of shoulda-matchers. You can see some discussion around this on their Github repo here, or on the rspec-rails repo here.
Update shoulda-matchers by running bundle update shoulda-matchers. You want the latest version (or at least 2.6.2) and this message should go away.


text:
Q: I have a svg file content and I want to remove a string based on matching substring How I can remove Author: SHARMSR based on matching condition Author from the below string
<text fill="#000000" fill-opacity="1" font-family="Arial" font-size="10" font-style="normal" font-weight="400" stroke="none" textLength="84.875" x="-42.4375" xml:space="preserve" y="3.5">Author: SHARMSR</text>

A: Use a simple regex in String.replaceAll
String s = "<text fill=\"#000000\"  y=\"3.5\">Author: SHARMSR</text>";
String result = s.replaceAll("Author[^<]+", "");
System.out.println(s);      // <text fill="#000000"  y="3.5">Author: SHARMSR</text>
System.out.println(result); // <text fill="#000000"  y="3.5"></text>


text:
Q: How to setup 2 NIC PC with a DHCP server on one NIC and LAN on the other. Ubuntu So I have a networking setup I need for a project. On one of my NICs I need to have a DHCP server. I've found for ubuntu there exists dhcp3-server for a dhcp server. I've done a bit of research, I have no idea where to start after that or how to separate one nic over the other.
I've never setup or configured networking on a linux computer, so I'm hoping you may understand what I'm trying to accomplish, and have some helpful insight or links.

A: in /etc/dhcp/dhcpd.conf
when you specify address ranges for dhcp. DHCP will only be made available on the network intefaces that include have those ranges.


text:
Q: An urn of 4 balls with 2 colors. Pick 2 balls and place them back 4 times. What's the probability of picking 2 balls of the same color twice in a row? An urn of 4 balls with 2 colors. Pick 2 balls and place them back 4 times. What's the probability of picking 2 balls of the same color twice in a row?
So the probability of picking 2 balls of the same color is $2\choose1$$2\choose2$/$4\choose2$, but I don't know the probability of getting that twice in a row out of 4 draws

A: Assumptions:

*

*There are two balls of one color and two balls of a second color

*Suppose the colors are Green and Red. A successful outcome occurs in any of these cases when you choose two green followed by two green, two green followed by two red, two red followed by two green, or two red followed by two red.

The probability of picking two balls of the same color in a single draw is as you found $\dfrac{1}{3}$. A single draw will be labeled $S$ for both balls are the same color and $D$ for the balls are different colors. Here are the possible outcomes:
$$\begin{array}{c|c|c}\text{Draws} & \text{Probability} & \text{2-in-a-row?} \\ \hline DDDD & \left(\dfrac{2}{3}\right)^4\left(\dfrac{1}{3}\right)^0 & \text{No} \\ DDDS & \left(\dfrac{2}{3}\right)^3\left(\dfrac{1}{3}\right)^1 & \text{No} \\ DDSD & \left(\dfrac{2}{3}\right)^3\left(\dfrac{1}{3}\right)^1 & \text{No} \\ DDSS & \left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2 & \text{Yes} \\ DSDD & \left(\dfrac{2}{3}\right)^3\left(\dfrac{1}{3}\right)^1 & \text{No} \\ DSDS & \left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2 & \text{No} \\ DSSD & \left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2 & \text{Yes} \\ DSSS & \left(\dfrac{2}{3}\right)^1\left(\dfrac{1}{3}\right)^3 & \text{Yes} \\ SDDD & \left(\dfrac{2}{3}\right)^3\left(\dfrac{1}{3}\right)^1 & \text{No} \\ SDDS & \left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2 & \text{No} \\ SDSD & \left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2 & \text{No} \\ SDSS & \left(\dfrac{2}{3}\right)^1\left(\dfrac{1}{3}\right)^3 & \text{Yes} \\ SSDD & \left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2 & \text{Yes} \\ SSDS & \left(\dfrac{2}{3}\right)^1\left(\dfrac{1}{3}\right)^3 & \text{Yes} \\ SSSD & \left(\dfrac{2}{3}\right)^1\left(\dfrac{1}{3}\right)^3 & \text{Yes} \\ SSSS & \left(\dfrac{2}{3}\right)^0\left(\dfrac{1}{3}\right)^4 & \text{Yes}\end{array}$$
Adding this up, I get:
$$3\left(\dfrac{2}{3}\right)^2\left(\dfrac{1}{3}\right)^2+4\left(\dfrac{2}{3}\right)^1\left(\dfrac{1}{3}\right)^3+\left(\dfrac{2}{3}\right)^0\left(\dfrac{1}{3}\right)^4 = \dfrac{7}{27}$$


text:
Q: Java gradle execute code I follow this starter tutorial.
I can not run the code with this command :
$ java -cp gs-gradle-0.1.0.jar hello.HelloWorld

I have this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/joda/time/LocalTime
    at hello.HelloWorld.main(HelloWorld.java:11)
Caused by: java.lang.ClassNotFoundException: org.joda.time.LocalTime
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

All import classes are not found. But with gradle command it works :
$ ./gradlew run

Why with java command, it doesn't work ?
Thanks

A: Of course it does not work, the Tutorial also told you so.
The application plugin adds the run task (and other tasks) that put your dependency on the classpath.
If you use the distZip or distTar task you get an archive with all your dependencies and with start scripts that set the correct classpath that you can use to run your application.
Read more about the application plugin at https://docs.gradle.org/current/userguide/application_plugin.html.


text:
Q: Improve query performance - SELECT and SUM from two table What I have :  (explain)
I Working with FreeRadius a radius server and I want to calculate today users total traffic used .
I have a table named as users , and second table is users_graph .
users_graph table collect bandwidth data for each 15minutes (96 row per day for each user) .
I try to make a query to collect users with a specified groupname and SUM of total traffic used today .
What I do :
I make below SQL query and test for a result , test with 20 user and 80 row on users_graph for each user .
Result : execute time of my query is about 3 seconds.
What I want :
I try to improve my query to give more performance and fastest execute time .
Is there a way to improve below query ?
MyQuery :
SELECT
  u.`UserName`,
  SUM(g.`Total`) totaltime
FROM
  users u
  INNER  JOIN `users_graph` g
    ON g.`UserName` = u.`UserName`
WHERE u.`GroupName` = 'Festival'  AND g.`Time` > '1408995000'
GROUP BY u.`UserName`;

Samle Resut :
UserName   GroupName    totaltime
---------  -----------  ----------
test123    Festival      81
test332    Festival      19
test523    Festival      29

EDIT:
Tables info :
/*Table: users_graph*/
----------------------

/*Column Information*/
----------------------

Field     Type          Collation          Null    Key     Default  Extra
--------  ------------  -----------------  ------  ------  -------  --------------
Guid      bigint(22)    (NULL)             NO      MUL     (NULL)   auto_increment
Time      int(11)       (NULL)             YES             0
UserName  varchar(255)  latin1_swedish_ci  YES             (NULL)
Down      int(11)       (NULL)             YES             0
Up        int(11)       (NULL)             YES             0
Total     int(11)       (NULL)             YES             0

/*Index Information*/
---------------------

Table        Non_unique  Key_name  Seq_in_index  Column_name  Collation  Cardinality  Sub_part  Packed  Null    Index_type
-----------  ----------  --------  ------------  -----------  ---------  -----------  --------  ------  ------  ----------
users_graph           1  Guid                 1  Guid         A              5584276    (NULL)  (NULL)          BTREE

/*DDL Information*/
-------------------

CREATE TABLE `users_graph` (
  `Guid` bigint(22) NOT NULL AUTO_INCREMENT,
  `Time` int(11) DEFAULT '0',
  `UserName` varchar(255) DEFAULT NULL,
  `Down` int(11) DEFAULT '0',
  `Up` int(11) DEFAULT '0',
  `Total` int(11) DEFAULT '0',
  KEY `Guid` (`Guid`)
) ENGINE=MyISAM AUTO_INCREMENT=5584277 DEFAULT CHARSET=latin1

/*Table: users*/
----------------

/*Index Information*/
---------------------

Table   Non_unique  Key_name    Seq_in_index  Column_name  Collation  Cardinality  Sub_part  Packed  Null    Index_type
------  ----------  ----------  ------------  -----------  ---------  -----------  --------  ------  ------  ----------
users            0  PRIMARY                1  id           A                21250    (NULL)  (NULL)          BTREE
users            0  UserName               1  UserName     A                21250    (NULL)  (NULL)          BTREE

/*DDL Information*/
-------------------

CREATE TABLE `users` (
`id` bigint(21) NOT NULL AUTO_INCREMENT,
`UserName` varchar(32) NOT NULL DEFAULT '',
`Pass` varchar(32) NOT NULL DEFAULT '',
`GroupName` varchar(32) NOT NULL DEFAULT '',
) ENGINE=MyISAM AUTO_INCREMENT=27456 DEFAULT CHARSET=latin1

A: Must index searched columns , for example if I want to search where time greater than equal , I must index column of time then , Mysql sort time row .
indexed columns can retrieve faster result .


text:
Q: Prevent memory leaks in WPF Working with WinForms you have to free memory after using gdi objects, event handlers, objects from native code, etc.
In WinForms I used to remove for example event handlers in the dispose method.
What is the best workaround to prevent memory leaks in Wpf? Is it the same as in Winforms using Dispose pattern? At all, do I have to care about event handlers, gdi objects in Wpf? What about the runtime created resources(Brushes, etc)?

A: This blog post lists the most common situations that cause memory leaks in WPF applications.

*

*Event handlers to objects in parent windows

*Registering to events from static objects

*Using timers

*Data binding

*Changing the Text property of a text box

It also describes how to fix these common issues.
Another good approach is to develop an app while following the standard guidelines and then use some kind of profiler to determine any memory leaks or performance bottlenecks.

A: From MSDN: Any WPF framework-level element (those objects deriving from either FrameworkElement or FrameworkContentElement) has three common lifetime events: Initialized, Loaded, and Unloaded.
.....
Unloaded is raised last and is initiated by either the presentation source or the visual parent being removed. When Unloaded is raised and handled, the element that is the event source parent (as determined by Parent property) or any given element upwards in the logical or visual trees may have already been unset, meaning that data binding, resource references, and styles may not be set to their normal or last known run-time value.

A: Some helpful links on WPF resource dictionary leaks:

*

*DynamicResource\StaticResource cause memory leaks

*Memory leak problem with ResourceDictionary and MergedDictionaries

A: Watch out for events: it's very easy to miss something, because all references from the delegate will exist until the delegate lives. I suggest to use weak event pattern when it's possible. Actually Microsoft uses it in their Prism framework.
http://msdn.microsoft.com/en-us/library/aa970850.aspx
Also check out an issue that I was catched by many times when learning WPF http://support.microsoft.com/kb/938416/en-us


text:
Q: Is it bad practice to renew an access tokens too often? I'm working against a RESTful service that gives me an access token which is valid for an hour. Each time I receive a response from the server, I check if the token has expired and if it has, I renew it and send the request again.
But this got me thinking: what keeps me from getting a new token each time I make a request instead? I would have saved a few lines of codes if I just sent a request for a new token before each request instead of handling the exception when the token actually expire. Are there any technological reasons to avoid this?

A:
what keeps me from getting a new token each time I make a request instead?

Nothing prevent you from getting a new token on each request. You will save few lines of code but the counterpart is that it will increase the number of requests against the authorization server.
The token you have is supposed to be valid for 1 hour. You don't have to ask if it is still valid on every request. Just use and and when the resource server return a 401 HTTP response, you renew it.

A: If you make a request on every call it may cause some latency issue. I hour window is really huge, for every request if you make a call you will end up making too many calls just to get a token when what you have was perfectly fine.
Having said that normally Access token are alive for somewhere between 5 to 10 mins (there is nothing wrong if its valid for longer duration but thats not how they meant to be used). You should not wait to get 401 from the server to refresh the token. Rather than even before making a call to server you can check if AT is going to expire in say next 1 minute and if is then you refresh the token.
Adding couple of lines in your code is a great trade off, if you can shave few milliseconds on your request. The time you save stacks up and lowers your latency
What it saves you from is the time you take to fetch an Access token.


text:
Q: Change CSS element in the same linked sheet to 2 html files My website pages are linked to a single CSS sheet, and I don't want to create another one just for one single detail.
I have a 'wrapper' id whose 'width' is 900px.
And a 'content' id whose 'width' is 540px, because there is a 'sidebar' on the right.
But in one of my pages, the photos one, I want the sidebar to disappear, and the 'content' div to take up all available space of the 'wrapper', it is to say 900px.
Is it possible to do it in the same CSS sheet? I wasn't able to find a solution but to create another file, that I have to keep changing because I modify the main one many times.

A: For example add attribute class to body element and use css selector weight to make changes only to desired page.

A: You can alway override a style. There are three ways of achieving this that I can think of:

*

*Add inline styles to the element itself (in this case style="width: 900px", the nearest declaration always wins)

*create and append a new  element, and add the text to override this style to it

*Modify the css rule itself by adding another declaration (#contetn2 or similar)

Override something already declared with the suffix !important like this:
content {
   width: 450px;
}

widecontent {
   width: 900px !important;
}


text:
Q: Use XML schema groups in XSL transformation I have group definitions in an XML schema. Like so:
<attributeGroup name="my_attributes">
    <attribute ref="ns:foo" />
    <attribute ref="ns:bar" />
</attributeGroup>

Also, I have an XML transformation, in which I want to be able to reuse these definitions. Is it possible to create a template that matches such a group? Something like this maybe:
<xsl:template matchGroup="my_attributes">
    <foobar>
        <xsl:copy-of select="@*"/>
        <xsl:value-of select="." />
    </foobar>
</xsl:template>

A:
Is it possible to create a template that matches such a group?
  Something like this maybe:
<xsl:template matchGroup="my_attributes">
    <foobar>
        <xsl:copy-of select="@*"/>
        <xsl:value-of select="." />
    </foobar>
</xsl:template>

No, the XSLT <xsl:template> instruction doesn't have a matchGroup attribute and
any compliant XSLT processor must raise a syntax error for this reason.
Something like this is probably close to what you are looking for:
<xsl:template match="@ns:foo[../@ns:bar]">
 <!-- Processing here -->
</xsl:template>

The meaning of the match pattern above:
Match any attribute with local-name() foo that is in the namespace to which the prefix "ns:" is associated, and whose "parent" (the ellement this attribute is attached to) *has also another attribute that is named* ns:bar.


text:
Q: Salesforce1  As APEX:SELECTLIST is one among the unsupported Visualforce components of Salesforce1 APP is there any other solution for the select list?

A: You can use hidden apex:inputText and add html select tag with apex:repeate for options and you will need to add JS that will fill in apex:inputText field


text:
Q: Invert array of arrays I have a string[][].
Each entry in the list represents a column in a document, each member of the array represents a line in this column.
Example:
0.0 | 1.0 | 2.0
0.1 | 1.1 | 2.1
0.2 | 1.2 | 2.2

Now I to write this to a file. However if I do that I first need to convert them to string[] where each element is one line, joined by let's say commas (.csv file).
Any suggestions how to do that?
I tried wrapping my head around it with several loops taking the n-th element of each column and stuff it in a buffer and then join these buffers together. I am sure I will get it to work that way, however I don't think that it is in any way efficient or good style.

A: Ok simple: assume that the entire array is rectangular (i.e. same number of items in all rows and same number of items in all columns). What you have to do now, is given an item at (x,y), change its position to (y,x).
So:
var array2 = new string[array1.GetLength(0), array1.GetLength(1)];
for(int i=0;i<array2.GetLength(0);i++){
    for(int j=0;j<array2.GetLength(1);j++)
        array2[i,j] = array1[j][i]; //this is the magic line
}

A: If you're starting with this:
string[][] original = new[] {
    new[] { "0.0", "0.1", "0.2" },
    new[] { "1.0", "1.1", "1.2" },
    new[] { "2.0", "2.1", "2.2" }
};

Then you can do this to work with each row in turn:
for (int column = 0; column < original.Length; column++)
{
    string row = string.Join(",", original.Select(o => o[column]));
    Console.WriteLine(row);
}

This yields the following output:
0.0,1.0,2.0
0.1,1.1,2.1
0.2,1.2,2.2


text:
Q: Summarizing dictionary with top two choices inventory = {'A':['Toy',3, 1000], 'B':['Toy',8, 1100],
              'C':['Cloth',15, 1200], 'D':['Cloth',9, 1300],
               'E':['Toy',11, 1400], 'F':['Cloth', 18, 1500], 'G':['Appliance', 300, 50]}

The alphabets are name of merchandise, the first field in the [] brackets are category of the merchandise, the second field in the [] brackets are price, the third are numbers sold.
I would like to get the top two most expensive (in price) merchandises for each category.  If I don't have at least two merchandises in each category, I would drop it.  So I should have the following result.
inventorySummary = {'B':['Toy',8, 1100], 'E':['Toy',11, 1400],
                     'C':['Cloth',15, 1200], 'F':['Cloth', 18, 1500]}

Could you help me what code I could use to facilitate this?  I need one that I could potentially use for not just top two priced items, but also top three or four priced items.  I will eventually use it against much bigger data set so if it could be more generic code that would be better.  Also I have a hard time understanding lambda expressions, if you choose to offer a code with lambda expression, could you please explain each part as to how it works so that I would be able to manipulate down the road for any changed needs.
I only have these modules available for my system:
bisect,
cmath,
collections,
datetime,
functools,
heapq,
itertools,
math,
numpy,
pandas,
pytz,
Queue,
random,
re,
scipy,
statsmodels,
sklearn,
talib,
time,
zipline

A: You can use itertools.groupby to create the groups:
from itertools import groupby

def summarize_inventory(inventory):
    # We use -price so that we are also sorting by descending price
    sort_key = lambda (code, (cat, price, sold)): (cat, -price)
    group_key = lambda (code, (cat, price, sold)): cat

    new_dict = {}
    sorted_inventory = sorted(inventory.iteritems(), key=sort_key)
    for cat, group in groupby(sorted_inventory, key=group_key):
        group = list(group)
        if len(group) > 1:
            for (code, item) in group[:2]:
                new_dict[code] = item
    return new_dict

Example
>>> summarize_inventory(inventory)

{'B': ['Toy', 8, 1100],
 'C': ['Cloth', 15, 1200],
 'E': ['Toy', 11, 1400],
 'F': ['Cloth', 18, 1500]}

A: To get the top N of any series in the most efficient way possible, use the heapq module. You'll have to create a heap per category:
from heapq import heapify, heappushpop

def summarize_inventory(inventory, top_n=2):
    categories = {}
    for id, info in inventory.items():
        cat, _, sold = info
        heap = categories.setdefault(cat, [])
        if len(heap) < top_n:
            heap.append((sold, id, info))
            if len(heap) == top_n:
                heapify(heap)
        else:
            heappushpop(heap, (sold, id, info))

    # produce the final summary, only include categories with enough items
    return {id: info
            for cat, heap in categories.items() if len(heap) == top_n
            for sold, id, info in heap}

The first loop builds the heaps up to size 2, heapifies those two items then uses the heapq.heappushpop() function to add the next item to the heap and remove the so-far smallest in one step.
This is a O(NlogK) solution; for an input of size N (the number of keys in the input dictionary) and asking for the top K elements, the heap queue approach takes N times log K steps to produce the solution.
If you want to compare this to a O(NlogN) sorting solution (sort by category and price, then group by category), then this solution less time to complete as N grows. For getting the top two results for a given 1000 items, this takes 1.000 * 1 == 1.000 steps. Sorting would take 1.000 * 10 == 10.000 steps. For 1.000.000 inputs, that becomes 1 million vs. 1 billion steps, etc.
For your given inventory that produces:
>>> summarize_inventory(inventory)
{'B': ['Toy', 8, 1100], 'E': ['Toy', 11, 1400], 'D': ['Cloth', 9, 1300], 'F': ['Cloth', 18, 1500]}
>>> from pprint import pprint
>>> pprint(_)
{'B': ['Toy', 8, 1100],
 'D': ['Cloth', 9, 1300],
 'E': ['Toy', 11, 1400],
 'F': ['Cloth', 18, 1500]}

The function works for any top N you might care to produce:
>>> summarize_inventory(inventory, 3)
{'A': ['Toy', 3, 1000], 'C': ['Cloth', 15, 1200], 'B': ['Toy', 8, 1100], 'E': ['Toy', 11, 1400], 'D': ['Cloth', 9, 1300], 'F': ['Cloth', 18, 1500]}
>>> summarize_inventory(inventory, 1)
{'E': ['Toy', 11, 1400], 'G': ['Appliance', 300, 50], 'F': ['Cloth', 18, 1500]}

A: enrico.bacis beat me to a itertools.groupby solution, but here's my version if it helps you out (I tried to do it FP style):
def summarize_inventory(inventory, top_n=2):
    sort_key = lambda (id, (category, price, sold)): (category, price)
    group_key = lambda (id, (category, price, sold)): category

    # items in inventory grouped by their category
    items_by_category = (
        (category, list(items))
        for category, items in itertools.groupby(
            sorted(inventory.iteritems(), key=sort_key),
            group_key
        )
    )

    # the top_n items from each category if there are >= top_n items
    inventory_summary = dict(itertools.chain.from_iterable(
        items[-1 * top_n:]
        for category, items in items_by_category
        if len(items) >= top_n
    ))

    return inventory_summary


text:
Q: JSCH access to login putty After successfully login into putty using jsch. I want to pass commands in string form directly from file and also enter should happen automatically.
If any one have idea please help me.
Thanks in advance


text:
Q: How to write an SQL query that uses wild-card map to do transformation I have a source table A with a number of columns. I want to do a transformation of the source table to a target table. I would like to have a mapping table with same columns as the source table A and with rows that make up the translations.
Here is an example of the table A:
COL1    COL2    COL3
aktie   ja         2
aktie   nej        3
obli    ja         2

and here is the mapping table
COL1    COL2    COL3        TRANSFORM
aktie   ja      NULL            3
aktie   NULL    NULL            4

Now, the idea is to join the source table with the mapping and get the transformed value returned. The use of NULL should serve as a wildcard. So my desired result should be that the first row in table A would match the first row in the mapping table and return the value 3
For the second row - and here is my challenge - I want it to match the second row in the mapping table because it is NOT matched by rows that have a value already (which would result in the transformed value 3) and as the second mapping row has NULL in column two, it should be treated as a wildcard (although taking into account other rows in the mapping table as well).
My first attempt would be something like
select A.*, m.res
from tab1 A
inner join mapping m on t.col1 = isnull(m.col1, t.col1)
                     and t.col2 = isnull(m.col2, t.col2)
and ...

but the problem is that the isnull(..,..) will match everything and not only return matches except the listed possible values that would result in a different transformation.
I am looking for a generic solution that would Work for any table with any number of columns, not only this particular table-layout mentioned here.
I have been thinking a lot about this and cannot really seem to come up with the solution, so please help :)

A: Here is one way to do this using a CTE (will work on SQL Server and Oracle)
WITH Map3 as
( -- TRANSFORM WILL BE NULL IF A MATCH WAS NOT MADE
   SELECT T1.COL1, T1.COL2, T1.COL3, M.TRANSFORM
   FROM Table1 T1
   LEFT JOIN Mapping M ON T1.COL1 = M.COL1
                      AND T1.COL2 = M.COL2
                      AND T1.COL3 = COALESCE(M.COL3, T1.COL3)
), Map2 as
(
   SELECT T1.COL1, T1.COL2, T1.COL3, COALESCE(T1.TRANSFORM,M.TRANSFORM)
   FROM Map3 T1
   LEFT JOIN Mapping M ON T1.COL1 = M.COL1
                      AND T1.COL2 = COALESCE(M.COL2, T1.COL2)
                      AND T1.TRANSFORM IS NULL
)
SELECT *
FROM Map2

I believe it is clear how this works and how to "extend" this to more columns.

If you can't use a CTE this is functionally the same and can be nested as far as you like:
SELECT T1.COL1, T1.COL2, T1.COL3, COALESCE(T1.TRANSFORM,M.TRANSFORM)
FROM (
   -- TRANSFORM WILL BE NULL IF A MATCH WAS NOT MADE
   SELECT T1.COL1, T1.COL2, T1.COL3, M.TRANSFORM
   FROM Table1 T1
   LEFT JOIN Mapping M ON T1.COL1 = M.COL1
                      AND T1.COL2 = M.COL2
                      AND T1.COL3 = COALESCE(M.COL3, T1.COL3)
) T1
LEFT JOIN Mapping M ON T1.COL1 = M.COL1
                   AND T1.COL2 = COALESCE(M.COL2, T1.COL2)
                   AND T1.TRANSFORM IS NULL


text:
Q: Laravel - Validating Array Input Request Data for Uniqueness within Database I'm having trouble validating an input array and checking using the unique: validation rule, and I was hoping someone could help me further.
Input (multiple of) from view:
<input type="text" class="form-control" name="contactNames[]" required>

an example of my dd($request):
+request: ParameterBag {#44 ▼
    #parameters: array:6 [▼
        "_token" => "0WBYH4G4aB4XtkQ1Vx29cIvaH7SbYYVcXI6yOuNn"
        "name" => "Brand Name"
        "groupCheckbox" => array:3 [▶]
        "contactNames" => array:2 [▼
            0 => "Contact Name 1"
            1 => "Contact Name 2"
        ]
        "emails" => array:2 [▼
            0 => "test@test.com"
            1 => "test2@test.com"
        ]
        "contactNumbers" => array:2 [▼
            0 => "07777777777"
            1 => "07777777777"
        ]
    ]
}

and within my controller, my validation:
$request->validate([
    'name' => 'required|string|max:255|unique:brands',
    'contactNames' => 'required|array',
    'contactNames.*' => 'required|max:255|string|distinct|unique:brand_managers',
    'emails' => 'required|array',
    'emails.*' => 'required|max:255|email|distinct|unique:brand_managers',
    'contactNumbers' => 'array',
    'contactNumbers.*' => 'numeric',
    'groupCheckbox' => 'required|min:1'
]);

I need to check whether a username is unique or not - the validation works fine if I don't use the unique: validation rule and the data posts correctly to my database, however I don't want multiple brand managers with the same details so need to validate the uniqueness of name and email address
The error I am getting is:

SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'contactNames.0' in 'where clause' (SQL: select count(*) as aggregate
  from brand_managers where contactNames.0 = Contact Name 1)

Thanks for your help in advance

A: I have found a solution - thanks for the help though - for anyone else in the future who may have the same problem here was my solution:
$request->validate([
    'name' => 'required|string|max:255|unique:brands',
    'contactNames' => 'required|array',
    'contactNames.*' => ['required', 'max:255', 'string', 'distinct', Rule::unique('brand_managers', 'name')],
    'emails' => 'required|array',
    'emails.*' => ['required', 'max:255', 'email', 'distinct', Rule::unique('brand_managers', 'email')],
    'contactNumbers' => 'array',
    'contactNumbers.*' => 'numeric',
    'groupCheckbox' => 'required|min:1'
]);


text:
Q: How to make a menu that repeats in C I'm making a file compressor program in C, and I'm creating a friendly menu that appears in the beginning of the program.
That's the simplified code:
Compress.c
int main()
{

    char directory[100];
    char option;
    bool exit = false;

    do
    {

        printf("|------------------------------------|\n");
        printf("|             Welcome!               |\n");
        printf("|                                    |\n");
        printf("|Select one of the following options:|\n");
        printf("|    1 - Compress a file             |\n");
        printf("|    2 - Decompress a file           |\n");
        printf("|    3 - Exit                        |\n");
        printf("|------------------------------------|\n");

        scanf(" %c", &option);

        switch(option)
        {
            case '1':
                printf("Enter the FULL directory or drag HERE the file you want to COMPRESS: \n");
                scanf(" %s", directory);

                /* COMPRESS FILE */

                break;

            case '2':
                printf("Enter the FULL directory or drag HERE the file you want to UNCOMPRESS: \n");
                scanf(" %s", directory);

                /* DECOMPRESS FILE */

                break;

            case '3':
                exit = true;
                break;

            default:
                printf("Invalid option!\n\n");
                break;
        }
    }while(exit == false);

    return 0;
}

After typing '1', for example, and typing a CORRECT directory, the program prints 10 times the menu and returns 0. But when I type an INVALID or NONEXISTENT directory, it works, because it prints only 1 time the menu and waits for user types the option again!
Why is it doing that?

A: Changing scanf(" %s") to this, did the trick:
getchar();
gets(directory);

//AFTER READING THAT DIRECTORY, WE NEED TO CHECK IF IT HAS QUOTES ON IT:
if(directory[0] == '\"')  //IF IT HAS, ENTER HERE
{
    /* REMOVE ALL QUOTES IN THE DIRECTORY */
}


text:
Q: Getting errors when starting an ionic project for the first time I cloned an ionic project online that works for others, but when I do an ionic serve, I get the below errors. The site says it that it started up, but there are tons of errors in the log, and going to the site just shows those same errors.
I have node 10.16.0, and it's using an Angular 5.2.0 codebase and Ionic. I ran the command of sudo npm install -g cordova@8.0.0 ionic@4.0.1 which I think was needed as well.
And looking at package.json, I see "angularfire2": "5.3.0"
ionic-app-scripts serve --address 0.0.0.0 --port 8100 --livereload-port 35729 --dev-logger-port 53703 --nobrowser
[app-scripts] [19:39:42]  ionic-app-scripts 3.2.4
[app-scripts] [19:39:42]  watch started ...
[app-scripts] [19:39:42]  build dev started ...
[app-scripts] [19:39:42]  clean started ...
[app-scripts] [19:39:42]  clean finished in 1 ms
[app-scripts] [19:39:42]  copy started ...
[app-scripts] [19:39:42]  deeplinks started ...
[app-scripts] [19:39:42]  deeplinks finished in 242 ms
[app-scripts] [19:39:42]  transpile started ...
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/auth/auth.d.ts, line: 8
[app-scripts]             Cannot find name 'User'.
[app-scripts]        L7:  readonly auth: FirebaseAuth;
[app-scripts]        L8:  readonly authState: Observable<User | null>;
[app-scripts]        L9:  readonly idToken: Observable<string | null>;
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/auth/auth.d.ts, line: 10
[app-scripts]             Cannot find name 'User'.
[app-scripts]        L9:  readonly idToken: Observable<string | null>;
[app-scripts]       L10:  readonly user: Observable<User | null>;
[app-scripts]       L11:  readonly idTokenResult: Observable<auth.IdTokenResult | null>;
[app-scripts]             Namespace ''*'' has no exported member 'IdTokenResult'.
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/auth/auth.d.ts, line: 11
[7:49 PM]
[app-scripts]       L10:  readonly user: Observable<User | null>;
[app-scripts]       L11:  readonly idTokenResult: Observable<auth.IdTokenResult | null>;
[app-scripts]       L12:  constructor(options: FirebaseOptions, nameOrConfig: string | FirebaseAppConfig | null | undefined, platformId: Object, zone: NgZone);
[app-scripts]             Namespace '''' has no exported member 'Database'.
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/firebase.app.module.d.ts, line: 13
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/firebase.app.module.d.ts, line: 14
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/firebase.app.module.d.ts, line: 16
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/firebase.app.module.d.ts, line: 18
[app-scripts]       L12:  export declare const FIREBASE_APP_NAME: InjectionToken<string | FirebaseAppConfig | undefined>;
[app-scripts]       L13:  export declare type FirebaseDatabase = database.Database;
[app-scripts]       L14:  export declare type FirebaseAuth = auth.Auth;
[app-scripts]             Namespace '''' has no exported member 'Auth'.
[app-scripts]       L13:  export declare type FirebaseDatabase = database.Database;
[app-scripts]       L14:  export declare type FirebaseAuth = auth.Auth;
[app-scripts]       L15:  export declare type FirebaseAnalytics = any;
[app-scripts]             Namespace '''' has no exported member 'Messaging'.
[app-scripts]       L15:  export declare type FirebaseAnalytics = any;
[app-scripts]       L16:  export declare type FirebaseMessaging = messaging.Messaging;
[app-scripts]       L17:  export declare type FirebasePerformance = any;
[app-scripts]             Namespace '''' has no exported member 'Storage'.
[app-scripts]       L17:  export declare type FirebasePerformance = any;
[7:49 PM]
[app-scripts]       L18:  export declare type FirebaseStorage = storage.Storage;
[app-scripts]       L19:  export declare type FirebaseFirestore = firestore.Firestore;
[app-scripts]             Namespace '''' has no exported member 'Firestore'.
[app-scripts]       L18:  export declare type FirebaseStorage = storage.Storage;
[app-scripts]       L19:  export declare type FirebaseFirestore = firestore.Firestore;
[app-scripts]       L20:  export declare type FirebaseFunctions = functions.Functions;
[app-scripts]             Namespace '''' has no exported member 'Functions'.
[app-scripts]       L19:  export declare type FirebaseFirestore = firestore.Firestore;
[app-scripts]       L20:  export declare type FirebaseFunctions = functions.Functions;
[app-scripts]       L21:  export declare type FirebaseRemoteConfig = any;
[app-scripts]             Namespace ''*'' has no exported member 'auth'.
[app-scripts]       L13:  // firebase auth - google - Create an instance of the Google provider object:
[app-scripts]       L14:  let googleProvider: firebase.auth.GoogleAuthProvider = new firebase.auth.GoogleAuthProvider();
[app-scripts]       L15:  // let twitterProvider: firebase.auth.TwitterAuthProvider = new firebase.auth.TwitterAuthProvider();
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/firebase.app.module.d.ts, line: 19
[app-scripts] [19:39:50]  typescript: node_modules/@angular/fire/firebase.app.module.d.ts, line: 20
[app-scripts] [19:39:50]  typescript: src/pages/signup/signup.ts, line: 14
[7:50 PM]
[INFO] Development server running!

       Local: http://localhost:8100/
       External: http://192.168.86.61:8100/
       DevApp: my0site@8100 on imac.lan

       Use Ctrl+C to quit this process

[INFO] Browser window opened to http://localhost/:8100!

[app-scripts] [19:39:50]  copy finished in 8.68 s
[app-scripts] [19:39:51]  watch ready in 9.22 s


text:
Q: Getting an "Error: Could not find or load main class" while running EMR? I am trying to run jobs in Alibaba Cloud E-MapReduce, it throws me an error like
Error: Could not find or load main class

For even while trying to execute predefined examples like word count this error occurs, so that I think I am having some configuration error.
What I am missing?

A: Alibaba Cloud E-MapReduce requires the path protocol header of the Job Jar as ossref in the job configuration.
just check the job configuration, if it is not ossref, change it to ossref.
I hope this will solve your problem.


text:
Q: Is it possible to add test elements on the fly to JMeter with Java code? I'm being able to create jmx files by using Java code, those output files contain elements such as test plan and samplers; however, I'm running an initialization routine that loads variables from disk and should create/configure new samplers based on that. I don't know how to access the running test plan element or add new sampler elements on the fly though.
Is it something possible to do? I've been browsing the API docs but haven't found a way to do it yet.

A: it is possible to add new elements on the fly but these new elements will not be executed because the StandardJMeterEngine is started and not aware of them unless you restart the test.
you can create one test containing the routines and create another test plans from a template that you modify, save and run.
another solution is to work only with Variables loaded by the routine
this method provide the possibility to access the testplan at runtime and modify their childs elements
 org.apache.jmeter.gui.GuiPackage.getInstance().getTreeModel().getTestPlan();

to execute a test :
FileInputStream in = new FileInputStream(testPlanPath);
HashTree testPlanTree = SaveService.loadTree(in);
in.close();
StandardJMeterEngine jmeter = new StandardJMeterEngine();
jmeter.configure(testPlanTree);
jmeter.runTest();

Do not hesitate if you need more informations.