text:
Q: How to share session between two django application? I have two django application which are on same server on  port 80 and 9002. i.e. urls are www.abc.com and www.abc.com:9002
Both share same database postgresql for authentication. I want to share the share the session data between them so that user logged in to one application can log in automatically in another application.
I read these answers : Multiple Django apps, shared authentication and How to get distinct Django apps on same subdomain to share session cookie?
And did this in my both django application:

*

*Used the same secret key in both.

*Added these lines:
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_NAME = 'abc'
SESSION_COOKIE_DOMAIN = '.abc.com'
But still I am unable to achieve the purpose.
How to share the session cookie between two django apps so that i can have shared authentication?

A: Other than you have to apply these settings to both applications,
the only thing missing with your approach is the SESSION_COOKIE_DOMAIN.
You set it to '.abc.com', which means it will work if your app has domain name: www.abc.com and somesubdomain.abc.com.
But your second app in this case www.abc.com:9002, by including the port it doesn't share the same TLD with www.abc.com. So, django thinks www.abc.com:9002 and www.abc.com are very different domain and not from the same root .abc.com.
If I'm working on this, there are several possible approach:

*

*Combine both app into one single root django app. Django app were modular anyway, so you could create one single ROOT_URL_CONF and DJANGO_SETTINGS_MODULE to specify how these two apps works in the same domain. You could, for example, append a different prefix url for each app.

*You use load balancer, or reverse proxy, such as nginx or haproxy to assign different subdomain for each app, then deploy each app in a different port. Let's say, the end result is you have the first django app deployed on first.abc.com and the second app in second.abc.com (All with port 80 in the frontend), then it will share the same session. Just remember that in the backend you need to assign the actual port that the app uses.
Additional notes from mine. In production settings, you also want to add ALLOWED_HOSTS settings and include .abc.com in the list.


text:
Q: Implementing Redux functionality using Context and Reducers in React not working Properly So i am trying to implement the functionality of redux using only react hooks as shown in the following links https://codeburst.io/global-state-with-react-hooks-and-context-api-87019cc4f2cf & https://www.sitepoint.com/replace-redux-react-hooks-context-api/ But I cant seem to get it to work properly for some reason. I am trying to implement a basic setup where the DO_ACTION action is dispatched when button is clicked and the counter global state is shown below the button. When I do click on the increment action button after clicking it a few times, I get undefined for some reason. What am I doing wrong here?
Before clicking

After clicking 3 or 4 times

Here is my folder structure just in case you think i am importing wrong stuff

Button component
import './Button.css';
import React, {useEffect, useContext} from 'react';
import {Context} from '../../store/Store.js';

const Button = ( props ) => {

const [state, dispatch] = useContext(Context);

const incrementAction = () => {
    dispatch({
        type:'DO_ACTION',
        payload: 1
    })
    console.log(state.number);
  };

return (

        <button onClick={() => incrementAction()}>Display Number!!!!</button>

{state.number}

    )
};

export default Button

here is my reducer
const Reducer = (state, action) => {
switch (action.type) {
    case 'DO_ACTION':
        return state + action.payload
    }
};

export default Reducer;

Here is my global store and HOC
import React, {createContext, useReducer} from "react";
import Reducer from './Reducer';

const initialState = {
    number: 5
};

const Store = ({children}) => {
    const [state, dispatch] = useReducer(Reducer, initialState);

    return (
        <Context.Provider value={[state, dispatch]}>
            {children}
        </Context.Provider>
    )
};

export const Context = createContext(initialState);
export default Store;

And here is my main App component that is wrapped with store to have it accessible throughout my app
import Store from './store/Store.js';
import Button from './components/Button/Button.js';

const App = () => {

    return (

          <Store>
            <Button />
            <OtherComponents /> //a bunch of other components go here like title, paging etc
          </Store>

    );
}

export default App;

A: You need to be returning the whole (cloned) state object from your reducer function, not just the property you want to update. You should also make sure you have a default case:
const Reducer = (state, action) => {
    switch (action.type) {
        case 'DO_ACTION':
            return {
                number: state.number + action.payload
            }
        default:
            return state;
    }
};

export default Reducer;

If you have more than one property in your state object you must remember to clone all of the other properties into it as well (e.g. {...state, number: state.number + action.payload}).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Refactoring Long and Too Many Branches Methods for Rubocop I provided an update below to some findings...
Here's a method I have in my current code:
def query(data_set, conditions)
  query_data_set = data_set.dup
  search_conditions = parse_conditions(conditions)

  search_conditions.each do |condition|
    if condition.class == Array
      condition.each do |term|
        if term.class == Symbol
          query_data_set = entity.send term, query_data_set
        else
          query_data_set = search_data_text(query_data_set, term)
        end
      end
    end

    if condition.class == Hash
      condition.each do |key, value|
        query_data_set = method("query_#{key}").call(data_set, value)
      end
    end
  end

  query_data_set
end

Rubocop hates this for three reasons:
C: Assignment Branch Condition size for query is too high. [17.03/15]
  def query(data_set, conditions)

C: Method has too many lines. [19/7]
  def query(data_set, conditions)

C: Use next to skip iteration.
  search_conditions.each do |condition|

I don't EVER want to skip an iteration so I'm not sure why I would use next at all. There is never a case where skipping an iteration would make sense for this bit of code.
So going to the other complaints, you'll see at that the top of this method I have already broken out one action (the call to parse_conditions). There's also a call to search_data_text. My only point here being I have tried to be modular where it seemed to make sense.
Even if I move that large search_conditions.each block to a separate method, Rubocop is going to complain that my new method is too long as well. Which I suppose means adding yet a third method that my second method will call? That seems odd to me. Or perhaps it means I have to not branch so much, I guess. But why is the branching bad? Even if I switch to some other structure (like a case...when), I'm still branching. And I do need to test those conditions because handling is different for a nested array, an array with a symbol, or a hash.
I'm trying to build up my intuition for being able to look at problems like this and figure out an effective and efficient solution .... but it seems what I end up doing is being terribly inefficient and ineffective with my time. That tradeoff is worrying me given that I can't see why my code is bad.
Anyone mind taking a stab at this and helping me see how I can get the above method into a state that maintains some semblance of readability but that fits into the style guidelines that Rubyists prefer?
----------------------
UPDATE
----------------------
About the best I could come up with is this:
def query(data_set, conditions)
  query_data_set = data_set.dup
  parse_conditions(conditions).each do |condition|
    query_data_set = check_conditions(condition, query_data_set)
  end
  query_data_set
end

def check_conditions(condition, data)
  if condition.class == Array
    condition.each do |term|
      data = entity.send term, data if term.class == Symbol
      data = search_data_text(data, term) unless term.class == Symbol
    end
  end

  if condition.class == Hash
    condition.each do |key, value|
      data = method("query_#{key}").call(data, value)
    end
  end
  data
end

That check_conditions method is still too long for Rubocop and still has too high of a branch condition size.
As far as I can see, and nowhere I've checked has been able to show me different, the only thing that can be done would be to perhaps make methods out of the checks for array and hash. In other words, each if condition in check_conditions would get its own method. But that seems needlessly silly to me. I'm basically breaking up logic, passing variables to different methods, just so that I can keep my method count below some arbitrary value.
This feels way wrong to me as a way to do design. But I don't see a way to change my logic such that it still accomplishes what it needs to but does so under seven lines per method.

A: def query(data_set, conditions)
  data_set = data_set.dup
  parse_conditions(conditions).each do |condition|
    condition.each do |e|
      case e
      when Array  then method("query_#{e.first}").call(data_set, e.last)
      when Symbol then entity.send(e, data_set)
      else             search_data_text(data_set, e)
      end
    end
  end
end

A: Okay, found a way to do it. It may not be the cleanest but nothing else was working. Here's what I did:
def query(data_set, conditions)
  query_data_set = data_set.dup
  parse_conditions(conditions).each do |condition|
    query_data_set = check_conditions(condition, query_data_set)
  end
  query_data_set
end

def check_conditions(condition, data)
  data = process_condition_array(condition, data) if condition.class == Array
  data = process_condition_hash(condition, data) if condition.class == Hash
  data
end

def process_condition_array(condition, data)
  condition.each do |term|
    data = entity.send term, data if term.class == Symbol
    data = search_data_text(data, term) unless term.class == Symbol
  end
  data
end

def process_condition_hash(condition, data)
  condition.each do |key, value|
    data = method("query_#{key}").call(data, value)
  end
  data
end

So I had one method that I thought was reasonable, albeit admittedly a bit wordy. But everything was in one place. This has now become four methods where, as a reader of the code, you have to trace the variables through those methods. I guess that's progress. :-/
Interestingly, after all this, my entire class is now considered too long by Rubocop. Sigh. Anyway, living with that particular arbitrary style is at least more palatable than living with the other arbitrary styles.

A: To expand on your own answer, I would maybe suggest some functional goodness... (i.e., Enumerable.inject plus lambda A.K.A. first order functions).
(Note that I did not question or change the logic of your own code; I simply transformed it mechanically).
def query(data_set, conditions)
  parse_conditions(conditions).inject(data_set) do |data_set, condition|
    check_conditions(condition, data_set)
  end
end

processors = {
  'Array' => lambda do |condition, data|
               condition.inject(data) do |data,term|
                 term.class == Symbol ? entity.send(term, data)
                                      : search_data_text(data, term)
               end
             end,
  'Hash' => lambda do |condition, data|
               condition.to_a.inject(data) do |data, pair|
                 method("query_#{pair[0]}").call(data, pair[1])
               end
             end
}

def check_conditions(condition, data)
  processors[condition.class.name].call(condition, data)
end

A few less lines of code (inconsequential), and the explicit if/else control structures plus explicit "data = " and "return data" parts are gone. Everything is very explicit now, and the chance for obscure little errors is less.
Of course, only do things like that if you are working in a team that knows/likes the functional style; some folks dig it, others hate it.
If you were not working on Hash and Array, I would likely suggest to use OO instead of the functions (i.e., distribute the two processing methods into their respective classes). Technically possible by re-opening Hash and Array; certainly not advisable though.


text:
Q: Unable to test Production Push Notifications through AdHoc I'm following Parse's Push Notification Tutorial for setting up my Parse app to now be able to send Production push notifications, rather than Development ones, so I can get it ready for the app store. This is covered in section 7.1 in the tutorial.
When I attempt to create an AdHoc provisioning profile, it only works if I create an iOS distribution certificate, when I create an APN production certificate, which is the correct one for this purpose, it shows me this:
If I decide to go ahead and use the iOS distribution certificate from this list instead:

The provisioning profile is successfully created, but again, it's not using the correct certificate for push notifications. Likewise, because I had to use the distribution one to create the profile, I therefore would have to use the certificates .p12 file when connecting my Parse Notification settings to this profile. When I attempt to do this, I unsurprisingly receive the following error:

because I'm uploading the .p12 of an iOS Distribution  certificate, and not the APN Production iOS certificate. When I try uploading the .p12 of the APN Production iOS certificate to Parse, it works, but my test iOS device doesn't receive push notifications, because the provisioning profile doesn't use that certificate, as I mentioned earlier.
Am I following the directions incorrectly? Why can't I make a provisioning profile using a Production APN certificate, so that it can work with Parse Push Notifications?

A: I have never used parse, but you have two exact production certificate.
This is an issue, revoke one of them and try again should work!

the provisioning profile doesn't use that certificate

I think you are misunderstanding what you need to do:

*

*delete the app from your device

*Build your app signed with distribution certificate

*Install the ad-hoc version of the app on your device

Here is an image to illustrate how the provision profile  works:

It's a good idea to check apple docs out
Also very important to check which provisioning profile you have used to sign and build the app.

A: Turns out my error was forgetting to set the code signing settings in both Project AND Targets.


text:
Q: What does the notation $\times_K \mathscr{X}_k$ mean? I need help understanding the second half of this equation. Specifically the $\times_K \mathscr{X}_k$ term. I believe the left hand side means that we have a set of n feature vectors each of which has k features. But, what is $\times_K$? Is $\mathscr{X}_k$ the $k$-th element of the set of all feature vectors?
$$\mathbf{x}^n = (x^n_1, x^n_2, \dotsc, x^n_K) \in \times_K \mathscr{X}_k.$$
I am still a student so, simple answers would be best.
I have checked the wiki table of math symbols as well as an online source for understanding set theory. But I do not understand the notation $\times_K \mathscr{X}_k$.
EDIT: To provide more information, this is from a research paper in computer science called "Timely Classification with Randomly Delayes Features" By Jie Xu
The full paragraph is:
We consider that a set of  classification tasks arrive in
sequence, indexed by {1,2,...,}. The -th task to arrive
is denoted by task . For each task , there is a cor-
responding data instance characterized by a feature vector
$^ = (^_1, ^_2, ..., ^_) ∈ ×_ _ ≜ .$ There is a label $^ ∈ $
associated with the instance $^$ but it is not revealed until
the classification is made. In the classical setting, a prediction
function  : $×_ _$ →  is used, taking the whole feature
vector $^$ as the input, to output a predicted label ˜$ ^$ . This
implicitly assumes that all features $^
_$ ,∀ become available
simultaneously so that the classifier can utilize all features. In
our considered setting, the different features of $^$ may not
arrive at the same time. Instead, features arrive in sequence
and let $^_$
denote the random delay associated with receiving
the feature
 , which may be different for different tasks .
Hence, in order to know the value of
 , we need to wait a
time of
 . Denote by ( 1 ,...,  ) the joint distribution of
the random delays.


text:
Q: How to find frequency of each element of Array in Swift Input : 1 3 4 2 3 1
Output:
Element 1 : Count 2
Element 3 : Count 2
Element 4 : Count 1
Element 2 : Count 1
var count:Int
let tempArray = [1, 1,1, 4 ,1]
var index  = 0
var fequency = [Int]()
for m in 0 ..< tempArray.count{
  fequency.append(-1)
}
print(fequency)
for i in 0 ..< tempArray.count{
  count = 1
  for j in i + 1  ..< tempArray.count{
    index = j
    if tempArray[i] == tempArray[j]{
      count = count + 1
   fequency [j] = 0
      print(fequency)
  }
    if fequency[i] != 0 {
        fequency[i] = count
     // print("frequency->",fequency)
    }

}
  print("\(tempArray[i]) occures at \(fequency[i]) times")

}


text:
Q: How do I increase size of maxJsonLength for web api method input parameter? Currently implementing a web method (mvc framework 4.5.2) which is supposed to received a list of items as a parameter input as bellow:
 [HttpPost]
        public ActionResult GetDummyResults(DummyProductsDto productsDto)}
{
    var dummy = getMeSomeResults(productsDto);
    return Json(new { result = dummy }, JsonRequestBehavior.AllowGet);
}

When my list of products is less than 2K, the method works just fine, if it goes over 2K items, it crashes with the exception: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength
property. Parameter name: input
I've tried a plethora of suggested tweaks for the web.config like ( <jsonSerialization maxJsonLength="2147483647"/> ) to no avail. Some others point to implement this inside the method: var serializer = new JavaScriptSerializer(); serializer.MaxJsonLength = Int32.MaxValue; but I guess this suggestion applies to issues with the response, not the request itself which seems to be the issue here. Any hint as to where should I be aiming at ? ... it seems to me, the request size of the input parameter to to be the culprit here, just not sure how to fix it.
-thanks,

A: I was able to implement ashiquzzaman code found over here: Can I set an unlimited length for maxJsonLength in web.config? He's basically overwriting MVC controller max json Deserializetion limit of 4 mb. (thanks)

A: Try these settings in your web.config:
<configuration>
   <system.web>
       <httpRuntime maxRequestLength="2147483647"/>
   <system.web>
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="2147483647"/>
           </webServices>
       </scripting>
   </system.web.extensions>
   <system.webServer>
       <security>
           <requestFiltering>
               <requestLimits maxAllowedContentLength="2147483647" />
           </requestFiltering>
       </security>
   </system.webServer>
</configuration>


text:
Q: Git apply patch to specific file outside of git repo I have two files, x_original.txt and x_updated.txt.
I used the following command to obtain a patch file:
git diff --no-index x_original.txt x_updated.txt > fix_something.patch

I now want to apply this patch to a file called x.txt.
The following is worth noting:

*

*x.txt is not in a git repo

*the filenames x_original.txt and x_updated.txt are included in fix_something.patch which makes no sense because these files won't exist when I'm applying the patch

What git command can I use to apply this patch? Or another utility if necessary? And what modifications should I make to the patch file?

A: I found out how to do it using the patch command:
patch -p1 x.txt fix_something.patch

This utility appears to ignore the filenames specified in the patch file, so there's no need to modify anything there.


text:
Q: Initialise arrays and dictionaries with large numbers of values I need to be able to intialise arrays in my source code with some pre-defined values, that look a bit like below. However each array is going to have possibly thousands of values.
@"key",@"value",
@"key",@"value",
@"key",@"value",
@"key",@"value",
...etc...

How do I initialse (for example) an NSDictionary with these values without having to have thousands of values inline with my source code, ie something like this:
tokens = [[NSDictionary alloc] initWithObjectsAndKeys:
    #import "keyvaluepairs1.h"
    #import "keyvaluepairs2.h"
    , nil];

or even just a pure array like this:
char[] tokens = {
    #import "schoolnames.h"
    #import "universitynames.h"
    }

What I am looking for is not an objective-c "trick", but more of an understanding on how you can instruct the compiler import or suck in contents of other files. I am open to other ideas on how to achieve this if required.

A: You could create a plist that is a NSDictionary of NSArrays.  Then easily read the plist into a NSDictionary and then retrieve each array from it.
 NSString *path = [[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"plist"];
 NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
 NSArray *array = [dict objectForKey:@"array1"];

As pointed out, this would be required to be read at least once each time the app is loaded from the 'not running' state

A: If your text file is in the format you show above, you'll need to write a simple parser to read the data into an NSDictionary.
Since the format "vocabulary" is simple, a linear parser based on NSScanner would be straightforward to implement.

A: After much searching, I believe I have found a simple way to achieve this without having to make sure there are text files lying around everywhere. You can make your header files look like this:
#define  SAMPLE_ARRAY \
@"a",   @"value",\
@"b",   @"value",\
@"c",   @"value",\
...etc...

And then import or use them like this:
tokens = [[NSDictionary alloc] initWithObjectsAndKeys:
    SAMPLE_ARRAY
    SAMPLE_ARRAY2
    nil];

Given that the data will never change, I can't see any major problems with this.


text:
Q: Is .Include still working on Entity Framework Core & .NET 5.0? When I try to write this code .Include is not recognized
dbContext.Field.Include(i => ..);

Example:

A: It looks like you miss the using statement so that the Include Extension is found.
So add using Microsoft.EntityFrameworkCore; to get access to Include.


text:
Q: How to remove the Square mouse pointer in WinForms in Visual Studio 2022 I have this strange issue with Visual Studio 2022. I have a Windows Forms app and in some forms I have a square as the mouse pointer. It doesn't let me do anything. I can't resize or move controls, etc.

It's the same issue this user had: https://www.youtube.com/watch?v=Qo1oqg2Wl5k.
However, the solution he used doesn't works for me.
The forms that present this issue are derived from another form, such as this:
public partial class Form1 : maintenance

How can I get back a normal mouse cursor?
EDIT: The issue is in the form designer, not when running the app

A: It is probably some debug feature. Try building using release preset and run the executable without debugger and report back if that worked or not.


text:
Q: Firestore Query using a map of values does not invoke listener when the map is modified As "collection group query" is still not implemented on Firestore I am using a map of values as a workaround. Here is the structure:
/chat/[room_id]/
                 user[ user_id ] = true

The query is something like:
db.collection( 'chat' )
  .doc( room_id )
  .where( 'user.' + user_id, "==", true )
  .onSnapshot( ... )

They query works perfectly, but if a "user-map" adds or remove the "user_id" field, the listener (onSnapshot) is not called. On Firebase console the value flashes indicating that a change was made.
According to the documentation maps are automatically indexed, so it should not be a indices problem.
Any idea?

A: Looking at the documentation we can see that:

Queries on multiple fields with range filters require a composite
  index. Unfortunately, this is not possible with the approach shown
  above. Indexes must be defined on specific field paths. You would have
  to create an index on each possible field path (such as
  categories.cats or categories.opinion) which is impossible to do in
  advance if your categories are user generated.

The "approach shown above" refers to the case where you are performing a compound query with a map of values (same example as yours). The solution they propose is to

encode all of the information for the query into the map values

Although not ideal, it might be useful for certain cases.


text:
Q: Apache not able to load javascript file Why this is the only script that is not loading? The other scripts load but this one don't.
When i open localhost everything works fine, but when i use the apache webserver, the script don't load.


text:
Q: Card Layout refreshing/updating cards I have a jFrame witch contains displayPanel and buttonPanel.
In the button pannel, there are 2 buttons (button1, button2).
When i press button1 - a new panel (card1) shows in the displayPanel. Card1 has a textfield and that writes the value to a database.
When i press button2 - a new panel (card2) shows in the displayPanel. Card2 has a combobox that shows all those values from database.
My problem - when i click on button1, submit my value, press button2 - combobox doesn't have that value shown yet. It only shows if i close my application and run it again.
How do i make it so each time i press 'button2' (from buttonPanel in jFrame), values in combobox are refreshed?
Here is the code from jFrame, that is responsible for showing cards:
 private void button1ButtonActionPerformed(java.awt.event.ActionEvent evt) {
       CardLayout card = (CardLayout) displayPanel.getLayout();
       card.show(displayPanel, "card1");
}

 private void button2ButtonActionPerformed(java.awt.event.ActionEvent evt) {
       CardLayout card = (CardLayout) displayPanel.getLayout();
       card.show(displayPanel, "card2");
}

Here is the code that gets the values from database and puts them into combobox in card2:
public void fillComboBox(){
    try {
    String sql = "SELECT * FROM Table1";
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery(sql);
    while (rs.next()){
    String user_name= rs.getString("user_name");
    pirmaspanelsvarbumoComboBox.addItem(user_name);
   }
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, e);
    }
}


text:
Q: How to fully decode a base64 string in PHP? I'm trying to implement the Google Safebrowsing update API v4 in PHP.
But I can't figure how to correctly decode the rawHashes.
(The rawHashes are 4-bytes-truncated sha256 hashes and then concatenated).
I am trying the native base64_decode of PHP but I can't fully decode the string, and I don't know what the next step is.
According to the API documentation here's how the rawhashes are encoded :
string (bytes format)
The hashes, in binary format, concatenated into one long string. Hashes are sorted in lexicographic order. For JSON API users, hashes are base64-encoded.
A base64-encoded string.

I an very simply decoding the string like so:
$decoded = base64_decode($rawHashes);

The base64 encoded string look like this:
"AAAIYAAAC90AABOxAAAjDgAALZIAAEbKAABIHwAA..."

And the base64 decoded string look like this:
b"\x00\x00\x08`\x00\x00\vÝ\x00\x00\x13±\x00\x00#\x0E\x00\x00-'\x00\x00FÊ\x00\x00H\x1F\x00\x00^\x06\x00\x00bF\x00\x00h²"

As you can see something is not right and I must have missed a step but I can't figure which one.

A: As Mjh said in the discussion nothing is wrong about base64_decode and nothing else is needed.

Nothing's wrong. You just aren't reading carefully. Here, read what it says: The hashes, in binary format. It says binary format. After decoding, you got binary representation of the data. Using bin2hex should return a human-readable hash. $hash = bin2hex(base64_decode($your_encoded_hash));   - Mjh

The decoded string was looking weird as it is binary data (Raw SHA256 hash) although it is totally correct. To get the hashes in a more convenient encoding it's possible to convert the binary represented data to hex represented data with the php function bin2hex
$hash = bin2hex(base64_decode($your_encoded_hash));

A: From what I know of base64_decode, it just works. Something must be wrong in your $rawHashes string. If you have line breaks in your string, you need to get rid of them by replacing them with an empty string. The hash that base64_decode needs should be one long line of base64 encoded string. It is not uncommon to receive a hash that is broken into multiple lines.
Try this ...
$decoded = base64_decode(str_replace(PHP_EOL, "", $rawHashes));


text:
Q: Better ways to handle dynamically generated forms in Django I have a form that allow users to log their activities. To make it simple, let's say I only have two fields that I want a user to fill out.

*

*Time

*Action

During a day, a user can fill out multiple time + action pairs. I used javascript on the front end to allow users to add these pairs as they wish.
Thus, I do not know how many pairs there will be beforehand. And thus, I cannot create a predefined ModelForm for it.
To deal with this issue, I labeled each Time and Action field with a unique name. So when I receive a POST request, I geta list like this inside the request.POST dictionary:

*

*time_1: 9:50

*action_1: wakeup

*time_2: 11:00

*aciton_2: workout

*...

Then, I subtract each pair out of the dictionary and put them into a ModelForm for validation and save to the database.
class TimeActionModel(Model):
    time = DateField()
    action = CharField(max_length=100)

class TimeActionForm(ModelForm):
    class Meta:
        model = TimeActionModel

class TimeActionView(View):
    def post(self, request, *args, **kwargs):
        self._subtract_and_save(request)

    def _subtract_and_save(request):
        #loop through the request.POST dictionary
            #pull out each pair
            #stuff each one into a ModelForm object
            if form.is_valid():
                form.save()

Here is my quesiton:

*

*Does this approach look right to you?

*What's the 'Django way' of dealing with such situation?

Thank you!

A: There is a concept in Django called formset:

A formset is a layer of abstraction to work with multiple forms on the same page. It can be best compared to a data grid.

The Django way would be to use Model formsets:

Like regular formsets, Django provides a couple of enhanced formset classes that make it easy to work with Django models.

Therefore you could create a model formset for your TimeActionModel as such:
from django.forms.models import modelformset_factory

TimeActionFormset = modelformset_factory(TimeActionModel)

You can read more on that in the documentation. It has extensive use cases and examples to cover your case.
UPDATE: The extras parameter of the formset is not quite important. You can easily manipulate the number of extra forms in your formset with a bit of javascript. There are also contrib packages for that such as django-dynamic-formset.
UPDATE2: The name of the fields depends on the prefix used too, which I recommend it in case of many different forms/formsets in a single page, but you can easily deduce it looking at a default form that Django renders.
Also please take not not to forget in your template to include {{ my_formset.management_form }} and {{ my_formsets_form.id }}!


text:
Q: Can not get child node in vanilla JavaScript for PhotoSwipe custom I am customizing the plugin PhotoSwipe 4.1.1 in combination with jquery mobile 1.4.5 and jquery 2.1.4 in order to open a larger image of a thumbnail on mobile.
There is some old code in the application which seems to be written in vanilla JavaScript and some jQuery.
Somewhere in the code must be a problem, the selector seems not to be working as it might not be able to get the child nodes. I am including the entire funtion at the end of this question.
The most important parts:
html:

test

Once I click on the thumbnail I do get this error:

Cannot read property 'split' of null

Error detail:
psw,psw-ui,psw-custom,v1.0.0.min.js:37 Uncaught TypeError: Cannot read property 'split' of null
    at parseThumbnailElements (psw,psw-ui,psw-custom,v1.0.0.min.js:37)
    at openPhotoSwipe (psw,psw-ui,psw-custom,v1.0.0.min.js:156)
    at HTMLDivElement.onThumbnailsClick (psw,psw-ui,psw-custom,v1.0.0.min.js:118)

lines:
37:  size = el.getAttribute('data-size').split('x');
156: items = parseThumbnailElements(galleryElement);
117: if(index >= 0) {
            openPhotoSwipe( index, clickedGallery );
     }

// nodelist object from consol.log
NodeList(8) [div#cl_gallery_main, a.ui-link, a.ui-link, a.ui-link, a.ui-link, a.ui-link, a.ui-link, a.ui-link]
0: div#cl_gallery_main
1: a.ui-link
2: a.ui-link
3: a.ui-link
4: a.ui-link
5: a.ui-link
6: a.ui-link
7: a.ui-link
length: 8
__proto__: NodeList

// first thumb element of object from consol.log
1: a.ui-link
accessKey: ""
assignedSlot: null
attributeStyleMap: StylePropertyMap {size: 0}
attributes: NamedNodeMap {0: href, 1: data-size, 2: data-details, 3: style, 4: class, href: href, data-size: data-size, data-details: data-details, style: style, class: class, …}
autocapitalize: ""
baseURI: "http://rex.watchgurus/omega/ala-kjdlkjshdl-kajsd-fkjh"
charset: ""
childElementCount: 2
childNodes: NodeList(2) [img, figure]
children: HTMLCollection(2) [img, figure]
classList: DOMTokenList ["ui-link", value: "ui-link"]
className: "ui-link"
clientHeight: 93
clientLeft: 0
clientTop: 0
clientWidth: 93
contentEditable: "inherit"
coords: ""
dataset: DOMStringMap {size: "900x1200", details: "Wiesbaden - 4.999 €"}
dir: ""
download: ""
draggable: true
firstChild: img
firstElementChild: img
hash: ""
hidden: false

The entire custom function:
// custom integration for PhotoSwipe Gallery
(function() {

    var initPhotoSwipeFromDOM = function(gallerySelector) {

        var parseThumbnailElements = function(el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                el,
                childElements,
                thumbnailEl,
                size,
                item;

            for(var i = 0; i < numNodes; i++) {
                el = thumbElements[i];

                // include only element nodes
                if(el.nodeType !== 1) {
                  continue;
                }

                childElements = el.children;

                size = el.getAttribute('data-size').split('x');

                // create slide object
                item = {
                    src: el.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10),
                    details: el.getAttribute('data-details')
                };
                item.el = el; // save link to element for getThumbBoundsFn

                if(childElements.length > 0) {
                  item.msrc = childElements[0].getAttribute('src'); // thumbnail url
                  if(childElements.length > 1) {
                      item.title = childElements[1].innerHTML; // caption (contents of figure)
                  }
                }

                var mediumSrc = el.getAttribute('data-med');
                if(mediumSrc) {
                    size = el.getAttribute('data-med-size').split('x');
                    // "medium-sized" image
                    item.m = {
                        src: mediumSrc,
                        w: parseInt(size[0], 10),
                        h: parseInt(size[1], 10)
                    };
                }
                // original image
                item.o = {
                    src: item.src,
                    w: item.w,
                    h: item.h
                };

                items.push(item);
            }

            return items;
        };

        // find nearest parent element
        var closest = function closest(el, fn) {
            return el && ( fn(el) ? el : closest(el.parentNode, fn) );
        };

        var onThumbnailsClick = function(e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;

            var eTarget = e.target || e.srcElement;

            var clickedListItem = closest(eTarget, function(el) {
                return el.tagName === 'A';
            });

            if(!clickedListItem) {
                return;
            }

            var clickedGallery = clickedListItem.parentNode;

            var childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;

            for (var i = 0; i < numChildNodes; i++) {
                if(childNodes[i].nodeType !== 1) {
                    continue;
                }

                if(childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }

            if(index >= 0) {
                openPhotoSwipe( index, clickedGallery );
            }
            return false;
        };

        var photoswipeParseHash = function() {
            var hash = window.location.hash.substring(1),
            params = {};

            if(hash.length < 5) { // pid=1
                return params;
            }

            var vars = hash.split('&');
            for (var i = 0; i < vars.length; i++) {
                if(!vars[i]) {
                    continue;
                }
                var pair = vars[i].split('=');
                if(pair.length < 2) {
                    continue;
                }
                params[pair[0]] = pair[1];
            }

            if(params.gid) {
                params.gid = parseInt(params.gid, 10);
            }

            return params;
        };

        var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;

            items = parseThumbnailElements(galleryElement);

            // define options (if needed)
            options = {

                galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                getThumbBoundsFn: function(index) {
                    // See Options->getThumbBoundsFn section of docs for more info
                    var thumbnail = items[index].el.children[0],
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();

                    return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
                },

                addCaptionHTMLFn: function(item, captionEl, isFake) {
                    if(!item.title) {
                        captionEl.children[0].innerText = '';
                        return false;
                    }
                    captionEl.children[0].innerHTML = item.title +  '
Standort: ' + item.details + '';
                    return true;
                },

            };

            if(fromURL) {
                if(options.galleryPIDs) {
                    // parse real index when custom PIDs are used
                    // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
                    for(var j = 0; j < items.length; j++) {
                        if(items[j].pid == index) {
                            options.index = j;
                            break;
                        }
                    }
                } else {
                    options.index = parseInt(index, 10) - 1;
                }
            } else {
                options.index = parseInt(index, 10);
            }

            // exit if index not found
            if( isNaN(options.index) ) {
                return;
            }

            if(disableAnimation) {
                options.showAnimationDuration = 0;
            }

            // Pass data to PhotoSwipe and initialize it
            gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);

            // see: http://photoswipe.com/documentation/responsive-images.html
            var realViewportWidth,
                useLargeImages = false,
                firstResize = true,
                imageSrcWillChange;

            gallery.listen('beforeResize', function() {

                var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1;
                dpiRatio = Math.min(dpiRatio, 2.5);
                realViewportWidth = gallery.viewportSize.x * dpiRatio;

                if(realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200 ) {
                    if(!useLargeImages) {
                        useLargeImages = true;
                        imageSrcWillChange = true;
                    }

                } else {
                    if(useLargeImages) {
                        useLargeImages = false;
                        imageSrcWillChange = true;
                    }
                }

                if(imageSrcWillChange && !firstResize) {
                    gallery.invalidateCurrItems();
                }

                if(firstResize) {
                    firstResize = false;
                }

                imageSrcWillChange = false;

            });

            gallery.listen('gettingData', function(index, item) {
                // if( useLargeImages ) {
                    item.src = item.o.src;
                    item.w = item.o.w;
                    item.h = item.o.h;
                // } else {
                //     item.src = item.m.src;
                //     item.w = item.m.w;
                //     item.h = item.m.h;
                // }
            });

            gallery.init();
        };

        // select all gallery elements
        var galleryElements = document.querySelectorAll( gallerySelector );
        for(var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i+1);
            galleryElements[i].onclick = onThumbnailsClick;
        }

        // Parse URL and open gallery if it contains #&pid=3&gid=1
        var hashData = photoswipeParseHash();
        if(hashData.pid && hashData.gid) {
            openPhotoSwipe( hashData.pid,  galleryElements[ hashData.gid - 1 ], true, true );
        }
    };

    initPhotoSwipeFromDOM('#cl_gallery');

})();

Why is Photoswipe not able to retrieve the image size? It is inside the html element.


text:
Q: How can I reshape a 3-dimensional 3024x4032x3 array into a 4-dimensional nx20x20x3 array in Python? I have an RGB image of dimensions 3,024x4,032. I want to slide a 20x20 window over this image and arrange all of the resultant 20x20x3 in a matrix to get a 4-dimensional array.
The image was read using matplotlib.image.imread and, hence, is stored as a NumPy array.


text:
Q: jQuery UI Accordion Is Choppy I am trying to use the accordion function built in to the jQuery UI. It works fine, but the animation is very choppy, I can't seem to figure out why. I've looked at other answers on here, and none have worked so far.
jQuery:

HTML:

All this markup and code is contained in the same HTML file.

A: It probably depends on what browser you are on. Many jQuery UI animations in IE8 and below are very 'choppy'.


text:
Q: In RefreshScope, why should we add the processing logic of getClass() when receiving the ContextRefreshedEvent notification In org.springframework.cloud.context.scope.refresh.RefreshScope, the logic for processing the ContextRefreshedEvent notification is as follows:
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        start(event);
    }

    public void start(ContextRefreshedEvent event) {
        if (event.getApplicationContext() == this.context && this.eager
                && this.registry != null) {
            eagerlyInitialize();
        }
    }

    private void eagerlyInitialize() {
        for (String name : this.context.getBeanDefinitionNames()) {
            BeanDefinition definition = this.registry.getBeanDefinition(name);
            if (this.getName().equals(definition.getScope())
                    && !definition.isLazyInit()) {
                Object bean = this.context.getBean(name);
                                // question 1
                if (bean != null) {
                                     // question 2
                     bean.getClass();
                }
            }
        }
    }

Question 1: If the bean does not exist, an exception will be thrown when the getBean method is executed. Why do we need to judge whether the bean is null?
Question 2: It seems meaningless to execute bean.getClass(), but why do you do it?
I hope someone can answer the above two questions. Thanks.


text:
Q: Sass convert string to color I am using mdl, which has color variables setup like $color-primary: '255, 0, 0' !default;
This is making it hard for me to take that color and lighten it.
I have tried using unquote(), but it is giving me an error:

Argument $color of lighten($color, $amount) must be a color

$color-primary: '255, 0, 0' !default;
$light-accent: lighten(unquote('rgb(#{$color-primary})'), 13.5%) !default;

Is there someway I can convert that to a color?

A: This is an interesting problem. You've found in the MDL source that $color-primary is actually just a string that includes quotes: "63,81,181".
Here's the tricky part: MDL is using these strings everywhere. They aren't actually ever evaluating those colours in a way that SASS understands them. So this:
unquote('rgb(#{$color-primary})')

doesn't return the SASS rgb() instance method, it just returns a plain ol' string.
That's a long way of saying that I don't think you can do what you're looking to do. You can use the other colours in the MDL $palette-indigo, though, in the format $palette-indigo-xxx (photo from material.io).

A: you couldn't use string as input for colors method
codepen
$color-primary: '255, 0, 0' !default;
$light-accent: lighten(convertStringToColor($color-primary), 40.5%) !default;

body{
  background: convertStringToColor($color-primary);
}

h1{
  color: $light-accent;
}


text:
Q: Validation using react hook form results in an error I am trying to use React Hook Form package in my form for validation and got this error when I refreshed the page. The idea is to collect the form input, validate it before sending to the server. However, I cannot get beyond this error message and don't know where to begin fixing it. Can Do you know how to fix it, if so - please help point me in the right direction on how to fix it?
My Form field

import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';

const login = () => {

    const {register, handleSubmit} = useForm();

    return (

                Sign in to your account

                Or

                    Register for an account

                    {/* Form */}
                <form className="space-y-6" action="/login" method="POST" onSubmit={handleSubmit((data)=>{
                    alert(JSON.stringify(data))
                })}>

                        Email address

                        <input ref={register} id="email" name="email" type="email" autoComplete="email" required className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />

                        Password

                        <input ref={register} id="password" name="password" type="password" autoComplete="current-password" required className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />

                        <input ref={register} id="remember_me" name="remember_me" type="checkbox" className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded" />

                        Remember me

                        Forgot your password?

                    <button type="submit" className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        Sign in
                    </button>

                </form>

                        Or continue with

                        Sign in with Google

    )
}

Error

Unhandled Runtime Error
TypeError: path.split is not a function

Call Stack

get
node_modules/react-hook-form/dist/index.esm.js (28:0)
eval
node_modules/react-hook-form/dist/index.esm.js (1426:0)
commitAttachRef
node_modules/react-dom/cjs/react-dom.development.js (20023:0)
commitLayoutEffects
node_modules/react-dom/cjs/react-dom.development.js (22808:0)
HTMLUnknownElement.callCallback
node_modules/react-dom/cjs/react-dom.development.js (188:0)
Object.invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js (237:0)
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js (292:0)
commitRootImpl
node_modules/react-dom/cjs/react-dom.development.js (22541:0)
unstable_runWithPriority
node_modules/scheduler/cjs/scheduler.development.js (653:0)
runWithPriority$1
node_modules/react-dom/cjs/react-dom.development.js (11039:0)
commitRoot
node_modules/react-dom/cjs/react-dom.development.js (22381:0)
finishSyncRender
node_modules/react-dom/cjs/react-dom.development.js (21807:0)
performSyncWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js (21793:0)
scheduleUpdateOnFiber
node_modules/react-dom/cjs/react-dom.development.js (21188:0)
updateContainer
node_modules/react-dom/cjs/react-dom.development.js (24373:0)
eval
node_modules/react-dom/cjs/react-dom.development.js (24758:0)
unbatchedUpdates
node_modules/react-dom/cjs/react-dom.development.js (21903:0)
legacyRenderSubtreeIntoContainer
node_modules/react-dom/cjs/react-dom.development.js (24757:0)
Object.hydrate
node_modules/react-dom/cjs/react-dom.development.js (24823:0)
renderReactElement
node_modules/next/dist/client/index.js (530:6)
doRender
node_modules/next/dist/client/index.js (799:2)
_callee2$
node_modules/next/dist/client/index.js (425:10)
tryCatch
node_modules/regenerator-runtime/runtime.js (63:14)
Generator.invoke [as _invoke]
node_modules/regenerator-runtime/runtime.js (293:0)
Generator.eval [as next]
node_modules/regenerator-runtime/runtime.js (118:0)
asyncGeneratorStep
node_modules/@babel/runtime/helpers/asyncToGenerator.js (3:0)
_next
node_modules/@babel/runtime/helpers/asyncToGenerator.js (25:0)
eval
node_modules/@babel/runtime/helpers/asyncToGenerator.js (32:0)
new Promise
<anonymous>
eval
node_modules/@babel/runtime/helpers/asyncToGenerator.js (21:0)
_render
webpack-internal:///./node_modules/next/dist/client/index.js (522:18)
render
webpack-internal:///./node_modules/next/dist/client/index.js (459:18)
eval
node_modules/next/dist/client/next-dev.js (85:6)
eval
node_modules/next/dist/client/dev/fouc.js (14:6)

A: I think the reason you are having this error is that you are using a different type of syntex. What version of react forms are you using? because there is a good chance you're are using v6 syntex on the newer v7 or vice-versa.
V7 - React Hook Form
V6 - React Hook Form
It is probably because of the way you pass the ref for register, here is an example from the documentation on how to use it:
<input
  {...register("fieldname", {
      maxLength: 2
  })}
/>


text:
Q: Is it possible to create a custom event for calendar similar to tasks add on in calendar I am a beginner with Google App maker. I want a custom calendar event similar to 'outOfOffice'/AppointmentSlots'. I used the tasks add on there is a new event type called 'Task' appearing when I try to create an event.
Also, There are new interactions with a task event type

I would like to create a new event type similar to tasks and new interactions when the event is clicked on. I am hoping that AppMaker would help me achive this. I did not find any api support in Google calendar for creating a new event type. Please advise


text:
Q: How does the Boot Indicator field fit inside the MBR partition table? Apparently the MBR is a 512 Byte data structure.

*

*446 bytes for the BootCode.

*64 bytes for The Partition Table

*2 bytes for the signature a the very end.

The Partition Table structure has four entries of 16 bytes each used to identify the type and location of partitions on a hard disk.
According to Microsoft

The first element of the partition table, the Boot Indicator field,
indicates whether or not the volume is the active partition. Only one
primary partition on the disk can have this field set.
Partition 1\ 0x01BE(446)
Partition 2\ 0x01CE(462)
Partition 3\ 0x01DE(478)
Partition 4\ 0x01EE(494)

As the Partition Table's four entries of 16 bytes each completely use up all available 64 bytes of space, how can there be any room left for the Boot Indicator Field?
Is the Boot Indicator Field crammed into whichever partition is active entry field space?(I cant imagine a regex operation to sniff out the Boot Indicator Field being ran for each entry...)
Perhaps I am visualizing this wrong but something seems illegal?


text:
Q: Adding multiple listeners to one EventEmitter on Node server I have node.js server, and clients connecting by AJAX HTTP long polling request.
I want to create one EventEmitter object and I want to add every new client to this object after received request from him.
What is proper way to do this? In other words: How use "emitter.on(event, listener)" in function runs for every client to have them all waiting in EventEmitter listeners array?

A: It's probably easier to have just one event emitter listener and have an array of waiting long polling requests.  Then, you are free to add/remove items from the array at any time as connections come and go and there's just one listener that processes whatever requests are in the array when an event occurs.


text:
Q: Magento 401 on API request after setting headers for cross origin I am trying to call the web API for products in Magento from a React Native app. After other stack exchange question & answers plus tutorials I am still receiving a 401 response. I know the call works because I can make it through postman.
Update: So I did not solve it, however I have found that if I use axios the request will work. This seems to be an issue with fetch.
.htaccess mod_headers.c settings
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
Header set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS"

app/etc/env.php
'x-frame-options' => 'CROSS-ORIGIN'

API Call from React Native
fetch(
      'http://localhost:8888/magento/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name&searchCriteria[filter_groups][0][filters][0][value]=product name',
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authentication: 'Bearer fwynACCESS_TOKENbal9tfr'
        }
      }
    )
      .then((res) => {
        if (res.status !== 200 && res.status !== 204)
          reject({ message: 'There was an error with the products service' })
        resolve(res.json())
      })
      .catch((err) => reject(err))

This also includes a web integration named Customers with all the API options set as accessible.


text:
Q: export table from R with ReporteRs with cells colored according to value Using the ReporteRs package in R I would like to export a data frame with colored cells to a table in a word document.
Following the code and instructions provided on this website: http://www.sthda.com/english/wiki/add-a-table-into-a-word-document-using-r-software-and-reporters-package
I tried to add colors to the cells in the table I am preparing. But I am unable to get the correct colors in the cells in the table I export.
The code below has a test data frame, and also installs the package.
The code produces a word.doc file with a table in, but the colors in the cells are wrong. The colors in the cells in the table in the word document are not matching the values that are in the cells. I suspect I have set the 'breaks' incorrect, but I am not sure how to set them correctly to get the table I want.
My input data frame has values from 1 to 5, and I would like the cells to be colored according to their values.
i.e. a cell with value 1 should be purple, a cell with value 2 should be blue, a cell with value 3 should be darkgreen, a cell with value 4 should be green and a cell with value 5 should be yellow.
#get the packages required
install.packages("ReporteRs")
library(ReporteRs)

# set working directory
setwd ("/your_own_working_dir/")

#make some test data
c2 <- c(1,2,3,5)
c3 <- c(2,2,3,2)
c4 <- c(4,3,2,1)
#bind the data in to a dataframe
cc <- t(cbind(c2,c3,c4))
dd <- as.data.frame(cc)

#turn the dataframe into a matrix
ee <- matrix(as.numeric(unlist(dd)),nrow=nrow(dd))

#define colors
#col =c("#FB0000", "#FB7F00", "#FBF000", "#6EFF4C")
col =c("purple", "blue", "darkgreen", "green", "yellow")

mycut = cut(ee,
            #breaks = c(-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1),
            breaks = c(1, 2, 3, 4 ,5),
            include.lowest = TRUE, label = FALSE )
color_palettes = col[mycut]
#see the colors in the color palette
unique(color_palettes)

corrFT = FlexTable( ee, add.rownames = TRUE )
corrFT = setFlexTableBackgroundColors(corrFT,
                                      j = seq_len(ncol(ee)) + 1,
                                      colors = color_palettes )
#show_col(color_palettes) #install from "scales" package
#make an empty doc
doc <- docx()

corrFT = setFlexTableBorders( corrFT
                              , inner.vertical = borderProperties( style = "dashed", color = "white" )
                              , inner.horizontal = borderProperties( style = "dashed", color = "white"  )
                              , outer.vertical = borderProperties( width = 2, color = "white"  )
                              , outer.horizontal = borderProperties( width = 2, color = "white"  )
)
doc <- addFlexTable( doc, corrFT)
writeDoc(doc, file = "r-reporters-word-document-correlation.docx")


text:
Q: How do I determine final ValueChange event on Kendo Angular DatePicker I need to set min and max dates for a Kendo Angular DatePicker.  This is pretty straight forward using [(max)]="maxDate" and [(min)]="minDate" and this works when using a mouse and clicking the DatePicker.
The problem is when using keyboard entry a user can select dates outside the min and max dates.  I have a valueChange event but it fires with every keystroke.  I cannot determine when the user is finished entering the entire date and then simply setting the date to min or max as needed.  I could set an onFocus event for the next control but that would be kludgy.
This is a snippet of the html code:
  <kendo-datepicker
    id="dpFirstPaymentDate"
    (valueChange)="onFirstPaymentDateChange($event)"
    [(value)]="firstPaymentDate"
    [(max)]="maxDate"
    [(min)]="minDate"
    [(focusedDate)]="firstPaymentDate"
    [rangeValidation] = "true"
    title="First Payment Date">
  </kendo-datepicker>

The angular code is this:
 protected onFirstPaymentDateChange(/*event: EventEmitter*/ value: Date): void {

        if (value > this.maxDate) {
          // This does not appear to be working
          value = new Date(this.maxDate);
          this.firstPaymentDate = new Date(this.maxDate);
        }
        else if (value < this.minDate) {
          value = new Date(this.minDate);
          this.firstPaymentDate = new Date(this.minDate);
        }

        this.maturityDate = new Date(value);
        this.maturityDate.setMonth(value.getMonth() + this.term);

    }

A complete plunker example is here: Plunker example

A: Okay since my comment is actually on point, so actually instead of using onchange event we should use the on blur event
<kendo-datepicker
    id="dpFirstPaymentDate"
    (blur)="onFirstPaymentDateChange($event)"
    [(value)]="firstPaymentDate"
    [(max)]="maxDate"
    [(min)]="minDate"
    [(focusedDate)]="firstPaymentDate"
    [rangeValidation] = "true"
    title="First Payment Date">
</kendo-datepicker>

and just a bit change on the onFirstPaymentDateChange function, since we are not getting the date value, might just get it with this.firstPaymentDate and we can continue to set the logic (max value). Here's working example in plnkr


text:
Q: Pthread heap buffer overflow I tried to create a multithread server using pthread. The compiling failed and gave a heap buffer overflow error.
I tried to change the buffer size, change the malloc size, etc., but got no luck. The code compiles successfully when the multithread part is removed. So I doubt this could be issues related within the thread memory allocation or free. Any ideas?
The warning looks like this
==6056==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000018 at pc 0x5603ede50e8a bp 0x7fffc737ded0 sp 0x7fffc737dec0
WRITE of size 8 at 0x602000000018 thread T0

Here is the server code.

#include <stdlib.h>

#include "gfserver-student.h"

#define BUFSIZE 256
#define USAGE                                                                 \
    "usage:\n"                                                                \
    "  gfserver_main [options]\n"                                             \
    "options:\n"                                                              \
    "  -t [nthreads]       Number of threads (Default: 21)\n"                 \
    "  -p [listen_port]    Listen port (Default: 10823)\n"                    \
    "  -m [content_file]   Content file mapping keys to content files\n"      \
    "  -d [delay]          Delay in content_get, default 0, range 0-5000000 " \
    "(microseconds)\n "                                                       \
    "  -h                  Show this help message.\n"

/* OPTIONS DESCRIPTOR ====================================================== */
static struct option gLongOptions[] = {
    {"content", required_argument, NULL, 'm'},
    {"delay", required_argument, NULL, 'd'},
    {"nthreads", required_argument, NULL, 't'},
    {"port", required_argument, NULL, 'p'},
    {"help", no_argument, NULL, 'h'},
    {NULL, 0, NULL, 0}};

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_worker = PTHREAD_COND_INITIALIZER;
steque_t *queue;
pthread_t *workers;

typedef struct enque_ctx{
    gfcontext_t *ctx;
    const char *filepath;
}enque_ctx;

extern unsigned long int content_delay;

extern gfh_error_t gfs_handler(gfcontext_t **ctx, const char *path, void *arg);
extern ssize_t process_perform(gfcontext_t *ctx, const char *path);

static void _sig_handler(int signo)
{
    if ((SIGINT == signo) || (SIGTERM == signo))
    {
        exit(signo);
    }
}

// thread process function
void queue_init(gfcontext_t *ctx, const char *filepath){
    enque_ctx *q_ctx = malloc(sizeof(enque_ctx));
    q_ctx->ctx = ctx;
    q_ctx->filepath = filepath;
    steque_enqueue(queue, q_ctx);
}

void *process(){
    while(1){
        pthread_mutex_lock(&mutex);
        while(steque_isempty(queue)){
            pthread_cond_wait(&cond_worker, &mutex);
        }
        enque_ctx *q_ctx = steque_pop(queue);
        pthread_mutex_unlock(&mutex);
        process_perform(q_ctx->ctx, q_ctx->filepath);

        if(q_ctx->ctx != NULL){
            gfs_abort(&q_ctx->ctx);
        }
        // free(q_ctx->filepath);
        free(q_ctx);
    }
}

/* Main ========================================================= */
int main(int argc, char **argv)
{
    int option_char = 0;
    unsigned short port = 10823;
    char *content_map = "content.txt";
    gfserver_t *gfs = NULL;
    int nthreads = 12;

    setbuf(stdout, NULL);

    if (SIG_ERR == signal(SIGINT, _sig_handler))
    {
        fprintf(stderr, "Can't catch SIGINT...exiting.\n");
        exit(EXIT_FAILURE);
    }

    if (SIG_ERR == signal(SIGTERM, _sig_handler))
    {
        fprintf(stderr, "Can't catch SIGTERM...exiting.\n");
        exit(EXIT_FAILURE);
    }

    // Parse and set command line arguments
    while ((option_char = getopt_long(argc, argv, "p:t:rhm:d:", gLongOptions,
                                      NULL)) != -1)
    {
        switch (option_char)
        {
        case 't': // nthreads
            nthreads = atoi(optarg);
            break;
        case 'h': // help
            fprintf(stdout, "%s", USAGE);
            exit(0);
            break;
        case 'p': // listen-port
            port = atoi(optarg);
            break;
        default:
            fprintf(stderr, "%s", USAGE);
            exit(1);
        case 'm': // file-path
            content_map = optarg;
            break;
        case 'd': // delay
            content_delay = (unsigned long int)atoi(optarg);
            break;
        }
    }

    /* not useful, but it ensures the initial code builds without warnings */
    if (nthreads < 1)
    {
        nthreads = 1;
    }

    if (content_delay > 5000000)
    {
        fprintf(stderr, "Content delay must be less than 5000000 (microseconds)\n");
        exit(__LINE__);
    }

    content_init(content_map);

    /* Initialize thread management */
    queue = malloc(sizeof(steque_t));
    steque_init(queue);
    workers = malloc(nthreads * sizeof(pthread_t));

    /*Initializing server*/
    gfs = gfserver_create();

    /*Setting options*/
    gfserver_set_port(&gfs, port);
    gfserver_set_maxpending(&gfs, 86);
    gfserver_set_handler(&gfs, gfs_handler);
    gfserver_set_handlerarg(&gfs, NULL); // doesn't have to be NULL!

    for (int i = 0; i < nthreads; i++) {
        if (pthread_create(&workers[i], NULL, process, NULL) != 0) {
            printf("failed to create worker %d\n", i);
            return -1;
        }
    }

    /*Loops forever*/
    gfserver_serve(&gfs);

    for (int i = 0; i < nthreads; i++) {
        if (pthread_join(workers[i], NULL) < 0){
            printf("failed to join pthread\n");
        }
    }

    steque_destroy(queue);
    free(queue);
    free(workers);
    free(gfs);
    content_destroy();
}

This is the handler code.
#include "gfserver-student.h"
#include "gfserver.h"
#include "content.h"

#include "workload.h"
#include "gf-student.h"

#define BUFSIZE 64000

extern void queue_init(gfcontext_t *ctx, const char *file_path);
pthread_mutex_t mutex;
pthread_cond_t cond_worker;

//
//  The purpose of this function is to handle a get request
//
//  The ctx is a pointer to the "context" operation and it contains connection state
//  The path is the path being retrieved
//  The arg allows the registration of context that is passed into this routine.
//  Note: you don't need to use arg. The test code uses it in some cases, but
//        not in others.
//
gfh_error_t gfs_handler(gfcontext_t **ctx, const char *path, void* arg){
    pthread_mutex_lock(&mutex);
    queue_init(*ctx, path);
    pthread_cond_signal(&cond_worker);
    pthread_mutex_unlock(&mutex);
    return gfh_failure;
}

ssize_t process_perform(gfcontext_t *ctx, const char *path){
    char buff[BUFSIZE];
    size_t filelen, size_transferred = 0;
    ssize_t recv_len, send_len;
    int flides;
    if((flides = content_get(path)) < 0){
        return gfs_sendheader(&ctx, GF_FILE_NOT_FOUND, 0);
    }
    printf("%d\n", flides);
    filelen = lseek(flides, 0, SEEK_END);
    gfs_sendheader(&ctx, GF_OK, filelen);

    while(size_transferred < filelen){
        recv_len = pread(flides, buff, BUFSIZE, size_transferred);
        if(recv_len <= 0){
            printf("Handle receive error\n");
            gfs_abort(&ctx);
            return -1;
        }
        send_len = gfs_send(&ctx, buff, recv_len);
        if(send_len != recv_len){
            printf("Handle send error\n");
            gfs_abort(&ctx);
            return -1;
        }
        size_transferred += send_len;
    }
    return size_transferred;
}

Original main function template

#include <stdlib.h>

#include "gfserver-student.h"

#define USAGE                                                               \
  "usage:\n"                                                                \
  "  gfserver_main [options]\n"                                             \
  "options:\n"                                                              \
  "  -t [nthreads]       Number of threads (Default: 21)\n"                 \
  "  -p [listen_port]    Listen port (Default: 10823)\n"                    \
  "  -m [content_file]   Content file mapping keys to content files\n"      \
  "  -d [delay]          Delay in content_get, default 0, range 0-5000000 " \
  "(microseconds)\n "                                                       \
  "  -h                  Show this help message.\n"

/* OPTIONS DESCRIPTOR ====================================================== */
static struct option gLongOptions[] = {
    {"content", required_argument, NULL, 'm'},
    {"delay", required_argument, NULL, 'd'},
    {"nthreads", required_argument, NULL, 't'},
    {"port", required_argument, NULL, 'p'},
    {"help", no_argument, NULL, 'h'},
    {NULL, 0, NULL, 0}};

extern unsigned long int content_delay;

extern gfh_error_t gfs_handler(gfcontext_t **ctx, const char *path, void *arg);

static void _sig_handler(int signo) {
  if ((SIGINT == signo) || (SIGTERM == signo)) {
    exit(signo);
  }
}

/* Main ========================================================= */
int main(int argc, char **argv) {
  int option_char = 0;
  unsigned short port = 10823;
  char *content_map = "content.txt";
  gfserver_t *gfs = NULL;
  int nthreads = 12;

  setbuf(stdout, NULL);

  if (SIG_ERR == signal(SIGINT, _sig_handler)) {
    fprintf(stderr, "Can't catch SIGINT...exiting.\n");
    exit(EXIT_FAILURE);
  }

  if (SIG_ERR == signal(SIGTERM, _sig_handler)) {
    fprintf(stderr, "Can't catch SIGTERM...exiting.\n");
    exit(EXIT_FAILURE);
  }

  // Parse and set command line arguments
  while ((option_char = getopt_long(argc, argv, "p:t:rhm:d:", gLongOptions,
                                    NULL)) != -1) {
    switch (option_char) {
      case 't':  // nthreads
        nthreads = atoi(optarg);
        break;
      case 'h':  // help
        fprintf(stdout, "%s", USAGE);
        exit(0);
        break;
      case 'p':  // listen-port
        port = atoi(optarg);
        break;
      default:
        fprintf(stderr, "%s", USAGE);
        exit(1);
      case 'm':  // file-path
        content_map = optarg;
        break;
      case 'd':  // delay
        content_delay = (unsigned long int)atoi(optarg);
        break;
    }
  }

  /* not useful, but it ensures the initial code builds without warnings */
  if (nthreads < 1) {
    nthreads = 1;
  }

  if (content_delay > 5000000) {
    fprintf(stderr, "Content delay must be less than 5000000 (microseconds)\n");
    exit(__LINE__);
  }

  content_init(content_map);

  /* Initialize thread management */

  /*Initializing server*/
  gfs = gfserver_create();

  /*Setting options*/
  gfserver_set_port(&gfs, port);
  gfserver_set_maxpending(&gfs, 86);
  gfserver_set_handler(&gfs, gfs_handler);
  gfserver_set_handlerarg(&gfs, NULL);  // doesn't have to be NULL!

  /*Loops forever*/
  gfserver_serve(&gfs);
}

A: This is almost certainly wrong:
enque_ctx *q_ctx = malloc(sizeof(q_ctx));

sizeof q_ctx is the size of a pointer, since that's what q_ctx is; you need to allocate enough memory to contain *q_ctx, which I suppose is larger than a single pointer.

A: In main ...
You define:
gfserver_t *gfs = NULL;

Later on, you do:
gfs = gfserver_create();

But, then you do (e.g.):
gfserver_set_port(&gfs, port);

This is incorrect.
You are passing the equivalent of a "double star" pointer (e.g.)
gfserver_t **

To a function that only takes a regular pointer (e.g.)
gfserver_t *

I'm surprised that this even compiles.
What you really want is (e.g.):
gfserver_set_port(gfs, port);

There are other calls that have similar issues.

Actually gfserver_set_port takes a double pointer as input, So I don't think the problem is here void gfserver_set_port(gfserver_t **gfs, unsigned short port); –
user2236600

Taking a double pointer for such a control struct is very unusual. I know of very few APIs that would take that approach.
I had done a web search prior to posting to verify the prototypes. The only match I came up with is: https://github.com/stewartboyd119/ud923-project1-gflib/blob/master/gfserver.h
It uses regular, single pointers for the four functions that your main code is calling.
So, I'm confused. The library/API you're using must be different, but it's not publicly available AFAICT.


text:
Q: Algorithms to compose music Suppose I want to write an application to compose music.
I'd like to feed a set of musical scores of a composer - e.g. Bach's Well tempered clavier' - and the program should prepare new scores in a similar style.
Are algorithms or even libraries known for this task?
WikiPedia provides this page about algorithmic music composition.

A: You could make something basic using Markov chains. The principle is to first produce some unit of music (a single note, for example) and then, based on the last produced unit, randomly select the next unit.
First, pass through the input music. Each time you see a particular note/other unit of music, simply record in the table what came after it. When you have gone trough the entire input material, you will have a frequency table of which units follow which (After 'A', 'B' appeared 29 times, 'C' appeared 12 times and 'A' appeared twice; after 'B' ... etc).
Now select an initial note. Select the next one randomly according to the frequencies recorded in the table. Repeat until satisfied.
This will probably not yield good results if applied to individual notes, instead try short phrases. Also, the quality will improve if you have access to a large corpus of source music.


text:
Q: method gets called multiple times in angular material autocomplete We have created a component using Angular material's autocomplete. To display the options, we are traversing through an array of 51 objects. I am applying a CSS class to the already selected option. The isAccountingTypeSelected method determines whether the option was selected or not.
The method gets called 51*28 = 1428 times. I don't seem to understand the reason? It should only be called 51 times, shouldn't it?
<mat-form-field class="full-width">
  <input type="text" matInput #autoCompleteInput [formControl]="autocompleteForm" [matAutocomplete]="auto" placeholder="Choose Accounting Type" aria-label="Number">

  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="accountingTypeSelected($event)">
    <mat-option *ngFor="let accountingType of filteredAccountingTypes | async" [value]="accountingType.code">

        {{ accountingType.name + ' (' + accountingType.code + ')' }}

    </mat-option>
  </mat-autocomplete>
</mat-form-field>

isAccountingTypeSelected(code: string): boolean {
  console.log('I was called');
  if (this.selectedAccountingTypes.find((accountingType: AccountingType) => accountingType.code === code)) {
    return true;
  }

  return false;
}

A: Angular uses changedetection lifecycle multiple times to check if the function has changed for [class.selected] or ngClass. If you use function, it will call multiple times. For this reason the use of function is not advised when you bind, instead you should calculate the values in your component.ts file and just bind the values to ngClass or [class].
Example: Stackblitz
N.B: We know when we change selected value it triggers a event change, we can calculate it and attach the calculation result to the [class.my-class] or ngClass.

A: Angular is gonna evaluate that expression every time it checks for changes, which in your case might be the css being added to your span elements.
Calling methods from the template in a for loop is not the best approach because they are called very often. You should instead store the result in a property and bind to this property instead.

A: It is a bind problem. Angular checks more times the result value. You can try with ChangeDetectionStrategy.CheckOnce

A: Your ngFor loop needs track a specific id so it won't re-render for nothing. Try this:
<mat-option *ngFor="let accountingType of filteredAccountingTypes | async; trackBy: trackByCode"[value]="accountingType.code">
</mat-option>

Then you add this function:
trackByCode(index: number, accountingType: yourType): string {
    return accountingType.code;
}


text:
Q: Insert XML element with attribute into SQL XML column I have the following XML data stored in [MyTable].Column1 which is an XML type column.

I want to insert a new element to it:

I'm using the following SQL, it executed successfully but when I query the same column value again, I do not see my new XML element. Do I miss certain syntax for inserting an element with attributes?
UPDATE [MyTable]
SET Column1.modify('insert <Setting Name="H" Value="0"/> as last into (/SettingValues)[1]')
WHERE ID = 'xxxxx'

A: First of all - for your next question: Please do not post pictures! Try to set up a test-scenario. Please read How to ask a good SQL question  and How to create a MCVE.
About your question
Your code - on the first sight - should work. But you obviously modified it to fit to this forum.
DECLARE @myTable TABLE(ID VARCHAR(100),Column1 XML)
INSERT INTO @myTable VALUES
 ('111'
  ,'<SettingValues>
     <Setting Name="A-name" Value="A-value"/>
   </SettingValues>')
, ('222'
  ,'<SettingValues>
     <Setting Name="A-name" Value="A-value"/>
   </SettingValues>');

UPDATE @MyTable
SET Column1.modify('insert <Setting Name="H" Value="0"/> as last into (/SettingValues)[1]')
WHERE ID = '222';

SELECT *
FROM @myTable

This works as expected.
ID  Column1
111 <SettingValues><Setting Name="A-name" Value="A-value" /></SettingValues>
222 <SettingValues><Setting Name="A-name" Value="A-value" /><Setting Name="H" Value="0" /></SettingValues>

After execution you see "1 row affected".
Some ideas:

*

*The filter is not fullfilled

*The given XML declares namespaces but never uses them... This is a bit odd. Have you reduced the namespaces and your original XML includes a default namespace (or the elements are prefixed somehow)?

*You are checking against the wrong target (other server, other schema, other table...

But: The code above should work...


text:
Q: Why referenced vector address cannot be dereferenced in cpp? I am trying to dereference a referenced vector address as follows:
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> p;
    p.push_back(1);
    p.push_back(2);
    p.push_back(3);
    p.push_back(4);
    p.push_back(5);
    p.push_back(6);
    cout << (*(&p)) << endl;
    cout << (*(&p + 3)) << endl;

    return 0;
}

But it fails.
Expecting output:
1
4

A: std::vector<int> p; is an object that manages consecutive storage of elements of type int.
&p would be an address of such an object. What that object contains is unspecified. You can expect a vector object to contain, e.g. the pointer to an array of elements allocated on the heap, the current size and capacity.
To get a pointer to the underlying elements, use p.data().
To access a specific element of a vector can use the overloaded operator[] (e.g. p[0], p[3]).
An iterator (e.g. p.begin()) can also be used as an abstraction around a pointer to an element:
int main() {
    vector<int> p;
    p.push_back(1);
    p.push_back(2);
    p.push_back(3);
    p.push_back(4);
    p.push_back(5);
    p.push_back(6);
    cout << (*(p.begin())) << endl;
    cout << (*(p.begin() + 3)) << endl;
}

The benefit of using iterators in place of raw pointers is that the access is bounds-checked in debug builds (in VC++ at least), and it will seamlessly work with other types of sequential containers.


text:
Q: After closing modal using X, have to click it twice to reopen it

//Get the modal
var modal = document.getElementById('myModal');

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

   Home
   |
   NWH X4
   |
   NWH X6
   |
   NDC X4
   |
   NDC X6
   |
   ReadMe

      ×

Exadata Capacity Read Me

Some text in the Modal Body

Some other text...

I have this code for in which I've created a readme modal,
If I click outside the modal it closes and I can reopen it with just a single click of the readme link,
however if I close the modal using the 'X' I have to click the readme link twice to get it to reopen.
I can't figure it out, and yes, I'm really new to this as well...

A:

.modal {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 1050;
        display: none;
        overflow: hidden;
        -webkit-overflow-scrolling: touch;
        outline: 0;
    }

    .modal-dialog {
        width: 600px;
        margin: 30px auto;
        position: relative;
        background-color: #fff;
        -webkit-background-clip: padding-box;
        background-clip: padding-box;
        border: 1px solid #999;
        border: 1px solid rgba(0,0,0,.2);
        border-radius: 6px;
        outline: 0;
        -webkit-box-shadow: 0 3px 9px rgba(0,0,0,.5);
        box-shadow: 0 3px 9px rgba(0,0,0,.5)
    }

    .modal-body {
        position: relative;
        padding: 15px;
    }

    .modal-header {
        padding: 15px;
        border-bottom: 1px solid #e5e5e5;
    }

    .close {
        float: right;
        font-size: 21px;
        font-weight: 700;
        line-height: 1;
        color: #000;
        text-shadow: 0 1px 0 #fff;
        filter: alpha(opacity=20);
        opacity: .2;
    }

    button.close {
        -webkit-appearance: none;
        padding: 0;
        cursor: pointer;
        background: 0 0;
        border: 0;
    }

           Home
           |
           NWH X4
           |
           NWH X6
           |
           NDC X4
           |
           NDC X6
           |
           ReadMe

              <button type="button" class="close" data-dismiss="modal">×</button>

Exadata Capacity Read Me

Some text in the Modal Body

Some other text...

I removed bootstrap css and just add need css for modal.
This is not completely enough solution for your problem but you can start from this and modify.


text:
Q: How to calculate consecutive sum in R? If for example I have a vector of numbers.
c(1:9)

Now, if I want to compute sum of three consecutive number in the following way:
(1+2+3,4+5+6,7+8+9)

how should I approach?

A: I learned to use this one correctly:
foo<-1:9
aggregate(foo,by=list(rep(1:3,each=3) ),FUN=sum)

For a longer input,  do this:
function (x,len) aggregate(x,by=list(rep(1:(length(x)/len),each=len) ),FUN=sum)

And because I'm still waiting for what-if.xkcd.com to update, here's the timings:
(and I did check that all calculate the right thing)
x<-1:99
len<-3
 microbenchmark(shadow(x,len),rawr(x,len),groth(x,len),carl(x,len),times=10)
Unit: microseconds
           expr      min       lq    median       uq      max
 shadow(x, len)   62.006   70.130   75.0480   97.926  180.884
   rawr(x, len)  541.797  564.033  571.9445  585.842  639.295
  groth(x, len)  514.002  525.548  547.5705  551.633  568.310
   carl(x, len) 1045.536 1099.844 1120.5840 1166.553 1346.582
 neval
    10
    10
    10
    10

So the matrix -- colSums is fastest.  I'll leave it to someone else to figure out the memory requirements of each approach.


text:
Q: Good way to handle missing AssociatedControlID I have a medium sized project with a lot of pages. One of the things that I've noticed is that we have a lot of labels that have AssociatedControlID pointing to controls that are not visible. The target controls are set visible when a user has edit permissions, but not normally.
This means that the html generated in not valid, which we'd like to get as close to as possible.
I attempted to implement a new label, which overrides the existing label control and render the for attribute only when needed. This proved painful as much of the functionality required was set to internal in the Label class.
Is there a better way?

A: Subclassing Label control is not that hard:
namespace MyNamespace
{
   public class BetterLabel : Label
   {
      protected override void OnPreRender(EventArgs e)
      {
         Control control = FindControl(this.AssociatedControlID);
         if (control != null && !control.Visible)
            this.AssociatedControlID = "";

         base.OnPreRender(e);
      }
   }
}

Here's how to use BetterLabel:
<%@ Register TagPrefix="uc1" Namespace="MyNamespace"  %>
...
<uc1:BetterLabel ID="Label1" runat="server" Text="Label" AssociatedControlID="TextBox1" />
<asp:TextBox ID="TextBox1" runat="server" Visible="false"></asp:TextBox>


text:
Q: Azure Functions Http trigger when recieving a pdf file then Analyze the form with Form Recognizer [python] So the following Workflow:

*

*A colleague sends a delivery receipt (pdf or image) on my Azure Functions Endpoint.

*The Azure Function uses the HTTP trigger to recieve the file.

*The file then is going to be analyzed by the FOrm Recognizer (Cognitive Services of Microsoft)

*Send a Response in form o a Json.

As I am new to this, I have some problems. This is how my code looks right now:
import logging
import requests
import azure.functions as func
import json

SUPPORTED_CONTENT_TYPES = ['application/pdf', 'image/jpeg', 'image/png']

# Define Form Recognizer Dependencies

apim_key = "key"
model_id = "formrecognizer model id"
formrecendpoint ="endpoint"

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Function processed a Request')

    # recieve the file
    file = req.files.get('file')

    body = None

    # Analyze Forms Endpoint
    endpoint = '......cognitive.microsoft.com/formrecognizer/v2.0-preview/cutom/models/modelID/analyze'

    # Analyze Form
    response = requests.post(endpoint, data = file, headers = {"Content-Type": '<file type>',"Ocp-Apim-Subscription-Key": apim_key})
    body = response.content

    #Return Response
    return func.HttpResponse(body,headers={'Content-Type':'application/json'})

But it just doesn't work.
I get the following error when trying to post a file via Postman (form-data , binary)
{
    "error": {
        "code": "1002",
        "message": "Analyze request is either invalid or missing required parameters. Refer to the API reference and retry your request."
    }
}

But in the Function itself I get STATUS: 200.


text:
Q: 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference My SearchView not works... I m trying to search in RecyclerView but it through an error Of JavaExeption...I have done everyThing that I can do, but the problem is still there where it was. Pls guide me I am a student.
'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
SupportAdapter code
public class SupportAdapter extends RecyclerView.Adapter<SupportAdapter.viewHolder> implements Filterable {
    private static final  String TAG = "SupportAdapter";
    private Context mContext;
    private List<SupportList> mData;
    private List<SupportList> mDataFull;

public static class viewHolder extends RecyclerView.ViewHolder{

    private TextView Category;
    private TextView City;
    private TextView Contact;
    private TextView Description;
    private TextView Organisation;
    private TextView Phone;
    private TextView State;
    private LinearLayout container;

    private viewHolder(View itemView) {
        super(itemView);

       container = itemView.findViewById(R.id.supportContainer);
        Category = itemView.findViewById(R.id.category);
        City = itemView.findViewById(R.id.city);
        Contact = itemView.findViewById(R.id.contact);
        Description = itemView.findViewById(R.id.description);
        Organisation = itemView.findViewById(R.id.name_of_org);
        Phone = itemView.findViewById(R.id.phone);
        State = itemView.findViewById(R.id.state);

    }
}

public SupportAdapter(Context mContext, List<SupportList> mData) {
    this.mContext = mContext;
    this.mData = mData;
    mDataFull = new ArrayList<>(mData);
}

@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.search_item_list,parent,false);

    return new viewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull SupportAdapter.viewHolder holder, int position) {

    holder.container.setAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_scale_animation));
    holder.Category.setText(mData.get(position).getCategory());
    holder.City.setText(mData.get(position).getCity());
    holder.Contact.setText(mData.get(position).getContact());
    holder.Description.setText(mData.get(position).getDescription());
    holder.Organisation.setText(mData.get(position).getOrganisation());
    holder.Phone.setText(mData.get(position).getPhone());
    holder.State.setText(mData.get(position).getState());
}

@Override
public int getItemCount() {
    return mData.size();
}

@Override
public Filter getFilter() {
    return mDataFullFilter;
}

private Filter mDataFullFilter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        List<SupportList> filteredList = new ArrayList<>();
        if (constraint == null || constraint.length() == 0){
            filteredList.addAll(mDataFull);
        }else {
            String filterPattern =constraint.toString().toLowerCase().trim();

            for(SupportList item : mDataFull){
                if(item.getCity().toLowerCase().contains(filterPattern)){
                    filteredList.add(item);
                }
                else if (item.getCity().toLowerCase().contains(filterPattern)){
                    filteredList.add(item);
                }
            }
        }

        FilterResults results = new FilterResults();
        results.values = filteredList;
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {

        mData.clear();
        mData.addAll((List) results.values);
        notifyDataSetChanged();

    }
};

SearchFragment
private RecyclerView NewRecyclerView;
private SupportAdapter supportAdapter;
private List<SupportList> mData;
private SearchView searchItem;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    ViewModelProviders.of(this).get(SearchViewModel.class);
    View root = inflater.inflate(R.layout.fragment_search, container, false);
    searchItem = root.findViewById(R.id.searchItem);
    NewRecyclerView = root.findViewById(R.id.searchList);
    supportAdapter = new SupportAdapter (getContext(),mData);
    NewRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    NewRecyclerView.setAdapter(supportAdapter);

    return root;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mData = new ArrayList<>();
    getSupport();

    searchItem.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            supportAdapter.getFilter().filter(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            supportAdapter.getFilter().filter(newText);
            return false;
        }
    });

}

Logcat
2020-04-28 00:58:02.828 12382-12382/com.praso.indiacovid_19 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.praso.indiacovid_19, PID: 12382
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
        at com.praso.indiacovid_19.ui.search.SearchFragment.onCreate(SearchFragment.java:64)
        at androidx.fragment.app.Fragment.performCreate(Fragment.java:2414)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1418)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2646)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2416)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2372)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:228)
        at android.app.ActivityThread.main(ActivityThread.java:7782)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)

A: res/menu/menu_main.xml
      <item
        android:id="@+id/menu_item_search"
        android:title="Search"
        android:icon="@drawable/ic_baseline_search_24"
        app:showAsAction="always"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        />

Just make sure to put this line in your code inside the manu
app:actionViewClass="androidx.appcompat.widget.SearchView"


text:
Q: Writing Formal version of a statement How do i write the formal version of the following statement: No integer is both non-positive and non-negative unless it is the zero integer.
Should i split the statement into the form $p$ unless $q$ with the predicate domain as $\mathbb{Z}$?
I will appreciate a detailed explanation on the interpretation of the statement in its predicate statement form instead of only providing the answer. Thanks.

A: I always use the following trick when dealing with an 'unless':  substitute 'if not'.
That is, 'P unless Q' becomes 'P if not Q'
Applied to your statement, we thus get: 'No integer is both non-positive and non-negative if it is not the zero integer'
Also, 'No P is Q' is the same as 'All P is not Q' or 'Any P is not Q', and thus we get:
'Any integers is not both non-positive and non-negative if it is not the zero integer'
Which translates to:
$$\forall x \in \mathbb{Z} (x \not =0 \rightarrow \neg (\neg x > 0 \land \neg x < 0))$$

A: $(\forall n\in\mathbb{Z}):n\geqslant0\wedge n\leqslant0\implies n=0$


text:
Q: Search with foreign key association I have an association that looks like:
belongs_to :question,
    -> { where lang: I18n.locale },
    class_name: "Translation",
    foreign_key: 'question_tid',
    primary_key: 'id'
has_many :questions,
    class_name: "Translation",
    foreign_key: 'id',
    primary_key: 'question_tid'

Schema looks like:
#
#  id                 :integer          not null, primary key
#  question_tid       :integer
#  category_id        :integer
#  default_answer_tid :integer
#  created_at         :datetime
#  updated_at         :datetime
#

I am trying to do a search query like this:
def self.find_by_search(search)
        return includes(:question).
               where("question like ?", "%#{search}%").
               sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
    end

However, the where does not seem to recognize the question association. How can I make it understand that I want the 'question' field which joins on the translation table?
Thanks

A: Write it:
def self.find_by_search(search)
  return includes(:question).
         where("question like ?", "%#{search}%").
         references(:question).
         sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) }
end

Documentation of includes clearly said :

conditions: If you want to add conditions to your included models you'll have to explicitly reference them


text:
Q: How can I refund a game purchased on the Nintendo Switch eShop? A few minutes ago, I accidentally purchased a game on the Nintendo Switch eShop. I have not launched the game, so it still has 0 hours played.
How can I refund a digital game purchased on the Nintendo Switch eShop?

A: Nintendo does not offer refunds for games or DLC purchased on the eShop:

Refund Request for Downloaded Game or DLC (Wrong Game, Didn't Like Game, Accidental Purchase)
Situation:
Refund request for digital content purchased through a Nintendo Shop Channel. (For example, incorrect game or DLC was downloaded, content was purchased by accident, you didn't like the game.)
What to do:

*

*We are unable to provide refunds or exchanges for mistaken purchases.

*Please be sure to read the game descriptions and check out the screen shots available through the Nintendo eShop before making purchases.

A: Nintendo does not offer refunds. However, customer support may. Good luck.

A: You can get refunds for games by calling Nintendo Customer Support. I made an accidental purchase, and regained my funds.


text:
Q: Callback with Decorator or Parameter in Python? I'm designing an API. What's preferred using
@event1
def event_callback():
     print "wooop"

or something like:
def event_callback():
    print "wooop"

event1(callback=event_callback)

A: The two alternatives are entirely equivalent. Decorator syntax was introduced because particularly for long functions it was easy to miss the decoration call following the definition, so you should use a decorator.