OpenLiberty - VisualVM

Question: Did anyone tried working with OpenLiberty and VisualVM? I was trying with IBM Liberty 18.104.22.168 and JDK 1.8, i get this exception when using CPU Profiling.

An exception occurred: java.lang.NoClassDefFoundError: org/graalvm/visualvm/lib/jfluid/server/ProfilerRuntimeCPUFullInstr
      at com.ibm.ws.util.WSThreadLocal.get(WSThreadLocal.java:69)
      at [internal classes]
Answer: Added <code>-Dorg.osgi.framework.bootdelegation=org.graalvm.*</code> to Liberty Server its working now.
For more info refer:
https://github.com/oracle/visualvm/issues/209
Comment: The only way this worked is by added this to my bootstrap.properties.  It did not work when I made this a JVM arg when running the jar or adding it to my jvm.options file

OpenLiberty - VisualVM


Why does database of db2 HADR standby server deactivate automatically?

Question: Im trying to configure SAP HADR with the primary and standby server. Configurations seems to be ok but the database of standby server deactivates automatically. When i run the command db2 activate database in the standby server it will successfully activated but after a few seconds database gets deactivated again. And with this scenario, nearsync of logs is not consistent. Please advice what would be the possible cause of deactivation of database.
SAP ECC6.0 DB6 9.1
Answer: You don't activate the database on the standby DB. The standby DB is always is rollforward mode. You can check this by typing db2top and them u.
Regards


Induced nontrivial homomorphism?

Question: I am caught up in a minor detail on a qualifying exam problem I am doing:
Show that there are no injective continuous functions $f: \Bbb R^n \to \Bbb R^2$ , $n>2$ with $f(0)=0$.
So far I have considered the punctured spaces at the origin, and so the problem changes to:
Show that there are no continuous injections from $\Bbb {R^n}-\{0\} \to \Bbb {R^2}-\{0\}$ for $n>2$.
To do this I want to look at the induced homomorphism between fundamental groups and say that it is nontrivial since the original function is injective. Can I say this? If so, why?
Comment: `\{0\}` ${}{}{}{}$
Answer: A continuous injective map doesn't necessarily induce an injective homomorphism on fundamental groups. Consider the embedding $S^1 \hookrightarrow \Bbb R^2$ for a counterexample.
What you need is the Borsuk–Ulam theorem. $f$ restricts to a continuous map $S^2 \to \Bbb R^2$, and this map cannot be injective by the theorem.
Comment: Nice proof but the fact that they said to assume $f(0)=0$ makes me think they had something else in mind.
Comment: @Seth That assumption is superfluous. You can always compose $f$ with a homeomorphism $\Bbb R^2 \to \Bbb R^2$ that maps $f(0)$ to $0$.
Comment: They had something else in mind. Up until the last line was essentially given in a hint. I forgot to mention that.
Comment: @AymanHourieh Yes, obviously it is a superfluous assumption.  I just meant that they probably added it to the statement because they thought that it would simplify the notation, which means they probably expected a proof using fundamental group somehow.

Induced nontrivial homomorphism?


NSSearchField calls action twice on clear

Question: I have a very simple NSSearchField setup. I want whenever user types in a character, if within a small time frame, user types no more inputs, it automatically calls action.
I connected NSSearchField's action from the interface builder to an IBAction in some other objects.
Problem I am facing: for some reason, when user clicks the close button or presses escape key to clear the search filed, the action gets triggered twice. Does anyone know how to avoid action getting called twice on clear?
#import "ViewController.h"

@implementation ViewController

- (IBAction) searchingStarts:(id)sender
{
    printf("action is triggered\n");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];
    // Update the view, if already loaded.
}

@end

You can simply drag a NSSearchField to storyboard and link its action to searchingStarts.
Here's my setup: https://github.com/YLiLarry/nssearchfield-bug
Comment: I start to think this is a bug..
Answer: I think you should use delegate to avoid this happen.
- (void)searchFieldDidEndSearching:(NSSearchField *)sender

Answer: The action is triggered by the button and because the value changes. If the action can't handle being called multiple times, set the delegate of the search field and implement NSSearchFieldDelegate methods
- (void)searchFieldDidStartSearching:(NSSearchField *)sender;

and
- (void)searchFieldDidEndSearching:(NSSearchField *)sender;

Answer: Swift version that worked for me:
Implement NSSearchFieldDelegate methods in your class:
extension MyClassName: NSSearchFieldDelegate {

    func searchFieldDidStartSearching(_ sender: NSSearchField) {
        disableFilter = false
    }

    func searchFieldDidEndSearching(_ sender: NSSearchField) {
        disableFilter = false
        // TODO: perform cleanup operations if necessary...
    }
}

Add disableFilter as a variable to your class:
class MyClassName: ViewController  {
...
/**
 Used to determine if the cancel button of the NSSearchField was pressed and
 take steps to avoid the NSSearchField from sending action messages.
*/
var disableFilter: Bool = false
...
}

Create the search function:
@objc
func search(_ sender: Any) {
    if disableFilter {
        return
    }

    // TODO: add your search implementation here...
}

Assign an action to the search field object, if done in IB ignore this:
override func viewDidLoad() {
    searchField.action = #selector(search(_:))
}

Answer: Here's a formula in a gentleman's language, for a case where my document view controller actually dispatches to child view controllers—I have a modular window constructions consisting of many tabs and split view containers.
@implementation MyDocViewController(search)
#pragma mark - NSSearchFieldDelegate

- (void) searchFieldDidStartSearching: (NSSearchField*) sender
{
    for (NSViewController* aController in self.childViewControllers)
    {
        if ([aController conformsToProtocol: @protocol(NSSearchFieldDelegate)])
        {
            [(NSViewController<NSSearchFieldDelegate>*) aController searchFieldDidStartSearching: sender];
        }
    }
}

- (void) searchFieldDidEndSearching: (NSSearchField*) sender
{
     for (NSViewController* aController in self.childViewControllers)
    {
        if ([aController conformsToProtocol: @protocol(NSSearchFieldDelegate)])
        {
            [(NSViewController<NSSearchFieldDelegate>*) aController searchFieldDidEndSearching: sender];
        }
    }
}
@end

In the storyboard, the search field delegate is linked to the above document view controller. There's no direct storyboard access to the sub components assembled in the window and this is why I dispatch to the child view controllers.
In one of the child controller, there will be the same protocol declarations and there will be a final search operation being done. Note that this works if only one child view controller actually sets itself as the target of the search field.
@implementation MyChildViewController(search)
#pragma mark - NSSearchFieldDelegate

- (IBAction) onSearch: (NSSearchField*) sender
{
    NSLog(@"Filtering on %@", sender.stringValue);

    [self rebuildNodes: sender.stringValue];
}

- (void) searchFieldDidStartSearching: (NSSearchField*) sender
{
    [sender setTarget: self];
    [sender setAction: @selector(onSearch:)];
    [self rebuildNodes: sender.stringValue];
}

- (void) searchFieldDidEndSearching: (NSSearchField*) sender
{
    [sender setTarget: nil];
    [sender setAction: nil];
    [self rebuildNodes: nil];
}
@end

@end
In my case, searches are wicked fast. In a CoreData -based object storage document structure, a search completes into a drawn graph highlighting objects in milliseconds, so I can actually search on-the-fly and reset as user enters new search terms.
If you have lengthy search cycles, it might be a good idea to invalidate a previous search timer when you receive new search terms and fire up a new timer (say 1sec) allowing the user to complete a meaningful search term before firing up.


How to Pass a Variable from Child to Parent

Question: I have a react function. This function returns a search bar. When the search bar is changed a variable called esQueryDsl is set. I want to pass this variable back to the parent and also render the search bar.
Child:
export const SearchBar2 = (props) => {
  const [query, setQuery] = useState(initialQuery);
  const [error, setError] = useState(null);

  const onChange = ({ query, error }) => {
    if (error) {
      console.log(error);
      setError(error);
    } else {
      console.log("query");
      setError(null);
      setQuery(query);
    }
    let esQueryDsl;

    try {
      esQueryDsl = EuiSearchBar.Query.toESQuery(query);
    } catch (e) {
      esQueryDsl = e.toString();
    }
  };

  const renderSearch = () => {
    return (
      <EuiSearchBar
        defaultQuery={initialQuery}
        box={{
          placeholder: 'search'
        }}
        onChange={onChange}
      />
    );
  };

  return (
    <Fragment>
      <EuiFlexGroup alignItems="center">
        <EuiFlexItem>{renderSearch()}</EuiFlexItem>
      </EuiFlexGroup>
    </Fragment>
  );
};

Parent:
class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      query: EuiSearchBar.Query.MATCH_ALL
    }
    this.handleSearchFill = this.handleSearchFill.bind(this);
  }

  handleSearchFill = (data) =>{
    console.log('handleSearchFill')
    this.setState({query:data})
  }

  render() {
    return (
      <>
        <EuiPage>
            <SearchBar2 onChange={this.handleSearchFill}/>
        </EuiPage>
      </>
    );}
}

When the search state is changed "query" gets logged to the console but "handleSearchFill" does not.
My intention is to pass the esQueryDsl back to the parent. Then pass it to a different child to render the results.
I was trying to refer to this question.
Comment: You could put the state in the parent component, and pass the updater function to the child component.
Comment: Have you considered lifting the state?
Comment: I think you're suggesting moving the onChange code from the child to the parent. The problem I have is that react doesn't allow me to use useState() in a class component.
Comment: just add props.onChange(esQueryDsl) after `esQueryDsl = EuiSearchBar.Query.toESQuery(query);`
Answer: Instead of defining a new state variable in the child. Use the state of the parent and pass a function that manipulates this state to the child. Now, whenever the query changes in the child, use the function passed as props to change the parent state. This is called lifting up the state.
From the code, I see that you've already done that
Changes:
Add this line in the try block in your onChange function
props.onChange(esQueryDsl);

Also, I don't think, the state query is useful in the child component.

To use this state in another child of the same parent, just pass this state (query) as a prop to that child.

Ex:
// In parent
return (
        <EuiPage>
            <SearchBar2 onChange={this.handleSearchFill}/>
            <SecondChild query={this.state.query}/>
        </EuiPage>
);


Java how to use a double or a string?

Question: Alright so I'm trying to get the user to input either the word "random" or a number (0.01) for a sales tax and my prompt can only use either keybd.next() or keybd.nextDouble() so how would I easily do this?
public void calculateSalesReceipt(){
    System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: ");
    double tax = keybd.nextDouble();
    if(tax < 0){
        System.out.println("You must enter a value equal to or greater than 0!");
    }else{
    getFinalPricePreTax();
    total = total;
    taxcost = total * tax;
    double finaltotal = total * taxcost;
    System.out.println("Sales Receipt");
    System.out.println("-------------");
    for(Item currentProduct : shoppingBag){
        System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost());
    }
    System.out.println("Total cost: $" + total);
    System.out.println("Total tax: $" + taxcost);
    System.out.println("Total cost with tax: $" + finaltotal);
}

Thanks
Answer: Assuming keybd is a Scanner
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
You need to use hasNextDouble() to determine if it's a double or not and then act accordingly.
Option B (though you say your requirements exclude this) is to simply read it as a String then do the conversion afterward with Double.valueOf(String) or Double.parseString(String) static methods and catching the NumberFormatException to determine validity.
Edit based on comments from OP:
System.out.println("Enter the sales tax ... blah blah");
if (keybd.hasNextDouble())
{
    double tax = keybd.nextDouble();
    // Do double stuff
}
else
{
   // Get String and Do string stuff
}

Comment: This is helpful but I don't know how to use it lol.  Yes, I am using a scanner
Comment: Don't know how to use ... what?
Comment: I've edited to show you, but I would be remis not to recommend a basic intro to programming book or at the very least recommend you go through the Java tutorials provided by Oracle. Not understanding how to use classes and methods is beyond the scope of StackOverflow.
Comment: This works the first time, but if i run it again, it just skips the asking part and calculates a random number?
Answer: You can use Double.parseDouble(String) to convert a string value to a double. If the string does not represent a double value, a NumberFormatException will be thrown.
double d;
if ("random".equals(string)) {
  d = 4.0; // random
} else {
  try {
    d = Double.parseDouble(string);
  } catch (NumberFormatException e) {
    // !
  }
}

Answer: You can use keybd.next() to grab the token as a string.  Then check if its a double.
Sample code:
String input= keybd.next();
try{
  Double input= Double.parseDouble(input);
  //execute code with double variable

} catch (ParseException ex){
  //call string handler code
}

Java how to use a double or a string?


Numba Vectorize TypeError: 'type' object is not subscriptable

Question: I am trying to make my code faster by using Numba and vectorizing.
My code is to get input from two 360 deg cameras and crop them. The main idea here is to learn how to use Numba and vectorizing. Below is my code:
import cv2
import time
from numba import vectorize
import numba

dim = 1440

@vectorize(['int[:, :, 3](int[:, :, 3])'], target='cuda')
def cropFaster(img):
        croppedImG = img[:,10:1100]
        return croppedImG

cap1 = cv2.VideoCapture(0)  # Set input device number
cap1.set(3, dim)  # Set Horizontal resolution
cap1.set(4, dim)  # Set Vertical resolution

cap2 = cv2.VideoCapture(1)  # Set input device number
cap2.set(3, dim)  # Set Horizontal resolution
cap2.set(4, dim)  # Set Vertical resolution

while (cap1.isOpened()):
        t1 = time.clock()
        ret1, img1 = cap1.read()
        ret2, img2 = cap2.read()
        croppedImgL =  cropFaster(img1)
        croppedImgR =  cropFaster(img2)
        t2 = time.clock() - t1
        print (t2)
        cv2.imshow("Left", croppedImgL)
        cv2.imshow("Right", croppedImgR)
        if cv2.waitKey(1) & 0xFF == ord('q'):
                break
cap1.release()

I get the following error:
Traceback (most recent call last):
  File "transparentAPI2.py", line 9, in <module>
    @vectorize(['int[:, :, 3](int[:, :, 3])'], target='cuda')
  File "/usr/local/lib/python3.6/dist-packages/numba/npyufunc/decorators.py", line 120, in wrap
    vec.add(sig)
  File "/usr/local/lib/python3.6/dist-packages/numba/npyufunc/deviceufunc.py", line 391, in add
    args, return_type = sigutils.normalize_signature(sig)
  File "/usr/local/lib/python3.6/dist-packages/numba/sigutils.py", line 26, in normalize_signature
    parsed = _parse_signature_string(sig)
  File "/usr/local/lib/python3.6/dist-packages/numba/sigutils.py", line 16, in _parse_signature_string
    return eval(signature_str, {}, types.__dict__)
  File "<string>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Any idea how to fix this?
Thanks
Answer: If you haven't found it by now, the exception comes from the signature. You need to explicitate not only the type but also the byte-size of each argument. So int is not acceptable, but int8 or int16 int32 or int64. However, this is not the only thing that is wrong with this function:

If you read the documentation, vectorize is only supposed to be used when the arguments are numbers, not arrays. What you are looking for in these cases is guvectorize, whereby the inputs and outputs can be arrays of various dimensions.
You can also not provide a number as array dimension in the signature, you must use :.
It is unlikely you will see any significant speed up using numba in this case, as you are only using numpy indexing inside the function. Numpy is already compiled C in the background.

I can't give you a working example because with guvectorize you also need to provide a numpy-style signature, and this doesn't work when the shape of the output does not relate to the shape of the input.


How do you append html in a variable if it already has HTML?

Question: I have some HTML saved in a variable. How can I append more HTML after the already existant one. Basically I use an If statment and I don't wanna re-type the code and reassign the whole html.
My code, += gives an error " Uncaught SyntaxError: Unexpected token += "
var sticky_add_cart_html = '{strip}
'+sticky_select+'Add to cart
{/strip}';
        if ($('input[name="quantity"]').length()) {
            var sticky_add_cart_html +=  '
 Quantity <input type="number" id="Quantity" name="bundle-sticky-quantity" value="1" min="1" class="product-form__input" pattern="[0-9]*">
';
        }

Comment: hahaha another js question where everything is downvoted, wonder why it's only js users who downvote everything, but my guess as to what's wrong would be length doesn't need the `()` and you don't need the `var` inside the if - the variable is already declared
Comment: @Pete its not only the js users who downvote, and its probably downvoted as much as it is because of an oversight on the code, or lack of googling
Comment: @mast3rd3mon I pretty much stick to 4 tags in so and by far the most downvotes for no good reason is for js questions - I have put up many answers that answer an OPs problem but as it is not done in the way a js "master" likes to do it, it gets downvoted - even though it is still correct, but just another way of doing things.  That's why I laugh at the js users, very toxic indeed, although I do agree, this whole site is heading that way
Answer: You are re-declaring the variable, on the third line in your example your have var sticky_add_cart_html ...., change it so it doesnt have the var instead
Answer: You are redefining your variable in your if statement
Try this :
var sticky_add_cart_html = '{strip}
'+sticky_select+'Add to cart
{/strip}';
    if ($('input[name="quantity"]').length()) {
        sticky_add_cart_html +=  '
 Quantity <input type="number" id="Quantity" name="bundle-sticky-quantity" value="1" min="1" class="product-form__input" pattern="[0-9]*">
';
    }


What module will show me all sql queries being run on the loaded page?

Question: My site is running slow and I suspect its a module, but not sure which one. Is there a module that can display all the sql queries being run on a loaded page? If there isn't maybe there is a command line tool that others use to monitor this data?
Answer: The Devel module has a query log option, which when enabled will show every query that's been run for a request at the footer of the page.
You can enable it at admin/config/development/devel once the module's installed.
Comment: Seems this is no longer available in D8.
Comment: @Randell Now it's a sub-module called _Web Profiler_
Comment: The [Web Profiler](https://www.drupal.org/project/webprofiler) project page says the module has been merged with the *Devel* module since November 9, 2015.
Answer: There is better query log we can get from mysql log( more here: https://stackoverflow.com/questions/6479107/how-to-enable-mysql-query-log )
It shows real mysql queries with real values while the Devel's log shows placeholders.
So to get log of a page shutdown Mysql server, add the "log=" line in my.ini and restart the server then do the page load and then again stop the server and comment the log command.


Prove for $f: \mathbb Q \to \mathbb R$ $f(x+f(y)) = f(x) + y$ that $f$ is injective

Question: I recently posted a question (Solving $f(x+f(y)) = f(x) + y$). However, I can't wrap my head around how to prove this function is injective. I tried using the answers in the responses but my I don't understand how "Let's start by plugging in x=0. We have f(f(y))=f(0)+y. This tells us that f is injective, since if $f(a)=f(b)$, then $f(0)+a=f(f(a))=f(f(b))=f(0)+b$ and hence $a=b$." works. If anyone can give a basic explanation that would be great.
Thanks in advance.
Comment: Why not ask the users who posted answers to the original post?  The logic is spelled out quite clearly in those responses....it's easy save for the technical fact that you first must argue that $f(x)$ is rational for all $x$.  Personally, I think that should just have been stated as an assumption....the "proof" that it is so comes down to "well, if it is not so, then the question does not make any sense".
Comment: This should be a comment on the answer that you don't understand, not a separate question.
Comment: Exactly where did you get stuck? If $f(a) =f(b) $, then $f(f(a))=f(f(b))$. Does that help?
Comment: The definition of "injective" is: for all $a, b$, if $f(a) = f(b)$ then $a = b$. I proved that. So I'm not sure why you're confused.
Answer: Recall that all that is needed to show injectivity is to show that the implication "if the function values are equal, then the function arguments must be equal" holds.
So, to check injectivity, the simplest test is: take equal function values $f(a)=f(b)$, and show that this already implies $a=b$.
This is exactly what this answerer did. Fix $f(a)=f(b)$, then (a bit longer)
$$f(f(a))=f(f(b))$$
so you can write
$$f(f(a))=f(0+f(a))=f(0)+a=f(0)+b=f(0+f(b))=f(f(b)).$$
Looking at the middle, you can see that $a=b$ holds, which is all we needed to test for.


Error reindexing attachments in Drupal 7 using Apache Solr Attachments module

Question: I've installed Solr 3.4.0 and Tika .10 on my Windows 2003/IIS6 server.  I have loaded the Apache Solr Attachments module and configured so I can search on documents attached to pages in my Drupal 7 web site.  When I reindex on the Apache Solr search configuration page I'm getting 5 of these notices:
Notice: Undefined index: filepath in apachesolr_attachments_add_documents() (line 133 of W:\www\drupal-7.8\sites\all\modules\apachesolr_attachments\apachesolr_attachments.index.inc).
The search index page indicates the attachments have been submitted for reindexing (message on the page -> "There are 0 items remaining to be examined for attachments out of 23 total.  The search index is generated by running cron. 100% of the site content has been sent to the server. There are 0 items left to send. " and "Number of documents in index: 23 (0 sent but not yet processed)").  On the Search settings page I see "100% of the site has been indexed. There are 0 items left to index." under Indexing Status.
Search is working for web site content but search for content in attachments is not working.    If I got into Solr admin and query I can see web site content but searches for words in attachments return no results.  So the attachments are not getting into Solr.  Any ideas about what this error means or how I can debug it?
Answer: So I figured this out in case anybody else runs into this issue.
In the 7.x-1.x version of Apache Solr Attachments, there is a line of code in apachesolr_attachments.index.inc that uses the PHP function mb_detect_encoding.  That command relies on the PHP EXIF extension being installed and it is not by default.  Once I modified my PHP installation to include it, it was able to process the files.  I ran into some other issues though but finally got it all working.  Details are posted here -> http://drupal.org/node/1377416


Different menu links depending on user account

Question: I need to create menu that has to be diffrent for each user.
<code>/user/%username%
/user/%username%/purchases
etc.
</code>
Is there way to do something like that? Thanks
Answer: Yes . You can use  Menu Token. (Menu Token module provides tokens, that could be used in title or in path of menu items. For example, if you create a menu item with path: "user/[current-user:uid]", the url will be changed "on fly" to: "user/1" )
Answer: I found the way that is not really good for me, but it is acceptable. I define items in hook_menu, and combine my meny with primary_tabs


502 badgateway wcf doesn't respond

Question: We have created a wcf service, which takes the multiple line items gives us response, when there is 4-5 line items, It is working fine and giving response back.
when we are trying with more than 10 line items, we were getting 504 gateway time out error initially, then now 502 bad gateway error we are getting.
we tried giving Usedefaultproxy=null or false, but it doesn't help. Below the custom binding code. can anyone help me here.
customBinding
<code>     binding name=CustomMapper UseDefaultWebProxy = null allowCookies=false maxBufferPoolSize=2147483647 maxBufferSize=2147483647 closeTimeout=00:15:00 openTimeout=00:15:00 receiveTimeout=00:15:00 sendTimeout=00:15:00

       webMessageEncoding webContentTypeMapperType="MyseOrdVerify.RawContentTypeMapper, MyseOrdVerify

     httpsTransport manualAddressing=true maxReceivedMessageSize=1524288000 transferMode=Streamed

      binding
</code>
customBinding
Answer: You may want to change the values of three properties:
maxConcurrentCalls, maxConcurrentInstances, and maxConcurrentSessions.
Try setting these values to be larger like this:
<code><system.serviceModel>
    <behaviors >
      <serviceBehaviors >
        <behavior name="nettcpBehavior">
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="True" />
          <serviceThrottling maxConcurrentCalls="2147483647" maxConcurrentInstances="2147483647" maxConcurrentSessions="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <bindings>
      <netTcpBinding>
        <binding name="MySessionBinding" />
      </netTcpBinding>
    </bindings>

</system.serviceModel>
</code>

502 badgateway wcf doesn't respond


How do I add a method to a property?

Question: Let's say I create a class with a property:
public class User
{
   private string _userID;

   public string UserID
   {
      get { return _userID; }
      set { _userID = value; }
   }
}

What do I have to do with the class and property to be able to have a method attached to the UserID property, such as a method that generates Xml around the user ID with the "dot" syntax:
User u = new User();
u.UserID = "Mike";
string xml = u.UserID.ToXml();

I can figure out how to write a method to put Xml tags around the value of the UserID, the part that is eluding me is how to make the method work with the property using the "dot" syntax.

All of these answers are useful, and thanks to everyone for contributing.  In fact, the answer I marked as "accepted" was precisely what I was looking for.  I appreciate the cautionary remakrs on extension methods (which I had never heard of before this), and of course it could be a problem to apply the extension method to all strings in some circumstances, but in this case I definitely wanted to apply the method ToXml() to all string properties in the class.  Just what the doctor ordered.  I am quite familiar with XmlSerialization, but in this case needed to avoid it for various reasons.
Answer: There are two ways:
Either the object/value that you're operating on has to have that method (such as when you have control over the object definition.)
public class UserIDObject
{
   public string ToXML() {}
}

public class User
{
   private UserIDObject _userID;

   public UserIDObject UserID
   {
      get { return _userID; }
      set { _userID = value; }
   }
}

User u = new User();
u.UserID = = new UserIDObject("Mike");
string xml = u.UserID.ToXml();

Or you can implement an Extension Method (MSDN) for the object.
Geeks with blogs has a good tutorial on Extension Methods and they can be applied to .NET 2.0 if you're running VS2008.
public static class MyMethods
{
    public static string ToXML(this string s) { }
}

Extension Methods are something that you want to weight heavily since an extension method applies to ALL objects of that class type. (IE. do I want all strings to be able to call .ToXML()?)
Comment: Just remember that the extension method will affect ALL Strings, which you may or may not want.
Comment: Very nice answer... you may want to add the implicit converting to his original desired data type (int).
Comment: @Tim - sorry, I'm not what you mean by implicit conversion to int datatype.
Answer: You can either:

Change _userID to be a custom class, wrapping a string and adding the methods you want.
Make an extension method for the string class (not recommended). This will affect all string objects
Comment: Same as "LFSR Consulting"'s comment... but still the right answer :)
Comment: He actually beat me to posting it :S
Comment: This is much more to the point even if it did come a bit later, and therefore more likely to actually be read and understood.
Answer: You have to add the method to the type of the property.  In this case the UserID is a string, so that will mean adding it to the string type and making it accessible from all strings.  I'm not sure that's a good idea, but if that's really want you want to do:
public static class StringUtils
{
    public string ToXmlElement(this string s, string elementName)
    {
       return string.Format("<{0}>{1}</{0}>", elementName, s);
    }
}

This doesn't exactly match your function signature, but it's something that makes a little more sense to attach to the larger string class.  The only other option is to use a different underlying type to hold your UserID, perhaps a custom class with an implicit conversion to string.
Finally, if you're just trying to write your user class to Xml in a generic way, look at the System.Xml.Serialization namespace.  Then you can just mark up your class like this and use an XmlSerializer instance to read or write the class.
[Serializable]
public class User
{
   private string _userID;

   [XmlElement()]
   public string UserID
   {
      get { return _userID; }
      set { _userID = value; }
   }
}

Comment: Since this ended up the accepted answer, I've edited the question to include some of the good points made by others.
Answer: Well, the short answer is that, even though it would be possible through extension methods, you don't want to do this.  It's bad form and not necessarily what you want.
A better technique would involve leveraging .NET XML serialization and handing it your object.  It can do the XML magic for you.
Answer: You essentially have several ways of accomplishing this task in C# 3.0, some more direct and akin to how you want it work, and some less. Firstly, let me clarify why it probably isn't immediately apparent to you how to accomplish such a thing:
Because the UserID property is of type string (as you have specified), all of its members are defined and thus limited to the members of String (at least in traditional Object-Oriented Programming [OOP]). This includes methods of course. You seem to want to add a ToXml method, which is not possible without having access to the type of the property (System.String in this case).
So your options are as follows:

Change the type of the property to a custom class (i.e. a UserIdentification class) and add the ToXml method to this. Not a very good solution in most cases to be honest, as it adds unnecessary complexity. Consider it only if you will need to add multiple methods/properties related to UserID.
Simply add the ToXml method to your User class (and call it something like GetIdXmlString). A decent solution, and probably what I would have chosen before C# 3.0 (and possibly still, depending on the circumstances).
Extension methods. This is a great feature added to the latest version of C#, which allows you to "extend" existing classes and interfaces by adding methods to them defined with a special syntax. See the linked article for more information, but your extension method will essentially look like this:
public static string ToXml(this string str)
{
    // Code for function goes here.
}

You can then simply call this method as if it actually belonged to the string class.
Take care however, as this last method may not always be appropiate (since it can be applied to all objects of type string in your code). If you want to write a generic ToXml function (with overloads?) that converts various objects into your own custom XML format, then fair enough, otherwise you may be better off with the 2nd suggestion. A helper class is another alternative, and although the syntax is slightly less nice it does at least mean that the ToXml method doesn't appear for all strings.

Anyway, hope this helps...
Answer: Well, you wouldn't do that with a String type.  You would create a new class that had all of the necessary string handling methods but that also implemented your "ToXml()" method.  Unfortunately, you cannot derive from the string class itself so you'll have to implement wrapper methods or some other way of delivering the string handling functionality that you also want.
Answer: instead of having a string, you need to have a class that actually supports ToXml()
Answer: I suppose you could be really crafty and do a property removal via AOP, replacing the property with a proxy class that had the right methods. But even if you did that, you would probably have to cast your new property to some interface - a double cast, actually, i.e.,
IXmlable x = (IXmlable)(object)this.UserId;
x.ToXml();

which would probably defeat the point of doing it in the first place. But hey - at least you'll get separation of concerns, right?
Seriously, I'd go with the other, simpler choices mentioned above. Unless you want to become an AOP guru, that is. :)
Answer: You could create a struct UserID value type, add the method to it and use it in your class instead of string.

How do I add a method to a property?


java couldn't take 2 continuous String input from user

Question: This code in java
boknam [variable] refers to bookname & bokauthor[variable] referes to bookAuthor just not to get confused [ this is not that point here]
Code
                String boknam;
                String bokauthor;
                System.out.print("Enter bookNAme: ");
                boknam = scan.nextLine();
                System.out.println("");
                System.out.print("Enter bookAuthor: ");
                bokauthor = scan.nextLine();

Here I want user to give input bookname & bookauthor but the output is

I
IT skips to take the input as bookNAme, it is only taking input as bookAuthor,
please help will be aprreciated
               System.out.print("Enter bookNAme: ");
                boknam = scan.nextLine();
                System.out.println("");
                System.out.print("Enter bookAuthor: ");
                bokauthor = scan.nextLine();

boknam = scan.nextLine();
This line here is not working, not asking for input
NOTE:- THE VARIABLE IS ALREADY ASSIGNED TO DON'T SAY YOU DIDNT INITIALIZED A STRING boknam
Comment: Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo)
Answer: Sometimes, we have to clear the buffer after getting integer input. Here, after getting your Choice input, we have to clear the buffer so just add an extra line scan.nextLine() before boknam = scan.nextLine(); and that should work just fine.


Show div after button click jquery

Question: Hi I try to show a div element in jQuery mobile when the user touch the button. I already created own classes for the button and for the div element, but nothing happens. What classes should I take?
JS:
    $(document).ready(function(){
 $(".commentbtn").on("click", function(e) {
    e.preventDefault(); // in some browsers a button submits if no type=
    $(this).siblings("div.comment").toggle();
});
});

CSS:
.comment {
    display:none;
}

HTML:
<?php foreach ($result as $key => $row): ?>

        <button class="commentbtn" data-rel="button">comment</button>

            <form data-ajax="false" name="login-form" class="login-form" action="./comments.php" method="post" style="padding:20px 40px;">

                    <textarea rows="1" name="text" id="text" class="foo"></textarea>

            </form>

<?php endforeach; ?>

Comment: Wheres the element with class `.btn-info`? if it does not exist, then your click event is useless.
Comment: You fire an event on .btn-info click, but there is no element with the class btn-info in your HTML.
Comment: Could you please leave out the PHP and paste only the affected parts of the output of the PHP?
Comment: PHP tag applied to be removed.
Comment: Also, in your code I only see one element with class `comment`, which means that your click function wont work since your code assumes there are multiple `comment` classes: `.closest(".comment").children(".comment")`,
Answer: Your button has class commentbtn, so you should use that instead of btn-info.  Also, you should be looking for the sibling div, not the closest.
$(".commentbtn").on("click", function(e) {
   e.preventDefault(); // in some browsers a button submits if no type=
   $(this).siblings("div.comment").show();
});

JSFiddle demo
Answer: You haven't got any element with the class .btn-info so you wouldn't be able to call the event from:
  $(".btn-info").on("click", function(e) {
    e.preventDefault(); // in some browsers a button submits if no type=
    $(this).closest(".comment").children(".comment").show();
  });

You have an element with the class .commentbtn which you would then do the same as you did with the .btn-info
  $(".commentbtn").on("click", function(e) {
    e.preventDefault(); // in some browsers a button submits if no type=
    // Console log the element
    console.log($(this).closest(".comment").children(".comment"));
    // Console log not showing the right element. So you need to get the
    // sibling of the clicked button
    // Instead of doing - $(this).closest(".comment").children(".comment").show();
    // You can do the following
    $(this).siblings("div.comment").show();
  });

.closest() - looks at the element itself and its parents for a match.
.siblings - Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
Example With .show();
Here an example with .toggle(); If you wanted to show/hide the comment with same button. (Just little extra for you to look at)
Example With .toggle();
UPDATE:
Example with .comment shown on load
Comment: Thank you, that works but when I load my page, the div become shown, how can I change it that the div only after the click, how in your fiddles, become shown? :)
Comment: @klamertd Which `div` are you talking about?
Comment: About this:`` I have the script in my head and edit it a bit. The div becomes after pageload showed.
Comment: @klamertd If you look at both my examples, you will see that it's not shown on page load, and it only shows on button clicked
Comment: Yes in your examples works it right but in my case its the other way around. ;) How can I change that or how can I show it first and after button click hide in your examples?
Comment: @klamertd Take look at my updated example, it will be shown on load, hidden on button click.

Show div after button click jquery


moving from test site to live

Question: I currently have a test Drupal site where I am testing the different modules and Views, display settings, etc that I would like to eventually use on my live site. But I am adding data to the test site as well, data that will also end up on the live site.
Because I am installing and uninstalling modules, would it be better to start the live site from scratch or can I safely move the test site to the live site without worrying about orphan code/settings slowing down or otherwise adversely affecting the live site?
Answer: One of the most common ways to move configuration data is to use the Features module.  However, this will move only configuration, not data (nodes/content).  Still, it's not too difficult to set up; you can take a look at this tutorial for an overview.
Moving data is much harder; the Migrate and Feeds modules are two common ways to do this but both are quite painful to set up and probably not worth the trouble.  For content, I just keep a list of the info in an Excel file and then cut and paste it in-- it's not a great solution, but in my case it saves a lot of time.

moving from test site to live


cat and grep from multiple files in python and write output to a file?

Question: i want a python equivalent of shell command cat logs/archived/app.2020-12-11* | grep "Sending" > sms_otp_logs_ack.log
I have tried by using sh module.
sh.grep(sh.cat(2020-12-18/126.96.36.199/app.*), string_to_grep)

This throws an error of no such file due to * wild card. How can i pypass this and also save the output to another file?
Comment: Did you try the python module os? check os.system() and use the same shell command as argument to os.system()
Comment: The `cat` is mildly useless here; like basically every properly written file manipulation tool, `grep` accepts an arbitrary number of file name arguments, with the marked benefit that it can print which file it found a match in if you would like that.
Comment: can you provide me the edited shell command to grep from all those files @tr
Answer: You can use glob module which finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, and then those found files are opened up in read mode to be searched for the desired string("Sending") in order the lines containing that string are to be appended to another file.
import glob, os

for f in glob.glob(os.path.join(path, "app.2020-12-11*")):
    with open(f, 'r') as f_in, open('sms_otp_logs_ack.log', 'a') as f_out:
        for line in f_in:
            if "Sending" in line:
                f_out.write(line)


callback after each post is executed in jQuery

Question: I have a loop to fetch data via $post. And after all the data is fetched, I need to have a callback function. My current code only callback first then and post. How can I do it the other way round?
function addMegaMenu(callback){
    $('#megamenu > ul > li').each(function(){
        $.post('/_menu.cfm',  function(data){
           console.log("post exec");
        })
    });
    callback.apply();
}
function addMobileIcon(){
    console.log("callback exec");
}
$(function(){
    addMegaMenu(function(){
        addMobileIcon();
    });
})

It prints out:
callback exec
post exec

I need to make it:
post exec
callback exec

Answer: First create a list of deferreds, each $.post will return a deferred...
$.post('/_menu.cfm',  ... in a loop

When you have that promise list:
$.when.apply($, promises).then(function(d) {
         console.log("done", this, d);
    }, function(e) {
         console.log("failed");
    });

Answer: Since you need to wait until all elements have done their callback, you have to keep track of how many outstanding POST requests there are:
var counter = 0;
function addMegaMenu(callback){
    $('#megamenu > ul > li').each(function(){
        counter++;
        $.post('/_menu.cfm',  function(data){
            counter--;
            console.log("post exec");
            if (counter==0) {
                callback.apply();
            }
        })
    });
}
function addMobileIcon(){
    console.log("callback exec");
}
$(function(){
    addMegaMenu(function(){
        addMobileIcon();
    });
})


Can F1-Score be higher than accuracy?

Question: I'm using sklearn's confusion_matrix and classification_report methods to compute the confusion matrix and F1-Score of a simple multiclass classification project I'm doing.
For some classes the F1-Score that I'm getting is higher than the accuracy and this seems strange to me. Is it possible or am I doing something wrong?
Answer: This is definitely possible, and not strange at all.
Recall how accuracy and the F1 score are defined:
$$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}\quad\text{and}\quad \text{F1}=\frac{2TP}{2TP+FP+FN}. $$

Now, probably the simplest possible way your F1 score can be greater than your accuracy is if you have just two observations, one TRUE and one FALSE. Suppose you classify both as TRUE. Then
$$ TP=1,\quad TN=0,\quad FP=1,\quad FN=0, $$
so
$$\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}=\frac{1+0}{1+0+1+0}=\frac{1}{2}$$
and
$$\text{F1}=\frac{2TP}{2TP+FP+FN}=\frac{2\times 1}{2\times 1+1+0}=\frac{2}{3} $$
and there you are.

Actually, you can create slightly bigger examples with the following R script. It considers pp TRUE and nn FALSE observations, and rolls out all the different combinations of predictions you might have. (It actually double-counts some constellations, but reducing these out would have made the script less legible.)
pp <- 2
nn <- 2
actuals <- c(rep(T,pp),rep(F,nn))
predictions <- expand.grid(lapply(1:(pp+nn),function(xx)c(T,F)))

accuracy_and_F1 <- function(actuals,pred) {
    TP <- sum(actuals & pred)
    TN <- sum(!actuals & !pred)
    FP <- sum(!actuals & pred)
    FN <- sum(actuals & !pred)
    structure(c((TP+TN)/(TP+TN+FP+FN),2*TP/(2*TP+FP+FN)),.Names=c("Accuracy","F1"))
}

result <- cbind(predictions,
    t(apply(predictions,1,function(xx)accuracy_and_F1(actuals,xx))))
result$F1_greater_than_Accuracy <- with(result,F1>Accuracy)
result

In this example with pp=2 and nn=2, the result is
    Var1  Var2  Var3  Var4 Accuracy        F1 F1_greater_than_Accuracy
1   TRUE  TRUE  TRUE  TRUE     0.50 0.6666667                     TRUE
2  FALSE  TRUE  TRUE  TRUE     0.25 0.4000000                     TRUE
3   TRUE FALSE  TRUE  TRUE     0.25 0.4000000                     TRUE
4  FALSE FALSE  TRUE  TRUE     0.00 0.0000000                    FALSE
5   TRUE  TRUE FALSE  TRUE     0.75 0.8000000                     TRUE
6  FALSE  TRUE FALSE  TRUE     0.50 0.5000000                    FALSE
7   TRUE FALSE FALSE  TRUE     0.50 0.5000000                    FALSE
8  FALSE FALSE FALSE  TRUE     0.25 0.0000000                    FALSE
9   TRUE  TRUE  TRUE FALSE     0.75 0.8000000                     TRUE
10 FALSE  TRUE  TRUE FALSE     0.50 0.5000000                    FALSE
11  TRUE FALSE  TRUE FALSE     0.50 0.5000000                    FALSE
12 FALSE FALSE  TRUE FALSE     0.25 0.0000000                    FALSE
13  TRUE  TRUE FALSE FALSE     1.00 1.0000000                    FALSE
14 FALSE  TRUE FALSE FALSE     0.75 0.6666667                    FALSE
15  TRUE FALSE FALSE FALSE     0.75 0.6666667                    FALSE
16 FALSE FALSE FALSE FALSE     0.50 0.0000000                    FALSE

So we see that having an F1 score greater than accuracy is a pretty common occurrence in this simple example already.

That said, accuracy is not a very good measure of predictive power: Why is accuracy not the best measure for assessing classification models? And every criticism against accuracy there applies equally to the F1 (and every other F$\beta$) score.

Can F1-Score be higher than accuracy?


Problem with SVN access control

Question: I have the following access control file
[groups]
admin = robu, jjtl, dat
user  = ulo
[/]
@admin = rw
@user  = rw

[/wlp]
@admin = rw

[/wesys]
@admin = rw
@user  = rw

But the user group still can browse the wlp, how can I remove the access? It is working if a take out from the root([/]) but I don't want to do that because we are using trac for repository browsing.
Comment: Which SVN layout you are using: single repository for multiple projects or each project have its own repository?
Answer: how if ?
 [groups]
 admin = robu, jjtl, dat
 user  = ulo

 [/]
 @admin = rw
 *=r

Answer: Try this:
[/wlp]
@admin = rw
@user =

With subversion permissions, a user will inherit the permissions form the parent folder unless there's an explicit match that alters those permissions further down the directory tree. So in your case, ulo inherits read access to /wlp from the the root folder, since he's a member of user and [/] is the closest match to the path where permissions for that group are defined.
By explicitly defining @user = under [/wlp] you're giving svn a closer match to the requested path which specifically states 'no access'.

Problem with SVN access control


In Python, how do I rotate a matrix 90 degrees counterclockwise?

Question: >>> def rotate_matrix( k: List[List[int]]):
    """
    For example, if I have:
    m = [[1,2,3],
         [2,3,3],
         [5,4,3]]
    rotate_matrix(m) should give me [[3,3,3],[2,3,4],[1,2,5]].
    """

Edit: Preferably without numpy.
Comment: I've tried the code in python IDLE and for some reason, it's outputting the original matrix instead of rotating it. Can you please help?
Comment: I just copied the code from the answer and ran it, it is perfect. Please check that you are printing the right array in your code, c.f. print( new_matrix )
Answer: Here is the counter clockwise matrix rotation as one line in pure python (i.e., without numpy):
new_matrix = [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]

If you want to do this in a function, then
def rotate_matrix( m ):
    return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]

and either way, the result for
m = [ [1,2,3], [2,3,3], [5,4,3]]

is
[[3, 3, 3], [2, 3, 4], [1, 2, 5]]

Aside, if you want the usual transpose, then the simple one line pure python version is
[[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

Comment: this code is good, can you expand this one line of code for understanding? thank you.
Comment: @VrushalRaut   Good question,  perhaps drawing a picture (or two) would help. Will try to find some time to look into it.
Comment: I've tried the code in python IDLE and for some reason, it's outputting the original matrix instead of rotating it. Can you please help?
Comment: I just copied the code from here and ran it,  it is perfect.  Please check that you are printing the right array in your code,  c.f.  print( new_matrix )
Comment: @DrM How would you change the code to rotate the matrix clockwise?
Answer: You could use the numpy function rot90
import numpy as np
m = np.array([[1,2,3],
         [2,3,3],
         [5,4,3]])

def rotate_matrix(mat):
    return np.rot90(mat)

Comment: "Edit: Preferably without numpy."
Answer: #solution1
print(list(list(x) for x in zip(*m))[::-1])

#solution2
print([[x[i] for x in m] for i in range(len(m))][::-1])

#solution3
r = []
i = 0
for row in m:
  listToAdd = [item[i] for item in m]
  r.append(listToAdd)
  i +=1
print(r[::-1])

Comment: @radoslav006 That's basically the rotation/pivot operation. The arguments to `zip` are distinct lists, and the output of `zip` is the nth element of each list grouped together.
Comment: Shorter if you're OK with tuples instead of lists: `list(zip(*m))[::-1]` or `[*zip(*m)][::-1]`
Comment: Why unpacking the m with `*` and then packing it back with `zip`?
Answer: def rotate_90_degree_anticlckwise(matrix):
    new_matrix = []
    for i in range(len(matrix[0]), 0, -1):
        new_matrix.append(list(map(lambda x: x[i-1], matrix)))

    return new_matrix

def rotate_90_degree_clckwise(matrix):
    new_matrix = []
    for i in range(len(matrix[0])):
        li = list(map(lambda x: x[i], matrix))
        li.reverse()
        new_matrix.append(li)

    return new_matrix

def rotate_90_degree_clckwise_by_zip_method(matrix):
    return list(list(x)[::-1] for x in zip(*matrix))

Answer: Look at this code. This is the way to rotate any matrix by 90 degrees using scratch
[This is the code to have a matrix rotated by 90 degrees][1]
    n = input("enter input:")
    l =[]

    while (n !=""):

        l.append(n.split(" "))
        n = input("enter input:")
        l1=[]
    for i in range(len(l[0])):
        l1.append([])
    for j in range (len(l1)):
        for p in range(len(l)):
           l1[j].append(l[p][-(j+1)])

    for s in l1:
         print(*s)
'''

  [1]: https://i.stack.imgur.com/c8jHC.png

Answer: Just flip the matrix vertically, then switch the upper-right triangle with the lower-left triangle
def rotate_matrix_ccw(mat):
    if mat is None:
        return None
    n = len(mat)
    if n == 1:
        return mat
    for i in range(n):
        if len(mat[i]) != n:
            raise Exception("Matrix must be square")
    # flip the matrix vertically
    for j in range(n // 2):
        for i in range(n):
            mat[i][j], mat[i][n - 1 - j] = mat[i][n - 1 - j], mat[i][j]
    # switch the upper-right triangle with the lower-left triangle
    for i in range(n):
        for j in range(i):
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
    return mat

Answer: You can loop through the original matrix and create a new one. This is my approach for counterclockwise, for the other way it would be similar.
This doesn't require it to be a square.
def left_rotate(mat):
    if not mat: return []
    colcount = len(mat[0])

    # Initialize empty lists
    new = [list() for _ in range(colcount)]
    # Go through the rows, append elements one by one
    for row in mat:
        for j in range(colcount):
            new[j].append(row[colcount - 1 - j])
    return new

Example:
>>> print(left_rotate([[1, 2], [3, 4], [5, 6]]))
[[2, 4, 6], [1, 3, 5]]

Answer: flip vertically (left to right) then transpose:
m = [[1,2,3],
     [2,3,3],
     [5,4,3]]
print([list(x) for x in zip(*[x[::-1] for x in m])])

Answer: def rotateMatrix(self, matrix):
    for i in range(len(matrix)):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    matrix.reverse()

Comment: Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer).
Answer: Rotate matrix anti-clockwise 90deg (In-place)
def rotate(matrix):
    for i in range(len(matrix) - 1, -1, -1):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    matrix.reverse()

Rotate matrix clockwise 90deg (In-place)
def rotate(matrix):
    matrix.reverse()
    for i in range(len(matrix)):
        for j in range(i):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

Answer: In case you're working with square matrixes (rows == cols) then you can use this:
list(zip(*reversed(a))) # 90 degrees clockwise

list(zip(*reversed(a)))[::-1] # 90 degrees counter-clockwise

Comment: Small typo in the counter-clockwise code snippet. You must remove the `reversed` so you have: `list(zip(*a))[::-1] # 90 degrees counter-clockwise`
Answer: def rotated_array(array):
    new_array = np.zeros([array.shape[0], array.shape[1]])
    for i in range(array.shape[0]):
        for j in range(array.shape[1]):
            t = array.shape[0]-j-1          # To Start with last row and first column
            new_array[i, j] = array[t, i]
    return new_array

Comment: The shape of new_array is the same as the shape of the original input array. This can't be correct if new_array is the original input array rotated by 90 degrees.


Why does Spark application takes longer to execute when reading dataset from Cassandra table than local file?

Question: I have the following code, and the application ends immediately after generating the result.
  def textProcess(sc: SparkContext) {

    val baseRDD = sc.textFile("C:\\myDrive\\test.log")
    val result = baseRDD.map { x => x }.reduce((accum, current) => accum)
    println(result)
    sc.close()
  }

But when I run the below code against Cassandra with spark-cassandra-connector,the application ends only after some 10 seconds delay.
  def dbProcess(sc: SparkContext) {

    val baseRDD = sc.cassandraTable("local_test", "configurations")
    val result = baseRDD.map { x => x.getString("keyname") }.reduce((accum,current) => accum)
    println(result)
    sc.close()
  }

Version Details
Spark version is 1.6.x
   <dependency>
        <groupId>com.datastax.spark</groupId>
        <artifactId>spark-cassandra-connector_2.10</artifactId>
        <version>1.6.0</version>
    </dependency>

    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>dse-driver</artifactId>
        <version>1.1.0</version>
    </dependency>

    <dependency>
        <groupId>com.datastax.cassandra</groupId>
        <artifactId>cassandra-driver-core</artifactId>
        <version>3.0.2</version>
    </dependency>

My question here is , why this delay when dealing with spark-cassandra-connector? is there any way to avoid this delay? or is this a version problem?(I tried with few other versions but the result is intact)
Answer:
why this delay when dealing with spark-cassandra-connector?

Basically, the difference boils down to the following two lines:
sc.textFile("C:\\myDrive\\test.log")

and
sc.cassandraTable("local_test", "configurations")

The former is a relatively cheap access to a local file while the latter accesses a remote Cassandra cluster that's a quite heavy network-wise operation.
Leaving a Cassandra cluster's performance aside, network access is certainly more time-consuming than accessing a local file, isn't it?
Comment: yes it makes sense. so this delay would increase if my cluster size grows?
Comment: It depends on how Cassandra handles new nodes and adding new nodes may not necessarily impact performance of any cassandra client, Spark including.
Comment: Okay.Thank you @Jacek Laskowski


Android ListView does not show list items

Question: I wanna add items to my list but it only shows the first one:
public class MainActivity extends Activity {

    Server server;
    TextView infoip, msg;
    TextView usersTitle;
    String[] array = {"a"};
    ArrayList<String> lst;
    ArrayAdapter<String> adapter;
    ListView userList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        lst = new ArrayList<String>(Arrays.asList(array));
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);
        userList = (ListView) findViewById(R.id.userList);
        userList.setAdapter(adapter);

From this other class method, everytime it is called I want the text to go below the first one. The method certainly runs but it does not put the text below the previous one. It just shows "a"! Anyone knows why?
activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        activity.lst.add(message);
                        activity.adapter.notifyDataSetChanged();

                    }
                });

I have also tried:
adapter.insert(String, int);

lst.add(int, String);

And even added in the onCreate method this:
lst.add(1, "2");
adapter.notifyDataSetChanged();

And still doesnt add the "2"!!
Answer: If you are adding items to Arraylist from another class ,you have to declare your Arraylist Static.So that it can hold items in memory.
Replace ArrayList lst with public static ArrayList
Comment: Using static fields is a terrible idea.
Answer: Here is the solution to your Problem.I have created an Activity class and Tests java class.
public class MainActivity extends Activity {
String[] array = {"a"};
public static ArrayList<String> lst;
ArrayAdapter<String> adapter;
ListView userList;
Tests tests = new Tests();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    userList = (ListView) findViewById(R.id.userList);
    lst = new ArrayList<String>(Arrays.asList(array));
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);

    userList.setAdapter(adapter);
    tests.callThread();
}

}
Here is the Tests.java Class
   public class Tests {
int i = 0;
String message = "";
Thread runOnUiThread;

public void callThread()

{

    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                while (i < 10) {
                    i = i + 1;
                    message = String.valueOf(i);
                    //Create a server socket object and bind it to a port
                    MainActivity.lst.add(message);
                }

                }catch(Exception e){
                    e.printStackTrace();
                }
        }
    }).start();
}

}
Just call your service inside this thread where I have incremented variable i and by this way you can populate the list in right order.
Answer: Can you tell whether the other class is Activity or Fragment ?
And while adding the data into Arraylist, you don't need the Thread to be run in order to insert new data to Arraylist
Comment: It's a java class and i need the thread cause it's a server connection method. I just want the users connected to be in a list.
Comment: So when you are calling the other class, you must pass the reference i.e. context of MainActivity class into your calling class.
Comment: Because then only you can call or use the members of that MainActivity class. Because in Android accessing other class members is totally different as comparison to core java programming.
Answer: Try to make "lst" and "adapter" both static.
Answer: I'm suspicious about the runOnUiThread. Can you provide more information why did you use this function? Also i highly recommend using RecyclerView
Also you can refer to this post for adding items to RecyclerView


How to add input data in json post

Question: I'm trying to send some post json data but I want to make it custom on every post I do with the user input, right now I'm doing it via CLI just to get the PoC.
Im having problems adding the custom input though, I tried this but it didn't work.
import requests
import json

ticket = input("Type the ticket you want to answer : ")
print("Ticket #" + ticket)

customInput = input("Type the message you will post : ")
print(answer)

headers = {
    'Content-Type': 'application/json',
}

data = '{ "helpdesk_note": { "body":customInput, "private":true }}'

response = requests.post('http://my.site.com/dir/dir/'+ticket+'/conversations/note.json', headers=headers, data=data, auth=('SOMEKEY', 'X'))

print("Ticket has been answered.")

When this happens it does not post any message but if I do have a premade "body" it posts if I add "" to my message e.g
data = '{ "helpdesk_note": { "body":"This will actually work", "private":true }}'

How can I make it as a custom input ??
Answer: Hello everyone thanks for your time and review, I just found out how to solve this situation in this link .
The code would look like this
data = json.dumps({ "helpdesk_note": { "body":customInput }})

Took it from this example
my_json_string = json.dumps({'key1': val1, 'key2': val2})

Thanks for the read stranger have a nice day stack.

How to add input data in json post


Duvida sobre comando list(zip) e conversão de dicionários para dataframes?

Question: Estou preenchendo algumas listas com entradas strings e outras numéricas e usando-as para preencher alguns dicionários com informações que preciso visualizar de forma alternada.
Eis que me surgiu a dúvida, o comando list(zip()) cria diversos dicionários associados a uma variável que eu posso acessar?
Consequentemente, posso associar uma variável a cada combinação de listas que eu queira? É possível converter esses dicionários em dataframes?
A=[]
B=[]
C=[]
list(zip(A,B))
list(zip(B,C))
list(zip(A,C))
list(zip(A,B,C))

Comment: Só um detalhe: segundo a [documentação](https://docs.python.org/3/library/functions.html#zip),  `zip` não retorna um dicionário, e sim um iterador de tuplas. Então se você faz `zip(A, B)`, ele retorna um iterador que, a cada iteração, retorna uma tupla contendo um elemento de `A` e outro de `B`. Ao fazer `list(zip(A, B))`, você tem uma lista com todas essas tuplas ([veja aqui](https://ideone.com/OUjkRp) um exemplo). O que o pandas faz é usar essas tuplas para criar o dataframe, e nem precisa de `list`, pode usar só `zip` direto, [veja](https://repl.it/@hkotsubo/AbsoluteUltimateEvaluations)
Answer: Sim. É possível converter dicionários em DataFrames. Na verdade, um dicionário com strings como chaves e valores como lista é uma forma pré-pronta de um pandas DataFrame. Com um dicionário no formato citado, basta usar o constructor pd.DataFrame para criar o dataframe. Exemplo:
import pandas as pd

data_dict={"Name":["Walter", "Saul", "Hank", "Sjyler"], "Age":[54,56,48,42], "Sex":["M","M","M","F"]}

pd.DataFrame(data_dict)

Output:
     Name  Age Sex
0  Walter   54   M
1    Saul   56   M
2    Hank   48   M
3  Sjyler   42   F

Como você notou, também é possível fazer isso usando a combinação do constructor de lista (list()) com o generator zip. No entanto, nesse caso, você precisa explicitar o nome das colunas. Exemplo:
names=["Walter", "Saul", "Hank", "Sjyler"]
age=[54,56,48,42]
sex=["M","M","M","F"]

pd.DataFrame(list(zip(names,age,sex)), columns=["Name", "Age", "Sex"])

Ouput:
     Name  Age Sex
0  Walter   54   M
1    Saul   56   M
2    Hank   48   M
3  Sjyler   42   F

Caso você não explicite o nome das colunas, o comando também funciona, mas  o nome das colunas será o default: [1,2,3].
Um informação adicional sobre a função zip. Essa função aplica uma espécie de distributiva nas listas para criar uma série tuples. Ela pertence à classe dos generators que são objetos usados para iteração, mas que, diferentemente de outros objetos utilizados para iteração, como list comprehensions, não geram um resultado. Por não não produzirem resultado, esses objetos usam menos memória. No seu caso específico, você só viu o resultado da função zip porque usou o list constructor.
Tudo isso para dizer que, embora seja possível, a construção de dataframes a partir de funções zip talvez não seja o procedimento mais comum. Usar dicionários me parece mais natural e mais simples.
Comment: Na verdade, nesse caso você gera o `DataFrame` do mesmo jeito, com a diferença que os nomes das colunas serão 1, 2, 3. Vou editar para deixar claro que o argument `columns` é opcional
Comment: Deixe-me tirar uma última dúvida, no caso, ao o comando list(zip()) para unificar as listas, estou restrito apenas a exibi-las de acordo com a ordem que escolhi na disposição das listas.

E ao usar pd.DataFrame(list(zip(...)) eu apenas posso exibir o Dataframe?

Estou perguntando isso porque notei que ele não mostra o DataFrame gerado no console de variáveis.
 mas existe a possibilidade de convertê-lo para uma variável que eu posso manipular?
Como as listas sou eu que insiro manualmente, faz mais sentido usar o primeiro método, porém apenas para aproveitar a dúvida


WPF Binding: Static resource cannot be resolved

Question: I tried to run this example but I got binding problem.
Designer highlights the error The resource "monthCollection" could not be resolved
How can I use Utility.MonthCollection as local resource?
XAML part:
<Window x:Class="FaceReport.WindowMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Rapor" Height="402" Width="600" WindowState="Normal">
<Grid Name="gridMain" x:Uid="uidGridMain">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <ComboBox SelectedIndex="0"
              DisplayMemberPath="Value" SelectedValuePath="Key" Margin="132,9,200,0"
              Grid.Row="3" Height="24" VerticalAlignment="Top" Name="cbBind"

              ItemsSource="{Binding Source={StaticResource Utility.ReportForCollection},
                Path=Utility.ReportForCollection}"
              />
 </Grid>
 </Window>

C# part:
namespace FaceReport
{
internal class Utility
{
    public enum ReportFor
    {
        Choose,
        All,
        Group,
        Person
    }

    private static Dictionary<ReportFor, string> _dictReportFor;
    public static Dictionary<ReportFor, string> ReportForCollection
    {
        get
        {
            return _dictReportFor;
        }
    }

    static Utility()
    {
        //initialize the collection with user friendly strings for each enum
        _dictReportFor = new Dictionary<ReportFor, string>(){
            {ReportFor.Choose, "Lütfen seçiniz..."},
            {ReportFor.All, "Herkes"},
            {ReportFor.Group, "Grup"},
            {ReportFor.Person, "Şahıs"}};
    }
}

///
/// Application's main form
///
public partial class WindowMain : Window
{
    ///
    /// Constructor
    ///
    public WindowMain()
    {
        InitializeComponent();
    }
}

Comment: Please post the relevant portion of your code rather than linking to an external website or blog.
Answer: You're missing this bit:

->this Utility class can be instantiated as a resource<- and then
  referenced in the ComboBox creation.

It'll look something like this:
<Application.Resources>
    <local:Utility x:Key="monthCollection"/>
</Application.Resources>

This bit:{Binding Source={StaticResource monthCollection}, Path=MonthCollection
says to find the static resource monthCollection and on it use the property MonthCollection so you first must instantiate the object which has `MonthCollection as a property and then reference that static resource.
You will probably also need a statement something like this added to the top of your file:
xmlns:local="clr-namespace:YourNamespaceHere"

Untested code below:
<Window x:Class="FaceReport.WindowMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:FaceReport"

 Title="Rapor" Height="402" Width="600" WindowState="Normal">

<Application.Resources>
    <local:Utility x:Key="reportCollection"/>
</Application.Resources>

 <Grid Name="gridMain" x:Uid="uidGridMain">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <ComboBox SelectedIndex="0" DisplayMemberPath="Value" SelectedValuePath="Key"  Margin="132,9,200,0" Grid.Row="3" Height="24" VerticalAlignment="Top" Name="cbBind"
     ItemsSource="{Binding Source={StaticResource reportCollection}, Path=ReportForCollection}" />
 </Grid>
</Window>

Answer: Please add an entry like below in app.xaml:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="/Skins/ControlSkin.xaml">
         </ResourceDictionary>
            <ResourceDictionary Source="/Skins/ListBox.xaml">
          </ResourceDictionary>
        </ResourceDictionary.MergedDicionaries>
    </ResourceDictionary>
</Application.Resources>


Why cant i sum up all of my values (user values) problem with while?

Question: I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
    n=input("PERSONS WEIGHT?")
    people=0

    answer= input( "Do we continue adding people ? y/n")
    if answer == "y" :
        continue
    elif answer == "n" :
        break
    else:
        print("You typed something wrong , add another value ")
    people +=1
    limit=300
    if a > limit :
        print("Cant use the lift")
    else:
        print("Can use the lift")

Comment: `cilveki=0` resets it back to 0 with each loop. Maybe you should have that outside of the loop.
Comment: you need to share your current code and explain the issue.
Comment: As I said, I'm new to this. I've been stuck here for awhile.
Comment: Side note that a is not defined, assuming this is all your code.
Comment: `limit=300` could be moved outside of the loop.
Comment: a=(all of the users' inputs added up)
Answer: You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
  n = int(input("Enter Number.? Press -1 for Exit: "))
  if n == -1:
    break
  sum = sum+n
print(sum)

Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Answer: Here's something for you to learn from that I think does all that you want:
people = 0
a = 0

while True:

    while True:
        try:
            n = int(input("PERSONS WEIGHT?"))
            break
        except ValueError as ex:
            print("You didn't type a number.  Try again")

    people += 1
    a += int(n)

    while True:
        answer = input("Do we continue adding people ? y/n")
        if answer in ["y", "n"]:
            break
        print("You typed something wrong , add another value ")

    if answer == 'n':
        break

limit = 300
if a > limit:
    print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
    print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))

The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.


How to test correlation between ordinal and a binary variable?

Question: I wanna know which test should I use to see if there's correlation between the number of risk factors for a disease (three groups: none, 1, 2 or more), and the presence of symptoms for this disease (two groups: yes or no).
I'm very confused about the hypothesis I want to test, but I think my question would be "As risk factors increase, do patients become more symptomatic?"
Answer: I'd phrase this as a logistic regression model, where the model is
$$
\log(\frac{p}{1-p}) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \epsilon_i,
$$
where $x_1$ is 1 if there is 1 risk factor present, zero otherwise,
and $x_2$ is 1 if there are 2 or more risk factors present, and zero otherwise.
Once the model has been fit (easy to do in R or Python), the coefficients can be interpreted as the difference in log odds between when the respective regressors are zero and one.
Note that $p$ is the likelihood of disease, and the expression $log(\frac{p}{1-p})$ is known as the log odds of the disease.


Pesquisa usando model

Question: Gostaria de usar o meu model para fazer pesquisa no Laravel.
Gostaria que, se possível, algum pudesse me explicar:
Tenho minha model
class minhaModel extends Model
{
    protected $table = "minha_model";
    public $timestamps = false;
    protected $primaryKey = 'ID_CAMPO';
    public $incrementing = false;
    public $sequence = 'MINHA_SEQUENCIA';
}

O que eu quero saber é porque isso aqui funciona:
    use Illuminate\Support\Facades\DB;
    /* ... */
    $model = DB::select( 'SELECT * FROM minha_model WHERE campo1 = ?', array( $codigo ) )

E isso aqui não funciona:
   use App\HamOcorrenciasAnvisa;
   /* ... */
   $model = MinhaModel::where( 'campo1', $codigo );

A tabela é:
id_campo | campo1 | campo2
  1      |  123   |  321
  2      |  222   |  333

Estou começando com Laravel.
Comment: Isso mesmo.. Deu certinho. Muito obrigado!
Comment: Colocada em baixo (; , obgado pelo requisito da resposta
Comment: E se fizeres: `$model = MinhaModel::where( 'campo1', $codigo )->get();`?
Comment: Pode adicionar resposta, por favor
Answer: Na realidade está tudo bem, mas incompleto.
Neste momento:
$model = MinhaModel::where( 'campo1', $codigo );

Apenas ficas com o Builder, não estás ainda a extrair os resultados, para isso precisas só de acresentar ->get();:
$model = MinhaModel::where( 'campo1', $codigo )->get();

Comment: que show essa resposta

Pesquisa usando model


'install-peerdeps' is not recognized as an internal or external command, operable program or batch file (windows 7)

Question: I'm trying to setup an ES6 starter project/template/workflow here and I'm trying to include Airbnb's ESLint/javascript style guide. I currently have ESLint setup in the project.
I am on Windows 7, node v8.11.1, npm v4.1.2.
Per instructions at https://www.npmjs.com/package/eslint-config-airbnb-base
I have installed install-peerdeps via:
npm install -g install-peerdeps

It looks like it's version 1.6.0.
When I then run:
install-peerdeps --dev eslint-config-airbnb-base

I get the following error:
'install-peerdeps' is not recognized as an internal or external
command, operable program or batch file.

My NODE_PATH variable is set to:
%AppData%\npm\node_modules

If I do a npm root -g I get:
C:\Users\<username>\AppData\Roaming\npm\node_modules

Anyone have any ideas how I can get install-peerdeps working?
Comment: npm paths have really bad issues. Try checking both of those physical paths, and running it directly from the node_modules where it installed in package manager console.
Comment: Do you think that be this file?  C:\Users\\AppData\Roaming\npm\node_modules\install-peerdeps\lib\install-peerdeps.js ? There's also a cli.js in lib.
Comment: It looks like perhaps it's the cli.js file?  From their package.json fie: "bin": {
    "install-peerdeps": "lib/cli.js"
  },
Answer: Do you have the install-peerdeps globally installed?
Try installing install-peerdeps the package as mentioned here and try again.
# If you're using npm
npm install -g install-peerdeps

# If you're using yarn
yarn add install-peerdeps -g

I had the same error on the OSX and I got it solved after I installed the install-peerdeps package. I hope it solves the error for windows as well.


use custom post type as a field in other custom post type

Question: here is what i definded so war in functions.php
function create_post_type(){
    register_post_type('my_persons',
        array('labels' =>
            array(
                'name' => __('Persons'),
                'singular_name' => __('Person')
            ),
            'public' => true,
            'menu_position' => 5,
            'rewrite' => array('slug' => 'persons'),
             'supports' => array('title', 'editor','thumbnail')
        )
    );
    register_post_type('my_shoes',
        array('labels' =>
            array(
                'name' => __('Shoes'),
                'singular_name' => __('Shoe')
            ),
            'public' => true,
            'menu_position' => 6,
            'rewrite' => array('slug' => 'shoes'),
             'supports' => array('title', 'editor')
        )
    );
    }
add_action('init', 'create_post_type');

What I'm trying to do is, when adding a new Person, I want to see a list of (already added) Shoes and select (via checkbox) which shoes he owns.
I already installed the "Advanced Custom Fields" Plugin. I know it is possible to define a CheckBox List of Shoes in there and use it as fields for Persons. But I want this field to be dynamically filled, when adding new "Shoes" custom posts.
It's hard to explain, but I guess you get the point. I am using Wordpress 3.7.1 by the way and I am completely new to this.
Any help is appreciated ;-)
Comment: I think that this plugin already have a drop-down list for custom_post_types..
Comment: If so, I can't find it.
Comment: I confused a the checkbox with dropdown. It has an option called post_object to generate Dropdown ( not checkbox I think..) but look at my answer . YOu can easily filter the checkbox .
Answer: See the Documentation here :
you will need to use a filter my_acf_load_field( $field ) , then query for your custom post type shoes : for example
 query_posts(array(
        'post_type' => 'shoes',
        'showposts' => 10
    ) );

And then populate the array of fields like the code examples in documentation.


Instrumental variable as a control variable

Question: I understand that instrumental variable is used to address endogeneity bias since there could be correlation between the variable of interest and the error term.
Suppose now we want to see the estimated effect of X on Y. After some searching, I still do not know why we can't simply include the instrumental variable (Z) as another control variable in the OLS regression. Yes, this variable can increase the multicollinearity because it's correlated with X and it's not correlated with the error term. But this can only reduce precision of the estimate on X but not produce much bias.
If I consider Z as another control variable and omit it from the model of Y on X, does it increase bias? I think it does because Z and X are correlated.
What am I misunderstanding here?
Comment: Part of the definition of an instrumental variable $z$ is that it does not affect $y$ *directly* (i.e., the so-called [exclusion restriction](https://stats.stackexchange.com/q/508564)), which means it should not belong in your regression model.
Answer: There is already a good answer, but I will try to explain the problem more explicitly with mathematics. However, to grasp the problem, you have to think of it in terms of causality, not just correlation; for this, DAGs can be quite helpful.
Here are the equations from the DAG in the previous answer:
$$ Y = \beta X + \gamma U + e $$
$$ X = \delta U + \theta Z + v$$
I've also introduced the independent error terms $e$ and $v$, which means that there is some exogenous variation in $Y$ and $X$ that is not explained by $U$ or $Z$. Note that we're also assuming that $U$ and $Z$ are independent.
If we regres $Y$ on $X$ by OLS, the theoretical analogue of the OLS-estimator is1
$$ \frac{Cov(X,Y)}{Var(X)} = \underbrace{\beta \vphantom{\frac{Var(U)}{Var(X)}}}_{\text{true parameter}} + \underbrace{\gamma\delta \frac{Var(U)}{Var(X)}}_{\text{omitted variable bias}}$$
Notice that $Z$ has nothing to do with the omitted variable bias (OVB); the only source of OVB is that $U$ causes both $X$ ($\delta$) and $Y$ ($\gamma$). To see how the OVB would be affected by adding $Z$ as a control variable we can use the Frisch–Waugh–Lovell (FWL) theorem. According to FWL, regressing $Y$ on $X$ with $Z$ as a control variable is the same as regressing $X$ on $Z$, saving the residuals and regressing $Y$ on those residuals. Let's denote the residuals $\tilde{X} = \delta U + v$.2 Now, a regression of $Y$ on $\tilde{X}$ yields
$$ \frac{Cov(\tilde{X},Y)}{Var(\tilde{X})} = \beta + \gamma\delta \frac{Var(U)}{Var(\tilde{X})}$$
Notice that the expression is essentially unchanged. $Z$ has neither removed nor introduced bias. However, because $Var(X)>Var(\tilde{X})$3, adding $Z$ as a control variable will amplify the omitted variable bias from $U$.
Here's how I would explain it in less technical terms: There is both good and bad variation in $X$. If it were possible, we would like to control for $U$ because that would remove bad variation from $X$ and reduce (get rid of) OVB. Controlling for $Z$ instead removes good variation from $X$. The situation had been different if
$$ Y = \beta X + \gamma U + \phi Z + e $$
In this case, $Z$ is not a valid instrument. Both $U$ and $Z$ are confounders and the only good (exogeneous) variation in $X$ that can be used to estimate its effect on $Y$ comes from $v$.

1 $$ \frac{Cov(X,Y)}{Var(X)} = \frac{Cov(\delta U + \theta Z + v, (\beta\delta + \gamma)U + \beta\theta Z + \beta v + e)}{Var(\delta U + \theta Z + v)} = \frac{\beta \left[\delta^2 Var(U) + \theta^2 Var(Z) + Var(v)\right] + \gamma\delta Var(U)}{\delta^2 Var(U) + \theta^2 Var(Z) + Var(v)} = \beta + \gamma\delta \frac{Var(U)}{Var(X)}$$
2Note that I'm cheating a bit here, becasue the residuals are actually $\tilde{X} = X - \hat{\theta}Z = \left(\theta - \hat{\theta}\right)Z + \delta U + v $. I believe the result still holds (at least approximately), but it's harder to prove.
3 $Var(X)-Var(\tilde{X}) = \delta^2 Var(U) + \theta^2 Var(Z) + Var(v) - \delta^2 Var(U) - Var(v) = \theta^2 Var(Z)$
Comment: 1. Because we have removed the variation from $Z$; see footnote 3 in edit. 2.  A regression of $X$ on $Z$ is what produces the residual $\tilde{X}$, which still contains variation from $U$ but no longer from $Z$. I think you might be confusing the definition of a variable (or "true model" / data generating process) and a regression
Comment: Thank you for the mathematics. This makes a lot of sense! I only want some confirmations. How can we know that $Var(X) > Var(\tilde{X})$? Is this because we have more variables in the regression of $X$, something related to lowering the variance (homoskedasticity)? Also, when you regressed Y on $\tilde{X}$, should $\tilde{X}$ be regressed on $Z$ instead of $U$? Am I misunderstanding?
Answer: The whole problem is that the effect of X on Y is confounded.  If you include the instrument in a regression, you do not isolate any effect of X on Y.
Consider the following DAG.

This is a typical DAG for an instrumental variable.  Here, we condition on the instrument and X, and there still exists a biasing path X <- U -> Y which the instrument does not block.

If I consider Z as another control variable and omit it from the model of Y on X, does it increase bias?

I'm not sure if it increases bias, but it certainly doesn't address confounding.
Comment: Thank you. It indeed does not address the correlation between X and the error term. However, I kept pondering about the bias if I included the IV. I think it's likely bias because Z and X are correlated. Even if X is now only the variation caused by Z, it's still correlated with Z, so the estimated coefficient on X must be biased when I omit Z. [wiki does not say about this clearly for me](https://en.wikipedia.org/wiki/Instrumental_variables_estimation#Testing_for_weak_instruments)


Erro "Missing '[' at start of message send expression"


Given a series of past coin tosses from an unfair coin, how can I calculate the confidence for the next toss result?

Question: So this is really difficult for me, but I would like to know if this is possible.
Let's assume I have an unfair coin (absolutely no assumptions can be made about the coin), and my past result has been T-T-T-H-T-H-T-T-T and I want to predict the the result of the next toss. In a way that let me formulate my answer in this way: "There is an X% confidence that the result of the next toss will be T". So I am trying to solve for X.
Comment: "*absolutely no assumptions can be made about the coin*" -- well, you seem to at least assume it has exactly two sides.
Comment: What it means "there is an X% confidence"? Simply that "there is probability X that the result will be T"? Or something else?
Answer:
I would like to know if this is possible. Let's assume I have an unfair coin (absolutely no assumptions can be made about the coin)

If you really can't make any assumptions about the coin, it's not possible. One key assumption is that each throw has a constant probability of tails. Perhaps your coin is unfair because it's made of a metal that deforms, and as you throw it it deforms in such a way that tails becomes more likely?

I want to predict the result of the next toss.

Making the assumption that throws have the same probability of tails (and that each throw is independent), you can then construct a model for the random variable $C$ of the coin landing on tails, where $C$ follows the Bernouilli distribution (each throw is a Bernouilli trial).
The model allows you ro estimate $P(C=\mathrm{tails})$. Of course you've seen 7 tails out of 9 and your estimate based on this sample is $P(C=\mathrm{tails})=7/9$. The model is helpful, because you only have 9 coin tosses, T-T-T-H-T-H-T-T-T, which isn't enough tosses to be sure that $7/9$ is a good estimate, and the model can help you quantify how sure you are about your estimate.

There is an X% confidence that the result of the next toss will be T

Here it's important to distinguish what is meant by probability and confidence. What you'd like to say is that there's an 7/9 probability the result will be T. But you could only do this if you have a very large number of tosses, much larger than 9. The probability 7/9 is known as a point estimate of the probability because it's the "best" single number you can give for the probability. It's helpful to give a range, which is where the confidence interval comes in.
Your model can give you a confidence interval around your point estimate. In this case a 95% confidence interval is from 0.40 to 0.97, which can be interpreted as meaning that it's plausible that the probability of seeing a tails on the next throw is anywhere from 0.40 to 0.97. (Strictly speaking it means that if you repeated your experiment of 9 coin tosses, then the confidence interval you got would contain the actual, true probability of rolling a tail 95% of the time. Look at the confidence-interval tag on this site for more information.)
Comment: I think you swapped heads and tails for your CI; the probability of *heads* should be .03 to .6.
Comment: @Dougal thankyou, I originally had 2/9 for the probability and then had to go through the whole post correcting it and missed one!
Answer: Think of a fair coin for the time being:
We can be reasonably sure that it is fair because we have tossed it, say, 100 times, and it has landed exactly 50 times on heads and 50 times on tails.
In reality, even using a fair coin would probably not get exactly half the throws resulting in heads and the other half in tails, due to the way you throw it, minor imperfections in the coin, and other factors. Also, due to the unpredictable nature of probability, even with a series of perfectly fair tosses it would actually be just as probable for all your throws to land on heads as a half heads/half tails distribution, or indeed any other combination of results. The chance of having a misleading result such as and "all heads" distribution is, however, very small if you toss the coin 100 times, and gets smaller and smaller as you do more tosses, thus showing the importance of gathering lots of data.
But putting aside these things that force our prediction to never be completely perfect, let's go back to the original point: we know beyond reasonable doubt a coin is fair because it lands half of the time on head, and the rest of the time on tails, no matter how may throws you do.
Now let's think of a different coin. We throw it 100 times, but it lands only 25 times on heads and 75 times on tails. Now, the coin could in fact still be a fair coin, and this strange result pattern just be a fluke, but that is very unlikely, so we'll have to suppose that the coin will always throw in this pattern, even if we increase the total number of throws to 100, or 10000, or a million, or even more. After we make this decision to stop throwing for the sake of accuracy and being sure, the maths is simple. As we did 100 throws, and the coin landed on heads 25 times, the coin landed on heads 25/100 times. So the probability of flipping this coin and it landing on heads is 25/100, and if we convert this to a percentage, it is 25%.
If you just want to get a mathematical formula and skip my explanations, the formula for the number of times the coin lands on heads is:
P = H/N
where P is the probability of the coin landing on heads, H is the number of times the coin landed on heads while you were throwing it, and N is the total number of throws you did.
This will give you a decimal (here 0.25), so to convert it to a percentage (here 25%), you multiply it by 100.
I hope this answers your question and was not too long.
Comment: @rocinante I believe the OP has to give further clarifications. He does not ask for "confidence X% that _the probability of_ obtaining Tails will be YY" - (which could point to a confidence interval around an estimated probability). He specifically writes "confidence X% that _we will obtain Tails_", and it is not clear what he means.
Comment: I don't think that this addresses any of the points in the question, though. The poster is asking about confidence (i.e. confidence interval) surrounding a probability, given past behavior, not about how to calculate a simple probability.
Comment: @Alecos Papadopoulus The question was tagged with "confidence interval", so I think the question is clear that the poster was *not* asking how to calculate a simple probability as the clumsy answer above asserts.
Comment: @rocinante You are probably right, but I do not trust tags to clarify a confusingly phrased question -this is why I have asked the OP for clarifications.


Can we share controll file in an univarsal (iPhone, iPad) Application?

Question: I developed a univarsal application,(iPhone, iPad). But later I tried to make them sepret, so i copied my folder in another directory and then linked my iPhone's control file with iPad's XIBs, and delegated them with Outlets, (my controll file remained in the iPhone folder, i just link them in iPad), after it i removed iPhone XIBs from this folder.
Now my project is working properly, BUT only if I execute the iPhone version first(even from that different directory), and then execute my iPad version, coz it share's the build file of iPhone.
But when I try to execute it Initially (after deleting prior installed version from simulator), it doesn't work, as it terminate after throwing following exception.
<code>2011-04-23 10:56:01.831 Tuscany[1837:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
*** Call stack at first throw:
(
0   CoreFoundation                      0x01683be9 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x014785c2 objc_exception_throw + 47
2   CoreFoundation                      0x0163c628 +[NSException raise:format:arguments:] + 136
3   CoreFoundation                      0x0163c59a +[NSException raise:format:] + 58
4   Foundation                          0x000d6b12 -[NSURL(NSURL) initFileURLWithPath:] + 90
5   Foundation                          0x000d6aa0 +[NSURL(NSURL) fileURLWithPath:] + 72
6   Tuscany                             0x0003572c -[SplashScreenViewController readyPlayer] + 77
7   Tuscany                             0x00035a62 -[SplashScreenViewController viewDidLoad] + 296
8   UIKit                               0x003e865e -[UIViewController view] + 179
9   UIKit                               0x0035e026 -[UIWindow addRootViewControllerViewIfPossible] + 51
10  UIKit                               0x0035d511 -[UIWindow _setHidden:forced:] + 303
11  UIKit                               0x0035d301 -[UIWindow _orderFrontWithoutMakingKey] + 50
12  UIKit                               0x0a2ac110 -[UIWindowAccessibility(SafeCategory) _orderFrontWithoutMakingKey] + 56
13  UIKit                               0x0035bfb5 -[UIWindow makeKeyAndVisible] + 39
14  Tuscany                             0x00003205 -[AppDelegate_iPad application:didFinishLaunchingWithOptions:] + 1472
15  UIKit                               0x0033b1fa -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163
16  UIKit                               0x0033d55e -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 439
17  UIKit                               0x00347db2 -[UIApplication handleEvent:withNewEvent:] + 1533
18  UIKit                               0x00340202 -[UIApplication sendEvent:] + 71
19  UIKit                               0x00345732 _UIApplicationHandleEvent + 7576
20  GraphicsServices                    0x01ce3a36 PurpleEventCallback + 1550
21  CoreFoundation                      0x01665064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
22  CoreFoundation                      0x015c56f7 __CFRunLoopDoSource1 + 215
23  CoreFoundation                      0x015c2983 __CFRunLoopRun + 979
24  CoreFoundation                      0x015c2240 CFRunLoopRunSpecific + 208
25  CoreFoundation                      0x015c2161 CFRunLoopRunInMode + 97
26  UIKit                               0x0033cfa8 -[UIApplication _run] + 636
27  UIKit                               0x0034942e UIApplicationMain + 1160
28  Tuscany                             0x00002b30 main + 102
29  Tuscany                             0x00002ac1 start + 53
)
    terminate called after throwing an instance of 'NSException'
</code>
here to mention i have worked hard with the line i'm establishing connection, and as i told same code run properly when I execute iPhone version first and then the iPad.
so please guied me with this,
thank you
Answer: What it says.
In the readyPlayer method you are trying to give a nil value to the fileUrlWithPath method.
You need to check why the path is nil.
Comment: Thank you a lot.. i have been stuck up with with it since last three days.. thanks again.. :)