text:
Q: B vs P pronunciation? I'm a native Arabic speaker -Egyptian- we don't have the V & P sounds natively, I'm fully capable of pronouncing the V sound & telling the difference between it & the F sound perfectly, but I struggle with P, I don't know if I'm pronouncing it as B or not & I struggle with telling the difference between the two even though I know it, both are a bobbing sound caused by the release of air build up, with the difference being that the B one is voiced, this is the exact difference between F & V with the V being voiced, but they both feel so short and exactly the same, for example Pat vs Bat, isn't the a kind of voiced, all I hear is the bob sound followed by a voiced a then the T sound, I feel that the bob is stronger in P, is this the only difference or am I missing something?
Is there any words in which the difference is more prominent, & is there a way to pronounce P correctly even if I can't tell the difference?
by the way I can in most cases guess correctly if a word -even if it's the first time hearing it- is written with P or B but I can't pinpoint the difference in hearing

A: I can feel for you and your difficulties. It is the ventriloquist with his alphabet of frozen lipped vocabulary that substitutes 'D' and 'T' for both 'P' and 'B'. It is only the context and words used that trick the ear into hearing the expected consonant. The only cure will be to expose yourself to the brunt of the language you wish to adapt to. For this I can recommend Python, Monty at length; http://montypython.50webs.com/scripts/Series_3/45.htm   This routine is about an Englishman who adapts to his own difficulties.

A: One way might be to contrast the words "stable" and "staple." In the word "staple," you have to briefly stop voicing between the /ā/ and /əl/ sounds, while the /p/ is being pronounced. In "stable," the whole series of sounds /ābəl/ is voiced. The difference is small, but most native speakers can tell them apart.
(edit: Some commenters say Americans pronounce those two words the same way; I'm American and I don't, so maybe it's a regional thing.)

A: The two sounds involve the same mechanical acts of the mouth. The "B" sound is infinitesimally slower which trends toward a kind of Buzzing sound, like the Bee insect's wings. The "P" sound is faster and sharper. Compare to a bang from fireworks. An explosive PoP.
As a side note, the "Z" sound uses different mouth actions but the same vocal cord action of "B", as in buZZing. It's a vibration, not a popping sound.

A: Try "P" by just exhaling heavy while slightly puckering your lips, similar to simply blowing candles out. Only use your breath and lips, not your vocal cord.
Try "B" by puckering your lips firmly and as you exhale vocalize the sound a lamb makes "bah, bah"
I've never tried to help someone with a pronunciation that isn't in front of me, in person… So I'm hoping my advice helps but if not then don't worry, it's likely due to my inexperience with teaching pronunciation, especially via Internet. If you are still having difficulties, let me know if you'd like to try via phone call or video call. I wouldn't mind taking the time to try a different method.

A: There's a little whiz of air in the P sound and none in the B sound.
It's kind of like actually saying a little H sound (as in "hooray") right after the P.
When both Americans and the English pronounce P, they blow a little air into the vowel. (Yes, they blow into P, no pun intended :)
It can be heard very well in the Beekeeping sketch with Mr. Prawnbaum.


text:
Q: How to allow minus sign for package name in .proto file? Here is the .proto file I used:
pkg/apis/workflow/v1alpha1/generated.proto
syntax = 'proto2';

package go-server.com.argo-new.pkg.apis.workflow.v1alpha1;

import "k8s.io/api/core/v1/generated.proto";
import "k8s.io/api/policy/v1beta1/generated.proto";
import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto";
import "k8s.io/apimachinery/pkg/runtime/generated.proto";
import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";

// Package-wide variables from generator "generated".
option go_package = "v1alpha1";

// ArchiveStrategy describes how to archive files/directory when saving artifacts
message ArchiveStrategy {
  optional TarStrategy tar = 1;

  optional NoneStrategy none = 2;
}

When I tried to compile:
protoc -I /usr/local/include -I . -I ./vendor -I /root/go/src \
       -I /root/go/pkg/mod/github.com/gogo/protobuf@v1.3.1/gogoproto \
       -I /root/go/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.12.2/third_party/googleapis \
       --include_imports --gogofast_out=plugins=grpc:/root/go/src \
       --grpc-gateway_out=logtostderr=true:/root/go/src \
       --swagger_out=logtostderr=true,fqn_for_swagger_name=true:. \
       pkg/apis/workflow/v1alpha1/generated.proto

it reminds me that:
pkg/apis/workflow/v1alpha1/generated.proto:6:11: Expected ";"

It's a compile error which means the package name should not contain -.
Are there any methods to use - in package name or any workaround?
Thanks!

A: Protobuf
It's not allowed, neither by proto2 specs (as in your example code) nor by proto3 specs.
As shown in the specs (either of above mentioned), a package declaration follows the pattern:

package = "package" fullIdent ";"

i.e. the keyword package followed by a fullIdent followed by one ; semicolon, where fullIdent is defined as:

fullIdent = ident { "." ident }

i.e. at least one ident followed by zero or more other ident's preceded by ., where ident is defined as:

ident = letter { letter | decimalDigit | "_" }

i.e. at least one letter, followed by zero or more letters ([A-Z], [a-z]), digits ([0-9]), or the underscore _ character.
So in conclusion, you can't have a minus (dash) - character in your protobuf package name.

Go
Additionally, as @colm.anseo pointed out, Go package names also don't allow dash - characters either:
PackageName = identifier . where identifier = letter { letter | unicode_digit } .
(The underscore character is considered a letter.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access "C:" from "x:\windows\system32>" if Windows is installed on laptop's M.2 ssd and no SATA disk? Is it possible to select "C:" from "x:\windows\system32>" if the only drive of the laptop is an M.2 ssd.
I understand the M.2 ssd is PCIe SSDs which do not use the Motherboards SATA Chipset interface to communicate between the SSD and the Windows File system.
The M.2 ssd driver is either provided by the manufacturer or by the OS itself.
X:" is from WinRe. The Windows is installed on the only laptop's ssd M.2 type. Even if this is the case I wouldn't have thought I would not be able to access "C:" from the command prompt of WinRe. When I get the "x:\windows\system32>", I am unable to change directory to "C:". Tried typing "C:" or any other letter and all I get "The system cannot find the drive specified. Tried to run "diskpart", then "list volume" and get "There are no volumes". Tried to run "list disk" and I get "There are no fixed disks to show". If however log in to Win10, and start cmd, I can then see "c:" drive.


text:
Q: Value is not facet-valid with respect to pattern I have this element in a XSD:
<xs:simpleType name="elementWithAsterisks">
  <xs:restriction base="xs:string">
    <xs:length value="16"/>
    <xs:pattern value="^[0-9*]*$"/>
  </xs:restriction>
</xs:simpleType>

The value of this element can be a number, or a number and asterisk, and its length must be 16 characters.  For example, the following strings should be valid:
 **1234567****01456**
 **1234567890654321**
 1***************

If I send a value like that to this element, XStream returns this message:

cvc-pattern-valid: Value '1234567****01456' is not facet-valid with
  respect to pattern '^[0-9*]*$' for type 'elementWithAsterisks'.

I'm using Java with XStream.  This is my code to validate it:
try {
    File xsdFile = new File("validation.xsd");
    SchemaFactory schemaFactory = SchemaFactory.newInstance(SCHEMA_LANGUAGE);
    factory.setSchema(schemaFactory.newSchema(xsdFile);
    SAXParser saxParser = factory.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setErrorHandler(new XmlValidationErrorHandler());
    reader.parse(new InputSource(inputStream));
    isValid = true;
} catch (SAXException | ParserConfigurationException | IOException ex) {
    ex.printStackTrace();
    isValid = false;
}

A: Regular expressions in XSD are implicitly surrounded by ^ and $.  Simply remove the explicit (redundant) ones from your xs:pattern, and your XSD will work as expected:
  <xs:pattern value="[0-9*]*"/>


text:
Q: algebraic integer in $\mathbb{Q}$($\zeta_n$) Let $\chi(\cdot)$ be an irreducible (over $\mathbb{C}$) character of an representation in a finite Group G:
Show that $\chi(g)$ is an algebraic integer in the cyclotomic
field $\mathbb{Q}$($\zeta_n$), where $\zeta_n$ := $e^{2\pi i/n}$.
I already got an answer here: my old question
But I struggle with the part, where he follows the similarity of M(g) to some diagonal matrix.
So any help or even a new approach?

A: A fact from linear algebra: If the minimal polynomial of a matrix $M\in \mathrm{M}_n(\mathbb{C})$ has no repeated roots then $M$ is diagonalizable. You can prove this as follows. If $p,q$ are coprime polynomials then using Bézout's identity we have $\ker(pq(M))=\ker(p(M))\oplus \ker(q(M))$. So in particular if the minimal polynomial of $M$ is say $(z-\lambda_1)\times\cdots\times (z-\lambda_k)$ with the $\lambda_i's$ distinct, then $\mathbb{C}^n = \ker(M-\lambda_1 I_n)\oplus \cdots \oplus (M-\lambda_k I_n)$, so $M$ is diagonalizable.
Now if $\rho:G\rightarrow \mathrm{GL}_n(\mathbb{C})$ is a representation with character $\chi(g)=\mathrm{tr}\left(\rho(g)\right)$ then $I_n=\rho\left(g^{|G|} \right)= \rho\left(g \right)^{|G|}$. Hence the minimal polynomial of $\rho\left(g \right)$, which is a divisor of $X^{|G|}-1$, has distinct roots. Hence $\rho\left(g \right)$ is diagonalizable with eigenvalues (which are some of the roots of $X^{|G|}-1$) in $\mathbb{Q}(\zeta_{|G|})$ and so is their sum, which is $\chi(g)$.


text:
Q: Header files without implementation I'm working on a open source project, which consist on a framework for iOS devices, and one of the methods is not working as I expected. I tried to search for the implementation of the method, but all I found was a a header file and the method declaration; I didn't find the implementation anywhere. Neither did I find the .m file corresponding to that class.
So I have some questions:

*

*How can a class exist without it's implementation and still its methods perform certain operations?

*What is the purpose of writing this kind of classes.

*In this kind of situations where should be the methods implemented?

Note
The open source project is FastPdfKit and the method is wholeTextForPage:

A: Well, those methods are somewhere, so it's not that they don't exist, you just can't see them.
Try for example to open UITableView.h, you can see the methods definition, but not the implementation. The implementation is hidden in the library, but you can't see it.
In a nutshell, developers do this to hide the details of the implementation of a class to other users. You just receive a header that tells you which methods you can use, and how, but the details about how are they implemented are hidden for you.
For example, Apple doesn't want you to see how they implemented UITableView, but they want you to know how you can use it.
Here you can find a tutorial about how to create a library for Objective-C:
Creating Static Libraries for Objective-C


text:
Q: Select element, which contains element with class x? I have a bunch of articles and want to select the first article-Element that contains a button which has the class add-to-cart-button and doesn't have the class btn--disabled.
What is the best way to do this with webdriver?

A: Try below XPath to select article that contains button with class "add-to-cart-button" and no class "btn--disabled":
//article[.//button[contains(@class, "add-to-cart-button") and not(contains(@class, "btn--disabled"))]]

A: You can try like this, xpath provide not() function and then used indexing over xpath to get first element
 (//button[not(@class,'btn--disabled') and contains(@class,'add-to-cart-button')])[1]


text:
Q: Typescript cant access object property I have little issue accessing object property in typscript. this works fine in js but doesn't in ts
let getUserName = {
    firstname : "timi",
    lastname: "oluwayomi",
    middlename: "ola",
    full : () => { return this.firstname + this.lastname + this.middlename } ,
    first: () => {  return this.firstname }
  }
console.log(getUserName.first())

in javascript output: timi
but ts throws error. is there a different way to access it in ts ?

A: just refer to the same object in the object, this is a hack IMO
let getUserName = {
    firstname : "timi",
    lastname: "oluwayomi",
    middlename: "ola",
    full : () => { return getUserName.firstname + getUserName.lastname + getUserName.middlename } ,
    first: () => {  return getUserName.firstname }
  }
console.log(getUserName.first())

A: this inside arrow function refers to the global object, so its giving error, you can try with traditional functions
 let getUserName = {
    firstname : "timi",
    lastname: "oluwayomi",
    middlename: "ola",
    full : function() { return this.firstname + this.lastname + this.middlename } ,
    first: function() {  return this.firstname }
  }
console.log(getUserName.first())

A: i was working on an component based project "Angular"
so i had to initialize first
getUserName : any;

getUserName = {
    firstname : "timi",
    lastname: "oluwayomi",
    middlename: "ola",
    full : () => { return getUserName.firstname + getUserName.lastname + getUserName.middlename } ,
    first: () => {  return getUserName.firstname }
  }
console.log(getUserName.first())

also thanks to Dean Van Greunen

A: You are accessing this within an arrow function. Inside an arrow function, this refers to the global object, not the execution context. See You Don't Know JS Yet - Chapter 3 - this Keyword for more info on this.
So, to start with, use this:
let getUserName = {
  firstname : "timi",
  lastname: "oluwayomi",
  middlename: "ola",
  full() { return this.firstname + this.lastname + this.middlename },
  first() {  return this.firstname },
}

As this is of type any in this case, as the TypeScript compiler cannot infer the type of your object for you, you will need to type the object yourself (usually a good idea anyway):
type GetUserName = {
  firstname: string;
  lastname: string;
  middlename: string;
  full(): string;
  first(): string;
}

let getUserName: GetUserName = {
  firstname: "timi",
  lastname: "oluwayomi",
  middlename: "ola",
  full(this: GetUserName) {
    return this.firstname + this.lastname + this.middlename;
  },
  first(this: GetUserName) {
    return this.firstname;
  },
};


text:
Q: Which is the best way to put a try-except-finally in delphi?
Possible Duplicate:
Delphi Exception Handling - How to clean up properly?
Use of Try/Finally/Catch Together in Delphi

I would like to know which is the best way to put try-except-finally in delphi? What I mean is in nested try block, which statement should come inside, for example, Example 1
// initialize / allocate resource (create objects etc.)
...
try
     try
        // use resource
        ...
     except
       // handle exception
       ...
     end;
finally
   // free resource / cleanup
   ...
end

Example 2
    // initialize / allocate resource (create objects etc.)
...
try
     try
        // use resource
        ...
     finally
       // free resource / cleanup
       ...
     end;
except
   // handle exception
   ...
end

Which is the best way to handle an exception in Delphi, Example 1 or Example 2. why?


text:
Q: Is it possible to find which vim/tmux has my file open? I use tmux at work as my IDE. I also run vim in a variety of tmux panes and will fairly often background the process (or alternatively I just close the window - I have vim configured not to remove open buffers when the window is closed). Now I've a problem, because a file that I want to edit is open in one of my other vim sessions but I don't know which one.
Is it possible to find out which one, without manually going through all my windows and panes? In my particular case, I know that I didn't edit it with vim ~/myfile.txt because ps aux | grep myfile.txt doesn't return anything.

A: It doesn't tell me everything, but I used fuser ~/.myfile.txt.swp which gave me the PID of the vim session. Running ps aux | grep <PID> I was able to find out which vim session I was using, which gave me a hint as to which window I had it open in.
Thanks to Giles's inspiration and a bit of persistence and luck, I came up with the following command:
⚘ (FNAME="/tmp/.fnord.txt.swp"; tmux switch -t $(tmux list-panes -a -F '#{session_name}:#{window_index}.#{pane_index} #{pane_tty}' | grep $(ps -o tty= -p $(lsof -t $FNAME))$ | awk '{ print $1 }'))

To explain what this does:
(FNAME="/tmp/.fnord.txt.swp";

This creates a subshell and sets FNAME as an environment variable. It's not, strictly speaking, necessary - you could just replace $FNAME with the filename yourself, but it does make editing things easier. Now, working from the inside out:
lsof -t $FNAME

This produces only the PID of the process that has open the file.
ps -o tty= -p $(...)

This produces the pts of the PID that we found using lsof.
tmux list-panes -a -F '#{session_name}:#{window_index}.#{pane_index} #{pane_tty}'

This produces a pane list of entries like session:0.1 /dev/pts/1. The first part is the format that tmux likes for targets, and the second part is the pts
| grep $(...)$

This filters our pane list - the trailing $ is so it will only match the one we care about. I discovered that quite by accident as I had pts/2 and pts/22, so there were two matches, whoops!
| awk '{ print $1 }'

This produces the session:0.1 part of the pane output, which is suitable for passing to tmux switch -t.
This should work across sessions as well as panes, bringing to focus the pane that contains your swap file.

A: the outline answer to your question is:
for all the tmux sessions:
  for all the windows in the session:
      for all the panes in windows:
         for all sub process pids (recursively):
            find the open files

all sessions:
tmux list-sessions -F '#{session_id}:#{session_name}
all windows:
tmux list-windows -F '#{window_id}XX#{window_index}XX#{window_name}' -t "$session_id"
all panes:
tmux list-panes -F '#{pane_id}:#{pane_index}:#{pane_pid}' -t ""$session_id":"$window_index""
all sub processe pids:
ps -o pid --no-headers --ppid $pid
open files:
lsof -p $pid
An implementation of the above which displays a tree of:
sessions
   windows
      panes
         process
            open files

to show which process has a file open (vim in my case too).

can be found at https://github.com/nkh/tmux-ls
it's been on github for 5 year but I encourage you to clone it in case it is removed (or github crashes)


text:
Q: How to get reference to the new DOM object after changing content with outerHTML? I have a division that I need to change its outer HTML upon an event. The problem is that upon setting the outerHTML I am not able to reference the new selected DOM object unless I explicitly catch it again.
Is there a way to directly update the variable reference upon calling outerHTML (in my case the reference of the div variable below) ?

$("#changeDiv").click(function(){

  var div = $(this).prev();
  div[0].outerHTML = `<div id="imSecondtDiv"> <p> World </p> </div>`;
  console.log(div); // logs [div#imFirstDiv, prevObject: n.fn.init[1], context: button#changeDiv]

  // the following line does not affect the newly added division
  // since the var `div` references the old DOM object
  // unless I add div = $(this).prev(); before setting the html of
  // the paragraph it will not set it
  div.find('p').html('Override');

});

 Hello

<button id="changeDiv" >Change Div 1</button>

A: I have solved this by getting a reference element (sibling or parent) of tag that's going to be replaced.
Here is a function which is not dependent on which element are you going to change:
function replaceElement(ele, outerHTML)
{
  var parent = false, refEle;
  //if element that's going to be changed has previousElementSibling, take it as reference. If not, the parentElement will be the reference.
  if (ele.previousElementSibling !== null)
    refEle = ele.previousElementSibling;
  else
  {
    refEle = ele.parentElement;
    //indicate that parentElement has been taken as reference
    parent = true;
  }
  //change the outerHTML
  ele.outerHTML = outerHTML;
  //return the correct reference
  if (parent)
    return refEle.firstElementChild;
  else return refEle.nextElementSibling;
}

So in your case, you would invoke it this way:
div[0] = replaceElement(div[0], '

 World

');

I hope it will work with jQuery as well, as I am writing all my scripts only in native javascript.

A: As you are seeing changing the outerHTML makes things behave a bit strangely, as you are completely replacing the original element but still referencing the old one.
It would be better to create a new div, add it after() the old one then remove() the old one. This maintains the position of the div in the correct place.

$("#changeDiv").click(function(){

  // get the oldDiv
  var oldDiv = $(this).prev();

  // Create a newDiv
  var newDiv = $('

 World

');

  // add newDiv after oldDiv one, then remove oldDiv from the DOM.
  oldDiv.after(newDiv).remove();

  // now you still have the reference to newDiv, so do what you want with it
  newDiv.find('p').html('Override');

});

 Hello

<button id="changeDiv" >Change Div 1</button>

Using outerHTML
If you really really do need to use outerHTML, you can simply grab $(this).prev() again:

$("#changeDiv").click(function(){

  var div = $(this).prev();
  div[0].outerHTML = `<div id="imSecondtDiv"> <p> World </p> </div>`;

  // the "new" div is now before the button, so grab the reference of THAt one
  div = $(this).prev();

  // the following line does not affect the newly added division
  // since the var `div` references the old DOM object
  // unless I add div = $(this).prev(); before setting the html of
  // the paragraph it will not set it
  div.find('p').html('Override');

});

 Hello

<button id="changeDiv" >Change Div 1</button>


text:
Q: seam-gen and flex I have integrated  seam and flex with FlamingoDS
I got html file from mxml file and I stored it in WebContent folder it's fine
then I want to create link named as 'Plan' in menu.xhtml
My aim is to get that html file when i clicked on this button I don't know what to do for that
so, I have created some test.xhtml in that top element is the
for the template attribute this element I have given the template.html
and I used
then for 'Plan' link I gave the view="/test.xhtml"
It's fine when I clicked on that link I am getting the test.seam file which includes our html file but this html file is coming in some fixed area with scroll bars only eventhough there is a lot of space to fit
Please  help...... me

A: First of all, it is very difficult to read your post. Please format it more readable.
Secondly, we can only guess what's wrong when we cannot see any code. But my hunch is that you are using s:decorate that includes some formating you are not aware of. This comes in standard seam-gen. Try removing that s:decorate stuff or point to another style you wish to use.


text:
Q: NSDocument app and file extension I have created a document based app that needs to open xml text files with a particular extension. When I created the project in Xcode using the NSDocument template I specified the extension I wanted and everything was working fine.
Following the Apple guide on how to build document based apps I went to edit the Info.plist file to add the details of the UTI that were missing before. Suddenly my app stopped opening files with the extension I want and in fact stopped opening any file. Also when I try to save a file the save dialog doesn't suggest any extension any more.
When I save a file and run the command mdls from the terminal I get
kMDItemContentTypeTree         = (
    "public.data",
    "public.item"
)

instead of public.xml I set for the UTI in the Info.plist.
It seems that my app stopped recognising the informations stored in the Info.plist. Is there anything I have to connect in Xcode in order to have this working?
Here is the relevant parts of my Info.plist file:
<key>CFBundleDocumentTypes</key>
<array>
    <dict>
        <key>CFBundleTypeExtensions</key>
        <array>
            <string>xmds</string>
        </array>
        <key>CFBundleTypeIconFile</key>
        <string>AppIcon</string>
        <key>CFBundleTypeName</key>
        <string>XMDS Script</string>
        <key>CFBundleTypeOSTypes</key>
        <array>
            <string>xmds</string>
        </array>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>com.dedalus.degs</string>
        </array>
        <key>NSDocumentClass</key>
        <string>Document</string>
    </dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.xml</string>
        </array>
        <key>UTTypeDescription</key>
        <string>XMDS Script</string>
        <key>UTTypeIconFile</key>
        <string>AppIcon</string>
        <key>UTTypeIdentifier</key>
        <string>com.dedalus.degs</string>
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>com.apple.ostype</key>
            <array>
                <string>xmds</string>
            </array>
            <key>public.filename-extension</key>
            <array>
                <string>xmds</string>
            </array>
        </dict>
    </dict>
</array>

A: I used the Project's Target Info setting to set the Document Type and UTI instead of the Info.plist file in Xcode 4.2 and 4.4. This pulls from the Info.plist file and modifies it after you change it. Try using that instead.
The Document Type defines the class that will handle the extension and the extension. The Exported UTIs represent the extensions for which your app is authoritative. See this Stackoverflow question:
What are "Imported UTIs" in Xcode 4?
My Exported UTIs conform to public.data ("Base type for any sort of simple byte stream, including files and in-memory data"). If you use an identifier, make sure it is the same in both the Document Type and Exported UTIs.


text:
Q: better way of handling list of dict or improving my code I have a dict
my_dict =
    { '123@com' : [ { 'event': 'event1', 'oldval' = 1, 'newval = 2}, { 'event': 'event2', 'oldval' = 11, 'newval': 22}, { 'event': 'event3', 'oldval' = 33, 'newval': 44}]
    {'1234@com' : { 'event1': 'oldval': 45, 'newval': 66},
    {'12345@com': [ {'event':'event2', 'oldval': 77, 'newval': 99}, { 'event': 'event3', 'oldval': '99', 'newval': 100'}]

So basically my goal is to build a list
 [ ['123@com', (2,1,True), (22,11, True), (44,33,True)], ['1234@com', (66,45,True), ('','',False),('','',False)], ['12345@com', ('',''False), (99,77,True), (100,99)]]

So my goal is to capture the value if event is changed and get the values and marked as true.
So the code which I am writing is as follows:
for key,value in my_dict.items():
  if str(my_dict).find('event1') >- 1 or str(my_dict).find('even2') > 1 or str(my_dict).find('event3') > -1:
  tmp_list = []
  tmp_list.append(key)
  if type(value) is dict:
    if value['event'] == 'event1':
       @ get all the value and append to tmp_list
    if value['event'] == 'event2':
      @ do the same thing as above
  else:
     for val in value:
      if val['name'] == 'event':
        @ do the same stuff.
      @do the same stuff again for rest of event.

So basically I am able to achieve my goal by following the above code pattern.
So any one can help me out in coding better,I will really appreciate it.
I don't like the way I am coding.
Thanks

A: Having heterogeneous lists like ['123@com', (2,1,True), (22,11, True), (44,33,True)] is a code smell.  It almost always means that you're trying to do too much with simple data types, and would probably be better served by actually using a class.  Assuming python 2.x:
class Event(object):
    def __init__(self, event, oldval, newval):
        self.event = event
        self.oldval = oldval
        self.newval = newval

class EventThing(object):
    def __init__(self, key, event_list):
        self.key = key
        self.event_list = [Event(**e) for e in event_list]

    def produceCondensedList(self):
        return [(e.oldval, e.newval, True) for e in self.event_list]

thing_list = [EventThing(key, event_list) for key, event_list in my_dict.items()]

It's not exactly the same as the example you gave, but without knowing more about your exact use case, it's hard to suggest precise answers.  The above should be enough to at least get you started.

A: This is the best way I could think of coding this.
def value_finder(val):
    return lambda ev,li: next((di[val] for di in li if di['event']==ev),'')

def event_finder(ev,li):
    return any(di['event']==ev for di in li)

def tuple_return(ev,li,nv,ov):
    return (nv(ev,li),ov(ev,li),event_finder(ev,li))

def main(my_dict):
    lis = []
    nv = value_finder('newval')
    ov = value_finder('oldval')
    events = ['event1','event2','event3']
    for key,value in my_dict.items():
        temp_list = [key]
        temp_list += [tuple_return(ev,value) for ev in events]
        lis.append(temp_list)
    print lis

my_dict = {'123@com':[{'event':'event1','oldval':1,'newval':2},
                      {'event':'event2','oldval':11,'newval':22},
                      {'event':'event3','oldval':33,'newval':44}],
          '1234@com':[{'event':'event1','oldval':45,'newval':66}],
          '12345@com':[{'event':'event2','oldval': 77,'newval': 99},
                      {'event':'event3','oldval':'99','newval':100}]}
main(my_dict)


text:
Q: Sum on divisors is almost- ever zero Take a positive integer $k$. Let $S \subseteq \mathbb{N}$ be the set of squarefree, and define $\displaystyle \rho_k = \mu*\omega^k$, where $ \displaystyle f* g = \sum_{d \mid n} f(d)g(n/d)$ .
Show that $\rho_k(n)$ is 0 for almost all $n \in S$.
Note: $\mu(n) $ is the moebius function and $\omega(n) = |\{p \mid n, p \text{ prime} \}|$

A: Let $n = p_1\cdots p_r$ be the prime factorization of $n\in S$. Then, its divisors are of the form $p_{i_1}\cdots p_{i_j}$ with $\{i_1,\ldots , i_j\}\subseteq \{1,\ldots , r\}$. Notice that $\mu(p_{i_1}\cdots p_{i_j}) = (-1)^j$ and $\omega^k(p_{i_1}\cdots p_{i_k}) = j^k$. Notice that there are $\binom{r}{j}$ divisors of $n$ which have $j$ prime factors.
Thus, your $\rho_k(n)$ is $$\rho_k(n) = \displaystyle\sum_{j=0}^r \binom{r}{j}(-1)^{r-j} j^k$$
Since this is the $r$-th forward difference of $x^k$ at $x=0$, for sufficiently large $r$ it must be $0$.
However, I don't know what notion of "almost all" you're using, because there is an infinite number of values for which $\rho_k$ isn't $0$ (eg at prime numbers), and I think that "almost all" usually refers to "all but finitely many".


text:
Q: How to get maximum sum of numbers drawn from multiple arrays - permutation don't work (16!) Yesterday I asked about How to find the maximum possible sum of numbers in arrays drawn from a unique array index and I was advise to use permutation - it worked well, but I wasn't aware that my arrays are much bigger than I assumed. I have arrays as big as [16] - so I have 16! possibilites...what could I use instead of permutation to get maximum possible sum?
edit. here is my arrays:
public static ArrayList<Double[]> tempArrayCreator() {
    ArrayList<Double[]> tempArray = new ArrayList<>();

    Double[] l1 = { 9.0, 13.5, 9.0, 9.0, 9.0, 13.5, 9.0, 13.5, 13.5, 13.5,
            9.0, 13.5, 13.5, 9.0, 13.5, 9.0 };
    Double[] l2 = { 6.0, 6.0, 13.5, 6.0, 9.0, 6.0, 6.0, 6.0, 6.0, 9.0, 6.0,
            6.0, 9.0, 9.0, 6.0, 9.0 };
    Double[] l3 = { 22.5, 22.5, 14.0, 22.5, 14.0, 22.5, 22.5, 22.5, 22.5,
            21.0, 22.5, 22.5, 21.0, 14.0, 22.5, 14.0 };
    Double[] l4 = { 6.0, 6.0, 7.0, 6.0, 7.0, 6.0, 6.0, 6.0, 6.0, 7.0, 9.0,
            6.0, 7.0, 7.0, 6.0, 7.0 };
    Double[] l5 = { 4.5, 6.75, 6.0, 4.5, 6.0, 6.75, 4.5, 4.5, 6.75, 9.0,
            4.5, 6.75, 9.0, 6.0, 6.75, 6.0 };
    Double[] l6 = { 6.0, 9.0, 5.0, 6.0, 5.0, 9.0, 6.0, 6.0, 9.0, 7.5, 6.0,
            9.0, 7.5, 5.0, 9.0, 5.0 };
    Double[] l7 = { 13.5, 13.5, 4.0, 13.5, 4.0, 13.5, 13.5, 13.5, 13.5,
            6.0, 13.5, 13.5, 4.0, 4.0, 13.5, 4.0 };
    Double[] l8 = { 4.5, 4.5, 4.0, 4.5, 4.0, 4.5, 4.5, 4.5, 4.5, 4.0, 4.5,
            4.5, 6.0, 4.0, 4.5, 4.0 };
    Double[] l9 = { 10.5, 10.5, 10.0, 10.5, 10.0, 10.5, 10.5, 10.5, 10.5,
            10.0, 10.5, 10.5, 10.0, 10.0, 10.5, 10.0 };
    Double[] l10 = { 11.25, 11.25, 3.0, 11.25, 3.0, 11.25, 11.25, 11.25,
            11.25, 3.0, 11.25, 11.25, 3.0, 3.0, 11.25, 3.0 };
    Double[] l11 = { 7.5, 11.25, 10.0, 7.5, 10.0, 11.25, 7.5, 11.25, 11.25,
            15.0, 7.5, 11.25, 15.0, 10.0, 11.25, 10.0 };
    Double[] l12 = { 7.5, 7.5, 12.0, 7.5, 8.0, 7.5, 7.5, 7.5, 7.5, 8.0,
            7.5, 7.5, 8.0, 8.0, 7.5, 8.0 };
    Double[] l13 = { 13.5, 13.5, 6.0, 13.5, 6.0, 13.5, 13.5, 13.5, 13.5,
            9.0, 13.5, 13.5, 9.0, 6.0, 13.5, 6.0 };
    Double[] l14 = { 9.0, 9.0, 8.0, 9.0, 8.0, 9.0, 9.0, 9.0, 9.0, 12.0,
            9.0, 9.0, 12.0, 8.0, 9.0, 8.0 };
    Double[] l15 = { 7.5, 7.5, 12.0, 7.5, 8.0, 7.5, 7.5, 7.5, 7.5, 8.0,
            7.5, 7.5, 8.0, 8.0, 7.5, 8.0 };
    Double[] l16 = { 18.0, 18.0, 10.0, 18.0, 10.0, 18.0, 18.0, 18.0, 18.0,
            15.0, 18.0, 18.0, 15.0, 10.0, 18.0, 10.0 };

    tempArray.add(l1);
    tempArray.add(l2);
    tempArray.add(l3);
    tempArray.add(l4);
    tempArray.add(l5);
    tempArray.add(l6);
    tempArray.add(l7);
    tempArray.add(l8);
    tempArray.add(l9);
    tempArray.add(l10);
    tempArray.add(l11);
    tempArray.add(l12);
    tempArray.add(l13);
    tempArray.add(l14);
    tempArray.add(l15);
    tempArray.add(l16);

    return tempArray;
}

A: The solution with permutation is actually a backtracking solution: you compute all possible sums and take the maximum sum. Backtracking always gives a correct result (since it considers every possibility) but is very slow.
Another aproach would be by writing a Greedy Algorithm (easy and fast, but fails in a lot of cases).
By searching on google, i found that the best solution for your problem is given by applying the so-called Hungarian Algorithm: http://www.hungarianalgorithm.com/examplehungarianalgorithm.php In your case, you are trying to find the maximum sum (the example is for minimum sum)

A: If I have got it right you want to find the maximum sum of arrays created by another array that contains all elements and whose indices are going to be placed in your new arrays.
So how many arrays are going there to be? Anyway not really important.
So why don't you take the max of each new array you have and just add it? And you might think "how do I know how the elements are going to be filled?".
Well, since you are only interested in the max sum you, you can take into consideration only the maximum N elements of your original array. You do know the elements in the original array, right?
So imaging that those let's say 3 (N = 3) arrays have each one of them one of these N numbers then you just keep these and there you go!
I don't know if I am missing something but you don't need permutation if that's the case. If not then explain the situation a little better. Just sum the larger N numbers.
Edit:
Since you have 16 arrays of 16 elements you can imagine that each array is split into smaller ones (say 4-elemens each).
int[] arr1 = {x, x, x, x, x, x, 16, x, 20, x, x, ,19, x, x, x, 17};

where x is an arbitrary number that is smaller than 16 (the smaller of the 4 biggest numbers).
It does not matter in which index it's going to be every one of these four numbers as long as they are not in the same index. So you can suppose that there (multiple) situation that they are not in the same index so the sum is just the sum of these 4 numbers.
One possible permutation could be (but any other with the above condition would do):
int[] smallArr1 = {x, x, x, 16};
int[] smallArr2 = {x, x, 17, x};
int[] smallArr3 = {x, 19, x, x};
int[] smallArr4 = {20, x, x, x};

So sum is just
int sum = 16 + 17 +19 + 20;

in any case.

A: I hope I do not misunderstand you but my solution would be to draw the biggest out of every ArrayIndex and then sum them up, because the biggest result consists of all biggest elements
public double maxPossibleSum(ArrayList<Double[]> lists) {

    double result = 0.0;

    for (int i = 0; i < lists.get(0).length; i++) {

    double biggest = lists.get(0)[i];

        for (int j = 1; j < lists.size(); j++) {

            if(lists.get(j)[i] > biggest){ //Find

                biggest = lists.get(j)[i];
            }

            result += biggest;
        }
    }

    return result;
}


text:
Q: Variable Amount of Input on the Same Line in C I have to scan the same line to get a variable amount of input (the user selects how many inputs they want to play with) for an array. I have to do it a character, an integer, and a floating-point.
I have tried for loop and did different things with spaces with nested loops and statements inside of the foor loop but nothing is working.
edit this isn't all of my code I added more of it so people have a better idea of what I'm trying to do.
#include <stdio.h>
#include <stdlib.h>

int main() {
    int ranNum1, ranNum2, ranNum3, ranNum4, playNum, ranPlay;
    int index1, index2, index3;

    printf("How many choices do you want to play with? ");
    scanf("%d", &playNum);
    srand(time(0));
    ranPlay = playNum + 1;
    ranNum1 = rand() % ranPlay;
    ranNum2 = rand() % ranPlay;
    ranNum3 = rand() % ranPlay;
    ranNum4 = rand() % 5;
    int kids[playNum];
    char marry [playNum];
    float money [playNum];
    printf("Who do you want to marry?\n");
    printf("(enter %d first name initials) ", playNum);
    for (index1 = 0; index1 < playNum; index1 + 1) {
        scanf("%c", &marry[index1]);
    }
    printf("How many kids do you want?\n");
    printf("(enter %d whole numbers) ", playNum);
    for (index2 = 0; index2 < playNum; index2 + 1) {
        scanf("%d", &kids[index2]);
    }
    printf("How much money do you want?\n");
    printf("(enter %d decimal amounts) ", playNum);
    for (index3 = 0; index3 < playNum; index3 + 1) {
        scanf("%f", &money[index3]);
    }
}

It compiles, it's just that when I run it it doesn't run right, when I input 3 characters and click enter, rather than printing the "How many kids do you want?" it just is blank.

A: running the latest posted code through the gcc compiler results in:
gcc    -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11  -c "untitled.c"
untitled.c: In function 'main':
untitled.c:10:11: warning: implicit declaration of function 'time' [-Wimplicit-function-declaration]
     srand(time(0));
           ^~~~
untitled.c:10:11: warning: conversion to 'unsigned int' from 'int' may change the sign of the result [-Wsign-conversion]
untitled.c:21:47: warning: statement with no effect [-Wunused-value]
     for (index1 = 0; index1 < playNum; index1 + 1) {
                                        ~~~~~~~^~~
untitled.c:26:47: warning: statement with no effect [-Wunused-value]
     for (index2 = 0; index2 < playNum; index2 + 1) {
                                        ~~~~~~~^~~
untitled.c:31:47: warning: statement with no effect [-Wunused-value]
     for (index3 = 0; index3 < playNum; index3 + 1) {
                                        ~~~~~~~^~~
untitled.c:5:36: warning: variable 'ranNum4' set but not used [-Wunused-but-set-variable]
     int ranNum1, ranNum2, ranNum3, ranNum4, playNum, ranPlay;
                                    ^~~~~~~
untitled.c:5:27: warning: variable 'ranNum3' set but not used [-Wunused-but-set-variable]
     int ranNum1, ranNum2, ranNum3, ranNum4, playNum, ranPlay;
                           ^~~~~~~
untitled.c:5:18: warning: variable 'ranNum2' set but not used [-Wunused-but-set-variable]
     int ranNum1, ranNum2, ranNum3, ranNum4, playNum, ranPlay;
                  ^~~~~~~
untitled.c:5:9: warning: variable 'ranNum1' set but not used [-Wunused-but-set-variable]
     int ranNum1, ranNum2, ranNum3, ranNum4, playNum, ranPlay;
         ^~~~~~~
Compilation finished successfully.

Don't let that final message from the compiler: "Compilation finished successfully."  fool you.  That is just the compiler saying that it implemented some kind (usually wrong) of work around for the problems in the code.


text:
Q: Передача замыкания в потоки Требуется передать замыкание в потоки.
Замыкание передается на функцию а дальше раздается 2м и более потокам. Раньше (может и не грамотно, но это работало) оборачивал замыкание в Arc<Mutex<function>> но это работает лишь одновременно с 1 потоком.
Потоки не должны завершатся! Потоки должны работать асинхронно.
Пример кода:
use std::sync::Mutex;
use std::sync::Arc;
use std::thread;

fn main() {
    println!("Start");
    test_thread(
        4,
        move |n| {
            println!("#Ulin Test ok. Thread {}", n);
        }
    );

    thread::sleep(std::time::Duration::from_millis(1_000));
}

pub fn test_thread<F>(count:u32, function: F) -> bool where F: Fn(usize) + Send + 'static{
    let arc_function = Arc::new(Mutex::new(function));

    for i in 0..count {
        let arc_function_1 = arc_function.clone();
        let n = i as usize;
        thread::spawn(
            move || {
                println!("Thread start {}", &n);
                let arc_function = arc_function_1.lock().unwrap();

                arc_function(n);

                //ПОТОК НЕ ДОЛЖЕН ЗАВЕРШАТСЯ
                loop {
                    thread::sleep(std::time::Duration::from_millis(3_000));
                }
            }
        );
    }
    true
}

Запуск: https://play.rust-lang.org/?gist=62319cad6b0196a980a2f13aeddab244&version=stable
Вывод:
Start
Thread start 2
#Ulin Test ok. Thread 2
Thread start 1
Thread start 3
Thread start 0

A: Добавь Sync в необходимые trait замыкания и убери с него оборачивающий Mutex. Тогда сможешь использовать замыкание, содержащее только Sync переменные, т.е. безопасные для одновременного использования из разных тредов. Те переменные, которые не безопасны, придётся оборачивать в Mutex, чтобы получить на них Sync.
Пример кода:
use std::sync::Arc;
use std::thread;

fn main() {
    println!("Start");
    test_thread(
        4,
        move |n| {
            println!("#Ulin Test ok. Thread {}", n);
            thread::sleep(std::time::Duration::from_millis(3));
            println!("#Ulin Test second ok. Thread {}", n);
        }
    );

    thread::sleep(std::time::Duration::from_millis(1_000));
}

pub fn test_thread<F>(count:u32, function: F) -> bool where F: Fn(usize) + Send + Sync + 'static{
    let arc_function = Arc::new(function);

    for i in 0..count {
        let arc_function_1 = arc_function.clone();
        let n = i as usize;
        thread::spawn(
            move || {
                println!("Thread start {}", &n);
                let arc_function = arc_function_1;

                arc_function(n);

                //ПОТОК НЕ ДОЛЖЕН ЗАВЕРШАТСЯ
                loop {
                    thread::sleep(std::time::Duration::from_millis(3_000));
                }
            }
        );
    }
    true
}

Запуск: https://play.rust-lang.org/?gist=92a0e9d4e827e2cf28a331a8a460557e&version=stable
Вывод:
Start
Thread start 3
#Ulin Test ok. Thread 3
Thread start 1
#Ulin Test ok. Thread 1
Thread start 2
#Ulin Test ok. Thread 2
Thread start 0
#Ulin Test ok. Thread 0
#Ulin Test second ok. Thread 3
#Ulin Test second ok. Thread 1
#Ulin Test second ok. Thread 2
#Ulin Test second ok. Thread 0


text:
Q: Probability calculation for salary of both employees over $1500, if known mean and variance I know the mean and the variance of 130 employees in an industry and I have to calculate the probability that 2 workers selected randomly have both salary above $1500. I also know the salary of every emploee in this indtry, from which I can calculate the mean and the variance.
Can you please give me a tip, because I'a little confused.

A: Lets say you have $a$ employees with salary $\ge\$1500$ and $b$ with salary $<\$1500$ (you said you have access to these numbers). There are ${a+b\choose 2}$ ways to choose two employees and ${a\choose 2}$ ways to choose two with high salary. So your probabiliy is
$$p=\frac{a\choose 2}{a+b\choose 2}=\frac{a(a-1)}{(a+b)(a+b-1)}.$$


text:
Q: containsObject NSMutableArray Lets say I alloc init an object and this object contains the exact same data as an object in an array, the only difference would be the location in memory.
If I called [myArray containsObject:identicalObject]; would it find the 'duplicate' object? Or does it only return true if the object is the exact same object in memory? If the objects match, like a .equals in java will that return true?

A: containsObject uses isEqual:. So, you should override isEqual: and hash methods.


text:
Q: JAVA sorting numbers, writing the highest one from each line in matrix i have got this problem. Hope you will understand it. Imagine a high jump competition. We have a program, that will make a matrix filled with random numbers from selected interval. Each line in the matrix stands for individual results. For instance we have matrix 3x3 and first line contains three attempts by one participant. Second line contains results of three attempts made by second participant and so on... Program should also write the highest jump of each participant and at the end, it should put them on some kind of winners podium. it will sort them from highest to lowest. I struggle with the sorting. Tried to use bubble surt but i wasnt succesful. Here is what i have so far:
import java.util.*;
public class Mat {
    int [][]b;
    int m;
    int n ;
    public Mat (int m, int n) {
        this.m = m;
        this.n = n;
        b = new int [m][n];
    }
    public void fillRandomly(int rangeFrom, int rangeTo) {
        Random rnd = new Random(); //that is instance of random numbers generator
        for(int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                b[i][j] = rangeFrom + rnd.nextInt(rangeTo - rangeFor + 1);
    }
    public void printout() {
        System.out.println("\n\n\tMatrix:");
        for(int i=0;i<b.length;i++){
            for(int j = 0; j < b[i].length;j++)
                System.out.printf("%4d",b[i][j]);
            System.out.println();
        }
    }
    public void maxNumberInLine () {
        for(int i=0; i < b.length; i++){
            int max = b[i][0];
            for(int j=1; j<b[i].length; j++)
                if(max < b[i][j]) {
                    max = b[i][j] ;
                }
            System.out.println("Highest number of line "+i+ " is :" + max );
        }
    }
}

A: Try this. Please excuse the errors, but I typed it straight here, no testing. You can get the gist of the solution though.
class Results {
   int order, result;
   //getters and setters

   public int compareTo(Object o) {
      if (o instanceof Results) {
          Results r=(Results) o;
          return(new Integer(result)).compareTo(r.getResult());
      }
      return(0);
   }
}

public int maxNumberInLine (int i) {
            int max = b[i][0];
            for(int j=1; j<b[i].length; j++)
                if(max < b[i][j]) {
                    max = b[i][j] ;
                }
            return(i);
    }

public void getPodium() {
    List<Results> results=new ArrayList<Results>();
    for (int i=0; i<b.length; i++) {
        Results r=new Results();
        r.setOrder(i);
        r.setResults(maxNumberInLine(i));
        results.add(r);
    }
    Collections.sort(results);
    //Now the podium is composed of the first three positions of the arraylist.
}

A: Given int[m][n] b populated with data, I would approach it as follows:
for (int[] a : b)
    Arrays.sort(a); // sort each jumper's results
List<Integer> podium = new ArrayList<>(m); // to hold indexes of podium order
for (int i = 0; i < m; i++)
    podium.add(i);
// sort the indexes based on the highest jump of the jumper at that index
Collections.sort(podium, new Comparator<Integer>() {
    public int compare(Integer o1, Integer o2) {
        // compare the highest jumps in reverse order
        return Integer.compare(b[o2][n - 1], b[o1][n - 1]);
    }
});

Now podium contains the indexes if the jumpers in highest to lowest order of their best jumps. The indexes of 1st, 2nd and 3rd are:
for (Integer i : podium.subList(0, 3))
    System.out.println(i);


text:
Q: How to write a Scala parser for paths? I am a beginner in scala writing a scala parser in which I need to parse a path like this (suppose x is an integer):
/hfds://xxx.xxx.xx.xxx:xxxx/path1/path2/filename1.jpg
I tried the following not sure if I am on the right track:
  def pathIdent: Parser[String] = ("/hdfs""+"""(\d+~\.\d*)"""+ ~("""(u[a-zA-Z0-9])*+"""+"\.[\\'"jpg]"").r

I know it has errors! I really need help on this!

A: You regex looks like it has typos. Try with something like this:
scala> val regex = """^/hfds://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$)""".r
regex: scala.util.matching.Regex = ^/hfds://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$)

Some sample path:
scala> val path = """/hfds://111.222.33.444:5555/path1/path2/filename1.jpg"""
path: String = /hfds://111.222.33.444:5555/path1/path2/filename1.jpg

Then do the matching:
scala> val regex(numbers,afterColon,fullPath,filename) = path
numbers: String = 111.222.33.444
afterColon: String = 5555
fullPath: String = path1/path2/filename1.jpg
filename: String = filename1.jpg

To catch parsing errors you can use pattern matching like this, e.g. parsing the filename:
def parseFilename(path: String): Option[String] = path match {
     case regex(numbers,afterColon,fullPath,filename) => Some(filename)
     case _ => println("parse error");None
}

It will return a Option of that filename:
scala> parseFilename(path)
res0: Option[String] = Some(filename1.jpg)

scala> val badPath="""/hfds://xxx.xxx.xx.xxx:xxxx/path1/path2/filename1.jpg"""
badPath: String = /hfds://xxx.xxx.xx.xxx:xxxx/path1/path2/filename1.jpg

scala> parseFilename(badPath)
parse error
res1: Option[String] = None


text:
Q: Reports against a single SQL Table I'm looking for a freeware program that is pretty much BusinessObjects.
We have 1 SQL table which has loads of data in it that users constantly want reports from. Everytime they ask it's an ad hoc query written just for the moment.
It would be much nicer to be able to give users a solution to create there own reports.  Kind of like BusinessObjects :),  but free and easy to use ofc :D

A: If you're on SQL Server, check out PebbleReports - free (at least now) and you can just ask for a license key.

A: Try JasperReports and its GUI, iReport.


text:
Q: Cannot get my github to branch "fatal error work tree" For this project I am remote from both instances (from home)and using PuTTY with SSH
$school = School
$aws = Amazon web service (instance running Puppet)
$school git created using git init --bare githubdir
branches  config  description  HEAD  hooks  info  objects  refs

$aws git created using
Mkdir githubdir && cd githubdir
git init
git remote add origin studentID@$school:githubdir

*

*I need to push from $school to $aws that is running Puppet to execute code from $school

*I need to submit work from $school
I have successfully pushed from $school to $aws but I wanted to setup branches for version control, however I get fatal error on $school:
[studentID@$school githubdir]$ git status
fatal: This operation must be run in a work tree
[studentID@$school githubdir]$ git branch
* master
  v1
[studentID@$school githubdir]$ git checkout master
fatal: This operation must be run in a work tree
[studentID@$school githubdir]$
[studentID@$school githubdir]$ git log
commit  3abd0c361ee*********
Author: Ben*** <studentID@$school>
Date:   Date

    first commit to the repo test

I can branch/checkout etc fine on $aws:
[awsUser@$aws githubdir]$ git status
# On branch master
nothing to commit, working directory clean
[awsUser@$aws githubdir]$ git branch
* master
[awsUser@$aws githubdir]$ git checkout master
Already on 'master'
[awsUser@$aws githubdir]$ git log
commit  3abd0c361ee*********
Author: Ben*** <studentID@$school>
Date:   Date

    first commit to the repo test
[awsUser@$aws githubdir]$ ls
firstFile
[awsUser@$aws githubdir]$

Have I got my understanding incorrect of flow? I was instructed to set up this way, but it seems that I have been told to write in $aws and push to $school?
Note: You are not giving me a solution to any assignment or graded type questions, this is purely an issues I am having with the environment and possibly the flow of execution?
Thanks!

A:
but it seems that I have been told to write in $aws and push to $school?

Yes: you are supposed to push to a bare repo (ie a repo without a working tree, without the actual files)
That is why you see errors like
[studentID@$school githubdir]$ git status
fatal: This operation must be run in a work tree

A:
Here's a simple model. $school is for storage only. $aws is for production only although it's possible to make changes and commits here. $local is for development. Every contributor can have one or more local repositories.
A work tree is a field where files are checked out and placed. For production and development you need a work tree, so these repoistories are created as non-bare repositories. For storage, the work tree is not necessary and a bare repository is enough. Some commands need a work tree, like git checkout, and others don't, like git log.


text:
Q: How to describe sets derived from same superset in ordinary language? How do we describe two related sets in comparative terms? For example, S1({{x}, {x}} : x ∈ N) and S2({{x}, {x}} : x ∈ N : 0 less than x less than 5)? Do we say that we have imposed a set rule (or set exclusion - not sure what 0 less than x less than 5 is called) on S2 such that S2 is a proper subset of S1 such that it is a set of ordered pairs whose domain and range are both limited to (0,5)? And, do we use the term related sets since that can be confusing with relations? Or, would the term similar sets be better?

A: You are right to describe $S_2$ as a proper subset of set $S_1$.
Every element in $S_2$ is an element of $S_1$, but not vice-versa. So we have $\;S_2\subsetneq S_1$, or alternatively: $S_2 \subset S_1$ and $S_2 \neq S_1$.
In "ordinary" language, we can say that $S_2$ is contained in $S_1$, but $S_1$ is not contained in $S_2$.
The added condition (restriction) that $x$ must meet in $S_2$ is equivalent to specifying $x \in  \{1, 2, 3, 4\}$.
So while $S_1$ is infinite, $S_2$ is finite, given the conditions $x \in \mathbb N$ and $0 \lt x \lt 5$. (Indeed, $S_2$ is the set of exactly $16$ ordered pairs.) So we can further describe the relationship by stating that $S_2$ is a finite subset of $S_1$.


text:
Q: Symfony 4 : $form->getData() returns empty array where same array is filled in $request->request->all() I'm facing a weird issue right now
Here is my code :
$data = [];

$form = $this->createFormBuilder($data, ["allow_extra_fields" => true,])
    ->add("attributes", FormType::class, ["allow_extra_fields" => true,])
    ->add('save', SubmitType::class, ['label' => 'Save'])
    ->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    return new Response("<pre>".print_r($request->request->all(),1).print_r($data,1)."</pre>");
}

As you can see, for debug purposes, I'm displaying the whole $request->request and $form->getData().
Surprisingly, the first one is totally filled with correct information, the second one is empty.
I'm a bit lazy to censor the information in this array (company information) by hand so here is a censored screenshot of the result :

Any idea why the form is not parsed ?
Thanks !

A: the standard symfony Form class stores extra data in one place, the extraData property, which can be accessed via getExtraData(). This is obviously not particularly helpful in the case of sub forms (it would probably have to be called on the sub form then). I assume, the allow_extra_fields flag is primarily meant to prevent the form from erroring out in case of extra data, since nobody in their right mind would use the Form class for no fields (hence no validation, and none of the perks of using the form class in the first place). So your usage is ... "innovative".
The proper way to do it, would be to very well define the structure which attributes can have within your form (optionally with required set to false), solving most of the actual problems people try to solve with forms. - This is what forms are meant to be, an object that recursively handles the fields/sub forms. If you just want to ignore / circumvent that ... well
The improper way would be, to probably teach some form type - via some datamapper or datatransformer or event handling stuff - to handle any arbitrary data provided.
The easiest way to do it: just use $request->request->all() possibly a deserializer.


text:
Q: \emph breaks tabularray when used in collected body content This is a follow up question regarding: How to use DTLforeach (datatool) within a tabularray table?.
Consider this MWE:
\documentclass{scrbook}
\usepackage{datatool,tabularray,xcolor}

\NewDocumentCommand{\crcEntry}{ o m m }{%
  \def\crcDB{#2}%
  \DTLifdbexists{\crcDB}{}{\DTLnewdb{\crcDB}}%
  \DTLnewrow{\crcDB}%
  \IfNoValueTF{#1}{\setkeys{#2}{#3}}{\setkeys{#1}{#3}}%
}

\makeatletter
\define@key{OtherFundingSource}{nameID}{%
  \DTLnewdbentry{\crcDB}{nameID}{#1}
}
\define@key{OtherFundingSource}{periodStart}{\DTLnewdbentry{\crcDB}{periodStart}{#1}}
\define@key{OtherFundingSource}{periodEnd}{\DTLnewdbentry{\crcDB}{periodEnd}{#1}}
\define@key{OtherFundingSource}{projectTitle}{\DTLnewdbentry{\crcDB}{projectTitle}{#1}}
\define@key{OtherFundingSource}{fundingAgency}{\DTLnewdbentry{\crcDB}{fundingAgency}{#1}}
\makeatother

\NewDocumentCommand{\crcOtherFundingSourceTable}{  }{%
  \def\tblrbody{}%
  \DTLforeach*{OtherFundingSource}{%
    \nameID=nameID,%
    \fundingAgency=fundingAgency,%
    \projectTitle=projectTitle,%
    \periodStart=periodStart,%
    \periodEnd=periodEnd%
  }{%
    \edef\tblrbody{\tblrbody
      {\nameID}
      & {x}
      & \projectTitle
      & \periodStart --\periodEnd
      & \fundingAgency\\
    }}%
  \begin{tblr}[%
    expand=\tblrbody,
    label={none},
    entry={none},
    long
    ]{
      colspec = {m{2.6cm}m{.8cm}X[m]m{1.3cm}m{2cm}},
    rowhead = 1,
    row{1} = {
      font={\bfseries},
      halign={c}
    },
  }
  PI %
  & Project %
  & Project title %
  & Funding period %
  & Funding agency\\
  \tblrbody
\end{tblr}}

\begin{document}
\crcEntry{OtherFundingSource}{
  nameID = {NAME},
  projectTitle = {This is my \emph{title}.},
  periodStart = {2020},
  periodEnd = {2023},
  fundingAgency = {LaTeX-funding}
}
\crcOtherFundingSourceTable
\end{document}

It will give me the error:

! Use of \@sDTLforeach doesn't match its definition.
\text@command #1->\edef \reserved@a {
\unexpanded {#1}}\ifx \reserved@a @emp...
l.77 \crcOtherFundingSourceTable

But I can compile when I delete \emph from the content.

A: never use \edef on arbitrary text content.
Use \protected@edef\tblrbody.


text:
Q: Conventional ADSL Modem/router - Internal arrangement Conventionally, when we register for a broadband Internet connection, the ISP provides us with a Modem/router. The modem will have a port for phone-line connection, and (say)4 Ethernet ports. I was just wondering about the internal connections within the router. Which of the following is the correct internal arrangement?

*

*Modem to Router(implicit) to Switch(all 4 slots)

*Modem to Router(all 4 slots)

*Modem to Switch(all 4 slots)

Now, consider another scenario where we get a modem with only one Ethernet port for output. Now if I need to connect 20 PCs to it in order to connect to the Internet, will buying a (say)30-Slot Switch suffice (or) should I buy a router and then connect it to a switch?
P.S. I asked the two questions together because when I asked the first question to a senior, he answered quickly. Then when I asked the second question immediately, he stumbled and told that he was not sure.
P.P.S. My understanding is that the modem which comes with more than one Ethernet output slot, would likely have a router setup internally. And the modem which comes with only one Ethernet slot would not have an internal router, and so it is devoid of any routing capabilities. Am I correct?

A: Devices commonly handed out by ISPs are called modem/routers as they have both a modem AND router built in. In virtual blocks it would be Modem <=> Router <=> Ethernet slots. (<=> denoting traffic possible in both directions.)
In physical hardware, it may be contain in a single chip or broken up into separate devices.
For a router, all data comes into the router from any node, is sorted and sent out on the destination port that the router deems to be the fastest path for the packet. This may be out to the internet or to another node within the network. A router is also a gateway between the internet and a LAN. It carries its own IP address that is usually the gateway IP.
A switch (not including managed switches) are dumb. They are only interested in what the IP address of each node connected to it is and where the gateway is. If a packet comes in and the destination IP address is that of a node connected to it, it will simply pass the information to the appropriate port. If it doesn't know the IP address, then it passes it to the gateway and lets the gateway deal with it. A switch doesn't have an IP address.
Most modems these days are capable of acting as a gateway in a very limited capacity. But typically, a modems job is to do just that (MOdulate signals going out, DEModulate signals coming in).
For your scenario, if you were using a modem/router, you could plug a switch into any of the ports and you'd be on your way. If it was a stand-alone modem, you would need to install a router and then a switch.
Regarding your P.P.S. as I said above, most later model modems have limited capabilities such as DHCP servers and could theoretically be used with just a switch but if you're talking about networking 20 nodes, I would recommend setting up a router to take advantage of router features like port forwarding, firewalls and access control.

A: What is the correct internal arrangement of a modem?
A typical modem will be option 1. The modem will be connected to a router, and the router will then be connected to a switch. The real nitty gritty gets much more complicated that that. For example, some of the Linksys 54G routers, use only a switch with vlan tagging to separate the WAN from the LAN ports.
Connecting 20 PCs to a modem
The modem likely has a built in router, however it is most likely only intended for a small office. It would be much better to connect the modem to a dedicated router, and then that router to a 24 or 48 port switch.
Some great options for a router for a small setup such as yours:
pfsense
clearOS
untangle

A: The answer to your questions is (in general)
An ADSL router with 4 ports (they are routers, not modems), typically contain an ADSL port which is routed to the 4 ethernet ports.   The 4 ethernet ports are typically individually accessible but bridged to behave like a dumb switch in software.    [ I know this because I have reconfigured a number of these devices to have different switches on different VLANS and route between them by changing the software to OpenWRT ].
A single port ADSL router (Its still a router even if its called a modem) routes packets between the ethernet and ADSL interface, but is still routing the packets.  We know this because the device will typically strip off the PPP overhead (ie the PPP bit in PPPoE or PPPoA) and then make that available to ethernet side of the connection.  The devices also often run a DHCP server so they can hand out an IP address.  These devices are generally slightly cut down version of 4 port routers.
An ADSL modem is the bit in the router which actually captures the raw frames.  In earlier times, ADSL routers were internal cards (which could go into a PC) which did this - they did not have routing functionality on board.   Remember too that a "modem" (or "conventional modem" is actually a device used to modulate a digital signal over an analog carrier - typically associated with speeds of 300 to 56400 bits per second and used over the phoneline in days gone by).


text:
Q: Pyshark doesn't free resources I read a .pcap file in python using pyshark. If I read the file multiple times, it seems that pyshark doesn't free resources. The resources are freed only when I close the python program.
import pyshark

def foo():
  for i in range(100):
      p = pyshark.FileCapture('/tmp/tmp.pcap')
  return

foo()
sleep(100)

Before the program starts
konstantin@linux-ks:~/Programs/skype-4.3.0.37> cat /proc/net/sockstat
sockets: used 945
TCP: inuse 12 orphan 0 tw 0 alloc 24 mem 0
UDP: inuse 14 mem 4

When the program runs
konstantin@linux-ks:~/Programs/skype-4.3.0.37> cat /proc/net/sockstat
sockets: used 1154
TCP: inuse 12 orphan 0 tw 0 alloc 24 mem 1
UDP: inuse 14 mem 4

The only way I found to mitigate the problem isn't crisp - simply increase the open file limit in the system so the limit is hardly reached.
/etc/security/limits.conf:

*               soft    nofile            10000
*               hard    nofile            10000

Could you help me to understand the reason of such puzzling behavior?
I suppose that pyshark or some package that pyshark uses open some file but doesn't close it properly.


text:
Q: Convergence in distribution of independent and uniform r.v.'s This is the text of the problem: Let $\left(X_{j}\right)_{j\ \geq\ 1}$ be independent and let $X_{j}$ have the uniform distribution on $\left(-j,j\right)$. Show that $\lim_{n \to \infty}{S_{n} \over n^{3/2}}=Z$ In distribution, where
$\mathcal{L}\left(Z\right) = N\left(0,\frac{1}{9}\right)$.
We are given the following hint: Show that the characteristic function of $X_{j}$ is $\varphi_{X_{j}}\left(u\right)=\sin\left(uj\right)/\left(uj\right)$; compute $\varphi_{S_{n}}\left(u\right)$, then $\varphi_{S_{n}/n^{3/2}}\left(u\right)$, and prove that the limit is $exp\left(-u^{2}/18\right)$ by using $\sum_{j=1}^{n}j^{2}=n\left(n + 1\right)\left(2n + 1\right)/6$.
Now, my difficulty is the following: I have shown that
$\varphi_{S_{n}/n^{3/2}}\left(u\right)=\prod_{j=1}^{n}\frac{n^{3/2}}{uj}\sin\left(\frac{uj}{n^{3/2}}\right)$. My next step was that I took $\ln$ of both sides, then used a Maclaurin expansion for $\sin\left(\frac{uj}{n^{3/2}}\right)$, and simplified to obtain that $\ln \varphi_{S_{n}/n^{3/2}}(u)=\sum_{j=1}^{n}\ln\left(1-\frac{1}{3!}\frac{u^{2}j^{2}}{n^{3}}+o\left(\frac{j^{4}}{n^{6}}\right)\right)$ (my little oh notation might be slightly off). Now, eventually, I want to be left just with a $j^{2}$ term, so that I can use the remaining part of the hint, simplify, and end up with $-\frac{u^{2}}{18}$. Getting there, though is the problem. I seem to be missing something technical. If somebody could fill in the steps between $\ln \varphi_{S_{n}/n^{3/2}}(u)=\sum_{j=1}^{n}\ln\left(1-\frac{1}{3!}\frac{u^{2}j^{2}}{n^{3}}+o\left(\frac{j^{4}}{n^{6}}\right)\right)$ and $-\frac{u^{2}}{18}$ in detail, that would be great. Or if what I did is the wrong approach, tell me what the right approach would be.
Thank you very much in advance!

A: We can avoid a further use of Taylor expansion using the inequality
$$-x-\frac{x^2}2\leqslant \ln(1-x)\leqslant -x,\quad 0\leqslant x\lt 1.$$
The notation "o" can be replaced by an integral remainder, thought it's not a problem.


text:
Q: Nested REGEX capture I am using a data format like
{item 1 | item 2 | item 3}

to split items into an array for further processing.  This Regex pattern works fine for that:
`{([^}]+)}`

but I'd like to nest the groups like this
{This is {item 1 | item 2 | item 3} | This is not {item 5 | item 6 | item 7 }}

I've tried several things with no luck.  Is there a way to match the most inner items first then work outwards from there?

A: If you want to find only the most nested arrays:
{([^{}]*)}

If you want to find all outer arrays you can do like this (note that it will work only if it is PCRE)
{((?(?={)(?R)|[^}])*)}


text:
Q: Is it possible to register the rest endpoints in MarkLogic Query console Is it possible to register the rest endpoints in MarkLogic Query Console using XQuery?

A: In Query Console, you can use the xdmp.http*() functions to call the REST API endpoints on the same server.
Hoping that helps,

A: I'm not sure what you mean by "register". Are you talking about creating a new REST API extension? If so, yes, you can, using the xdmp:http-* functions, as @ehennum noted. However, taking that approach will lead to one-off solutions and I wouldn't recommend it. You'd be much better off using ml-gradle, a tool specifically for deploying MarkLogic code and configuration.


text:
Q: Any way to stream a file in linux I have a terminal output which I'd like to be available to several users
currently something like:
command > /var/logs

for the input, and:
watch tail -30 /var/logs

for the input terminals.
however this is undesirable because watch only polls as opposed to outputting when there is updates and tail doesn't allow scrollback.

A: You want a program like screen or tmux.

A: Two problems you posit:

watch only polls as opposed to outputting when there are updates

tail -f does not poll. As of version 7.5 of GNU Coreutils, tail -f will use the Linux kernel's inotify interface to receive signals from the kernel indicating that the file has been modified. If you don't use GNU Coreutils, or use a version older than 7.5 for some reason, it will poll once per second. It probably also polls on non-Linux POSIX operating systems (BSD, Solaris, etc) but you would have to research it on a case-by-case basis: some of these OSes use GNU Coreutils but the kernel doesn't support inotify; some of them don't use GNU Coreutils to implement tail at all.

tail doesn't allow scrollback

The less command is specifically designed to buffer data from stdin (e.g. from the tail command) and allow you to scroll back and forth. The buffer is not unlimited, but you can use command line options to increase or decrease the buffer as well as modify how long the buffer is for back-scroll and forward-scroll.
So something like, maybe,
tail -f /var/logs | less
would allow you to keep a scrollback buffer of the logs without polling (tail just sits there idle consuming no CPU until the kernel tosses it a signal letting it know that the file has been modified).
If you need multiple users to be able to read from the same buffer, you could just run tail -f /var/logs within a screen session. My original answer didn't take into account that you want to run this so that multiple users can see the same log data at the same time. @Let_Me_Be mentioned screen and then it occurred to me that that's probably your best bet.
So putting my solution and @Let_Me_Be's solution together:
screen -mdS logview -- tail -f /var/logs
Warning: Untested. Please edit if it's wrong. But I think we're close on the trail to a proper solution here.
Now you just need to have screen in multi-user mode. This is a little complicated, so I'll let this site speak for itself. The gist is that you have to add multiuser on to your ~/.screenrc file. Also see the Common Problems at the bottom of that link.
Now, for users to view the log:
screen -rS logview
should do it.


text:
Q: Unexpected EOF exception I am trying to read/write an ArrayList of custom (serializable) objects to a file. It is working as expected, except for one thing: I am getting an EOFexception when reading the file. Here is my code:
class FileHandler {
    private final String FILENAME = "storage.txt";

    ArrayList<Plane> readFromFile(Context context) {
        ArrayList<Plane> returnList = new ArrayList<>();
        Plane temp;

        try {
            FileInputStream fileInputStream = context.openFileInput(FILENAME);
            ObjectInputStream objectInStream = new ObjectInputStream(fileInputStream);

            while ((temp = (Plane)objectInStream.readObject()) != null) {
                returnList.add(temp);
            }

            objectInStream.close();
        }
        catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return returnList;
    }

    void writeToFile(ArrayList<Plane> inData, Context context) {
        FileOutputStream fileOutputStream;
        ObjectOutputStream outputStream;

        try {
            fileOutputStream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
            outputStream = new ObjectOutputStream(fileOutputStream);

            for (Plane p: inData) {
                outputStream.writeObject(p);
            }

            outputStream.close();
            fileOutputStream.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The file gets written and read as intended, but I'm getting an EOF exception when reading the file. No idea why. I thought my while-loop would make sure that couldn't happen?

*

*Why am I getting this exception?

*Plane is serializable. Is it possible to read and write to file if I changed Plane to be parcable instead? (How?)

A:
Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions. If there is no corresponding writeObject method, then the end of default serialized data marks the end of the allotted data.

This is what I found on https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html
The last attempt to read data occurs when there is no data. The while-loop condition doesn't really check whether there is data to read or not. It tries to read it regardless.


text:
Q: How to nest JSON data? I have a json object and I need to nest it so I can work with  it much better.
my json looks as follow:
[
  {
    "lat": null,
    "lng": null,
    "locationId": null
  },{
    "lat": null,
    "lng": null,
    "locationId": null
  }
]

and I need to wrap it nest it and have the result as:
{
  "number_returned": 2, //returns result_list count
  "data": {
    "result_list": [
      {
        "lat": null,
        "lng": null,
        "locationId": null
      },
      {
        "lat": null,
        "lng": null,
        "locationId": null
      }
    ]
  }
}

A: I assume the simple idea (in pseudo code) is to do this:
new_json = {
    "number_returned": old_json.length,
    "data": {
        "result_list": old_json
    }
}

assuming that old_json is a string containing JSON you have,
and new_json will be string with JSON you want to have;
the javascript to do all you need will look like this:
var obj = JSON.parse(old_json);
var result_obj = {
    "number_returned": obj.length,
    "data": {
        "result_list": obj
    }
}
var new_json = JSON.stringify(result_obj);


text:
Q: MARQUARDT en Regresion No Lineal en R estaba intentando ajustar la siguiente ecuación (G~G0*exp(-(b12)*t^-(b13))/exp(-(b12)*t0^-(b13)) por regresión no lineal en R, a partir del siguiente script de SAS:
proc model data=five method=MARQUARDT maxiter=1000

Mi duda surge en como ajustar dicha ecuación con el método MARQUARDT.
Hasta ahora lo que hice en R fue lo siguiente:
library("nlstools")
nls=nls(G~G0*exp(-(b12)*t^-(b13))/exp(-(b12)*t0^-(b13)),data=ajuste,start=list(b12=3.405398, b13=0.40278))
summary(nls)
resi=nlsResiduals(nls)
plot(resi)

Sin embargo, nose como especificar el algoritmo de MARQUARDT, porque el que viene por defecto en R es el de Gauss -newton en la función nls. Me pueden ayudar o tengo que usar otra librería?
Muchas gracias!!

A: Puedes utilizar la librería minpack.lm y comparar los resultados con vários métodos presentes en optimx
#preliminares, datos y librerías

library("nlstools")
library(optimx)
library(minpack.lm)

G0=10
t0=2
t=2:20
b12=3.405398
b13=0.40278
G=G0*exp(-(b12)*t^-(b13))/exp(-(b12)*t0^-(b13))+rnorm(19,0,0.2)

#Funciones

Gfun=function(x,t,G0,t0){
  Gc=G0*exp(-(x[1])*t^-(x[2]))/exp(-(x[1])*t0^-(x[2]))
  return(Gc)
}

Gresid <- function(parS, GObs, t,G0,t0) { # Resíduos
  GObs-Gfun(parS,t=t,G0=G0,t0=t0)
}

parStart=c(.2,.4)

ssqfun(parStart,G,t,G0,t0) # parS=parStart  GObs=G

#Levenberg-Marquardt

nls.out <- nls.lm(par=parStart, fn = Gresid, GObs = G, t = t,G0=G0,t0=t0,
                  control = nls.lm.control(nprint=1,
                                           ftol = .Machine$double.eps,
                                           ptol = .Machine$double.eps,
                                           maxfev=10000, maxiter = 500))
summary(nls.out)

ssqfun <- function(parS, GObs, t,G0,t0) { # suma de resíduos al cuadrado
    sum((GObs-Gfun(parS,t=t,G0=G0,t0=t0))^2)
}

res<-optimx(parStart,fn=ssqfun,
             control=list(all.methods=TRUE, save.failures=TRUE, trace=0), t=t,G0=G0,t0=t0,G=G)
res

El resultado será algo así:
# > summary(nls.out)
#
# Parameters:
#   Estimate Std. Error t value Pr(>|t|)
# [1,] 3.353064   0.018053  185.74   <2e-16 ***
# [2,] 0.419175   0.006355   65.96   <2e-16 ***
#   ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
# Residual standard error: 0.1538 on 17 degrees of freedom
#
# No todos optimizan -> convcode  diferente de 0
# > res
#                p1        p2         value       fevals gevals niter convcode  kkt1  kkt2 xtimes
# BFGS         3.352734 0.4192914  4.023068e-01    197     47    NA        0 FALSE  TRUE   0.00
# CG          15.433766 3.5751572  1.169458e+03    503    101    NA        1 FALSE FALSE   0.00
# Nelder-Mead  3.352300 0.4194201  4.023563e-01     97     NA    NA        0 FALSE  TRUE   0.00
# L-BFGS-B     3.352734 0.4192921  4.023069e-01     45     45    NA        0 FALSE  TRUE   0.00
# nlm          5.101472 0.1906924  3.428862e+01     NA     NA   100        1 FALSE  TRUE   0.01
# nlminb       3.353064 0.4191751  4.022989e-01     35     51    22        0  TRUE  TRUE   0.00
# spg          3.353068 0.4191737  4.022989e-01    108     NA    93        0 FALSE  TRUE   0.16
# ucminf       3.353006 0.4191950  4.022991e-01     26     26    NA        0 FALSE  TRUE   0.00
# Rcgmin             NA        NA 8.988466e+307     NA     NA    NA     9999    NA    NA   0.00
# Rvmmin             NA        NA 8.988466e+307     NA     NA    NA     9999    NA    NA   0.00
# newuoa       3.353064 0.4191753  4.022989e-01    147     NA    NA        0  TRUE  TRUE   0.00
# bobyqa       3.353064 0.4191753  4.022989e-01    245     NA    NA        0  TRUE  TRUE   0.00
# nmkb         3.353022 0.4191850  4.022997e-01    154     NA    NA        0 FALSE  TRUE   0.00
# hjkb         0.200000 0.4000000  1.200466e+04      1     NA     0     9999    NA    NA   0.00


text:
Q: How to start an activity which is in Android? I want to start auto reject list with intent. Like this code:
            Intent intent = new Intent("WHICH SHOULD I WRITE CODE IN HERE?");
            startActivity(intent);

How can I this?

A: If the first activity is MainActivity and the second activity is SecondActivity:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);


text:
Q: Android MMS Example I tried to follow this answer about sending MMS through code.
However, I stopped when he start talking about BroadCastRecivers and Android git and not providing the code. I really get lost with this. It was very straight at the beginning but it becomes so complicated after that.
Can any one explain the missing code in that answer or provide it if it is exist ?
Thanks a lot

A: To those who might be interested:
MMS Functionality is a bit unreliable, not well-documented feature in Android. So, the existed solutions will not work always. You can't depend on them, yet.

A: In order to send MMS on Android, you can alternatively use a commercial MMS SDK instead of using the internal stack.
There's one from Winwap here that let's you send and receive MMS messages with simple functions, like the send-example from their docs:
1. Initialize the API by calling the mmss_init function
2. Connect to the HTTP Proxy or WAP Gateway using the mmss_connect function
3. Create MMS message of type SEND_REQUEST_TYPE by calling mms_message_create function
4. Add MMS headers using mms_set_header_str, mms_set_header_encstr or mms_set_header_long functions. Mandatory headers TRANSACTION_ID, FROM and CONTENT_TYPE shall be set. Also at least one of the headers TO, CC or BCC shall be set. Other headers suitable for this type of message are optional
5. Add content to MMS Message by the help of mms_add_content function
6. Call the mmss_send_message function
7. Destroy MMS message using mms_message_destroy function
8. Disconnect from the HTTP Proxy or WAP Gateway using the mmss_disconnect function
9. Finalize the API by calling the mmss_fini function

The downside is, it's a commercial product not available for free.

A: I do not have experience in this type of problem but maybe this will help you out a bit:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "some text");
String url = "\\sdcard\\potrait.PNG";
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
sendIntent.setType("image/png");
startActivity(sendIntent);

This is a copy from here.
This is another example.


text:
Q: Collect IMU data from Oculus Quest 2 while using it on another app I have searched a lot for this but I was not lucky enough to find a reasonable solution.
I am trying to collect the raw data generated by the Oculus Quest 2 sensors, while using it with different applications (such as Beat Saber, Forklift Simulator, ecc.).
This last step is very important, otherwise I guess that the answer would simply be "To access the sensors you should Unity/Unreal Engine and create your own app". Am I right?
Is it possible to do what I am trying to do? If so, is there a way to do this without creating an application from scratch (maybe some third-party open source software publicly released on Github). Thanks a lot for any help.


text:
Q: Processing include/require directives in PHP Background:
I'm building an automated test framework for a PHP application, and I need a way to efficiently "stub out" classes which encapsulate communication with external systems. For example, when testing class X that uses DB wrapper class Y, I would like to be able to "swap in" a "fake" version of class Y while running automated tests on class X (this way I don't have to do full setup + teardown of the state of the real DB as part of the test).
Problem:
PHP allows "conditional includes", which means basically that include/require directives are handled as part of processing the "main" logic of a file, e.g.:
if (condition) {
    require_once('path/to/file');
}

The problem is that I can't figure out what happens when the "main" logic of the included file calls "return". Are all of the objects (defines, classes, functions, etc.) in the included file imported into the file which calls include/require? Or does processing stop with the return?
Example:
Consider these three files:
A.inc
define('MOCK_Z', true);
require_once('Z.inc');
class Z {
    public function foo() {
        print "This is foo() from a local version of class Z.\n";
    }
}
$a = new Z();
$a->foo();

B.inc
define('MOCK_Z', true);
require_once('Z.inc');
$a = new Z();
$a->foo();

Z.inc
if (defined ('MOCK_Z')) {
    return true;
}
class Z {
    function foo() {
        print "This is foo() from the original version of class Z.\n";
    }
}

I observe the following behavior:
$ php A.inc
> This is foo() from a local version of class Z.

$ php B.inc
> This is foo() from the original version of class Z.

Why This is Strange:
If require_once() included all of the defined code objects, then "php A.inc" ought to complain with a message like
Fatal error: Cannot redeclare class Z

And if require_once() included only the defined code objects up to "return", then "php B.inc" ought to complain with a message like:
Fatal error: Class 'Z' not found

Question:
Can anyone explain exactly what PHP is doing, here? It actually matters to me because I need a robust idiom for handling includes for "mocked" classes.

A: According to php.net, if you use a return statement, it'll return execution to script that called it. Which means, require_once will stop executing, but the overall script will keep running. Also, examples on php.net show that if you return a variable within an included file, then you can do something like $foo = require_once('myfile.php'); and $foo will contain the returned value from the included file. If you don't return anything, then $foo is 1 to show that require_once was successful. Read this for more examples.
And I don't see anything on php.net that says anything specifically about how the php interpreter will parse included statements, but your testing shows that it first resolves class definitions before executing code in-line.
UPDATE
I added some tests as well, by modifying Z.inc as follows:
    $test = new Z();
    echo $test->foo();
    if (defined ('MOCK_Z')) {
        return true;
    }
    class Z {
        function foo() {
            print "This is foo() from the original version of class Z.\n";
        }
    }

And then tested on the command line as follows:
    %> php A.inc
    => This is foo() from a local version of class Z.
       This is foo() from a local version of class Z.

    %> php B.inc
    => This is foo() from the original version of class Z.
       This is foo() from the original version of class Z.

Obviously, name hoisting is happening here, but the question remaining is why there are no complaints about re-declarations?
UPDATE
So, I tried to declare class Z twice in A.inc and I got the fatal error, but when I tried to declare it twice in Z.inc, I didn't get an error. This leads me to believe that the php interpreter will return execution to the file that did the including when a fatal runtime error occurs in an included file. That is why A.inc did not use Z.inc's class definition. It was never put into the environment, because it caused a fatal error, returning execution back to A.inc.
UPDATE
I tried the die(); statement in Z.inc, and it actually does stop all execution. So, if one of your included scripts has a die statement, then you will kill your testing.

A: Okay so behavior of the return statement in PHP included files is to return control to the parent in execution.  That means the classes definitions are parsed and accessible during the compile phase.  For instance, if you change the above to the following
a.php:
<?php
define('MOCK_Z', true);

require_once('z.php');

class Z {
    public function foo() {
        print "This is foo() from a local version of class Z in a.php\n";
    }
}

$a = new Z();
$a->foo();

?>

b.php:
<?php

    define('MOCK_Z', true);
    require_once('z.php');
    $a = new Z();
    $a->foo();

?>

z.php:
<?php

if (defined ('MOCK_Z')) {
    echo "MOCK_Z definition found, returning\n";
    return false;
}

echo "MOCK_Z definition not found defining class Z\n";

class X { syntax error here ; }

class Z {
    function foo() {
        print "This is foo() from the original version of class Z.\n";
    }
}

?>

then php a.php and php b.php will both die with syntax errors; which indicates that the return behavior is not evaluated during compile phase!
So this is how you go around it:
z.php:
<?php

$z_source = "z-real.inc";

if ( defined(MOCK_Z) ) {
    $z_source = "z-mock.inc";
}

include_once($z_source);

?>

z-real.inc:
<?php
class Z {
    function foo() {
            print "This is foo() from the z-real.inc.\n";
        }
}

?>

z-mock.inc:
<?php
class Z {
    function foo() {
            print "This is foo() from the z-mock.inc.\n";
        }
}

?>

Now the inclusion is determined at runtime :^) because the decision is not made until $z_source value is evaluated by the engine.
Now you get desired behavior, namely:
php a.php gives:

Fatal error: Cannot redeclare class Z in /Users/masud/z-real.inc on
  line 2

and php b.php gives:

This is foo() from the z-real.inc.

Of course you can do this directly in a.php or b.php but doing the double indirection may be useful ...
NOTE
Having SAID all of this, of course this is a terrible way to build stubs hehe for unit-testing or for any other purpose :-) ... but that's beyond the scope of this question so I shall leave it to your good devices.
Hope this helps.

A: It looks like the answer is that class declarations are compile-time, but duplicate class definition errors are run-time at the point in the code that the class is declared.  The first time a class definition is in a parsed block, it is immediately made available for use; by returning from an included file early, you aren't preventing class declaration, but you are bailing out before the error is thrown.
For example, here are a bunch of class definitions for Z:
$ cat A.php
<?php
error_reporting(-1);

$init_classlist = get_declared_classes();
require_once("Z.php");
var_dump(array_diff(get_declared_classes(), $init_classlist));

class Z {
  function test() {
    print "Modified Z from A.php.\n";
  }
}

$z = new Z();
$z->test();

return;

class Z {
  function test() {
    print "Another Z from A.php.\n";
  }
}

$ cat Z.php
<?php
echo "In Z.php!\n";
return;

class Z {
  function test() {
    print "Original Z.\n";
  }
}

When A.php is called, the following is produced:
In Z.php!
array(0) {
}
Modified Z from A.php.

This shows that the declared classes don't change upon entering Z.php - the Z class is already declared by A.php further down the file.  However, Z.php never gets a change to complain about the duplicate definition due to the return before the class declaration.  Similarly, A.php doesn't get a chance to complain about the second definition in the same file because it also returns before the second definition is reached.
Conversely, removing the first return; in Z.php instead produces:
In Z.php!

Fatal error: Cannot redeclare class Z in Z.php on line 4

By simply not returning early from Z.php, we reach the class declaration, which has a chance to produce its run-time error.
In summary: class declaration is compile-time, but duplicate definition errors are run-time at the point the class declaration appears in the code.
(Of course, having not confirmed this with the PHP internals, it might be doing something completely different, but the behavior is consistent with my description above. Tested in PHP 5.5.14.)

A: This is the closest thing I could find in the manual:

If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return().

And this is true regarding functions. If you define the same function in A and Z (after the return) with PHP 5, you'll get a fatal error as you expect.
However, classes seem to fall back to PHP 4 behavior, where it doesn't complain about functions defined after return. To me this seems like a bug, but I don't see where the documentation says what should happen with classes.

A: I've thought about this for a while now, and nobody has been able to point me to a clear and consistent explanation for the way PHP (up to 5.3 anyway) processes includes.
I conclude that it would be better to avoid this issue entirely and achieve control over "test double" class substitution via autoloading:
spl-autoload-register
In other words, replace the includes at the top of each PHP file with a require_once() which "bootstraps" a class which defines the logic for autoloading. And when writing automated tests, "inject" alternative autoloading logic for the classes to be "mocked" at the top of each test script.
It will naturally require a good deal of effort to modify existing code to follow this approach, but the effort appears to be worthwhile both to improve testability and to reduce the total number of lines in the codebase.