text:
Q: Why does "Take Ownership" (and other) context menu (items) have selection limit? Using "Take Ownership Shortcut". Everything works fine, but it appears there are limits - when selecting more than 15 folders, "Take Ownership" context menu entry disappears. Same goes with files, 15 is maximum.
Where does that limit of 15 come from and why does it exist?

A: If you have selected more than 15 files in File Explorer of Windows, options like Open, Print, and Edit disappear from the context menu. Here you can see the context menu has no options like those.

❇ This issue is not new to Windows 10. It also affects Windows 7, Windows 8/8.1 and Windows Vista. This is to avoid accidentally performing these actions on a large number of files at once, which can cause the computer to stop responding. To resolve this problem, there is registry tweak given by Microsoft.

*

*Open Registry Editor (regedit.exe). Go to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer registry key. Create a 32-bit DWORD value named MultipleInvokePromptMinimum by right clicking the right pane in registry editor. Even if you are running 64-bit Windows, you still need to create a 32-bit DWORD value.

*Set its value data in decimal to the number of items in Explorer for which you wish to have Take Ownership context option visible. In the example below, I set the DWORD value data to 20 in decimal, so context menu commands will remain accessible for up to 20 selected files.

*Then restart Explorer or sign out and sign in back to your PC. Now, you can select more than 15 files again and see that the missing Take Ownership context menu items are visible now.

*N.B. If you set up User Access Control (UAC) Prompt to full secure mode, then you see many UAC prompts pop up during take ownership. So take ownership some few files at once. Microsoft recommends "only increasing this value to a reasonable number in a controlled environment and only where users really need this value increased".
 Associated Articles::

*

*Microsoft Support: Context menus are shortened when more than 15 files are selected

*WinAero: Windows 10 context menu items missing when more than 15 files are selected

*Ghacks: Fix Context Menu Items Missing In Windows Explorer

*AskVG: [FIX] Open, Edit and Print Context Menu Items Missing in Windows 7 When 15+ Files Selected

*SevenForums: Restore Missing "Open", "Print", and "Edit" Context Menu Items when more than 15 Files are Selected


text:
Q: Method like getView() for GridLayout (not GridView) For an App I am working on, I have a GridLayout that I populate dynamically. It works great except for one thing. Right now, I'm simply loading all the images I want to display at once. However, the number of images I have to load can vary, meaning there is a risk of an OutOfMemoryException. What I need is a method like getView() in GridView, only then for GridLayout. I have been thinking about this a while now, but I'm still stuck. Does anybody have suggestions for an approach?

A: GridLayout is used for aligning items in a grid. This is similar to grid systems in desings. GridLayout cannot work with adapters, which is what GridView is for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PDF js worker bundled with a hashed name with Webpack I need to use PDF.js with Webpack, I followed the documentation that tells you to add an entry for pdf.worker.
Here is the entry and output of my webpack config:
entry: {
    index: './src/client/home/home.jsx',
    'pdf.worker': 'pdfjs-dist/build/pdf.worker.entry'
},
output: {
    path: path.join(__dirname, 'build/client'),
    publicPath: '/',
    filename: [name]-[chunkhash].js,
}

And still according to the documentation, in the javacript code, I need to specify the worker path like this:
pdfjsLib.PDFJS.workerSrc = '/pdf.worker.bundle.js';

The issue is that I use chunkhash for the generation of the file so it cannot find pdf.worker.bundle.js.
I see two solutions:

*

*Remove the hash for the worker ONLY in webpack: [name]-bundle.js
But how can I tell webpack to ONLY do this for the worker and not the other .js files?

*Change the value of pdfjsLib.PDFJS.workerSrc after the code is generated, how can I do that?
Also, am I right to think that the first solution is not good since the user will always cache the same worker?


text:
Q: Strange Notation in Linear Algebra Question I've taken courses on linear algebra before, so I know enough where I can usually get by, but I saw the following question on my homework, and have no idea how to interpret it:

For the next two questions, let:
$$ B_2 = \Biggl\{ \begin{bmatrix}1 & 1\\1 & 3\end{bmatrix},
\begin{bmatrix}1 & 1\\3 & 1\end{bmatrix}, \begin{bmatrix}1 & 3\\1 &
1\end{bmatrix}, \begin{bmatrix}3 & 1\\1 & 1\end{bmatrix} \Biggl\} $$
$$ B_3 = \Biggl\{ \begin{bmatrix}1 & 0\\0 & 0\end{bmatrix},
\begin{bmatrix}0 & 1\\0 & 0\end{bmatrix}, \begin{bmatrix}0 & 0\\1 &
0\end{bmatrix}, \begin{bmatrix}0 & 0\\0 & 1\end{bmatrix} \Biggl\} $$
Find: $P_{B_3 \leftarrow B_2}$

I have done multiple searches (although I honestly have no idea what to search for at this point) trying to figure out what on Earth "$P_{B_3 \leftarrow B_2}$" could possibly mean in this context, and I have come up with nothing. It looks like it may be referring to polynomial space with "$P$", but that doesn't make any sense given the provided matrices.
Does anyone know what "$P_{B_3 \leftarrow B_2}$" means?

A: It means "the transition matrix from the (ordered) basis $B_2$ to the (ordered) basis $B_3$". Thus, for this question, it is
$$P_{B_3\leftarrow B_2}=\begin{bmatrix}
1&1&1&3\\
1&1&3&1\\
1&3&1&1\\
3&1&1&1\end{bmatrix}$$
It takes a vector in $M_{2×2}(\mathbb R)$ expressed in the basis $B_2$ and returns that same vector in the basis $B_3$.


text:
Q: merge of directories in clearcase I merged  directories in two different views using clearcase. The directories can have difference in the no. of files and subdirectories.
After merge The listing of files merged on merge manager doesnot match with no. of files
checkedout on to-clearcase view.
ie. lsco on the merged-to view and
    No. of files checked out on merge manager(I didn't checkout any files prior to merge operation)

A: It depends on the history of the two versions of a directory being merged from one branch to another:

*

*if one version has removed files (i.e. has  less files than the other version)

*if said version is merged onto the other,

the resulting version will have less files than initially shown in the view.
That could be because:

*

*that view is not the one used for the merge

*that view is the correct one, but with an eclipsed or hijacked content (privates files replacing versioned files)

In any case, what would help in the mentioned view is:

*

*a 'cleartool ls' in the directory merged

*a 'cleartool ls' in the parent directory of the directory merged.

The output of those two commands would help to confirm the exact status of the files merged within that directory, as well as the status of the directory itself.


text:
Q: event listener resize window not working on first expand only I'm trying to make the side buttons in the carousel(3rd slide) change based on the inner slide container size resizing with media query. I've got it working except for one bug. When I resize back from smaller responsive, the button doesn't change, until I resize again (smaller or bigger but on the same media query)

*

*Site to reproduce error: https://9wk9h.csb.app/

*The Full Code: https://codesandbox.io/s/my-portfolio-2021-9wk9h
This is the block of code used in the file src/Components/AboutComponents/AboutCarousel.js:
  useLayoutEffect(() => {
    if (slideIndex === slideIndexes.fun) {
      const handleResize = debounce(() => {
        setIsScreenResized(!isScreenResized);
        console.log('isScreenResized changed =', isScreenResized);
        console.log('---------------------')
      }, 100);

      window.addEventListener('resize', handleResize, false);

      return () => {
        window.removeEventListener('resize', handleResize, false);
      }
    }
  },[slideIndex, slideIndexes, hobbyTabIdSelected, isScreenResized, setIsScreenResized]);

See the following use case below to reproduce the issue:

A: The issue was the transition had a timout of 1 second set in the index.css for all which would include the height resize(being read by the eventListener):
.div-about-carousel-slide-container {
  ...
  transition: all 1000ms ease-in-out; /* double size of about-carousel-slide-hide */
}

Therefor the content list would not complete the resize until after 1 second, and the debouncer was set to 0.1second (to read before the content resized).
The Fix:
Since we want to keep slide transition to keep the opacity flash, we change it to the following:
.div-about-carousel-slide-container {
  ...
  transition: opacity 1000ms ease-in-out; /* double size of about-carousel-slide-hide */
}

(Note: I'm probably going to refer to this question in the feature on why setting transition to all is a bad default habbit)


text:
Q: Vault is already initialized error message I deployed the following helm chart for vault and I get the following error "Vault is already initialized" when doing "vault operator init" command.  I do not understand why it is already initialized.
Also, when I enable readinessProbe the pod keeps restating I assume because it is not initialized properly.
global:
 enabled: true
 tlsDisable: false
server:
  extraEnvironmentVars:
    VAULT_CACERT: /vault/userconfig/vault-server-tls/ca.crt
  logLevel: debug
  logFormat: standard
  readinessProbe:
   enabled: false
  authDelegator:
    enabled: true
  extraVolumes:
  - type: secret
    name: vault-server-tls # Matches the ${SECRET_NAME} from above
 standalone:
  enabled: true
  config: |
   listener "tcp" {
     address = "[::]:8200"
     cluster_address = "[::]:8201"
     tls_cert_file = "/vault/userconfig/vault-server-tls/tls.crt"
     tls_key_file  = "/vault/userconfig/vault-server-tls/tls.key"
    }

  storage "file" {
    path = "/vault/data"
  }


text:
Q: How to play an audio file repeatedly without a memory leak? I am using NAudio to play a wav file
    WaveOut waveOut;
    WaveFileReader reader;
    bool laeuft = false;
    private void abspielen()
    {
        if (!laeuft)
        {
            reader = new WaveFileReader("test.wav");
            waveOut = new WaveOut();
            laeuft = true;
        }
        waveOut.Init(reader);
        waveOut.Play();
    }

It plays only once and stays mute. Before that I used
    private void abspielenAsync(string was)
    {
        using (var reader = new WaveFileReader(was))
        {
            using (var waveOut = new WaveOut())
            {
                waveOut.Init(reader);
                waveOut.Play();
            }
        }
    }

Which worked repeatedly, but somewhere in this is a memory leak. Where is it? How to play repeatedly without a memory leak?


text:
Q: Is there any indication that the the other ship in "Night Terrors" was Tamarian? 'Cos both "Night Terrors" and "Darmok" involve a completely metaphorical language.  I know this is not a lot to go on.
On the other hand, the aliens in "Night Terrors" were able to communicate telepathically with Deanna, and clearly the Tamarians in Darmok did not (would not or could not).

A: No, there is no indication that the other ship was Tamarian.
The language used, "eyes in the dark" and "one moon circles", are telepathic messages as explained by Deanna Troi. There is no indication that the aliens in the other ship literally send these words. For all we know they telepathically send images of the binary star system, which Deanna "sees" as two eyes in the dark, and a schematic depiction of a hydrogen atom, which Deanna "sees" as a planetary system.
Since we do not know if words or images were telepathically sent, we have no way of knowing what the aliens' actual language is, or if they have a (spoken) language at all.

A: The original screenplay would indicate that the "other vessel" was some kind of energy-based lifeform.

EXT. SPACE - THE ENTERPRISE (OPTICAL):
grabs power, accelerates, skims through the last sparks
  of the diminishing explosion... directly into the
  center of the rift...
And passing it, going the opposite direction... a
  shapeless mass... a sparkling energy field... the
  other ship.
Night Terrors - Screenplay.

Since the Tamarians are neither energy-based, nor obviously telepathic, it seems highly unlikely (to the point of impossibility) that it's one of their vessels.


text:
Q: Curl -d vs --data-binary Using this [https://github.com/prometheus/pushgateway][1] we are trying to push one metric to prometheus.  It seems to require the data in a very specific format.
It works fine when doing their example curl of
echo "some_metric 3.14" | curl --data-binary @- http://pushgateway.example.org:9091/metrics/job/some_job

Yet doing a curl with -d option fails as missing end of line/file
curl -d 'some_metric 3.15\n' http://pushgateway.example.org:9091/metrics/job/some_job

I'm trying to understand the difference in behaviour since I believe both are doing POST commands and I need to replicate this --data-binary option in node.js via "request.post" method but I seem to only be able to replicate the curl -d option which doesn't work.
Any suggestions on hints on what the difference is between -d and --data-binary and to do the equivalent to --data-binary from within node.js?

A: From curl man page:

--data-ascii
(HTTP) This is just an alias for -d, --data.
--data-binary
(HTTP) This posts data exactly as specified with no extra processing whatsoever.
If you start the data with the letter @, the rest should be a filename. Data is posted > in a similar manner as -d, --data does, except that newlines and carriage returns are > > preserved and conversions are never done.
Like -d, --data the default content-type sent to the server is application/x-www-form-> > urlencoded. If you want the data to be treated as arbitrary binary data by the server > then set the content-type to octet-stream: -H "Content-Type: application/octet-stream".
If this option is used several times, the ones following the first will append data as > described in -d, --data.

Using @- will make curl read the filename from stdin.
So, basically in your first variant you send a binary file named "some_metric 3.14".
In the second one, you're sending an ascii string "some_metric 3.15\n".
If you want curl to strip new lines before sending, use --data-ascii or -d option:
echo "some_metric 3.14" | curl -d @- http://pushgateway.example.org:9091/metrics/job/some_job

A: There's no difference between --data or --data-binary if you're passing a regular string
curl --data somekey=somevalue example.com

the value is handled by the same code and these two arguments act exactly the same.
But curl also lets you tell it to read the contents for --data or --data-binary from a file, by passing @filename or @- to read from stdin:
curl --data @./some/path/to/a/file.txt example.com

This is where there is a difference. --data will send the file with all \n and \r characters removed, whereas --data-binary will send the entire file as-is (actually it'll send the first GiB (1024*1024*1024 bytes) of the file).


text:
Q: Can I access a file saved in internal memory from a Fragment? I have a file saved in internal memory and I access it like:
getApplicationContext().openFileInput("database.xml");

But, application context is only limited to Activity classes. So, I was wondering if there is a way to access those files from Fragments?

A: You could use the Activities Context with getActivity() instead of getApplicationContext().


text:
Q: Python / Pandas: Convert 'Day of Year' Integer into Full Date I know with a Datetime object, I can extract the numeric day of year (e.g. January 1st = 1, December 31st = 365) with .dayofyear like this:
some_datetime.dayofyear

Is there a way I can reverse this and take an integer for the dayofyear and convert it back to a full date?
I searched through datetime and tried a few things, but nothing seemed to work.

A: You can do:
df['date'] = df['days'].apply(lambda x: dt + pd.Timedelta(f'{x}D'))
print(df)

   days       date
0    32 2020-02-02
1   150 2020-05-30
2   200 2020-07-19

Sample Data
# set some start date
dt = pd.to_datetime('2020-01-01')
df = pd.DataFrame({'days': [32, 150, 200]})

A: An interesting alternative is to use the origin parameter of pandas' to_datetime() :
days = [32, 150, 200]
pd.to_datetime([d-1 for d in days], unit='D', origin=pd.Timestamp('01-01-2020'))

Be sure to subtract one day since the first day is already accounted for in the initialization.
Credits go there.


text:
Q: How to declare a function with an argument which is an array? I need to declare a function that has 32 arguments, so it would be handy to put an unique argument: an array of 32 elements.
I don't find the syntax to do that, I've tried everythinh like:
function x=myfunction(str(32)) (etc...)
But without success.

A: Unlike other languages, MATLAB can accept matrices as a single argument; so you could just check that the input argument is a vector of length 32:
function x = myfunction(arg)
    if length(arg) ~= 32
        error('Must supply 32 arguments!');
    end

    %# your code here
end

If it's a variable number of arguments, check out varargin:
function x = myfunction(varargin)

But for 32 arguments, consider using an input structure:
function x = myfunction(argStruct)

    if length(fieldnames(argStruct)) ~= 32
        error('not enough arguments!');
    end

Supply arguments in the structure, then pass the structure:
>> myArgs = struct();
>> myArgs.arg1 = 5;
>> myArgs.arg2 = 7;
>> %#(etc)
>> x = myfunction(myArgs);

Then in the function, you could either call argStruct.arg1, etc, directly; or unpack it into 32 different variables inside the function. I would give the fields descriptive names so you don't refer to them as arg1, etc inside your function. For that many input arguments, people using the function probably won't remember the order in which your function requires them to pass inputs to. Doing it with a struct lets users pass in arguments without needing to think about what order those inputs are defined.

A: To add to @strictlyrude27's awesome answer, it looks like you may misunderstand how function declarations work in Matlab. You wrote:
function x=myfunction(str(32))

However, you don't need to declare the type of input in matlab. Just give it a name, and then use it. So, the proper syntax for a declaration would be:
function x = myfunction(myInput)


text:
Q: RoR nested forms with dropzone and some insight? I'm somewhat new to RoR, I've made some nice things in it but while trying my hand at drag and drop file uploading I came across some problems, right now I'm trying dropzone js, however I fail to understand some things, specially when it comes to making a nested form with it, I've investigated about this for 2 days now and I'm still confused on how to properly set up my form, so far I have something like this:
<%= form_for(@event, :html => { :multipart => true}) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.fields_for :images do |image|
    <%= f.file_field :image %>
  <% end %>
<% end %>

It's pretty straightforward, the real one has a couple more attributes but they are submitting with no problems, even the image is submitting no problem, problem is that I don't know how to use dropzone inside my form, I've tried multiple approaches and all leave me with either no dropzone or an error uploading the images to the database, any advise on how to manage this?


text:
Q: How to hide button when checkbox is checked via ng-show and ng-model need to hide button when any checkboxes is checked.
Here is my code:
need to show button if checkbox is checked and hide button if checkbox is not checked:
Edit
when I checked next checkboxes:

                    <input type="checkbox" ng-model="showButton">

I think hide button not working if I use ng-repeat. Because If I use only one  it is working correctly.

A: I think you should add an click event to handle this.
And you need add checked variable inside $data to store if this row is checked and a global showbutton for button's ngIf
Like :

            <input type="checkbox" ng-model="row.checked" ng-change="rowCheck()">

function rowCheck(){
     $scope.showButton = !$data.every(x=>x.checked);
}


text:
Q: iBeacon monitoring mode proximity for beacon region I have a question about iBeacons in monitoring mode. I want to have an interaction with a notification being sent to a user if the device is in 1-2m vicinity to the beacon.
There used to be a function called:
 var radius: CLLocationDistance { get }

It's now deprecated so there's no way to set range of the beacon region.
So the different states inside, outside, unknown can't be configured. Most long range beacons have a region of more then 60m which makes the region to big for any interaction in your home.
What I had to do was to lower the power of the BLE chip I used via AT commands to -4hz. Now the span is around 3-4m, which is better bit still not what I want. I've tried tin jars to try to lower the signal even more but it doesn't make a big difference. Even tin foil around the BLE chip.
Have anybody found a way to specify a Beacon region? The proximity needed to have inside region to be triggered with this function:
   func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for beaconRegion: CLRegion){}

Ranging mode doesn't seem to work in conjunction with monitoring so I can't use proximity which otherwise would be a solution.
   func update(distance: CLProximity) {}

A: A few points:

*

*You are correct that you cannot set the range for beacon monitoring.

*The radius field was never designed for beacon monitoring, but rather for geofences, so that never worked to do what you want.

*Reducing the transmitter power is generally not reliable because as you have seen, you cannot control the trigger distance well enough, and it results in a large variance in the distance where the trigger happens.

*Ranging does work in conjunction with monitoring, with some limitations, so this is the best technique to accomplish what you want.
I have described the technique in more detail in my answer to this related question.


text:
Q: How to prove $A = (A \cap B) \cup (A - B)$ and show that $(A \cap B)$ and $(A - B)$ are non-intersecting. I thought about starting with $A = (A \cap B) \cup (A)$ since $(A-B)$ is essentially saying only consider $A$. This would then lead me to proving $A = (A \cap B)$. However I'm completely stuck on how to prove they are non-intersecting.

A: HINT
You can use $A - B = A \cap B^C$

A: By definition:
$A\cap B=\{x|x \in A \text { and }x\in B\}$
$A-B=\{x|x \in A \text { and } x \not \in B\} $
$C\cup D=\{x| x \in C \text { OR } x\in D\} $
So $(A\cap B)\cup (A-B)=$
$\{x|(x\in A \text { and }x\in B)\text { OR } (x\in A \text { and }x \not \in B)\}= $
$\{x|x \in A \text { and } x \text{ either is or isn't in } B\}=$
$\{x|x \in A \text { and nothing can be said about whther} x \text { is in }B\}= $
$\{x|x\in A\} =$
$A $.
===
Likewise
$(A\cap B)\cap (A-B)=$
$\{x|(x\in A\text{ and } x\in B)\text{ and } (x\in A \text { and }x\not \in B\} =$
$\{x|x \in A \text { and } x \text { is both in and not in }B\} $
There can't be any elements that are both in and not in a set.  So these do not intersect.

A: Let $A,B \subset X$.
Using Bram28's hint:  $A - B = A \cap B^C$.
1) Distributive Law:
$(A \cap B) \cup (A \cap B^C) = $
$A \cap (B \cup B^C) = A \cap X = A$ .
2) Associative and Commutative Law:
$(A \cap B) \cap (A \cap B^C) = $
$A \cap (B \cap B^C) = A \cap \emptyset = \emptyset$.


text: Q: How to update nodejs version I am trying to update NodeJS version from node v10.15.1 to v12.18.0 How we can do it. Is it possible?. Any update command are there? Anyone knows please help to find the solution.


text:
Q: WidgetKit preview stopped working after switching to M1 Apple silicon Have recently switched to M1 Macbook Pro. The project I've been working on stopped previewing the WidgetKit extension file (for other swiftui files preview works as intended). Xcode on my previous machine (not M1) previews the WidgetKit file well. Here is the warning I get when trying to preview WidgetKit extension file on M1 mac:
RemoteHumanReadableError
ProcessError: Failed to launch widget extension: The operation couldn't be completed. (CHSErrorDomain error 1050.)


text:
Q: Issue mocking argparse with unittest I have client code that I need to test
def arg_parser(arg_parse=None):
    if not arg_parse:
        arg_parse = sys.argv[1:]
    parser = argparse.ArgumentParser()
    parser.add_argument('--a', type=str, required=True)
    parser.add_argument('--b', type=str, required=True)
    return parser.parse_args(arg_parse)

def main():
      arg_parse = arg_parser()
      update_config(arg_parse)
      ......

def update_config(conf_args: argparse):
    # read default YAML configuration file
    with open('resources/config.yaml', 'r') as file:
        conf = yaml.safe_load(file.read())
    # Updated the YAML configuration file
    if conf_args.a: // gives error here
        ..........

if __name__ == '__main__':
    main()

And I am testing this main method by mocking the arg_parser method
@mock.patch('test.prepare.arg_parser')
def test_main(mock_arg_parser):
    args = arg_parser(['--a', 'a1',
                       '--b', 'b1'])

    mock_arg_parser.return_value = args
    ...
    main()

But I am getting an exception when I try to access arguments from argparse (arg_parse.a)
        # read default YAML configuration file
        with open('resources/config.yaml', 'r') as file:
            conf = yaml.safe_load(file.read())
        # Updated the YAML configuration file
>       if conf_args.a:
          AttributeError: 'list' object has no attribute 'a'

Unfortunately, I can't align client code so need to fix the test.

A: so it turns out you don't need to involve mocking at all -- you can simplify your code as follows:
def arg_parser(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--a', type=str, required=True)
    parser.add_argument('--b', type=str, required=True)
    return parser.parse_args(arg_parse)

def main(argv: Sequence[str] | None = None):
      arg_parse = arg_parser(argv)
      update_config(arg_parse)
      ......

def update_config(conf_args: argparse):
    # read default YAML configuration file
    with open('resources/config.yaml', 'r') as file:
        conf = yaml.safe_load(file.read())
    # Updated the YAML configuration file
    if conf_args.a: # gives error here
        ..........

if __name__ == '__main__':
    main()

and then in your test pass through the argument list explicitly:
def test_main():
    main(['--a', 'a1', '--b', 'b1'])

no need for a complicated mocking!
this works because argparse.ArgumentParser.parse_args defaults to sys.argv[1:] when passed None (as happens in your script by default) but you can pass your testing arguments for your test!  I go over this technique in a video I made


text:
Q: multiple spans in a charsequence when ever I set a span in a charsequence, then set the text in a text view its fine, it comes out right. I am using this
Ssb.setSpan(new StyleSpan(Typeface.ITALIC), start, end, 1);
Then set the text of the TextView.
But when I get the text from the text view and then get the text from it using tv.getText(); it returns the CharSequence expected but when I set the span somewhere else in the cs the other span when the text is set it's not there.
Im sorry for lack of code. I have no proper internet access at home so im posting this from my phone.

A: try this
Spannable mSpannable = textview.getText(); // will hold old spans.
mSpannable.setSpan(new StyleSpan(Typeface.ITALIC), start, end, 1); // do some new span


text:
Q: Averaging results from a list of lists where every nth list is a reptition So I wrote a model that computes results over various parameters via a nested loop. Each computation returns a list of len(columns) = 10 elements, which is added to a list of lists (res).
Say I compute my results for some parameters len(alpha) = 2, len(gamma) = 2, rep = 3, where rep is the number of repetitions that I run. This yields results in the form of a list of lists like this:
res = [ [elem_1, ..., elem_10], ..., [elem_1, ..., elem_10] ]

I know that len(res) = len(alpha) * len(gamma) * repetitions = 12 and that each inner list has len(columns) = 10 elements. I also know that every 3rd list in res is going to be a repetition (which I know from the way I set up my nested loops to iterate over all parameter combinations, in fact I am using itertools).
I now want to average the result list of lists. What I need to do is to take every (len(res) // repetitions) = 4th list , add them together element-wise, and divide by the number of repetitions (3). Sounded easier than done, for me.
Here is my ugly attempt to do so:
# create a list of lists of lists, where the inner list of lists are lists of the runs with the identical parameters alpha and gamma
res = [res[i::(len(res)//rep)] for i in range(len(res)//rep)]

avg_res = []
for i in res:
    result = []
    for j in (zip(*i)):
        result.append(sum(j))
    avg_res.append([i/repetitions for i in result])

print(len(result_list), avg_res)

This actually yields, what I want, but it surely is not the pythonic way to do it. Ugly as hell and 5 minutes later I can hardly make sense of my own code...
What would be the most pythonic way to do it? Thanks in advance!

A: In some cases a pythonic code is a matter of style, one of its idioms is using list comprehension instead of loop so writing result = [sum(j) for j in (zip(*i))] is simpler than iterating over zip(*i).
On the other hand nested list comprehension looks more complex so don't do
avg_res = [[i/repetitions for i in [sum(j) for j in (zip(*j))]] for j in res]

You can write:
res = [res[i::(len(res)//rep)] for i in range(len(res)//rep)]

avg_res = []
for i in res:
    result = [sum(j) for j in (zip(*i))]
    avg_res.append([i/repetitions for i in result])

print(len(result_list), avg_res)

Another idiom in Programming in general (and in python in particular) is naming operations with functions, and variable names, to make the code more readable:
def sum_columns(list_of_rows):
  return [sum(col) for col in (zip(*list_of_rows))]
def align_alpha_and_gamma(res):
  return [res[i::(len(res)//rep)] for i in range(len(res)//rep)]

aligned_lists = align_alpha_and_gamma(res)

avg_res = []
for aligned_list in aligned_lists:
    sums_of_column= sum_columns(aligned_list)
    avg_res.append([sum_of_column/repetitions for sum_of_column in sums_of_column])

print(len(result_list), avg_res)

Off course you can choose better names according to what you want to do in the code.

A: It was a bit hard to follow your instructions, but as I caught, you attempt to try sum over all element in N'th list and divide it by repetitions.
res = [list(range(i,i+10)) for i in range(10)]
N = 4
repetitions = 3
average_of_Nth_lists = sum([num for iter,item in enumerate(res) for num in item if iter%N==0])/repetitions
print(average_of_Nth_lists)

output:
85.0

explanation for the result: equals to sum(0-9)+sum(4-13)+sum(8-17) = 255 --> 255/3=85.0
created res as a list of lists, iterate over N'th list (in my case, 1,5,9 you can transform it to 4,8 etc if that what you are wish, find out where in the code or ask for help if you don't get it), sum them up and divide by repetitions


text:
Q: What will the rank be, if a matrix multiply its transpose? Let's say we got a matrix $A_{n\times k}$ and $n>k$, and the column rank of $A$ is $k-1$ if we pre- and postmultiply its transpose, i.e. $A^TA$ and $AA^T$.
Is the rank of $A^TA$ and $AA^T$ still $k-1$?

A: For a real matrix $A$, $\|A x\|^2 = x^T A^T A x$ so $A x = 0$ if and only if $A^T A x = 0$.
Thus the ranks of $A^T A$ and $A$ are always equal.  Similarly, $\text{rank}(A) = \text{rank}(A^T) = \text{rank}(A A^T)$.


text:
Q: How to set data from JSON in Calendario? I've recently downloaded the Calendario jQuery plugin from http://tympanus.net/codrops/2012/11/27/calendario-a-flexible-calendar-plugin/
It works well, and the example in the index.html says that I can set up events in the calendar like this:
cal.setData({
    '03-01-2013' : 'testing',
    '03-10-2013' : 'testing',
    '03-12-2013' : 'testing'
});

There's no problem, the tests are show up in the calendar, and I can click on any of these. I want to set up a simple database for the events in the calendar, to make it easier to store and handle, and I need to create a simple UI for the plugin.
I have this javascript (jQuery) function on my page:
var dates = {};
$.post('ajax.php?getdates').done(function(r){
    alert(r);
    dates = $.parseJSON(r);
    alert(dates);
});
cal.setData( dates );

I have the database with some test datas, but when I pass it to the plugin via an AJAX request, it doesn't show up in the calendar.
You can view the page here: http://hafehungarykft.tarhelykeszito.hu/naptar/?nologin
And the AJAX page here: http://hafehungarykft.tarhelykeszito.hu/naptar/ajax.php?getdates&nologin
You can access the pages with the nologin flag for testing purposes. I hope someone can help me.

A: I've now realized that the dates was in the wrong format. I used YYYY-MM-DD instead of the preferred MM-DD-YYYY. It was a painful mistake taking days to solve, simply because of my inattention...


text:
Q: Matlab: Loop issue This is quite a simple issue, but I've been struggling with it. sortedd and sortedfinal_d are 8 x 1000 Matrices and I am using the loop below to check if any of the elements in sortedfinal_d lies between two consecutive elements of sortedd, in terms of magnitude. I'm doing this along each row. overall_p is a 8 x 1000 Matrix as well, but at the end of this process I end up having final_p as a Matrix of Zeros. I don't know why this is.
for k=2:1000
    for s=1:1000
        for j=1:8
            if sortedd(j,k) > sortedfinal_d(j,s) && sortedfinal_d(j,s) > sortedd(j,k-1)
                final_p(j,s) = overall_p(j,k);
            end
        end
    end
end

EDIT: Added data for the inputs as shown below:
sortedd (first four columns) =
   0.219977361620113   0.219996752039812   0.220344444223787   0.220593274018691
   0.272807483153955   0.273682693068593   0.273846498221277   0.274060049642900
   0.327201460264565   0.327375792227635   0.327572790857546   0.327856448530021
   0.380389118311424   0.380845274148177   0.380893687870765   0.381015090963159
   0.434832574575088   0.434860658844550   0.435021604722982   0.435119929919457
   0.487119089589798   0.488128501559782   0.488207451439073   0.488430455768512
   0.540652551559395   0.541303305046034   0.542195194863130   0.542234381085921
   0.595254195563241   0.595296064375604   0.595376090156252   0.595377962767971

sortedfinal_d =
   0.182086792394190   0.182406508309366   0.182406508309366   0.182808976400818
   0.233058295607543   0.233058295607543   0.233158455616954   0.233158455616954
   0.286243848617693   0.286357973626582   0.286918095670684   0.287393171241241
   0.336938335090164   0.336938335090164   0.337094505106945   0.337669618738100
   0.390287818652551   0.390567879874952   0.390567879874952   0.390670502700602
   0.446995120903824   0.447270251510681   0.447452123072880   0.447597175111267
   0.501060785098551   0.501060785098551   0.501060785098551   0.501060785098551
   0.551311219045087   0.551463923687602   0.551463923687602   0.551653815175502

Thanks a lot

A: Do you have to use loops to accomplish this?
matching_d = sortedfinal_d(:,1:end-1) < sortedd(:,2:end) ...
                  & sortedd(:,2:end) < sortedfinal_d(:,2:end);
final_p(matching_d) = overall_p(matching_d);

If you can show us a small sample input (say, 1x5 versions of sortedd and sortedfinal_d) and output (the corresponding matching_d) it would be easier for us to help troubleshoot.

A: If i set your matrices to random numbers, final_p does return some numbers.
So your code works as is. Post your dataset or at least describe the dataset in some detail, this will make it much easier to diagnose the problem.
I have reduced 1000 down to 10 and re-ordered the iteration variables to i, j, k to make it easier to follow:
sortedd = rand(8, 10);
sortedfinal_d = rand(8, 10);
overall_p = rand(8, 10);

for i=2:10
    for j=1:10
        for k=1:8

            if sortedd(k,i) > sortedfinal_d(k,j) && sortedfinal_d(k,j) > sortedd(k,i-1)
                final_p(k,j) = overall_p(k,i);
            end
        end
    end
end

final_p


text:
Q: Why Array.zeroCreate still fills null for non nullable type? Does it imply that whenever I am passed an array of a non nullable type, I should still check if it is null? Actually it is not even possible to check <> null but have to use operator.unchecked .How is it better than C#?
type test=
    {
        value: int
    }

let solution = Array.zeroCreate 10

solution.[0] <- {value = 1}
solution.[1].value   // System.NullReferenceException: Object reference not set to an instance of an object

type test =
  {value: int;}
val solution : test [] =
  [|{value = 1;}; null; null; null; null; null; null; null; null; null|]
val it : unit = ()

A: It depends where the array is being passed from.
If the array is created and used only within F#, then no, you don't need to check for null; in fact, you shouldn't check for null (using Unchecked.defaultOf) because the F# compiler optimizes some special values like [] (and None, in certain cases) by representing them as null in the compiled IL.
If you're consuming an array being passed in by code written in another language (such as C#), then yes, you should still check for null. If the calling code just creates the array and doesn't mutate it any further, then you'll only need to perform the null checks once.
EDIT : Here's a previous discussion about how the F# compiler optimizes the representation of certain values using null: Why is None represented as null?

A: As the documentation for Array.zeroCreate indicates, it initializes the elements to Unchecked.defaultof<_>.  This therefore carries with it all of the same caveats that direct use of Unchecked.defaultof does.  Generally, my advice would be to use Array.create/Array.init whenever possible, and to treat  Array.zeroCreate as a possible performance optimization (requiring care whenever dealing with non-nullable types).

A: You're creating a record type, which is implemented as a class, which is indeed nullable.  If you intended to create a struct, your code should look something like this:
type test =
    struct
        val value: int
        new(v) = { value = v }
        override x.ToString() = x.value.ToString()
    end

let solution = Array.zeroCreate 10

solution.[0] <- test(1)

This outputs: val solution : test [] = [|1; 0; 0; 0; 0; 0; 0; 0; 0; 0|]
You could also write the type using the Struct attribute, saving you a level of indentation.
[<Struct>]
type test =
    val value: int
    new(v) = { value = v }
    override x.ToString() = x.value.ToString()


text:
Q: Как вызвать функцию в компоненте после того как свойство в vuex store изменится? У меня есть хранилище данных в vuex и два компонент.
Первый компонент это range slider, в котором я меняю значения слайдера и сразу же отправляю их в store.
Второй это компонент в котором мне нужно вызвать мою функцию при изменении store.
my store
state: {
    value: 0,
      rgbColors: {
        red: 0
      }
  },

Как я понимаю мне нужно использовать store.subscribe.watch.rgbColors.red или store.watch.rgbColors.red ведь так?
И если это так то как это использовать и вызвать функцию при изменении значения?

A: Просто поставьте watcher в нужном компоненте, не забыв замапить туда нужный state.
computed: {
    rgbColors() {
      return store.state.rgbColors;
    }
}

watch: {
    rgbColors: {
        handler(newValue, oldValue) {
            if(newValue !== oldValue) {
                //ваш код
            }
        },
        deep: true //если нужно отслеживать изменение свойств
    }
}


text:
Q: Safari iOS 6 operation bug I have the following problem. I'm currently developing an online game for Facebook. It's made with an HTML5 canvas and I'm using the melonJS Javascript engine.
Suddenly my game objects were not visible anymore and I even found the reason. The engine sets a flag on each object, indicating whether this object is visible. Therefore the engine checks whether the viewport (represented as a rectangle object) contains the object (also represented as a rectangle object).
This is the code of the described function ('this' is the object, 'r' is the viewport in this case):
/**
 * check if this rectangle is intersecting with the specified one
 * @param  {me.Rect} rect
 * @return {boolean} true if overlaps
 */
overlaps : function(r) {
return (this.left < r.right && r.left < this.right && this.top < r.bottom && r.top < this.bottom);
}

I know it sounds very strange, but for some reason this function returns 'false' even when it should return 'true'! But it's not a bug in the engine, and not a bug in my game. This bug only appears on the latest Safari version (Mac version unknown and iOS6 on iPad).
For some reason this bug does NOT appear, if the developer console is shown. If it's hidden, the bug appears immediately.
Does anyone know of this problem?

A: If this is still a problem, you can file a bug report on the melonJS issue tracker: https://github.com/melonjs/melonJS/issues
It may have been related to some code that has changed since this question was asked ("visible" and "in viewport" are now treated as separate things since melonJS 0.9.5)


text:
Q: Update .net core web app on iis I am developing a web app (web service) using Visual Studio 2015 net core v1 und hosting it on an Windows Server 2012 R2 with iis.
It is running well, but the changes I make are not being used.
In visual studio I save the changes and go to the publish section and publish it. I take the publish output folder and replace the original folder with it.
But it seems like it is not changing anything because I still get the old answers.
I tried restarting the website, but it did not change anything.
EDIT:
if I debug it, it works perfect

A: Like Ankesh Kumar mentioned: selecting an other output folder solver this problem.


text:
Q: Proof, that polynomial $\prod_{i=1}^{n} (X - a_i) + 1 \in K[X]$ doesn't have roots We have $n$ different elements $(a_1,...,a_n)$ that are all the elements of $K$ and  $\in$  finite field $K$.
I want to prove, that  $\prod_{i=1}^{n} (X - a_i) + 1 \in K[X]$ doesn't have roots
I know, that if $a_i$ is a root of polynomial $p \in K[X]$ , then exists $f \in K[X]$ such that $p = (x - a_i)f$
How can we use this fact in order to prove the statement?

A: If $\;\{a_1,...,a_n\}\;$ are not all the elements of $\;K\;$ the claim still is false even if $\;K\;$ is a finite field, for example:
$$K=\Bbb F_3\;,\;\;a_1=0,\,a_2=1\implies g(x)=x(x-1)+1=x^2-x+1$$
and still $\;g(2)=0\;$ ...
If $\;a_1,...,a_n\;$ are all the elements of the finite field $\;K\;$ then the claim is true, since
$$g(x)=\prod_{k=1}^n(x-a_k)+1\implies g(a_j)=1\neq0\;,\;\;\forall\,j=1,2,...,n$$

A: Let $k$ be a finite field, and set $p(x) = 1 + \prod_{\alpha\in k}(x - \alpha)\in k[x]$. Then a root of $p$ is simply an element $\beta$ (say, $\beta\in\bar{k}$ some algebraic closure of $k$) such that $p(\beta) = 0$. If $\beta\in k$, then
\begin{align*}
p(\beta) &=1 + \prod_{\alpha\in k}(\beta - \alpha)\\
&= 1 + (\beta - \beta)\cdot\prod_{\alpha\in k\setminus\{\beta\}}(\beta - \alpha)\\
&= 1 + 0\cdot\prod_{\alpha\in k\setminus\{\beta\}}(\beta - \alpha)\\
&= 1.
\end{align*}
Since $1\neq 0$, $p$ has no roots in $k$. Of course, any polynomial with coefficients in a field has roots in the algebraic closure of that field, so $p$ has roots in this sense.
If you really want to use your fact, you can proceed by contradiction: suppose $\beta\in k$ is a root of $p$. Then $p(x) = (x - \beta)q(x)$ for some $q\in k[x]$. But then
\begin{align*}
1 &= p(x) - \prod_{\alpha\in k}(x - \alpha)\\
&= (x - \beta)q(x) - (x - \beta)\prod_{\alpha\in k\setminus\{\beta\}}(x - \alpha)\\
&= (x - \beta)\left(q(x) - \prod_{\alpha\in k\setminus\{\beta\}}(x - \alpha)\right).
\end{align*}
This is a contradiction, as $r(x) = (x - \beta)\left(q(x) - \prod_{\alpha\in k\setminus\{\beta\}}(x - \alpha)\right)$ is $0$ when $x = \beta$, but $1\neq 0$.


text:
Q: Receipt of notification of the arrival of new data from API I have data on from the api on my app
I am sending the new data from my site
I want to put a message or notification on the application about the arrival of new data for this API
What is the best way to do this task?
This is the data I got
struct VideoView_Msrhiat: View {

@StateObject var model = Api()

var body: some View {

    VStack {
            ScrollView(.vertical, showsIndicators: false) {
                ForEach(model.models) { item in

VStack {
                                Text(item.title)
            }
        }
    }
    .onAppear() {
        model.getData(url: APIgetURL.Tap1)
    }
}
}

Also
struct model : Identifiable, Codable {

let id = UUID()
var color : String?
var details : String
}

class Api : ObservableObject{

@Published var models : [model] = []

func getData (url : String) {

    guard let url = URL(string: url) else { return }
    var request = URLRequest(url: url)
    let token = "38|Xxxx"

    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")

    URLSession.shared.dataTask(with: request) { data, responce, err in

        guard let data = data else { return }

        do {
            let dataModel = try JSONDecoder().decode([model].self, from: data)

            DispatchQueue.main.async {
                self.models = dataModel

        } catch {
            print("error: ", error)
        }
    }
resume()
    }
}


text:
Q: How do I write an MVC 1 app with MVC 2? I went to http://www.asp.net/mvc and the web installer offered me the option to install MVC 2, but not MVC 1.
I thought MVC 2 was still in beta? Either way, I need to write an MVC 1 app. In visual studio, my only choice is either ASP.NET Web Application or ASP.NET MVC 2 Web Application.
Can anyone advise?

A: You actually don't have to remove MVC 2.  You can have v1 and v2 installed side-by-side with no issues.

A: Remove MVC2 and download and install MVC 1 from here


text:
Q: How to avoid sharing session in different browser in ASP.NET MVC We are using session in our ASP.NET MVC application. Our config setting is as below
<sessionState cookieless="true" regenerateExpiredSessionId="true" timeout="20"/>

It generates url as:
http://localhost:34343/(S(ypr1jdz2lk5ysiqearcrbgty))/Dashboard

Scenario we want to achieve is: if we login to application in Chrome and open new tab of chrome then user should be logged. This is working fine.
But if user opens up new Chrome window or any other browser's window and tried to access above dashboard url, user should redirect to login page again, which is not happening now.
We believe this is because of the session is shared between all the browsers.
The application is stable and we don't want to change any config setting for this.
Is there any way or workaround by which we can avoid session sharing in another browser window or another browser?
In-short, we want to achieve same behavior how Gmail works, it asks for login if copy and paste inbox's url in new browser window or in new browser.


text:
Q: Why 'excedances' of permutations? For a permutation $\pi=\pi_1\pi_2\cdots\pi_n$ written in one-line notation, an index $i$ for which $\pi_i > i$ is usually called an 'excedance.' To me, this seems like a mispelling of what should be 'exceedance': many dictionaries list 'exceedance' as a valid word, but none I can find consider 'excedance' a correct spelling of any word. Also, as far as I know, 'excedance' is pronounced like 'exceedance' (that is, ex-ceed-ance). But, while both 'excedance' and 'exceedance' are to some extent used for this permutation concept, it seems that 'excedance' is much more common.
Question: Does anyone know the origin of the spelling 'excedance' for this permutation concept? Is it an error which has become standard?

A: Mea culpa. Comtet used the term excédence. When writing EC1 I needed an English term for this concept. For some reason I didn't like the word exceedance. I thought it looked better without the double e, analogous to proceed and procedure. Thus I made up the word excedance.


text:
Q: Using firebase with WatchKit I am attempting to use the firebase database in my watchKit app. I have developed this feature on my iPhone application but have found it difficult to do the same on my Watch app. When I attempted to import firebase into the VC class in watch app, it is creating an error no such module 'firebase'.
Is it possible to use firebase inside a watch app?

A: Sadly there is no Firebase support for watchOS2 and watchOS3 due to the fact that there's no support for CFNetwork in these versions of watchOS and Firebase is highly dependent on this framework. Source (thanks for the link @FrankvanPuffelen in comments).
You have two alternatives:

*

*Use the Firebase REST API directly from your watch app.

*Handle all Firebase communication from the iPhone app and use the WatchConnectivity framework to send the relevant changes to your watch app.

Depending on your exact use case, you could choose any of the two. The main advantages/disadvantages of these two are that the WatchConnectivity framework is quite limited as in when it can be used. Both of your apps needs to be running at least in the background for the WatchConenctivity framework to work. On the other hand, if you choose to use the REST API, you don't need the watch app to communicate with the iPhone counterpart, the watch app can directly get the Firebase data using network requests. However, in this scenario, the network usage will be bigger, since you will need to essentially fetch the same information both for the iPhone and watch apps.
Update for watchOS 6:
Firebase Messaging has been released with watchOS support, however, the Realtime Database along with other Firebase SDKs are still not supported. You can track the progress of them in this GitHub issue, which also contains links to the specific feature request issues for the other SDKs.

A: Firebase v7.9.0 added WatchOS support for realtime database.
https://firebase.google.com/support/release-notes/ios#realtime-database


text:
Q: Translation and Rotation vectors from view matrix (and back) Question
I have a view matrix of my camera (as 4x4 matrix) and I'd like to extract rotation and translation vectors from it, and back (from rot and transl vectors to view matrix).
I have found some forumals for doing this but they does not work.
How can I do that?
Background
For an augmented reality application I compute the view matrix from the distortion parameters and solvePnP. The method works: I find some points in the image plane (by clicking them) and, knowing the points in the real world, I can estimate the camera position.
The clicking procedure has some errors (click are not exact), so I'd like to refine the camera position by manually modify the translation and rotation vectors.
So I'm looking for a way to have vectors from matrix, and then go back, from vectors to matrix.
Tests
What I'm doing till now is:
void matrix2vector(cv::Mat n) { // n is the pose matrix
    this->position[0] = n.at<float>(3);
    this->position[1] = n.at<float>(7);
    this->position[2] = n.at<float>(11);

    float rx, ry, rz;
    rx = atan2(n.at<float>(9), n.at<float>(10));
    ry = atan2(-n.at<float>(8),
               sqrt( n.at<float>(9)*n.at<float>(9) + n.at<float>(10)*n.at<float>(10) ));
    rz = atan2(n.at<float>(4), n.at<float>(0));
    this->angle[0] = rx * RAD2DEG;
    this->angle[1] = ry * RAD2DEG;
    this->angle[2] = rz * RAD2DEG;
}

void vector2matrix() {
    _viewMatrix =  cv::Mat::eye(4, 4, CV_32F);
    rotateX(_viewMatrix, _viewMatrix, -angle[0]);
    rotateY(_viewMatrix, _viewMatrix, -angle[1]);
    rotateZ(_viewMatrix, _viewMatrix, -angle[2]);
    _viewMatrix.at<float>(3) = position[0];
    _viewMatrix.at<float>(7) = position[1];
    _viewMatrix.at<float>(11) = position[2];
}

where the rotations methods are:
inline
void rotateX(cv::Mat &src, cv::Mat &dst, float angleDegree) {
    dst = src.clone();

    float c = cosf(angleDegree * DEG2RAD);
    float s = sinf(angleDegree * DEG2RAD);
    float m4 = src.at<float>(4),
          m5 = src.at<float>(5),
          m6 = src.at<float>(6),
          m7 = src.at<float>(7),
          m8 = src.at<float>(8),
          m9 = src.at<float>(9),
          m10= src.at<float>(10),
          m11= src.at<float>(11);

    dst.at<float>(4) = m4 * c + m8 *-s;
    dst.at<float>(5) = m5 * c + m9 *-s;
    dst.at<float>(6) = m6 * c + m10*-s;
    dst.at<float>(7) = m7 * c + m11*-s;
    dst.at<float>(8) = m4 * s + m8 * c;
    dst.at<float>(9) = m5 * s + m9 * c;
    dst.at<float>(10)= m6 * s + m10* c;
    dst.at<float>(11)= m7 * s + m11* c;
}

inline
void rotateY(cv::Mat &src, cv::Mat &dst, float angleDegree)
{
    float c = cosf(angleDegree * DEG2RAD);
    float s = sinf(angleDegree * DEG2RAD);
    float m0 = src.at<float>(0),
          m1 = src.at<float>(1),
          m2 = src.at<float>(2),
          m3 = src.at<float>(3),
          m8 = src.at<float>(8),
          m9 = src.at<float>(9),
          m10= src.at<float>(10),
          m11= src.at<float>(11);

    dst.at<float>(0) = m0 * c + m8 * s;
    dst.at<float>(1) = m1 * c + m9 * s;
    dst.at<float>(2) = m2 * c + m10* s;
    dst.at<float>(3) = m3 * c + m11* s;
    dst.at<float>(8) = m0 *-s + m8 * c;
    dst.at<float>(9) = m1 *-s + m9 * c;
    dst.at<float>(10)= m2 *-s + m10* c;
    dst.at<float>(11)= m3 *-s + m11* c;
}

inline
void rotateZ(cv::Mat &src, cv::Mat &dst, float angleDegree)
{
    float c = cosf(angleDegree * DEG2RAD);
    float s = sinf(angleDegree * DEG2RAD);
    float m0 = src.at<float>(0),
          m1 = src.at<float>(1),
          m2 = src.at<float>(2),
          m3 = src.at<float>(3),
          m4 = src.at<float>(4),
          m5 = src.at<float>(5),
          m6 = src.at<float>(6),
          m7 = src.at<float>(7);

    dst.at<float>(0) = m0 * c + m4 *-s;
    dst.at<float>(1) = m1 * c + m5 *-s;
    dst.at<float>(2) = m2 * c + m6 *-s;
    dst.at<float>(3) = m3 * c + m7 *-s;
    dst.at<float>(4) = m0 * s + m4 * c;
    dst.at<float>(5) = m1 * s + m5 * c;
    dst.at<float>(6) = m2 * s + m6 * c;
    dst.at<float>(7) = m3 * s + m7 * c;
}

A: The answer is dependent upon whether you're using column or row vectors to transform vectors by matrices. Assuming you have a matrix M and a vector v and you transform it by v' = Mv, you're using column vectors. If instead you have v' = vM you're using row vectors.
To find the translation, simply check where the vector [0 0 0 1] ends up. If you're using column vectors, you'll find that the last column of your matrix is where the translation lies. The first three elements of that last column will be the translation vector (x,y,z). Similarly, in a row vector you'll find that the last row of your matrix is where the translation lies. The first three elements of the last row of your matrix will be the translation vector (x,y,z).
For rotation, try multiplying your matrix by the vector [1 0 0 0]. This will tell you where the "x axis" maps to. Similarly for [0 1 0 0] (y axis) and [0 0 1 0] (z axis). Whether you're using column or row vectors, the relevant entries are the 3x3 sub-matrix in the top left of your 4x4 matrix. The only thing that changes between row and column vectors is whether or not the mapped axis is a column vector or row vector in the submatrix.
Hope that helps.


text:
Q: Python: Options for Freezing WITHOUT Dependencies? What options exist for shipping Python 3 code in a self-executing bytecode form but without the overhead of all dependencies (requiring Python to be installed on the user's computer)? I'm currently using PyInstaller to create all-in-one packages, but they're so large it would be useful to also offer a version that doesn't contain Python for those that already have it, which would presumably be orders of magnitude smaller.

A: Possibly a docker container might help. Docker is an open source shipping platform. Make a docker image out of your code and ship the image. On the other side, you just need to run the image. Of course, you need to install Docker to pack and to run the image. you can find more details about docker here.


text:
Q: String safe functions vs security enhanced CRT Are the StringCch* functions considered safer then the safe versions of the CRT string functions.
Is StringCchCatW safer then wcscat_s? Or StringCchCopyW vs wcscpy_s?

A: This is tagged C++, so you should not use either of them, but std::wstring instead.

A: It really depends on how you are dealing with strings in your application.
With the Windows SDK many people end up mixing a lot of c-runtime, and windows api calls - because the windows api is a C API layered on top of the c-runtime it is difficult for windows programmers to know they are doing this, and why it is (potentially) wrong.
But, basically, at some point of your application development, you really should choose where you are going to get your basic data types from. Especially in the case of string data as the localization apis, that effect sorting, collation and so on are quite different.
You can choose to use the c-runtimes string support. This involves using strings that are typed as "const char*" or wchar_t. Microsoft's c-runtime specifically (it is possible to develop windows applications with GCC, so this distinction can be important if you want to write code that compiles on multiple compilers) offers a set of functions in , based off storing text data in _TCHAR's, and using the _MBCS and _UNICODE macros to switch the functions from single character, to multi byte character to wide character supporting versions.
If you choose to use the c-runtimes string abstractions, then using the c-runtimes "safe" string routnes would make the most sense.
Alternatively, Windows GUI applications frequently choose to use the windows SDK data types: CHAR, INT, WCHAR, TCHAR, DWORD etc. Strings, would be represented by LPCTSTR variables usually, and in this case, continuing to use the windows abstractions, SafeStringCch etc. make the most sense.
Really, the worst thing you can do in a program is keep on bouncing between using windows API calls, and c-runtime calls, as they have different rules sometimes for how they deal with edge cases... and this can lead to some very hard to spot bugs.


text:
Q: ORM performance: is greenDAO faster than ORMLite? I've been using ORMLite in my application and I was considering whether to move to greenDAO.
Performance is a huge part of that decision, and greenDAO's Features page says:

For the same given entity, greenDAO inserts and updates entities over
  2 times faster, and loads entities 4.5 times faster for loading
  entities than ORMLite.
  ...
  (Figures and chart updated 10-23-2011)

I thought ORMLite's config file generation step should remove the need for reflection at runtime.
The ORMLite changlog suggests that the greenDAO benchmark was done after the config file feature was released, but the greenDAO features page doesn't explicitly say if a static config file was generated for the test.

4.26: 9/26/2011 (svn r1978)
   * ANDROID: Added field configuration utility to avoid Dao creation performance problems with annotations.

There have also been ORMLite performance fixes since then, e.g.

4.40: 4/16/2012 (svn r2516)
   * ANDROID: Big performance bug fix when creating DAOs. Foreign fields always used reflection instead of table configs.

Can anybody confirm if there is still a big performance difference between greenDAO and ORMLite?  Thanks!

A: We've just published a Github project that we used to compare the performance of ORMLite and GreenDao to raw SQLite:
https://github.com/daj/android-orm-benchmark
The project also allows you to compare the performance of an in-memory database to an on disk one.
The headline results are:
GreenDao is much faster than ORMLite.  It is roughly:

*

*3X faster at writing large numbers of objects.

*50% faster at reading in all 10000 entries in a single table.

*2X to 3X faster at an indexed read of a single row (though both were very fast).

*15X faster at doing a LIKE search for 100 records in a 10000 entry table.

The project contains both a naive raw SQLite benchmark, and an optimized SQLite benchmark.
GreenDao vs unoptimized raw SQLite

*

*GreenDao is 2X faster for the write benchmark.

*GreenDao is 25% slower for the read benchmark.

GreenDao vs optimized raw SQLite

*

*GreenDao is 50% slower for the read and write benchmarks.

For detailed results please see the Github repository above.
Of course we may have bugs in our benchmarking code...if you find any please fork, fix and submit a pull request!  :-)
Disclaimer: make sure you do your own research before choosing GreenDao over ORMLite.


text:
Q: Google BigQuery SQL: working with an array? I'm a newbie at SQL and Google BigQuery.
I'm trying to run the following query to get a list of names and counts, however I see that I am getting an array error and don't know how to fix it. Any help appreciated.
ERROR MESSAGE:
Cannot access field harmonized on a value with type ARRAY at [5:27]
#standardSQL
-- Applications_Per_Assignee
SELECT assignee_harmonized.name AS Assignee_Name, COUNT(*) AS Number_of_Patent_Apps
FROM (
SELECT ANY_VALUE(assignee.harmonized.name) AS Assignee_Name
FROM `patents-public-data.patents.publications` AS patentsdb
GROUP BY Number_of_Patent_Apps
)
GROUP BY assignee_harmonized.name
ORDER BY Number_of_Patent_Apps DESC;

A: Looks like there are a few things wrong with your query.

*

*assignee is a string, I think you want to look at assignee_harmonized.name

*You will want to UNNEST() assignee_harmonized

*ANY_VALUE() only selects a random value, which does not sound like what you want

*You have a GROUP BY in your inner select, which will not give you the results you want

*You don't really need a subquery for this type of query.

#standardSQL
SELECT ah.name AS Assignee_Name, COUNT(*) AS Number_of_Patent_Apps
FROM `patents-public-data.patents.publications` AS patentsdb
LEFT JOIN UNNEST(assignee_harmonized) ah
GROUP BY 1
ORDER BY 2 DESC

A: Below is for BigQuery Standard SQL
#standardSQL
SELECT
  ah.name AS Assignee_Name,
  COUNT(*) AS Number_of_Patent_Apps
FROM `patents-public-data.patents.publications`,
UNNEST(assignee_harmonized) ah
GROUP BY Assignee_Name
HAVING Number_of_Patent_Apps < 1000
ORDER BY Number_of_Patent_Apps DESC
-- LIMIT 10

with output
Row Assignee_Name                   Number_of_Patent_Apps
1   SAMSUNG ELECTRONICS CO LTD      600678
2   CANON KK                        579731
3   MATSUSHITA ELECTRIC IND CO LTD  560644
4   HITACHI LTD                     531286
5   SIEMENS AG                      486276
6   MITSUBISHI ELECTRIC CORP        461673
7   IBM                             438822
8   SONY CORP                       438039
9   FUJITSU LTD                     384270
10  NEC CORP                        357193


text:
Q: Attach debug to process Unity doesn't work I created new 3d unity project, then in asserts I created c# script if I click on it twice Visual Studio 2017 is opened. Then I would like to make a debug, so I set debug point and click in Unity on play button and nothing happes.

There is no attach button or something like this.
What am I doing wrong?

A: This happens randomly to me as well. The way I fix it it to go Unity->Edit Menu->Preferences->External Tools, and set the External Script Editor to something else, and then revert it back to Visual Studio.
If that fails, just underneath that dropdown there is a button Regenerate Project Files, which helps when your VS project files get messed up.
Also, upgrading to the latest version of Visual Studio and Unity Tools for VS could help.

A: My bad if I misunderstood this question, but all you have to do for unity to update your scripts for your game is ctrl + s, this will let unity know you made changes to the script and it will apply those changes.


text:
Q: Problema mostrando mi servlet tengo un problema tratando de mostrar el resultado del servlet. Lo que estoy tratando de hacer es agarrar ciertos caracteres que se introducen al formulario, y estos que me despliegue el resultado. Mi problema es cuando quiero desplegar el resultado, solo me aparece una pagina en blanco, que estoy haciendo mal?
O si tambien tengo errores en como capturar los datos indiquenme por favor, muchas gracias a todos por responder.
Les dejo mi codigo y mi servlet:
Pagina JSP

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>PAGINA DE EVENTOS</title>

Generador de RFC

Ingresa tus datos:

        <form method="post" action="rfc">

            Nombre:<input type="text" name="textName" id="idNombre">

            Primer Apellido:<input type="text" name="text1Apellido" id="idApellido">

            Segundo Apellido:<input type="text" name="text2Apellido" id="idApellido2">

            Año:<input type="text" name="textAño" id="idAño">

            Mes:<input type="text" name="textMes" id="idMes">

            Dia:<input type="text" name="textDia" id="idDia">

            <input type="submit" name="btnSubmit" value="Enviar Datos" />

            </form>

Servlet rfc
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

try(    PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
            out.println("");
            out.println("");
            out.println("<title>Generador de RFC:</title>");
            out.println("");
            out.println("");

String Nombre = request.getParameter("textName");
        String Apellido = request.getParameter("text1Apellido");
        String Apellido2 = request.getParameter("text2Apellido");
        String Año = request.getParameter("textAño");
        String Mes = request.getParameter("textMes");
        String Dia = request.getParameter("textDia");

String rfc;

rfc = Apellido.trim().substring(0,2);
rfc = rfc.concat(Apellido2.trim().substring(0,1));
rfc = rfc.concat(Nombre.trim().substring(0,1));
rfc = rfc.concat(Año.substring(2,4));
rfc = rfc.concat(Mes);
rfc = rfc.concat(Dia);

            out.println("
Tu Rfc es: "+rfc.toLowerCase()+"
");
            out.println("");
            out.println("");

}
}
}

Mi web.xml
<servlet-mapping>
        <servlet-name>rfc</servlet-name>
        <url-pattern>/rfc</url-pattern>
    </servlet-mapping>

A: He resuelto mi problema, en vez de pasarla por el método doPost fue por processRequest, ademas de añadir web.xml.


text:
Q: Android checkbox cannot use onclick when I set enable=false in xml chkSend.setOnClickListener(sendClickListener);

private OnClickListener sendClickListener = new OnClickListener() {
    @Override
    public void onClick(View v) {

    }
};

I have to set the checkbox disabled,but I need to user the onclick,how can I do?
I found someone said that can work,But I don't know how to use it?
public class BtCheckBox extends CheckBox {
    public BtCheckBox(Context context) {
        super(context);
    }

    public BtCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BtCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean performClick() {
        return callOnClick();
    }
}

A: This is impossible because when you disable the checkbox, this means it is not clickable.

A: If you want to make your checkBox Unchecked on some condition, you can check that on setOnCheckedChangeListener();
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
               @Override
               public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                     if(isChecked)
                     {
                        checkBox.setChecked(false);
                     }
               }
           });


text:
Q: Calculus Question: $\int_0^1\frac{(x-x^2)^4}{1+x^2}dx$ I have no idea how to find this integral:
$$\int_0^1\frac{(x-x^2)^4}{1+x^2}\ dx\ ?$$
Any help would be appreciated. Thanks in advance.

A: HINT :
$$
\begin{align}
\int_0^1\frac{(x-x^2)^4}{1+x^2}\ dx&=\int_0^1\frac{x^4-4x^5+6x^6-4x^7+x^8}{1+x^2}\ dx\tag1\\
&=\int_0^1\left(x^6-4x^5+5x^4-4x^2+4-\frac4{1+x^2}\right)\ dx.\tag2\\
\end{align}
$$
See binomial theorem for $(1)$ and polynomial long division for $(2)$. Also
$$
\begin{align}
\int_0^1\frac1{1+x^2}\ dx=\frac\pi4
\end{align}
$$
by letting $x=\tan\theta$. The answer is $\ \color{blue}{\dfrac{22}7-\pi}$.


text:
Q: Does middleman s3_sync ignore .txt files by default? It looks like middleman s3_sync doesn't upload my robots.txt. Is there a way to enable it to always upload a specific file?

A: It depends on the version of Middleman S3_Sync that you are using.
Versions 3.0.x build the list of files based on the content of the build directory. In that case, copying the file into the build directory will include it in the sync.
Versions 3.3.x moved to the Middleman sitemap in preparation of MM 4. It currently only syncs the files that Middleman is aware of. Copying a file into the build directory doesn't make S3_Sync aware of it.
In the second case, there are two options available.
The first one is to move robot.txt to the source directory. This will include it in the sitemap and it will be sync'ed.
The second is to open an issue (or even better, a pull request) that will ask for the ability to include files that originate from outside of the source directory.
It would help to get the version of Middleman and s3_sync that you are using.


text:
Q: Expression Blend 4 Patches Where can I get the list of patches/service packs for Expression Blend 4?

A: Service Pack 1 for Expression Blend 4 is currently out.
http://www.microsoft.com/expression/service-packs/Blend.aspx


text:
Q: Why this recursive function doesn't break? Short version:
# -*- coding: UTF-8 -*-

import re
import itertools

targ = ['\t- Task 09', '\tThis is a comment', '\t\t- Subtask 9.02', '\t\t\t- Subsubtask 9.03', '\t\t\t\t- Subsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.02', '\t\t\t\t\t- Subsubsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.03 @done', '\t\t\t- Subsubtask 9.04', '\t\t\t\t- Subsubsubtask 9.19 @done']

def DoneChild2Parent(l):
    tasks = [(k,v) for k,v in enumerate(l) if re.search('\t+-\s.*',v)]
    for x,y in tasks:
        if (x,y) == tasks[len(tasks[1:])]:
            print (x,y), '==', tasks[len(tasks[1:])]
            return l #Also tried break here.
        elif re.search('(?!.*@done)\t*-\s.*', y):
            next_task = tasks[tasks.index((x,y))+1]
            if next_task[1].count('\t') > y.count('\t'):
                subtasks = list(itertools.takewhile(lambda t: t.count('\t') > y.count('\t'), [z for w,z in tasks[tasks.index(next_task):]]))
                if all('@done' in subtask for subtask in subtasks):
                    l[x]+=' @done'
                    DoneChild2Parent(l)
    # return l #when using break above
print DoneChild2Parent(targ)

This function should return when matching the latest element of the list. Right now it just keeps looping. It identifies when (x,y) == tasks[len(tasks[1:])]:, but neither return nor break take me out of the loop.

After Comments:
This is a more reduced version of the code. I reduced the argument to as small as possible while keeping the problem:
# -*- coding: UTF-8 -*-

import re

targ = ['\t- Task 09', '\tThis is a comment', '\t\t- Subtask 9.02', '\t\t\t- Subsubtask 9.03', '\t\t\t\t- Subsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.02', '\t\t\t\t\t- Subsubsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.03 @done', '\t\t\t- Subsubtask 9.04', '\t\t\t\t- Subsubsubtask 9.19 @done']

def DoneChild2Parent(l):
    tasks = iter([(x,y) for x,y in enumerate(l) if re.search('\t+-\s.*',y)])

    for k in tasks:
        if re.search('(?!.*@done)\t*-\s.*', k[1]):
            nt = tasks.next()
            if nt[1].count('\t') > k[1].count('\t'):
                subtasks = [subtask for subtask in l[k[0]:] if subtask.count('\t') > k[1].count('\t') and re.search('\t+-\s.*',subtask) ]
                if all('@done' in subtask for subtask in subtasks):
                    l[k[0]]+=' @done'
                    DoneChild2Parent(l)
    return l

print DoneChild2Parent(targ)

Concerning @abarnert questions: I need the "next task" to compare the amount of '\t' between it and the task in question. If the next task has more '\t' than task, means next task is a subtask of task. If all children of task are marked with "@done" it should also mark task. I filter the whole input to avoid comments (according to the syntax), which would break the code. I also keep the index from the original list to add the '@done' tag afterwards. I hope this code runs smoother to all of you. Thank you for the kindness of passing by and reading this wall of text (:

A different version of the code with the same problem:
# -*- coding: UTF-8 -*-

import re
import itertools

targ = ['\t- Task 09', '\tThis is a comment', '\t\t- Subtask 9.02', '\t\t\t- Subsubtask 9.03', '\t\t\t\t- Subsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.02', '\t\t\t\t\t- Subsubsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.03 @done', '\t\t\t- Subsubtask 9.04', '\t\t\t\t- Subsubsubtask 9.19 @done']

def DoneChild2Parent(l):
    tasks = [(k,v) for k,v in enumerate(l) if re.search('\t+-\s.*',v)]
    for x,y in tasks[:-1]:
        if re.search('(?!.*@done)\t*-\s.*', y):
            next_task = tasks[tasks.index((x,y))+1]
            if next_task[1].count('\t') > y.count('\t'):
                subtasks = list(itertools.takewhile(lambda t: t.count('\t') > y.count('\t'), [z for w,z in tasks[tasks.index(next_task):]]))
                if all('@done' in subtask for subtask in subtasks):
                    l[x]+=' @done'
                    DoneChild2Parent(l)
    return l

print DoneChild2Parent(targ)

Really long explanation with original code:
Apologies for the open title and above all for asking you to identify a problem instead of only suggesting a solution to an issue already found. The code below is the reduced version of the code I'm using, I removed a few useless functions, but the outcome is just the same. The printed result on the console will guide us through my problem:
# -*- coding: UTF-8 -*-

import re
import itertools

targ = '\t- Task 09\n\tThis is a comment\n\t\t- Subtask 9.01 @done\n\t\tThis is a subtask comment\n\t\t- Subtask 9.02\n\t\tAnother comment\n\t\t\t- Subsubtask 9.01 @done\n\t\t\t- Subsubtask 9.02 @done\n\t\t\tWhy so many comments?\n\t\t\t- Subsubtask 9.03\n\t\t\t\t- Subsubsubtask 9.01 @done\n\t\t\t\tJust another comment to break your code\n\t\t\t\t- Subsubsubtask 9.02\n\t\t\t\tBreak, break, break\n\t\t\t\t\t- Subsubsubsubtask 9.01 @done\n\t\t\t\t\tThis is the last comment, I promise\n\t\t\t\t- Subsubsubtask 9.03 @done\n\t\t\t\tI lied.\n\t\t\t- This is the task of interest\n\t\t\t\t- Subsubsubtask 9.03 @done\n\t\t\t\tI love lying\n\t\t\t- Subsubtask 9.05 @done\n\t\t- Subtask 9.03 @done\n\t\tOk, this is truly the last comment.\n\t\tNah.'

regex =  re.split('\n(?=^\t-\s)', targ, 0, re.M)

c = 0
def DoneChild2Parent(l):
    global c
    c+=1
    tasks = iter([(x,y) for x,y in enumerate(l) if re.search('\t+-\s.*',y)])

    print "=================\n==:: ROUND %s ::==\n================="%(c)

    for k in tasks:
        print "* Step 1: %s => This is the task being checked:" %(str(k))
        if re.search('(?!.*@done)\t*-\s.*', k[1]):
            print "* Step 2: %s => Was not done so we check the next task/subtasks" %(str(k))
            nt = tasks.next()
            if nt[1].count('\t') > k[1].count('\t'):
                print "* Step 3: %s => is the next subtask" %(str(nt))
                subtasks = [subtask for subtask in l[k[0]:] if subtask.count('\t') > k[1].count('\t') and re.search('\t+-\s.*',subtask) ]
                print "* Length of subtasks is",len(subtasks)
                print "* Step 4: Subtasks for %s\n" %(k[0]),subtasks
                if all('@done' in subtask for subtask in subtasks):
                    print "\n* Step 5: Adding @done to %s at index %s" %(k[1].strip(), k[0])
                    print "Before: ",l[k[0]]
                    l[k[0]]+=' @done'
                    print "After: ",l[k[0]],"\n---------------------\n"
                    DoneChild2Parent(l)
                else:
                    print "\n* Step 5: Not everything is done yet\n---------------------\n"

    return l

for task in regex:
    itask = task.split('\n')
    DoneChild2Parent(itask)

The string is a task list using the syntax from TaskPaper, a task manager for Mac that uses plain text files. A task starts with '- ', a project ends with ':'(absent in this example), a comment is neither. Indentation defines hierarchy between tasks and comments. When a task is marked as done, it gains a tag '@done' (every tag starts with @). For this example I'm using a single, multi-layered task. The regex and the for-loop in the end are there in case of multiple main-tasks (when the project is the direct parent).
The function loops through every task from the list, checks if it is undone and contains subtasks. Afterwards, it collects all its subtasks and checks if they're all marked as @done, if so, it marks the parent-task as @done as well.
When you run this script, you'll find out that the purpose works, but the loop proceeds for more than intended and takes a weird direction. I named the task where the problem occurs as 'This is the task of interest' so you can easily spot it on print.
The task of interest is correctly marked as @done in the Round 3 of the script. The script continues to loop until it marks the main-task in Round 5, meaning that every subtask is marked as @done (the list was built with that in mind). Now, please, take a good look at Round 6. It was supposed to be the latest loop, where the function would check that there's nothing left to do and return the value, however, as you may notice by the following lines:
* Step 1: (22, '\t\t- Subtask 9.03 @done') => This is the task being checked:
* Step 1: (4, '\t\t- Subtask 9.02 @done') => This is the task being checked:

It checks the last task and loops back to the start. I don't know why it loops back at the second task. This behaviour repeats and the task that begins the re-loop is always different. I'd like to know why that happens. But worst, you'll notice that at a given moment the script finds the 'Task of interest', the one we marked as @done before, undone and operates the loop again. The result is that the 'Task of interest' ends up with 3 @done tags attached to it:
After:              - This is the task of interest @done @done @done

The outcome I'm looking for is Round 8 at Round 6. Thank you for your attention and I'm sorry for such a long text.

A: I'd start by asking exactly what you hope this regexp matches:
if re.search('(?!.*@done)\t*-\s.*', k[1]):

Explain your intent in words?  Are you, for example, surprised that it matches this string:
"abc @done- def"

?  Do you realize that the trailing .* in that regexp serves no purpose (the regexp matches exactly the same strings with and without it)?
I don't know whether it's related to your problem ;-), but I've seen a lot of regexps in my life, and I can't guess what you hoped this one would do.  My best guess is that you hope it matches \t*-\s not immediately preceded by @done - but in that case you want a negative look*behind* assertion instead.

A: Thank you for your help. This StackOverflow thread helped me a lot. I just had to place a break in the right place:
# -*- coding: UTF-8 -*-

import re
import itertools

targ = ['\t- Task 09', '\tThis is a comment', '\t\t- Subtask 9.02', '\t\t\t- Subsubtask 9.03', '\t\t\t\t- Subsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.02', '\t\t\t\t\t- Subsubsubsubtask 9.01 @done', '\t\t\t\t- Subsubsubtask 9.03 @done', '\t\t\t- Subsubtask 9.04', '\t\t\t\t- Subsubsubtask 9.19 @done']

def DoneChild2Parent(l):
    tasks = [(k,v) for k,v in enumerate(l) if re.search('\t+-\s.*',v)]
    for x,y in tasks:
        if re.search('(?!.*@done)\t*-\s.*', y):
            next_task = tasks[tasks.index((x,y))+1]
            if next_task[1].count('\t') > y.count('\t'):
                subtasks = list(itertools.takewhile(lambda t: t.count('\t') > y.count('\t'), [z for w,z in tasks[tasks.index(next_task):]]))
                if all('@done' in subtask for subtask in subtasks):
                    l[x]+=' @done'
                    DoneChild2Parent(l)
                    break
    return l

print DoneChild2Parent(targ)

Why this happened? Simple, the loop would call the function, but it wouldn't end. So when the last-loop called no function and concluded, it would return the result to the previous function and proceed with the loop, which would find other issues already fixed in previous tasks and call the function again, generating the mess you saw (:


text:
Q: How to fix Code Runner ReferenceError: function is not defined issue? I've already installed node.js and i've done all the path stuff, but still Code Runner isn't working as expected, this is the output after running the code:
console.log(sum(5, 2))
^
ReferenceError: sum is not defined


text:
Q: read nested json and convert it to tidy data I am trying to convert a json to a tibble that follow Tidy Data principles.
The website http://pv.servelelecciones.cl/ has some nice regional data. Because I cannot provide a direct link to "Aysen region" as the url doesn't change, this is the data they are displaying:
|listapacto                          |partido  |votos|porcentaje|electo|
|------------------------------------|---------|-----|----------|------|
|H. SUMEMOS                          |         |365  |4,52%     |      |
|TODOS                               |         |113  |1,40%     |      |
|50. EDUARDO ROMO LAFOY              |IND-TODOS|69   |0,86%     |      |
|51. SARA MARTINEZ MONDELO           |IND-TODOS|44   |0,55%     |      |
|CIUDADANOS                          |         |252  |3,12%     |      |
|52. VICTOR MANUEL BORQUEZ FINCKE    |CIUD.    |53   |0,66%     |      |
|53. MARISOL LUSDEMIA PINILLA VEJAR  |CIUD.    |199  |2,47%     |      |
|K. COALICIÓN REGIONALISTA VERDE     |         |200  |2,48%     |      |
|DEMOCRACIA REGIONAL PATAGONICA      |         |200  |2,48%     |      |
|54. ELSON BORQUEZ YAÑEZ             |DRP      |59   |0,73%     |      |
|55. PEDRO ANTONIO VERGARA ROJAS     |DRP      |42   |0,52%     |      |
|56. JESSICA ANDREA TORRES BORQUEZ   |IND-DRP  |59   |0,73%     |      |
|57. TAMARA ANDREA ESPINOZA GUTIERREZ|DRP      |40   |0,50%     |      |
|N. LA FUERZA DE LA MAYORIA          |         |2.958|36,66%    |      |
|PARTIDO RADICAL SOCIALDEMOCRATA     |         |346  |4,29%     |      |
|58. JORGE CALDERON NUÑEZ            |PRSD     |346  |4,29%     |      |
|PARTIDO SOCIALISTA DE CHILE         |         |1.651|20,46%    |      |
|59. MARISOL MARTINEZ SANCHEZ        |PSCH     |1.651|20,46%    |      |
|PARTIDO COMUNISTA DE CHILE          |         |322  |3,99%     |      |
|60. ROXANA PEY TUMANOFF             |IND-PCCH |322  |3,99%     |      |
|PARTIDO POR LA DEMOCRACIA           |         |639  |7,92%     |      |
|61. RENE OSVALDO ALINCO BUSTOS      |IND-PPD  |639  |7,92%     |*     |
|O. CONVERGENCIA DEMOCRATICA         |         |2.297|28,47%    |      |
|PARTIDO DEMOCRATA CRISTIANO         |         |2.297|28,47%    |      |
|62. MIGUEL ANGEL CALISTO AGUILA     |PDC      |1.882|23,32%    |*     |
|63. CARMEN GLORIA MARTINEZ CARDENAS |PDC      |224  |2,78%     |      |
|64. RENE ANSELMO LEGUE CARDENAS     |PDC      |191  |2,37%     |      |
|P. CHILE VAMOS                      |         |1.963|24,33%    |      |
|UNION DEMOCRATA INDEPENDIENTE       |         |605  |7,50%     |      |
|65. NESTOR MERA MUÑOZ               |UDI      |605  |7,50%     |      |
|PARTIDO REGIONALISTA INDEPENDIENTE  |         |132  |1,64%     |      |
|66. PATRICIO HENRIQUEZ BARRIENTOS   |PRI      |132  |1,64%     |      |
|EVOLUCION POLITICA                  |         |365  |4,52%     |      |
|67. GEOCONDA NAVARRETE ARRATIA      |EVOP.    |365  |4,52%     |      |
|RENOVACION NACIONAL                 |         |861  |10,67%    |      |
|68. ARACELY LEUQUEN URIBE           |RN       |861  |10,67%    |*     |
|CANDIDATURA INDEPENDIENTE           |         |286  |3,54%     |      |
|69. CECILIO AGUILAR GALINDO         |IND      |286  |3,54%     |      |

I'd like to read the json data that feeds their website to obtain a tibble like the table above, and from that move to a tidy structure.
If I just try to read the data directly:
require(data.table)
require(jsonlite)
require(dplyr)

x <- fromJSON("http://www.servelelecciones.cl/data/elecciones_diputados/computo/comunas/114501.json")

y <- as_tibble(x$data)

Then I get some locked information in the last column:
> y
# A tibble: 6 x 7
  a                               b     c     d      e     f     sd
* <chr>                           <lgl> <chr> <chr>  <chr> <chr> <list>
1 H. SUMEMOS                      NA    365   4,52%  4     ""    <data.frame [2 × 7]>
2 K. COALICIÓN REGIONALISTA VERDE NA    200   2,48%  4     ""    <data.frame [1 × 7]>
3 N. LA FUERZA DE LA MAYORIA      NA    2.958 36,66% 4     ""    <data.frame [4 × 7]>
4 O. CONVERGENCIA DEMOCRATICA     NA    2.297 28,47% 3     ""    <data.frame [1 × 7]>
5 P. CHILE VAMOS                  NA    1.963 24,33% 4     ""    <data.frame [4 × 7]>
6 CANDIDATURA INDEPENDIENTE       NA    286   3,54%  NA    NA    <data.frame [1 × 7]>

Of course I tried

*

*How to read nested JSON structure in R?

*Read Json file into a data.frame without nested lists
Any help is highly welcome.

A: One possibility, instead of writing a funcion, is to use tidyr and unnest as many times as required.
In my case:
require(data.table)
require(jsonlite)
require(dplyr)
require(tidyr)

x <- fromJSON("http://www.servelelecciones.cl/data/elecciones_diputados/computo/comunas/114501.json")

y <- as_tibble(x$data)

y1 <- y %>% filter(a == "CANDIDATURA INDEPENDIENTE")
y2 <- y %>% filter(a != "CANDIDATURA INDEPENDIENTE") %>% unnest(sd)


text:
Q: How to size flex-items without percentages? I am trying to create a flexbox-based grid, with the content being 2/3 width  and the side bar the remaining 1/3.
I have used percentages for the width in each col, which unfortunately are giving me errors in the navigation and header.
Why is this? And how can I make this without using percentages, to avoid the errors?
CodePen demo

@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700);
*,
*:before,
*:after {
  box-sizing: border-box;
}

html body {
  margin: 0;
  padding: 0;
  font-family: 'Open Sans', sans-serif;
}

h1,
h2,
h3,
h4,
h5,
p,
a,
li,
ul {
  margin: 0;
  padding: 0;
}

/* centres content of website in a width of 950px */

.container {
  width: 80%;
  margin: 0 auto;
}

/* Header styling */

header {
  background: #66b3ff;
  /*   padding: 10px; */
}

/* Logo */

#logo h1 {
  font-weight: 300;
  margin-top: 30px;
}

#logo h1 span {
  font-weight: 600;
}

/* end of Logo */

/* Nav */

nav ul {
  margin: 0;
  padding: 0;
  display: flex;
  margin-top: 50px;
}

li {
  flex: 1;
  list-style: none;
}

a {
  text-decoration: none;
}

/* End of header styling */

/* Columns */

.col1,
.col2,
.col3,
.col4,
.col5,
.col6,
.col7,
.col8,
.col9,
.col10,
.col11,
.col12 {
  margin: 0 5px 0 5px;
}

.row {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}

.col1 {
  width: 8%;
}

.col2 {
  width: 16%;
}

.col3 {
  width: 25%;
}

.col4 {
  width: 33%;
}

.col5 {
  width: 41%;
}

.col6 {
  width: 50%;
}

.col7 {
  width: 58%;
}

.col8 {
  width: 66%;
}

.col9 {
  width: 75%;
}

.col10 {
  width: 83%;
}

.col11 {
  width: 91%;
}

.col12 {
  width: 100%;
}

BespokeDesignAgency

HOME

ABOUT

GALLERY

CONTACT

Main Website content here

Authentic truffaut put a bird on it tacos crucifix. Kale chips craft beer austin, organic small batch salvia squid. Readymade health goth put a bird on it, yr semiotics shabby chic williamsburg selfies man braid godard. DIY blog lomo selvage. Pabst
        echo park tacos, kinfolk chicharrones thundercats farm-to-table offal twee keffiyeh affogato irony helvetica banjo. Bicycle rights XOXO irony mumblecore tofu, keffiyeh kitsch retro plaid seitan street art. Chartreuse ennui helvetica 90's you probably
        haven't heard of them godard, DIY keffiyeh listicle 3 wolf moon mustache.

side bar here

footer content

A: Consider using the flex-grow property for sizing flex items. This property tells flex items what amount of free space in the container they should absorb.
Here are some examples of how flex-grow distributes space in a row:

.container:nth-child(1) > .box { flex-grow: 1;  background-color: lightgreen; }
.container:nth-child(1) > .box:last-child { background-color: lightpink; }
.container:nth-child(2) > .box:nth-child(1) { flex-grow: 3; background-color: aqua; }
.container:nth-child(2) > .box:nth-child(2) { flex-grow: 7; background-color: orange; }
.container:nth-child(2) > .box:nth-child(3) { flex-grow: 1;  background-color: orangered;}
.container:nth-child(3) > .box:nth-child(1) { flex-grow: 10; background-color: yellow; }
.container:nth-child(3) > .box:nth-child(2) { flex-grow: 5; background-color: lightgreen; }
.container:nth-child(3) > .box:nth-child(3) { flex-grow: 1; background-color: tan; }
.container:nth-child(4) > .box:nth-child(1) { flex-grow: 5; bacground-color: pink; }
.container:nth-child(4) > .box:nth-child(2) { flex-grow: 10; background-color: aqua; }
.container:nth-child(4) > .box:nth-child(3) { flex-grow: 25; background-color: tan; }
.container:nth-child(4) > .box:nth-child(4) { flex-grow: 50; background-color: tomato; }
.container:nth-child(4) > .box:nth-child(5) { flex-grow: 99; background-color: yellow; }

body {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.container {
    display: flex;
    width: 95%;
    padding: 5px;
    border: 1px solid #ccc;
    background-color: lightyellow;
}

.box {
    height: 50px;
    background-color: lightgreen;
    border: 1px solid #aaa;
    display: flex;
    justify-content: center;
    align-items: center;
}

flex-grow: 1

flex-grow: 1

flex-grow: 3

flex-grow: 7

flex-grow: 1

flex-grow: 10

flex-grow: 5

flex-grow: 1

flex-grow: 5

flex-grow: 10

flex-grow: 25

flex-grow: 50

flex-grow: 99

jsFiddle demo

Note that the flexbox spec recommends using flex-grow as part of the flex shorthand property.

7.2 Components of
  Flexibility
Authors are encouraged to control flexibility using the flex
  shorthand rather than with its longhand properties directly, as the
  shorthand correctly resets any unspecified components to accommodate
  common uses.

For a detailed description of how flex-grow works, see this post:

*

*flex-grow not sizing flex items as expected

When working with the flex property refer to the spec for a summary of common values.

*

*7.1.1. Common Values of flex

A: in the case of a flexbox, if you set flex:1; to childs, it will spray them evenly.
2 childs = 50% average including margin , bordeers ...
3 childs = 33% average ...
if you have 2 childs, and want 33% / 66% set : flex:1; to one and flex:2; to the other .or flex:33.33 and flex:66.66 if this seems clearer to you :)
examples:

.flex {
  display:flex;
}
div div {
  flex:1;
  padding:0.5em;
  border:solid;
  margin:5px;
}
.f2 {
  flex:2;
}


text:
Q: How to convert dict in list to dict in python? I have this list below
my_list =
[
    {
    "id": "841",
    "category": "category1",
    "nutrients": [
        {
        "name": "B12",
        "description": "good"
        },
        {
        "name": "A",
        "description": "eyes"
        }
    ]
    "status": "yes_survey"
    }
]

and I want this dictionary below
(I want to remove just outside [ ] sign...)
my_ dict =
   {
    "id": "841",
    "category": "category1",
    "nutrients": [
        {
        "name": "B12",
        "description": "good"
        },
        {
        "name": "A",
        "description": "eyes"
        }
    ]
    "status": "yes_survey"
    }

How can I do it? I tried dict() method but It doesn't work.


text:
Q: Get id of element on Mouseover in jquery Firstly I know this question has very simple answer but first understand my problem.
This is my html and script.

Script :
function FacebookprofileTip(post, delay) {
    //How do I get element id here
    //Non-relevant code
}

As per my requirement I want to get the id of "img" tag onmouseover event. but already I am passing 2 arguments to function for post and delay time to display tooltip message. So please tell me how can I get id in jquery.

A: Its has very simple solution, pass the this reference to element which invoke the event to event handler. Then you can read id property.

Change function as
function FacebookprofileTip(post, delay, elem) {
     alert(elem.id)
     //Rest of your code, now you can play with elem as required
}

function FacebookprofileTip(post, delay, elem) {
  alert(elem.id)
}


text:
Q: How to upload assets to s3 from webpack I'm new to webpack.I want to upload my minified js file to s3 using webpack.I used follwing code in webpack.config.js file.
   const webpack = require('webpack');
var S3Plugin = require('webpack-s3-plugin');

     module.exports = {
         entry: './src/app.js',
         output: {
             path: './bin',
             filename: 'app.bundle.js'
         },
          plugins: [
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false,
                },
                output: {
                    comments: false,
                },
            }),
            new S3Plugin({
          // Only upload css and js
          include: /.*\.(css|js)/,
          // s3Options are required
          s3Options: {
            accessKeyId: 'key',
            secretAccessKey: 'key',
            region: 'Oregon',
            signatureVersion: 'v4',
     /*       s3BucketEndpoint: true,*/
            endpoint: "endpoint"
          },
          s3UploadOptions: {
            Bucket: 'bucketname'
          }
        })
        ]
     };

but i'm getting following error in webpack ERROR in S3Plugin: Error: Non-file stream objects are not supported with SigV4 in AWS.S3 how can i solve this issue?

A: Change the signatureVersion to v3:
  s3Options: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    signatureVersion: 'v3',
    region: 'eu-central-1'
  },

A: Try this s3-plugin-webpack fork:
npm install git+https://github.com/fabianfett/s3-plugin-webpack.git
as suggested by the author:
https://github.com/MikaAK/s3-plugin-webpack/issues/43#issuecomment-238854713
Tested with 'eu-central-1' region. Should work using 'us-west-2' (Oregon) too.


text:
Q: Is there a way to omit NAs when using the dplyr package Lag function in R? I have two columns of data and I want to subtract one from the previous row entry of the other. The lag() function in dplyr is perfect for this, but unfortunately I have NAs in the second row of data. This means that when calculating the new value for rows when the previous row has an NA in the second column is resulting in NA's (see below table):

Value 1
Value 2
New Value

NA
2
NA

13
3
11

6
NA
3

6
4
NA

5
4
1

Is there a way to omit then NAs and have it use the last actual value in the second column instead? Like an na.rm=TRUE  that can be added? The result would look like:

Value 1
Value 2
New Value

NA
2
NA

13
3
11

6
NA
3

6
4
3

5
4
1

A: One option would be to mutate Value 2 beforehand and fill the NA with the last non-NA value:
df %>%
  tidyr::fill(`Value 2`, .direction = "down")

A: After making that New.Value, you can fill the NA with previous value using fill() from tidyr package.
library(dplyr)
library(tidyr)

df <- tibble::tribble(
  ~Value.1, ~Value.2, ~New.Value,
    NA, 2, NA,
   13,3,11,
   6,NA,3,
   6,4,NA,
   5,4,1,
  )

df

#> # A tibble: 5 × 3
#>   Value.1 Value.2 New.Value
#>     <dbl>   <dbl>     <dbl>
#> 1      NA       2        NA
#> 2      13       3        11
#> 3       6      NA         3
#> 4       6       4        NA
#> 5       5       4         1

df %>%
  fill(New.Value, .direction = "down")

#> # A tibble: 5 × 3
#>   Value.1 Value.2 New.Value
#>     <dbl>   <dbl>     <dbl>
#> 1      NA       2        NA
#> 2      13       3        11
#> 3       6      NA         3
#> 4       6       4         3
#> 5       5       4         1

Created on 2022-07-08 by the reprex package (v2.0.1)