Xcode 9 GM - WKWebView NSCoding support was broken in previous versions

Question: Does anyone know how to fix this error with Xcode 9 GM? I'm working on an app made with Xcode 8.3, the deployment target is for iOS 9.3 and I never had this problem before. I don't find any information here or on Apple forums yet :(
Edit: This error came when I put a WKWebView into interface builder, not if I use it programmatically.

Edit 2: Well, it's finally not a bug, see Quinn's answer below to have more information about this behavior. Thanks to him for the explanation.
Comment: See my answer below. This is not a bug in Xcode 9; without this build error, you would instead get a crash in -initWithCoder: at runtime prior to iOS 11.
Comment: I just change my deployment target to 11
Comment: This should be a comment on Kampai's answer, but I don't have enough reputation points to comment. Besides explicit iOS versions the 'Builds for' dropdown in the 'File Inspector' also contains the **Deployment Target (..)** option. I prefer managing versions at a single place if possible and wanted to change the build target anyway. I was fully confused it still said **Deployment Target (9.3)** although I changed the corresponding entry in the general settings to **11.0**. **Restart** of XCode (11.3.1) was necessary to make everything work as expected, the option 'Deployment Target (11.0)' was
Answer: The error is correct behavior, and not a bug in Xcode 9. Although WKWebView was introduced in iOS 8, there was a bug in -[WKWebView initWithCoder:] that was only fixed in iOS 11, which always crashed at runtime and thus prevented configuring one within Interface Builder.
https://bugs.webkit.org/show_bug.cgi?id=137160
Rather than allow developers to build something in IB that would be broken at runtime, it is a build error. It's an inconvenient limitation since iOS 11 was only recently released, but there's really no other good option.
The workaround for older deployment targets is to continue to add the WKWebView in code, as @fahad-ashraf already described in his answer:
https://developer.apple.com/documentation/webkit/wkwebview
Comment: Hi Quinn, I believe the man who works at Apple :-) I also found your bug report about that : https://lists.webkit.org/pipermail/webkit-unassigned/2014-September/640090.html Thank you for your answer it's really surprising for new developers like me when we encountering a behavior like that. Thanks again.
Comment: what if we want to support in ios10 also?. in my app i need to support ios 10 also.How can we solve this issue?
Comment: just curious why did it take Apple until iOS 11 to figure out a fix?
Answer: This seems to be a bug in Xcode 9 and was also present in the betas. You will only get the build error if you are creating a WKWebView through the storyboard. If you progmatically create the WKWebView in the corresponding ViewController class file, you should be able to build on iOS versions below iOS 11.
Here is the approach given on Apple's website for how to accomplish this:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!

    override func loadView() {
        super.loadView()
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string: "https://www.apple.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }}

You should then be able to implement WKWebView functionality as you normally would.
Source: https://developer.apple.com/documentation/webkit/wkwebview
Comment: don't forget `super.loadView()`
Comment: `super.loadView()` has to be at the beginning. Without it, nothing shows.
Comment: hi :), do you know how I can set the constraints of this `webview` to below my NavigationBar? This solution of you works but it covers the whole screen.
Comment: @AbedNaseri i think you don't need to put constraints... you can instantiate storyboard and then  self.navigationController?.pushViewController(youVC, animated: true) .
Comment: programmatically set the frame / constrain is the key.
ps. I didn't use super.loadView()
Answer: If you want to realize a custom UIViewController with other components in addition you can make a "container" through the storyboard called for example webViewContainer:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
    @IBOutlet weak var webViewContainer: UIView!
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let webConfiguration = WKWebViewConfiguration()
        let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: self.webViewContainer.frame.size.width, height: self.webViewContainer.frame.size.height))
        self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
        webView.translatesAutoresizingMaskIntoConstraints = false
        self.webViewContainer.addSubview(webView)
        webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
        webView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true
        webView.uiDelegate = self

        let myURL = URL(string: "https://www.apple.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }

Comment: If you are getting the error `[LayoutConstraints] Unable to simultaneously satisfy constraints`, don't forget the line `webView.translatesAutoresizingMaskIntoConstraints = false`.  If you leave it set to true, it will create a whole set of constraints for your `webView` automatically which will conflict with the constraints you add programmatically.  [Apple Docs](https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco).
Comment: Worked! tested in iOS 11 and swift 4.1
Comment: Just change the following line

From:
`let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webViewContainer.frame.size.height))`

To:

`let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: self.webViewContainer.frame.size.width, height: self.webViewContainer.frame.size.height))`
Comment: Thank you so much, it's really help. It's a bug know by Apple
Answer: If you are moved from older target to iOS 11.0 and still you are getting this error, then use below solution.

Go to Storyboard (Main.storyboard), click on any Scene.
Select 'File Inspector' which is the right side property window of Xcode
Change 'Builds for' value to 'iOS 11.0 and Later'
Compile and Build
Comment: @VyachaslavGerchicov: I don't know about you, but in the industry, we do have such older projects which need to be converted to newer tech. So many facing the same problem. I already mentioned in the answer that "if you are moved from older target". Don't think of only one case.
Comment: This works for me thanks for pointing this annoying IB setup. The warning is gone right away. Actually, I think this more practical and should be accepted answer. Agree with @Kampai, actually, we are forced to move to the new version of iOS, since the Apple keep changing their fundamental frameworks
Comment: Simplest solution for fixing this issue. Thanks!
Comment: After doing it when running on simulator with iOS 10.x app crashes.
Comment: @Ramis: I was doing it for iOS 10, I never got app crash, what was the crash log?
Comment: @Kampai: Currently I can not remember exact crash log. So can not answer to your question.
Comment: For those considering building for iOS 11 and above, as of August 6, 2019 only 3% of users are using < iOS 11.
Answer: I have faced the same issue but it can be tackle if we add WKWebView programmatically.

Do whatever design you want to make in storyboard but leave the room for WKWebView, in that area drag & drop a view and name it as webViewContainer and declare these two properties,
@property (weak, nonatomic) IBOutlet UIView *webViewContainer;
@property(nonatomic, strong)WKWebView *webView;

Now create and add webView like this:
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self.webView = [self createWebView];
    self = [super initWithCoder:aDecoder];
    return self;
}

createWebView function is declared as,
-(WKWebView *)createWebView
{
     WKWebViewConfiguration *configuration =
               [[WKWebViewConfiguration alloc] init];
     return [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
}

Now add this newly created webView to your containerView, like this, :
-(void)addWebView:(UIView *)view
{
      [view addSubview:self.webView];
      [self.webView setTranslatesAutoresizingMaskIntoConstraints:false];
      self.webView.frame = view.frame;
}

Finally, just load your Url like this,
-(void)webViewLoadUrl:(NSString *)stringUrl
{
     NSURL *url = [NSURL URLWithString:stringUrl];
     NSURLRequest *request = [NSURLRequest requestWithURL:url];
     [self.webView loadRequest:request];
}

Thanks for reading this.
Answer: WebKit was introduced in iOS 8 but it was released with an error which caused in a runtime crash, If you are using Xcode 9/10, your project configuration support less than iOS 11 and if you are trying to add WKWebView using interface builder. Xcode immediately shows a compile-time error.
WKWebView before iOS 11.0 (NSCoding Support was broken in the previous version)
Although WKWebView was introduced in iOS 8, there was a bug in –[WKWebView initWithCoder:] that was only fixed in iOS 11.

Resolution is you must add WKWebView through code (Only if you are supporting below iOS 11). That actually sounds strange.
Another solution is to change the Interface Builder Document Builds for the option to iOS 11 and later (If you're migrating from older target to iOS 11 and still getting the same error).
Answer: //For Swift
import WebKit

class ViewController: UIViewController {
var webView: WKWebView!

// MARK:- WebView Configure
override func loadView() {
    let webConfig = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero, configuration: webConfig)
    view = webView
}

override func viewDidLoad() {
    super.viewDidLoad()
    // call urlrequest fun
    loadURLRequest()
}

//MARK:- Webview URLRequest
func loadURLRequest()  {
    let urlString = "https://www.google.com"
    let url = URL(string: urlString)
    let urlRequest = URLRequest(url: url!)
    webView.load(urlRequest)
}
}

// For Objective C
#import <WebKit/WebKit.h>

@interface ViewController ()<WKNavigationDelegate,WKUIDelegate>{
WKWebView *webView;
}

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

NSURL *url = [[NSURL alloc] initWithString: @"https://www.google.com"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
    [webView loadRequest: request];
}

- (void)loadView {
[super loadView];

WKWebViewConfiguration *configu = [[WKWebViewConfiguration alloc] init];
webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configu];
webView.UIDelegate = self;
self.view = webView;
}

@end

Answer: import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {

    @IBOutlet weak var webViewContainer: UIView!
    private var webView: WKWebView?

    override func viewDidLoad() {
        super.viewDidLoad()

        addWebView()

        let myURL = URL(string: "https://www.apple.com")
        if let myURL = myURL {
            let myRequest = URLRequest(url: myURL)
            webView?.load(myRequest)
        }
    }

    private func addWebView() {
        let webConfiguration = WKWebViewConfiguration()
        let size = CGSize.init(width: 0.0, height: self.webViewContainer.frame.size.height)
        let customFrame = CGRect.init(origin: CGPoint.zero, size: size)
        self.webView = WKWebView (frame: customFrame, configuration: webConfiguration)
        if let webView = self.webView {
            webView.translatesAutoresizingMaskIntoConstraints = false
            self.webViewContainer.addSubview(webView)
            webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
            webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
            webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
            webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
            webView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true
            webView.uiDelegate = self
        }
    }
}

Answer: You can just set IPHONEOS_DEPLOYMENT_TARGET >= 11
[Deployment Target]
Answer: UIWebView is deprecated in iOS11 and WKWebView works only in iOS11 - this sounds like a bug in Xcode GM.
Comment: Yep. The only workaround I found if you want to deploy on previous version of iOS is to add your WKWebView programmatically.


Does bottleneck guitar use different tuning?

Question: A naive question from a non-musician, so be kind please.
I'm curious whether playing with a bottleneck slide requires different tuning than 'ordinary' playing. I've seen great players picking and fretting in what seem like a perfectly normal style, then introducing a bottleneck and playing in what feels like a totally different style, with no retuning.
In other cases, I've seen a player in the same situation switch guitars just to play bottleneck, presumably because it requires a different tuning.
So do the first class of players just learn to pick differently on a guitar tuned for bottleneck, or what?
Comment: To address the core of your question, does it *require* a different tuning: Unless a guitarist corrects me, no. There might be a tradition of other tunings, but no reason you can't use a slide with standard tuning. You might see people switching guitars for other reasons, like reaching for a steel guitar for resonance.
Comment: @AndyBonner - slide playing is far more effective when the tuning favours the harmony of the piece. 'Require' opens a big can of worms.
Comment: My basic lack of understanding: I'm not sure how often a slide player hitting chords or even multiple strings at once. I was assuming we were talking a mostly melodic, "lead" context.
Comment: Open tuning is more typical, but standard can be used too. https://www.premierguitar.com/lessons/a-beginners-guide-to-standard-slide
Comment: @Tim - yeah, 'require' wasn't the best word. Good info here regardless.
Answer: Yes - and no. Standard tuning will mean judicious angling of the bottleneck or whatever's being used. A perpendicular angle will give a minor triad on the top 3 strings, but moving it to an angle can produce a major one - albeit not spot on in tune.It'll also give a major triad (the relative major at the same fret, and the VII either 5 or 7 frets away)- Theodore, thanks for the reminder!
For that reason, most players will have an open tuned guitar, where perpendicular placing will make major or minor chords easily. Another (slight) problem for some is that for slide playing, the strings are better with a higher action, which means for ordinary playing, it's not so pleasant. So either way, there's a compromise - or use (at least) two differently tuned guitars.
Comment: A perpendicular angle will also give a major triad in 2nd inversion on the 2nd through 4th strings.  That's How I'll often play slide chords on a standard-tuned guitar.
Comment: @Theodore - true - completely forgot that - I use it in songs in G, for a harmonic chord at 12th fret (G) and 7th fret (D). Thanks for the reminder!
Answer: This is of course up to you how you tune the guitar, but slide guitar players often use open tunings, to make the most use of the slide touching several strings perpendicularly.
See e.g. What is an "open tuning"?
Comment: This is also covered well in the [Technique section](https://en.wikipedia.org/wiki/Slide_guitar#Technique) of Wikipedia's article on Slide guitar.
Answer: There's a lot to playing slide that becomes much easier when you tune to an open tuning, especially when you're playing and accompanying yourself.
However, a triad (root, third and fifth) comes for free on the second, third and fourth strings of a guitar in standard tuning, making it easy to jump between bottleneck and standard playing. You might want to string the guitar up with higher tension strings and higher action than you would normally like, but nothing too out of line. This makes more sense in a band situation.


arrayformula with ifs, isblank and AND/OR in google sheets

Question: What I am trying to achieve is a formula that checks the top row for "all are blank" or "all are not blank" in specified ranges. Depending on the conditions the cell with the formula gives back 1 of 3 words or leaves it blank.
I further illustrate this with the colours in the following images

The formula I have so far:
=ArrayFormula(ifs((not(isblank(A1:B1*C1:E1*G1:I1))*(isblank(J1:L1*N1:P1))),"SEND",
not(isblank(A1:B1*J1:L1*N1:P1))*isblank(C1:E1*G1:I1),"RECEIVE",
not(isblank(A1:B1*C1:E1*G1:I1*J1:L1*N1:P1)),"TRANSFER",
ISBLANK(A1:B1+C1:E1+G1:I1+J1:L1+N1:P1),""))
I don't understand what is wrong with the formula. As for example in the case when J1:L1*N1:P1 are filled, isblank(J1:L1*N1:P1) returns false when i want that to be true.
Comment: Well, what's the problem with what you have so far?
Comment: Right now it gives back "TRANSFER" no matter what's in the row. so how i want it is as follows; ranges are filled="TRANSFER", any of the range J:P is not filled="SEND", any of the range C:I is not filled="RECEIVE", any of the above is FALSE=empty cell
Answer: Here are the individual IF statements:
=IF((COUNTIF(A1:E1,"?*")=5)*(COUNTIF(G1:L1,"?*")=6)*(COUNTIF(N1:P1,"?*")=3)=TRUE,"TRANSFER","")

=IF((COUNTIF(A1:E1,"<>")=5)*(COUNTIF(G1:I1,"<>")=3)*(COUNTIF(J1:L1,"")=3)*COUNTIF(N1:P1,"")=3,"SEND","")

=IF((COUNTIF(C1:E1,"")=3)*(COUNTIF(G1:I1,"")=3)*(COUNTIF(J1:L1,"<>")=3)*COUNTIF(N1:P1,"<>")=3,"RECEIVE","")

Here are the nested IF statements.
=IF((COUNTIF(A1:E1,"?*")=5)*(COUNTIF(G1:L1,"?*")=6)*(COUNTIF(N1:P1,"?*")=3)=TRUE,"TRANSFER",IF((COUNTIF(A1:E1,"<>")=5)*(COUNTIF(G1:I1,"<>")=3)*(COUNTIF(J1:L1,"")=3)*COUNTIF(N1:P1,"")=3,"SEND",IF((COUNTIF(C1:E1,"")=3)*(COUNTIF(G1:I1,"")=3)*(COUNTIF(J1:L1,"<>")=3)*COUNTIF(N1:P1,"<>")=3,"RECEIVE","")))

Comment: Thank you! that definitely helped me steer into the right direction. There were a couple of little mistakes relating to my specific requirements, but your statements are sound. So I adjusted your statements to my liking
Comment: Glad you were able to modify it to suit your needs. Just two notes. ISODD may not be necessary. Also, if you ever have functions in a cell which show the values, "<>" won't catch them. That's where "?*" will help.
Answer: So with the help of Nate I came up with the following formula:
=IFS(ISODD((COUNTBLANK(A1:E1)=0)*(COUNTBLANK(G1:L1)=0)*(COUNTBLANK(N1:P1)=0)),"TRANSFER", (ISODD((COUNTIF(A1:E1,"<>")=5)*(COUNTIF(G1:I1,"<>")=3)*(COUNTIF(J1:L1,"")=3)*COUNTIF(N1:P1,"")=3)),"SEND",ISODD((COUNTIF(C1:E1,"")=3)*(COUNTIF(G1:I1,"")=3)*(COUNTIF(J1:L1,"<>")=3)*(COUNTIF(N1:P1,"<>")=3)),"RECEIVE",true,"")


Results of GET Request inside block are being cached and not updating when GET request values are changed

Question: I have a block plugin that contains a form that performs a get request and reloads the current page. Currently it's set to allow a user to submit a state from a drop down box to be used as a filter.
This issue I'm having is the results from the get request are cached. It works after clearing the cache but right after, once I submit again with a new value for the dropdown the results do not update on the page, even though I can clearly see that the get request has changed. Below is the code I currently have
public function build() {
    $request = \Drupal::request();
    /* GET Variables */
    $state = (empty($request->get('state')))?'':$request->get('state');

    $render = '
    <form method="GET" class="relief-network-form">

    State:

    <select class="state" name="state">
        <option value="">Pick One</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
    </select>

    <input type="submit" value="Filter">
    </form>';
    return array(
        'test'    => [
            '#type'  => 'html_tag',
            '#tag'   => 'p',
            '#value' => 'State:'.$state.'-',
        ],
        'form'       => [
            '#type'     => 'inline_template',
            '#template' => $render,
        ],
    );
}

When submitting this form after the cache is cleared it displays the proper state in the p tag above the form, but afterwards it never changes. I have a feeling it has to do with using cache tags after reading the documentation here https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays
but to be honest I'm having trouble making sense of it, and I'm not sure how I would apply the examples to the current situation.
Is there a way to prevent the results of a GET request inside a block plugin from being cached?
Answer: You don't need cache tags, you need a cache context for the query key state:
$build['#cache']['contexts'][] = 'url.query_args:state';

Comment: I think that Block plugins add their cache contexts via a public method, [getCacheContexts](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Cache!CacheableDependencyInterface.php/function/CacheableDependencyInterface%3A%3AgetCacheContexts/8.2.x).
Comment: I think what I've seen how drupal handles cache metadata it should be placed in the render array. For example if you have a field that needs own cache metadata the field formatter builds a render array with the cache metadata placed in it. This field can be in a block, a controller or anywhere else.
Comment: Nothing wrong with using the block method, both work. Especially if you have conditions and only sometimes return something, then using getCacheContexts() can be easier as it is very important to *always* return the relevant cache contexts as your block might otherwise be cached empty for every condition


GCP/Infrastructure : Should a network admin be an organization admin?

Question: When setting up an organization's architecture/infrastrucutre in GCP, I am struggling to understand the division of responsibilities between general infrastructure creator/manager (typically, a terraform service account that has the accesses to organization-level roles) and general network administrator. The way I understand it, the former creates the projects, folders, handles the billing and IAM. While the latter handles everything network related, i.e. The Shared VPC, subnets, firewall rules, policies related to network-resources allocation etc...
In a past question I struggled with setting up a Shared VPC, only to come to the conclusion that the role roles/compute.xpnAdmin, involved in creating the Shared VPC, needs to be set at the organization's level. Which means that if I want to create (and perhaps manage?) the VPC, my network admin needs the same level of permissions as my infrastructure admin.
In this post's accepted answer it is stated that:

Google Cloud recommends that the Shared VPC Admin be the owner of the
shared VPC host project.

What is the correct paradigm if I want to set my network admin as the VPC admin; should I really be okay with my network admin having access to org level actions?
Comment: Refer to this article,
https://cloud.google.com/blog/products/identity-security/get-more-control-over-your-compute-engine-resources-with-new-cloud-iam-features
as you say, you can assign iam rights to the organization, but you can also assign iam to the resource itself.
Answer: The answer to your question "Should a network admin be an organization admin?" is clearly NO: 2 different roles, it's not the same admin responsibility!
However, by reading the content, my answer will be YES, a network admin can have the roles attached to the organisation level.
It doesn't make them an organization admins, only a network admins for the whole organization, and this time, yes, it's a valid pattern.
A better pattern is not to set a net admin "person", but a net admin "group", because most of the time, it's a whole team that manage the network for an organization.


Diffusion equation issue

Question: I need help, I'm stuck on this problem. Below is my progress.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\on{u}_{x}\pars{x,t} =
-\sum_{n = 1}^{\infty}\on{a}_{n}\pars{t}\,n\sin\pars{nx}}$ already satisfies
$\ds{\on{u}_{x}\pars{0,t} = \on{u}_{x}\pars{\pi,t} = 0}$. Note that
\begin{equation}
\int_{0}^{\pi}\cos\pars{mx}\cos\pars{nx}\,\dd x =
{\pi \over 2}\,\delta_{mn}\label{1}\tag{1}
\end{equation}
$\ds{\on{u}\pars{x,t} =
\sum_{n = 1}^{\infty}\on{a}_{n}\pars{t}\cos\pars{nx} + \on{f}\pars{t}}$ which must satisfies the above partial differential equation. Namely,
\begin{align}
&\sum_{n = 1}^{\infty}\dot{\on{a}}_{n}\pars{t}\cos\pars{nx} + \dot{\on{f}}\pars{t} +
\sum_{n = 1}^{\infty}\on{a}_{n}\,n^{2}\pars{t}\cos\pars{nx} =
\expo{-x}\label{2}\tag{2}
\end{align}
Integrate both members of (\ref{2}} over $\ds{x \in \pars{0,\pi}}$:
$$
\dot{\on{f}}\pars{t}\pi = -\expo{-\pi} + 1 \implies
\on{f}\pars{t} = {1 - \expo{-\pi} \over \pi}\,t + c
$$
$\ds{c}$ is a constant.
Use (\ref{1}) and (\ref{2}):
\begin{align}
&\dot{\on{a}}\pars{t} + n^{2}\on{a}\pars{t} =
{2 \over \pi}\int_{0}^{\pi}\expo{-x}\cos\pars{nx}\dd x =
{2 \over \pi}\,{1 - \expo{-\pi}\pars{-1}^{n} \over 1 + n^{2}}
\equiv \varphi_{n}
\\[5mm] &\
\totald{\bracks{\expo{n^{2}\,t}\on{a}_{n}\pars{t}}}{t} =
\varphi_{n}\expo{n^{2}\,t} \implies
\expo{n^{2}\,t}\on{a}_{n}\pars{t} -
\on{a}_{n}\pars{0} =
{\varphi_{n} \over n^{2}}\pars{\expo{n^{2}\,t} - 1}
\\[5mm] &\
\on{a}_{n}\pars{t} = \on{a}_{n}\pars{0}\expo{-n^{2}\,t} +
{\varphi_{n} \over n^{2}}\pars{1 - \expo{-n^{2}\,t}}
\\[5mm] &\
\on{u}\pars{x,t} =
{1 - \expo{-\pi} \over \pi}\,t + c +
\sum_{n = 1}^{\infty}\on{a}_{n}\pars{0}
\expo{-n^{2}\,t}\cos\pars{nx}
\\[2mm] + &\
\sum_{n = 1}^{\infty}
{\varphi_{n} \over n^{2}}\pars{1 - \expo{-n^{2}\,t}}
\cos\pars{nx}
\end{align}
Since $\ds{\on{u}\pars{x,0} = 0}$:
$$
0 = c +
\sum_{n = 0}^{\infty}\on{a}_{n}\pars{0}\cos\pars{nx}
\implies c = 0\ \mbox{and}\ \on{a}_{n}\pars{0} = 0\ \forall n
$$
Finally,
$$
\on{u}\pars{x,t} =
{1 - \expo{-\pi} \over \pi}\,t +
{2 \over \pi}\sum_{n = 1}^{\infty}
{1 - \expo{-\pi}\pars{-1}^{n} \over n^{2}\pars{n^{2} + 1}}\pars{1 - \expo{-n^{2}\,t}}
\cos\pars{nx}
$$

Diffusion equation issue


How to write $(2n-1) (2n-2) (2n-3) (2n-4)$ in terms of $n$ factorials

Question: I want to get the final equations in terms of $n$, for example $n = 3$, then the equation is: $(2n-1) * (2n-2) * (2n-3)$, if $n = 4$, then the equation is: $(2n-1) (2n-2) (2n-3) (2n-4)$.
Comment: $\frac{(2n-1)!}{(2n-5)!}$ Although I woudn't call this "simplification" :)
Comment: $\frac{(2n-1)!}{(n-1)!}$
Comment: my bad, I want to get the final equations in terms of n, for example n = 3, then the equation is : (2n-1) * (2n-2) * (2n-3), if n = 4, then the equation is : (2n-1) * (2n-2) * (2n-3)* (2n-4)
Comment: thank you! how did you get that?
Answer: Let's adress some cases:

n:=1 : n
(One term, given by (2n-1), reduces to 1 which was your n)

n:=2 : n(n+1)
(Two terms, (2n-1)(2n-2), reduces to $3*2$ which is n(n+1)

n:=3 : n(n+1)(n+2)
(Three terms, (2n-1)(2n-2)(2n-3), reduces to $5*4*3$,  a pattern, so

...

n:=n : n(n+1)(n+2)...(2n-1), using this pattern in terms of n as desired.

Note that when n is also the number of multiplicative elements, the last element (2n-n) is exactly n.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: thank you, I edit the question, but I still don't understand how to get (2−1)! / (−1)!
Answer: I think you are trying to write the expression
$$
(n)(n+1)...(2n-1)
$$
in a simpler form. Notice that
$$
(2n-1)!=(1)(2)...(2n-1)
$$
while
$$
(n-1)!=(1) (2)... (n-1)
$$
so
$$
\frac{(2n-1)!}{(n-1)!}=(n)(n+1)...(2n-1).
$$


Verilog FIFO code written with different styles..one not working and another not working.Can someone explain

Question: I have written verilog code for fifo using fillcount to check as the means for checking if it is full or empty.
There are 2 versions of the same code.
One is whereI have a seprate always always block for reading,writing,empty /full ,fillcount,and one for incrementing the pointers.This works fine,I have tested it and it works fine.
module FIFO (clk, reset, data_in, put, get, data_out, fillcount, empty, full);
parameter DEPTHP2 = 8 ;
parameter WIDTH = 8 ;
input [WIDTH-1:0] data_in;
input put, get, reset, clk;
output fillcount;
output reg [WIDTH-1:0] data_out;
output reg empty, full;

reg [3:0]fillcount ;
reg [WIDTH-1:0] fifo_1[0:DEPTHP2-1];
reg [2:0] rp,wp;

always@(posedge clk or posedge reset)
begin
   if( reset )
   begin
      wp <= 0;
      rp <= 0;
   end
   else
   begin
      if( !full && put )    wp <= wp + 1;
          else  wp <= wp;

      if( !empty && get )   rp <= rp + 1;
      else rp <= rp;
   end

end

always @(fillcount)
begin
if(fillcount==0)
  empty =1 ;
  else
  empty=0;

  if(fillcount==8)
   full=1;
   else
   full=0;
end

always @(posedge clk or posedge reset)
begin
   if( reset )
       fillcount <= 0;

   else if( (!full && put) && ( !empty && get ) )
       fillcount <= fillcount;

   else if( !full && put )
       fillcount <= fillcount + 1;

   else if( !empty && get )
       fillcount <= fillcount - 1;
   else
      fillcount <= fillcount;
end

always @( posedge clk or posedge reset)
begin:Reading
   if( reset )
      data_out <= 0;
   else
   begin
      if( get && !empty )
         data_out <= fifo_1[rp];

      else
         data_out <= data_out;

   end
end

always @(posedge clk)
begin:Writing

   if( put && !full )
      fifo_1[ wp ] <= data_in;

   else
      fifo_1[ wp ] <= fifo_1[ wp ];
end

endmodule

Another way is where I had combined the few always blocks together which effectng the logic(in my understanding!!)But it does not work for case when I try to read the data after writing immediately.It passes all other test cases.
I am not sure what went wrong..
It would be great if someone could point where I am going wrong.
//The code that is not working

always@(posedge clk or posedge reset)
begin:Writing
         if(reset)
        wp<=0;
        else
        if( put && !full)
        begin
            fifo1[wp]<=data_in;
            wp<=wp+1;
        end
        else
        begin
            fifo1[wp]<=fifo1[wp];
            wp<=wp;
        end
end

always@(posedge clk or posedge reset)
begin:Reading
    if(reset)
    begin
        rp<=0;
        data_out<=0;
    end
        else
    if(get && !empty)
    begin
        data_out<=fifo1[rp];
        rp<=rp+1;
    end
    else
    begin
        fifo1[rp]<=fifo1[rp];
        rp<=rp;
    end
end

always@(posedge clk or posedge reset)
begin:Fillcount
    if(reset)
        fillcount<=0;
        else
    if((!full && put ) && ( !empty && get))
        fillcount<=fillcount;
    else if(!full && put)
        fillcount<=fillcount+1;
    else if(!empty && get)
        fillcount<=fillcount-1;
    else
        fillcount<=fillcount;

end

always@(fillcount)
begin
    full=(fillcount==8);
    empty=(fillcount==0);
end

endmodule

Another question :
The general way of coding in verilog as far as I have learned is to use fsm to draw the state diagram and use them..But I had a hard time when I try to code for the memory element like fifo,Tcam or double clock fifo.
Is there any approach or  a way to do coding for these elements .
Sorry for the long question
Answer: In your "Reading" process your are inadvertantly writing to your fifo memory:
fifo1[rp]<=fifo1[rp];

If you get rid of that it looks like things should work okay.
As a side note, in a sequential process you don't need to explicitly set values that aren't changing.
For example, if you take this process of yours:
always@(posedge clk or posedge reset)
begin:Writing
  if(reset)
    wp<=0;
  else
    if( put && !full)
    begin
        fifo1[wp]<=data_in;
        wp<=wp+1;
    end
    else
    begin
        fifo1[wp]<=fifo1[wp];
        wp<=wp;
    end
end

you can rewrite it as:
always@(posedge clk or posedge reset)
begin:Writing
  if(reset)
    wp<=0;
  else
    if( put && !full)
    begin
        fifo1[wp]<=data_in;
        wp<=wp+1;
    end
end

and you will get the exact same behavior in sim and the same hardware when you synthesize.  You are implying registers in your code and they will maintain their state unless explicitly changed.


The last (and the weirdest) problem from Chen`s "Brief Introduction to Olympiad Inequalities"

Question:
Let $a$, $b$, $c$ be positive reals satisfying $a + b + c = \sqrt[\large 7]{a} + \sqrt[\large 7]{b} + \sqrt[\large 7]{c}$. Prove that $a^a b^b c^c ≥ 1$.

This is the last problem from this excellent overview of various inequality problems by Evan Chen.
I suspect the author left it for the end of his document as a very difficult problem, or as a problem that has a beautiful or an unexpected solution.
I tried using Cauchy and Hoelder inequalities in some ways, and some substitutions, but no luck so far.
I am curious what would you guys say about the problem. Also, is there something special about number $7$ regarding this problem? Would the statement hold if there was $19$ instead of $7$? What about the case with four, five, six numbers? What about the case with only $a$ and $b$?
Comment: There was slight correction of the statement. The error was related to the editor on this site inserting some characters for quoted text.. Sorry about that.
Answer: First of all, the solution: by weighted AM-GM we have
$$1 = \frac{a}{a+b+c} a^{-6/7} + \frac{b}{a+b+c} b^{-6/7} + \frac{c}{a+b+c} c^{-6/7} \ge (a^ab^bc^c)^{\frac{-6/7}{a+b+c}}. $$
Of course, from this solution it's clear that both the number of variables and the choice of the number $7$ is irrelevant. (Pedagogically and aesthetically, I'm of the opinion that it's usually better to include the specific, concrete instance if it's clear how to generalize it.)
Seeing as I'm the author of this problem (which was the second problem of ELMO 2013), I can comment on its creation too. I had long known that one could get $a^2+b^2+c^2 \ge a^ab^bc^c$, when $a+b+c=1$, using weighted AM-GM.  I really wanted to see if I could get something more decent, since the problem is rather trivial in that formulation. After two hours of playing around with this weighted idea before I decided to put a condition of $a^2 + b^2 + c^2 = a + b + c$ so that the left-hand side of $\frac{a^2+b^2+c^2}{a+b+c} \ge a^{\frac{a}{a+b+c}} b^{\frac{b}{a+b+c}} c^{\frac{c}{a+b+c}}$ would be nice.  Suddenly I realized I could just factor out the exponent, and the whole thing simplified super nicely as $a^ab^bc^c \le 1$. And so after some cosmetic changes it became the problem you see now.
Answer: Let $r> 1$ and $a+b+c = \sqrt[r]a+\sqrt[r]b+\sqrt[r]a$ for positive $a, b, c$.  We need to show $a^ab^bc^c \ge 1$.  Equivalently, it is enough to show for $x> 0$,
$$f(x) = x \log x -\frac{r}{r-1}(x - \sqrt[r]x) \ge 0$$
Looking at $f'(x)$, we get that its sign is determined by the sign of
$$g(x) = (r-1)\log x+\frac1{\sqrt[r]{x^{r-1}}}-1$$
and $g'(x) = \dfrac{(r-1)}{rx^2}(rx-\sqrt[r]x)$ which crosses the positive x-axis only once from the bottom.  So $g(x)$ has two zeros, easily $g(1)=0$ and there is another in $(0, 1)$.  The sign of $g(x)$ is then $+, - , +$ where the sign changes happen at the roots.
Finally, this means $f(x)$ has two extrema, the first is in $(0, 1)$ and is a maximum, and the second is at $x=1$, and is the minimum.  As $f(1) = 0$ is this minimum, we have $f(x) \ge 0$
Comment: It is not equivalent, but one way implication. $f(x)\ge 0 \implies f(a)+f(b)+f(c)\ge 0 \implies a\log a + b\log b+ c\log c \ge 0 \implies $ the initial problem holds. This is because the portion in brackets sums to the constraint. Try it out and it should be evident. The method works for more variables as well.
Comment: Thanks, I am just not clear about the equivalence of the initial problem and the first functional inequality. Would you mind explaining the details?


real root of $x^4-x^3\sin x-x^2\cos x$

Question: How many real roots does $x^4-x^3\sin x-x^2\cos x$ have?

I want to make derivative for such equation, but it seems doesn't work for solving problem.
Comment: Please use $\sin, \cos$ etc. for functions to improve readability: `\sin, \cos`
Comment: @AlexR Oh, come on! It's not like anyone's sitting at their desk, looking at that and thinking that $sin$ means $s \times i \times n.$
Comment: @alexqwx Okay read $sinx cosy tanz$ and rant again.
Comment: @alexqwx: Nevertheless, it's easier to read with that edit. It's perfectly clear what I mean by, "Its' eaSIEr to REAd WiTh THaT ed1t," but the former is still an improvement over the latter.
Comment: What do you mean by saying that the derivative "doesn't work"?
Comment: @AlexR $sin(x) \ cos(y) \ tan(z)$ is as easy to read as $\sin(x) \cos(y) \tan(z)$. You're cheating by using no spacing between functions!
Comment: Apart from being readable, your question has to be understandable too. I don't think you'd have trouble finding it's derivative, so what does that last line mean?
Comment: @Amzoti But u can't prove these are real roots.
Comment: @UserX Edited. sorry
Comment: Well, yea, evaluating its derivative isn't gonna help you. You can factor $x^2$ but then you're left with numerical methods only.
Answer: There's a root at $x=0$. Now we can divide by $x^2$, getting $f(x)=x^2 - x \sin x - \cos x$.
$f (0) = -1 < 0$, but the term $x^2$ makes $f (x) > 0$ for large x, so there are two zeroes.
$f' (x)=2x-\sin x - x\cos x + \sin x = 2x - x \cos x = x (2 - \cos x)$. This is only zero when $x=0$, so f (x) has just two zeroes, and the original function has three.

real root of $x^4-x^3\sin x-x^2\cos x$


Bayesian A/B test - using an updated prior based on collected data

Question: I have a question about whether I would be adding bias to an A/B test by updating my prior based on combined A & B data, and then running the A/B test on that prior.
My A/B test is click through rates, so I am using a beta-binomial distribution set-up.
I have estimated priors for my population based on previous data, but due to complications it may not accurately represent the population that the test is being run on. As an example, say that my prior is Beta(34, 726) distributed, but if I combine my A and B data (while controlling for sample rates) I can update that prior to Beta(26, 1032).
Would it be valid then to use Beta(26, 1032) as my prior for my A/B test, or am I adding bias by using prior based on my results?
(a) My data is standard binomial distributed data. I am interested in 1 as a success and 0 as a failure. The data is generated by users which I have various characteristics on (age, tenure of user, etc.)
(b) If I did beta-binomial regression on 3 user characteristics, such as the ones I mentioned above, I would get a prior that represents those 3 characteristics. However, due to the nature of the experiment, there are more characteristics that define the population that weren't accounted for in the regression. For example, I know the prior for age 20-28 users. The experiment yields a higher proportion of male users than the total population, and males have different behaviors than females.
(c) I want to update my prior so that it can reflect the different behaviors that weren't accounted for in the regression.  I have collected data from a treatment group and a holdout group. I would update the prior using the calculations you listed. I then want to use this prior to estimate the posterior distributions for a treatment group and a holdout group, and calculate the effect of the treatment.
Comment: Could you describe in greater detail: (a) your data, (b) the "complications" you mention, (c) your exact procedure (e.g. how did you update your prior?). Your question is unclear since in standard beta-binomial setting it is impossible for updated prior to ave any of the parameters smaller then previously since it is Beta(alpha+number of successes, beta + number of failures), where since we are talking about counts, they can't be negative...
Comment: Thanks for editing, it's much clearer now. I wonder, this sounds like you basically had two logistic regression models and wanted to combine both models, then why won't you do this directly rather then use them to get priors etc. ?
Answer: I don't see any problems with the approach to be honest based on the information you've provided. I believe that combining the A/B results to update your prior is a reasonable thing to do
Answer: If I understand correctly, you are A/B testing, i.e. collecting data under condition A and under B, and you want to know whether the a binomial proportion is higher under condition A compared with B. Additionally, you have a model that gives you possibly good, possibly questionable predictions about what you expect in condition A and B based on some other data that was not part of the A/B test you are about to analyze.
In that case, this is closely related to proof of concept trials in drug development, where one often tries to bring in data on control group outcomes. Here, it seems we have information about both A and B (not just one of them), but that doesn't change all that much. In that setting, approaches like the robust meta-analytic predictive prior, borrowing through hierarchical models and various related alternatives are very popular.
Doing this all without introducing bias/type I error rate inflation is of course challenging and not entirely possible, but these methods aim to minimize the impact of clearly having gotten the prior wrong.
If you have a prior and some new data, you can implement the idea of the second paper above quite easily. E.g. here's one way to do something like that using the brms R package:
library(tidyverse)
library(brms)

# Example data, where the data strongly suggest our prior information on
# B is wrong, while what we observe for A is reasonably compatible with our prior information
example = tibble(group=c("A", "A", "B", "B"),
                 historicalA=c(1L, 0L, 0L, 0L), # Historical A = pseudo-data for A equivalent to our prior information on condition A
                 historicalB=c(0L, 0L, 1L, 0L), # Historical B = pseudo-data for B equivalent to our prior information on condition B
                 success=c(25, 5, 500, 5),
                 cases = c(1000, 200, 1000, 200))

brmfit1 = brm( success | trials(cases) ~ 0 + group + historicalA + historicalB,
               family=binomial(link=logit),
               prior = prior(class="b", coef="groupA", normal(0, 3.14)) +
                 prior(class="b", coef="groupB", normal(0, 3.14)) +
                 prior(class="b", coef="historicalA", double_exponential(0, 0.5)) +
                 prior(class="b", coef="historicalB", double_exponential(0, 0.5)),
               data=example)

summary(brmfit1)
```


Regressing on nuisance features as pre-processing

Question: A friend recently told me about a technique to remove the effects of an unwanted feature $x$ in a response variable $y$. He mentioned an example from genetics. By regressing $y$ on $x$ (or a polynomial in $x$ to capture higher order interactions in the data), the residuals represent the variation unexplained by the "nuisance" predictors. As a simple example, say you wanted to remove the effects of tire pressure and car age (and their interactions) on gas milage performance. The errors soak up all of the information that is left after explaining away tire pressure & car age. It's not hard to see how this kind of approach would be useful for reducing large datasets, like the ones you'd see in genetics, to key features.
This approach flips conventional wisdom about regression on its head. I was wondering: Is this is a common practice? Are there any examples where it has been applied or, better yet, any theory on the subject? From what I can tell, it seems somewhat unique to genetic data (since noisiness in the observations makes fitting a full linear model difficult).
Comment: But to comment, this is exactly what is done when you include multiple variables in a linear model. You do not need to perform a "pre-process" with some variables and then use the rest. In fact this may be wrong as you may end up getting biased results.
Comment: See https://en.wikipedia.org/wiki/Partial_correlation.
Comment: Thanks for your response! One issue with genetic data is the dimensionality. Removing features (age, sex, BMI, whatever) may help isolate signal and help deal with numerical instability issues that arise when the design matrix gets too big. Also, we may not care about the regression coefficients - but regressing out certain factors can help us identify the conditional relationships in subsequent analyses (which may not be another regression).
Answer: As @user2974951 says in a comment, this is just what you do with multiple regression to control for other variables.   This two-step approach doesn't really "remove features" in a way that avoids the dangers of overfitting from a "too big" design matrix and its low case/predictor ratio.
Once you start using outcomes in your analysis, as this approach does, you have to take that use of the outcomes into consideration in downstream analysis or you risk overfitting. Frank Harrell's course notes and book go into these issues in some detail, in particular in Chapter 4 and in several detailed examples. You don't win anything with the two-step approach.
In the regression context, penalizing the coefficients of the "nuisance features" while keeping the main factor of interest unpenalized is a principled way to proceed, controlling for those features while minimizing overfitting. This paper describes and illustrates the approach.
How to proceed with a non-regression downstream analysis would depend on the nature of that analysis. As @user2974951 also says, any pre-processing via linear regression could lead to problems in downstream analysis (in particular if the linear model isn't properly specified). At the least, to document that you aren't overfitting, you would need to repeat the entire modeling process (including that pre-processing to remove nuisance predictors) on multiple bootstrap samples of your data set.


Add checkbox setting to a multiple value field

Question: I have an image field with unlimited values. I want to add a checkbox to each image to use this image on the homepage. I would then check for that value in tpl file. How do I add a checkbox setting to this field?
Looks like a user did it in this post but didn't state how: Add a configuration checkbox in field setting
Answer: You need to use field collections to group fields together.. Field settings is used for field configuration...
According to your requirement you would like to choose for each field value associated value to track whether image should be displayed or not in home page.. Field collections does this and have integration with views..


Is there a way to delete unused fields?

Question: I created many fields for content type.Now I don't need these fields anymore.
I deleted the fields from the content type but the fiels data remains in the database.
How can I delete the field and all its related data?
Comment: Have a look through the posts in [this search](http://drupal.stackexchange.com/search?q=field_purge_batch)
Comment: You need to run `cron` jobs to delete field permanently.
Comment: instances will be queued for deletion after the last instance deleted. delete them and run cron job.
Comment: @Clive thanks. Do you mind to move your comment as an answer so that I can accept it?
Answer: Sometimes running cron does not entirely delete a field, especially if the field was ever used in a field collection. First, make sure the field isn't used anywhere else. Check all content types, field collections, custom user fields, etc. if the field is really not used but running cron does not delete the field table from the database, you may have to delete it manually. You can do this manually with a SQL query or via phpmyadmin.
Comment: Running `cron`should do the trick as Jayendra mentioned... you can do that manually, otherwise it should run periodically and then you would notice that eventually the data was no longer in the database.

Is there a way to delete unused fields?


plostly histogram facet row animation frame

Question: Here is a sample of my data:

Time,Value,Name,Type
0,6.9,A,start
40,6.9,A,start
60,6.9,A,start
0,0.01,B,start
40,0.01,B,start
60,0.01,B,start
0,1.0,C,start
40,1.0,C,start
60,1.0,C,start
0,0.08,D,start
40,0.08,D,start
60,0.08,D,start
0,0.000131,E,End
40,0.00032,E,End
60,0.99209,E,End
0,0.002754,F,End
40,0.00392,F,End
60,0.01857,F,End
0,0.003,G,End
40,0.00516,G,End
60,0.00746,G,End
0,0.00426,H,End
40,0.0043,H,End
60,0.0095,H,End
0,0,I,End
40,0.0017,I,End
60,0.0183,I,End

And my code below:
import plotly.express as px
import pandas as pd
df=pd.read_csv('tohistogram.csv')
fig_bar = px.histogram(df,x='Name',y='Value',animation_frame='Time',color='Name',facet_row='Type')
fig_bar.update_layout(yaxis_title="value")
fig_bar.update_xaxes(matches=None)
fig_bar.for_each_xaxis(lambda xaxis: xaxis.update(showticklabels=True))
fig_bar.show()

`
Fig1:

Fig2:

With the data point listed above, I wanted 2 histogram separated by type (start,end) in one frame with one animation_frame
Tried the above code, as one can see from the image I could partial achieve but from Fig1: second histogram has (A,B,C,D),excepted just E to I.
2. Figure 2 was when I played the run button and auto scaled then I see A-D are gone and only E-I,
This is what I wanted to achieve in the first place itself, before running 2 histogram should sort as per 'Type'
A. Is it possible I tried couple of things like removed color
fig_bar = px.histogram(df,x='Name',y='Value',animation_frame='Time',facet_row='Type')
histogram sorts as per 'Type' of course no color but no label in second x-axis.

B.fig_bar = px.histogram(df,x='Name',y='Value',color='Name',facet_row='Type')
It sorts but no animation

What I am trying is it possible?
need 2 histogram with in the same frame sorted by 'Type',color and animation_frame?

C. Only if possible then, how to label y-axis of the first histogram from sumofValues to user-defined axis name and also have its own axis range.

D.I didn't come across any example but on the histogram, on mouse hover can I show another simple line graph image instead of text or value?
Thank you
Answer: I switched from histogram to bar and rest was the same
fig_bar = px.bar(df,x='Name',y='Value',animation_frame='Time',color='Name',facet_row='Type')

I could fix section A,B,C
But D I am yet to get example for hover either for histogram or Bar Chart


Hierarchy in entity reference view display

Question: I have a hierarchical taxonomy vocabulary of page categories:
<code>Category A
  - Category A1
  - Category A2
Category B
  - Category B1
</code>
I would like to list some of them (conditionally) as options on my Page content type. For that, I am using an Entity Reference field, with the "Views" reference method.

I created a Taxonomy view with the Entity Reference display for that, but this way, the categories display as options without hierarchy:

Is there any way to selectively display taxonomy terms as field options on a content type, maintaining the hierarchy?
Answer: I just came across this question, because I had the same issue. The solution I've found is to use a Relationship; no extra modules required.

Add a Relationship and choose "Parent Term". Check on "Require this Relationship" in the dialog box.
In the "Filter Criteria" section of the view, add the "Term" field (NOT the "Parent" field*). If you want, you can choose to show the hierarchy in a dropdown, in prep for choosing the term in step 4.
Choose the created Relationship in the "Relationship" field of the filter dialog box.
Choose the Parent term in that same filter dialog box (to use your example, say "Category A").

Now your view should output only the children of that parent term. (Again, using your example, if you chose Category A, your view would output:
Category A1
Category A2
*there is a "Parent" field in the Filter field options, and it seems intuitive to use that, but using that only outputs the top-level hierarchy of the Taxonomy, even when combined with an AND with the Taxonomy field. Maybe a bug?
Answer: IMHO, the best module to show hierarchical taxonomy options on a form is Term Reference Tree.
Unfortunately, the D8 version development has stalled out a bit.  But it is still useful.  I recommend the dev version with the patch from this issue:
Allow to configure widget settings


What is this data type? It's some input data from leetcode

Question: I'm doing some exercises of Databases from LeetCode. I want to test my codes on my laptop using MySQL. I hope to have a easy way to import data.
Here is the input data from LeetCode:\
<code>{"headers":{"insurance":["PID","TIV_2015","TIV_2016","LAT","LON"]},"rows":
{"insurance":[[1,224.17,952.73,32.4,20.2],[2,224.17,900.66,52.4,32.7],
[3,824.61,645.13,72.4,45.2],[4,424.32,323.66,12.4,7.7],
[5,424.32,282.9,12.4,7.7],[6,625.05,243.53,52.5,32.8],
[7,424.32,968.94,72.5,45.3],[8,624.46,714.13,12.5,7.8],
[9,425.49,463.85,32.5,20.3],[10,624.46,776.85,12.4,7.7],
[11,624.46,692.71,72.5,45.3],[12,225.93,933,12.5,7.8],
[13,824.61,786.86,32.6,20.3],[14,824.61,935.34,52.6,32.8]]}}
</code>
What is the data type?
Comment: ```what is the data type?``` => it's JSON string
Answer: This is a JSON string. JSON is a common data interchange format.


pass tkinter user inputs into document's table

Question: its my first contact in here. i am quite new in programming.
i write the below code.
i need to pass the users inputs to the table docx. but i kinda stuck.
THe problem is that the user can appear as many inputs wants. so i find difficult to use entry.get() to an entry which doesnt have variable to call. I tries to make the entry and combo to list and pass it to the table rows but doesnt seem to write it correctly. below you will find the last correct program of mine(before all tries and errors).
from docx import Document
from tkinter import *
from tkinter import ttk

w = Tk()
w.geometry('700x800')
w.config(bg='#DCDCDC')

def add_combo_r():
    combo_res = ttk.Combobox(w, value = options_res).pack()

def add_entry_r ():
    descr_res_text = Entry(w).pack()

def generate():

    document = Document()

    table1 = document.add_table(rows=2, cols=1,style= 'Table Grid')
    hdr_cells = table1.rows[0].cells
    hdr_cells[0].paragraphs[0].add_run('NUMBERS ').bold = True

    document.save('test.docx')

btn = Button(w,text='ganarate docx', command=generate).pack()

b_res = Button(w, text = "add next result", command= add_combo_r).pack()
b_res_text = Button(w, text= "add next result by myself", command = add_entry_r ).pack()

options_res = ["1", "2","11", "12","21", "22","31", "32","41", "42","51", "52"]
combo_res = ttk.Combobox(w, value = options_res).pack()
descr_res_text = Entry(w).pack()

w.mainloop()

i tried to get the below table as a result:

NUMBERS

1(combo result)

stairs (entry result)

12(combo result)

22(combo result)

turbo(entry result)

i appreciate any help!!!
Comment: _" i find difficult to use entry.get() to an entry which doesnt have variable to call"_ why aren't you creating a variable that you can call the `get` method on?
Comment: The thing is that user can createas as many combo_res and combo_res_text he wish with a button click. User may decide that wants 2, 5 inputs or 100 inputs. so i need the button to generate a new variable in each click that my new combos and entries will be linked with, then somehow i need to count the inputs and generate the table in correst rows.
Comment: Store the entry widgets in a list.
Answer: I reply the answer in case someone else need it in the future. :)
from docx import Document
from tkinter import *
from tkinter import ttk

w = Tk()
w.geometry('700x800')
w.config(bg='#DCDCDC')

entries_1 = []
counte1 = 0

def add_entry_r():
    global counte1
    entries_1.append(Entry(w))
    entries_1[-1].grid(row=0,column=counte1,padx=5)
    counte1 += 1

def add_combo_r():
    global counte1
    entries_1.append(ttk.Combobox(w, value = options_res))
    entries_1[-1].grid(row=0,column=counte1,padx=5)
    counte1 += 1

def generate():

    document = Document()
    table1 = document.add_table(rows=counte1+1, cols=1,style= 'Table Grid')
    hdr_cells = table1.rows[0].cells
    hdr_cells[0].paragraphs[0].add_run('NUMBERS ').bold = True
    k=0
    for i in range(len(entries_1)):
        x=entries_1[k].get()
        row_cells=  table1.rows[i+1].cells
        row_cells[0].paragraphs[0].add_run(x)
        k+=1

    document.save('test.docx')

btn = Button(w,text='genarate docx', command=generate).grid(row=4,column=0,padx=5)

b_res = Button(w, text = "add next result", command= add_combo_r).grid(row=2,column=0,padx=5)

b_res_text = Button(w, text= "add next result by myself", command = add_entry_r ).grid(row=3,column=0,padx=5)
options_res = ["1", "2","11", "12","21", "22","31", "32","41", "42","51", "52"]

w.mainloop()


How do you add a resource to a subnet in Terraform?

Question: I need to protect all my resources (which are in different subnets) by firewall and therefore I need to know how to assign subnet to each resource.
I am wondering what is the easiest way to connect any resource to a subnet ?
I have seen different resources which can connect to a subnet by different solution. It is very confusing for me since apparently every resource has its own solution to get connected to the the subnet.
Here are some example:
Databricks can be connected by adding delegation to subnet as below:
resource "azurerm_subnet" "private_snet" {
  name                 = "subnet-private"
  resource_group_name  = var.resource_group_name
  virtual_network_name = azurerm_virtual_network.test_vnet.name
  address_prefixes     = ["10.0.1.0/24"]

  delegation {
    name = "databricksprivatermdelegation"

    service_delegation {
      name = "Microsoft.Databricks/workspaces"
    }
  }
}

However, azurerm_mssql_server uses very different resource called azurerm_mssql_virtual_network_rule, to place sql database to a subnet as below:
resource "azurerm_mssql_virtual_network_rule" "example" {
  name      = "sql-vnet-rule"
  server_id = azurerm_mssql_server.example.id
  subnet_id = azurerm_subnet.example.id
}

When it comes to azurerm_storage_account it has its own solution called network_rules as below:
resource "azurerm_storage_account" "example" {
  name                = "storageaccountname"
  resource_group_name = azurerm_resource_group.example.name

  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"

  network_rules {
    default_action             = "Deny"
    ip_rules                   = ["18.104.22.168"]
    virtual_network_subnet_ids = [azurerm_subnet.example.id]
  }

}

and finally the azurerm_data_factory has no argument to connect it to a subnet.
So, in short, my question is:
Is there any easy and straight forward solution which i can setup my resource to a azurerm_subnet ?
Comment: Sadly no. As you mentioned it is resource specific.
Comment: Is this something you can do manually on the Azure console??  ... From what you are saying `every resource has its own solution to get connected to the subnet` I get a feeling you should be contacting the Azure tech support team
Comment: > Is this something you can do manually on the Azure console??
console as CLI tooling or portal?

CLI tools have even larger differences between different resource types and it might even more complicate things. Portal should be recommended because OP asked help with templating.
Comment: @Sal-IaS the short answer is no... even in azure portal you would have seen that the networking options are different for different resources and it heavily depends on how the resource is actually implemented under the hood... there is no one stop solution in this case... and as u mentioned in case of data factory there are no argument to connect to subnet as connectivity can only be enabled as private or public end point.. so all the steps are strictly resource specific and cant be generalized
Answer: TLDR
Answer 1: if you want to use service endpoints only there is no simple unified way to configure resources to allow access from subnet. Consider using private links.
Answer 2: Identify different types of Azure service VNet integrations: https://learn.microsoft.com/en-us/azure/virtual-network/vnet-integration-for-azure-services

You need to re-iterate your plans and identify what kind of integration your resources have with Virtual Networks.
High-level description of Azure service integration with VNets: https://learn.microsoft.com/en-us/azure/virtual-network/vnet-integration-for-azure-services
Service endpoint

incoming traffic to resource
enables resources deployed/injected into subnets to communicate with target resource
configuration required

target resource: allow access from given subnets
source subnets:

enable service endpoints

serviceEndpoints property

turn on (VNet Service endpoint policy)[https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-service-endpoint-policies-overview] for extra safety

serviceEndpointPolicies property

Azure changes routing and IP addresses automatically after service endpoint is turned on. No extra interaction is required after adding incoming rule for resource and adding service endpoint support for source subnet.
Private endpoint

Private link is similar with service endpoint but newer and can be configured more
Incoming traffic to resource
(list of supported services)[https://learn.microsoft.com/en-us/azure/private-link/availability]
Following extra resources are needed

private endpoint

mostly metadata

network interface

traffic to this interface is routed to target resource

optional private DNS zones and related resources

recommended, otherwise usage of IP addresses and/or hosts-file changes are needed

optional NSG rules for extra security

VNet injection / deployment into VNet

Azure service is deployed/injected into VNet
outgoing and incoming traffic goes through VNet
Some services requires dedicated subnet => only one service type can be deployed into dedicated subnet

Your examples:
Databricks
Databricks supports VNet injection After deploying databricks into VNet it can securely connect Azure resources that are using:

service endpoints
private links
or are deployed into VNet(same or other subnet, even subnets on other VNet if peering exists)

Azure SQL
Azure SQL supports both service endpoint and private link. Your example just adds access from services deployed into azurerm_subnet.example. "to place sql database to a subnet" does not really happen.
Storage account
Storage account supports both service endpoint and private link.
virtual_network_subnet_ids is just a list that contains allowed subnet ids.
Data factory
To enable VNet integration with data factory you have two solutions
Azure-hosted integration runtime

enable managed virtual network feature

Run self-hosted integration runtime(SHIR) on Azure VM

if you run SHIR on Azure then you can use service endpoints and private link to secure connection to other Azure services.

Summary
First of all: identify your resource types: how they can be integrated with Azure VNets
Resource firewall/network rules are resource specific like you noticed with Azure SQL and Azure Storage differences. If you need more unified access control and configuration I recommend using private enpoint:

private endpoint is separated resource type => configuration is independent from target resource
if extra access control is needed, you can use network security groups to limit traffic into private endpoint

The bicep template example(Azure SQL with private endpoint + VM) gives a good high-level overview how private link templating works. Finding correct Terraform resource types should be easier after seeing Microsoft's Bicep examples.
Deployment/Injection to VNet still uses resource-specific configuration/template properties and must be done case-by-case.


clearing all fields in html form except one, and adding a value to the exceptional field

Question: I use this jquery to clear (not reset) all the fields on a form:

One of the fields in the form is named 'data1'. I have not been able to, after I clear the form, then, set a value in 'data1' to the value I want.
Comment: after clearing all of them ,you can set the value only for the exceptional one
Comment: Did you do: `case 'radio': this.checked = false;}}).end().find('data1').val('your_val')`?
Answer: After you clear all the elements, do:
$(ele).find('[name=data1]').val("defaultvalue");

Answer: Add reset type button inside your form so that on clicking it all values in the fields get cleared.
<input type="reset" id="clear" value="Clear"/>

And, add the value to the field you want as:
$("#clear").click(function(){
    $("input[name='data1']").val("Your Value");
});

Answer: Add button inside your form so that all values in the input fields will be cleared OnClick event.
$('#posting_comment')[0].reset();


find the maximum value of $m$ where $3^m$ be a factor of $A_{1395}$.

Question:
Consider the number $A_{1395}=\underbrace{333\cdots3}_{1395}$. what is
the maximum value of $m$ where $3^m$ be a factor of $A_{1395}$.
$a) 2\quad\quad b)3\quad\quad c)4\quad\quad d)5\quad\quad e)6$

Here is my attempt :
We have $A_{1395}=3\times \underbrace{111\dots1}_{1395}$ sum of the digits of $\underbrace{111\cdots1}_{1395}$ is $1395$ which is a multiply of $9$. therefor this number is dividable to $9$. so we conclude $A_{1395}$ has the factor $3^3$ . to see whether it has more factor of $3$ or not I divided it to $27$. after doing some steps of long division I got:
$$\underbrace{11\cdots1}_{1395}÷27=4115226\cdots$$
Unfortunately I couldn't see any pattern as the result. so I don't know how to check this number has more factor of $3$ or not.
Comment: Hint: the [LTE-lemma](https://brilliant.org/wiki/lifting-the-exponent/)
Comment: @Raffaele it is an Olympiad problem from Iran. it was for $1395$ from Solar calendar ;) (about $4$ years ago)
Comment: I'm not sure how to get the result quickly in an explicit form, but you can easily find it with a short search in this case. To get started, just imagine your number as $(10 ^ {1395} - 1) / 3$. If it is divisible by $3 ^ m$, then $10 ^ {1395} - 1$ is divisible by $3 ^ {m + 1}$. So $10 ^ {1395}$ is comparable to $1$ modulo $3 ^ {m + 1}$. Now you just need to find the largest suitable m.
Comment: Amazing: they already did Math Olympiads in 1395
Comment: LMAO! I got it! It was the Iranian calendar @Soheil
Answer: Write using the binomial theorem,
\begin{align}
999\cdots 9 &= 10^{1395} -1 \\
&= (1+9)^{1395} -1 \\
&= \left(\array{1395\\1}\right)\cdot 9 + \left(\array{1395\\2}\right)\cdot9^2 + \cdots 9^{1395}
\end{align}
But $1395 = 3^2 \cdot 5 \cdot 31$.  So, the first term is divisible by $3^4$ and each term thereafter is divisible by $3^5$ meaning the sum is divisible $3^4$ and not by $3^5$.  Accordingly, $333\cdots 3$ is divisible by $3^3$ but not $3^4$.  The answer is therefore $3$.
Comment: @Raffaele thanks for correcting!
Comment: Nice solution ;)
Comment: @Soheil Thank you.
Answer: We write the number as ${10^{1395}-1\over 3}$
By Euler Thorem,
$10^{162}\equiv1\pmod{243}$ so $10^{1395}\equiv10^{99}\pmod{243}$
Since $10^{99} \equiv 28^{33}\equiv82^{11}\equiv(-80)^5\times82\equiv82^2\times(-80)\times82\equiv(-80)^2\times82\equiv-80\equiv163\pmod{243}$
We know $10^{99}-1\equiv162\pmod{243}$ which implies $10^{1395}-1\equiv 162\pmod{243}$
Therefore $10^{1395}-1$ is not a multiple of $243$ but is a multiple of $81$.
So ${10^{1395}-1\over 3}$ is a not multiple of $81$ but is a multiple of $27$
Answer: For $x\in\Bbb N$, letr $v_3(x)$ be the exponent of the maximal power of $3$ dividing $x$.
If $n=3^ka+1$ with $k\ge1$ and $3\nmid a$, then
$$ n^3=3^{3k}a^3+3^{2k+1}a^2+3^{k+1}a+1
=3^{k+1}(a+3^k(\ldots))+1$$
i.e.,

If $v_3(n-1)>0$ then $v_3(n^3-1)=1+v_3(n-1)$.

Note that $A_{1395}=\frac{10^{1395}-1}3$, so what we are looking for is $m=v_3(10^{1395}-1)-1$.
By the above remark,
$$m=v_3(10^{1395}-1)-1=v_3(10^{465}-1) = v_3(10^{155}-1)+1. $$
Also, as $v_3(10^3-1)=1+v_3(10-1)=3$, so that
$$ 10^{155}=(10^3)^{51}\cdot 100\equiv 100\equiv 19\pmod{27}$$
(but $\equiv 1\pmod 9$). We conclude
$$v_3(10^{155}-1)=2 $$ and ultimately
$$ v_3(A_{1395})=3.$$
Answer: Consider an extension 9f the familiar sum of digits test for divisibility by $9$.
The number $999$ factors as $27×37$ or with prime factors, $3^3×37$.  Thus if you add three-digit blocks together to cast out multiples if $999$, you are also casting out multiples of $27$ and $37$ and thus the sum of tyree-digit blocks tests for divisibility by these factors.
This can be extended to higher powers of $3$.  The sum of nine-digit blocks tests for divisibility by $81$, and more generally adding blocks of $3^k$ digits tests for divisibility by $3^{k+2}$
In your case, then, first sum the three-digit blocks to get  $333×465$ where each of $465$ blocks is $333$.  Since $333$ is a multiple of $9$ and $465$ is a multiple of $3$, your three-digit block sum passes for divisibility by $27$.
Next try the nine-digit block sum getting $333333333×155$.  The three-digit blocks of $333333333$ add up to a multiple of $27$, but dividing out a factor of $3$ gives $111111111$ which fails that test.  So $333333333$ is a multiple of $27$ but not $81$, and $155$ is not a multiple of $3$, so the nine-digit block sum which equals their product fails divisibility by $81$.
Thus the maximum power of $3$ that divides $A_{1395}$ is $3^3=27$.


Pandas: Multiple date formats in one column

Question: I have two date formats in one Pandas series (column) that need to be standardized into one format (mmm dd & mm/dd/YY)
Date
Jan 3
Jan 2
Jan 1
12/31/19
12/30/19
12/29/19
Even Excel won't recognize the mmm dd format as a date format. I can change the mmm to a fully-spelled out month using str.replace:
df['Date'] = df['Date'].str.replace('Jan', 'January', regex=True)
But how do I add the current year? How do I then convert January 1, 2020 to 01/01/20?
Answer: Have you tried the parse()
from dateutil.parser import parse
import datetime

def clean_date(text):
  datetimestr = parse(text)
  text = datetime.strptime(datetimestr, '%Y%m%d')
  return text

df['Date'] = df['Date'].apply(clean_date)
df['Date'] = pd.to_datetime(df['Date'])

Comment: I get this error: Parser must be a string or character stream, not Series.                                        I need to parse an entire Pandas series, but really only the rows in the wrong date format.
Comment: Check the answer now
Answer: If it's in a data frame use this:
from dateutil.parser import parse
import pandas as pd

for i in range(len(df['Date'])):
    df['Date'][i] = parse(df['Date'][i])
df['Date'] = pd.to_datetime(df['Date']).dt.strftime("%d-%m-%Y")

Comment: Thank you. The df['Date'] series is a datetime64[ns] type. I converted it to a string first: df['Date'] = df['Date'].astype(str) before running your code. Once I did, I got this error: :5: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df['Date'][i] = parse(df['Date'][i])
Answer: Found the solution (needed to use apply):
df['date'] = df['date'].apply(dateutil.parser.parse)


Persistent VPN on Windows Server 2008 says local only

Question: I have set-up a Persistent Connection VPN in Server Manager > Network Interfaces tab. It has been working but we have recently changed the IP address and I'm not sure if it is working anyone. The status is enabled, with state connected, but in the currently connected to, it says it is just a local connection - is that correct? Is there a good method to check the connection is working?
Answer: After a number of tests we found the VPN was working, so the local connection was correct.


Can't Figure Out The Convert String

Question: Can anyone help? I am trying to get INR price, But it only gives me USD
(string) convert - return pricing info in terms of another currency. I don't know how to.
<?php
error_reporting(0);
$url = 'https://api.coinmarketcap.com/v2/ticker/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result1 = curl_exec($ch);
curl_close($ch);
$live_price = json_decode($result1, true);
?>

Comment: Perhaps if you hit it hard? Use a hammer?
Comment: On a more serious note: Your question is lacking specifics. Show us some code. See: https://stackoverflow.com/help/how-to-ask
Comment: Read [ask] and [mcve]. I have no idea what you're talking about.
Comment: i am sorry i don't understand all of these. I am completely new in to coding and trying to learn how it works.
Comment: @Roy being new only excuses you so much.  It's not an excuse for not taking the time to write out a proper question and including context about your problem.
Comment: @Devon I guess you beat me to it :)
Comment: that's the problem. It took me an hour to figure out to enter the code in the box and i still couldn't get it right. I really apologize. But i will soon learn how this medium works.
Comment: Coinmarketcap uses an API with simple *get* requests. `echo file_get_contents('https://api.coinmarketcap.com/v2/ticker/');` brought me more info than your attempted curl request. But that is mainly because I `echo` it. You don't. You set a variable... and that's it.
Comment: @Xorifelse can you show me the exact code how to. I know nothing about coding. How i managed to get that was days of work and through youtube and google. If you can give the exact line of code and where to place it. I used this is the $  for price display.
Answer: The request: https://api.coinmarketcap.com/v2/ticker/ gives the following JSON:
"data": {
    "1": {
        "id": 1,
        "name": "Bitcoin",
        "symbol": "BTC",
        "website_slug": "bitcoin",
        "rank": 1,
        "circulating_supply": 17140537.0,
        "total_supply": 17140537.0,
        "max_supply": 21000000.0,
        "quotes": {
            "USD": {
                "price": 6780.98,
                "volume_24h": 3704860000.0,
                "market_cap": 116229638586.0,
                "percent_change_1h": -0.42,
                "percent_change_24h": -0.03,
                "percent_change_7d": 2.62
            }
        },
        "last_updated": 1531177530
    },
    etc...

Meaning, to go through all the values:
foreach($live_price['data'] as $mainkey => $index){
  foreach($index as $k => $v){
    if($k == 'quotes'){
      $v = $live_price['data'][$mainkey]['quotes']['USD'];
      echo $v['price'];
    } else {
      echo "Hi, I'm index as '$k' and my value is '$v'";
    }
  }
}

Comment: slowly starting to understand this. But where is the convert string in it. Because by default the USD price is displayed with the above code. But there is something called String "convert" that coinmarketcap needs so that i could display the "INR" rupees price.
Comment: You might want to make a [different request](https://coinmarketcap.com/api/) then
Comment: you're quite helpful. Thank you so much and i really appreciate. If i could just get the idea how the convert string works and where and how to place it on my code that i created. I could simply display the INR. Guess this coding business is not my cup of tea.
Comment: Again, simple matter of [changing the request](https://api.coinmarketcap.com/v2/ticker/?convert=INR) to the API. So in my example I use `$live_price['data'][$mainkey]['quotes']['USD']` Change `USD` to `INR` to get that array's result.
Comment: yeah i tried that. But what worked was changing the URL to https://api.coinmarketcap.com/v2/ticker/?convert=INR
Answer: Change $url to this:
$url = 'https://api.coinmarketcap.com/v2/ticker/?convert=INR';
It will give you both 'USD' and 'INR'.
Comment: wow that worked thanks. But some displays INR and some doesn't any reason why. Can i just get INR?
Comment: you're genius that simply worked. Thanks so very much
Comment: @Roy Nothing special, just try to search for documentation before coding :)
https://coinmarketcap.com/api/

Can't Figure Out The Convert String


Calling C function from Objective-C loses passed in values

Question: I'm trying to keep a float[] of my table row heights. I found a nice class for doing so here: http://forums.macnn.com/t/224809/nsmutablearray-vs-a-plain-c-array-for-storing-floats.
The problem is that once the C function (located in another file) gets called, the float that I passed in becomes 0. This happens every single time, regardless of the float value.
C function:
typedef struct
{
    float *array;
    int count;
} floatArray;

BOOL AddFloatToArray ( floatArray *farray, float newFloat )
{
    if ( farray->count > 0 )
    {
        // The array is already allocated, just enlarge it by one
        farray->array = realloc ( farray->array, ((farray->count + 1) * sizeof (float)) );

        // If there was an error, return NO
        if (farray->array == NULL)
            return NO;
    }
    else
    {
        // Allocate new array with the capacity for one float
        farray->array = (float *)malloc ( sizeof (float) );

        // If there was an error, return NO
        if (farray->array == NULL)
            return NO;
    }
    printf("Adding float to array %f\n", newFloat);
    farray->array[farray->count] = newFloat;
    farray->count += 1;
    printArrayContents(farray);
    return YES;
}

int printArrayContents( floatArray* farray)
{
    printf("Printing array contents\n");
    for(int j=0; j < farray->count; j++)
        printf("%f\n", farray->array[j]);

    return 0;
}

Called from:
    NSDictionary* review = [self.reviews objectAtIndex:indexPath.row];
    returnHeight = [ReviewCell cellHeightForReview:review];
    NSLog(@"Adding height to array: %0.0f", returnHeight);
    AddFloatToArray(heights, returnHeight);

Here's what gets logged:
2012-09-28 11:46:12.787 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 101
Adding float to array 0.000000
Printing array contents
0.000000
2012-09-28 11:46:12.788 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 138
Adding float to array 0.000000
Printing array contents
0.000000
0.000000
2012-09-28 11:46:12.788 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 122
Adding float to array 0.000000
Printing array contents
0.000000
0.000000
0.000000
2012-09-28 11:46:12.789 iOS-app[1605:c07] -[ProductDetailViewController tableView:heightForRowAtIndexPath:] [Line 598] Adding height to array: 139
Adding float to array 0.000000
Printing array contents
0.000000
0.000000
0.000000

How can I ensure that the correct value is actually inserted into the float[]?
Comment: Tried the code exactly as you posted it and called using `CGFloat returnHeight = 120.f; AddFloatToArray(heights, returnHeight);` and works like a charm in my Xcode. Are you sure you didn't strip anything from your code when you c/p it here?
Comment: Everything's here. It's probably worth mentioning that the C functions are in a different file though.
Answer: I didn't declare the functions in the .h I was #importing. So everything compiled and ran, but the classes weren't communicating correctly. You'd think that would raise a warning or error.
Comment: It should have triggered a warning "Implicit declaration of function xxx is invalid in C99". Check that you have the `-Wimplicit-function-declaration` flag on.
Comment: I also saw sometimes the "xxx undefined. assuming extern returning int" warning that could be related (not knowing the function signature, because you didn't import the headers, the compiler assumed the function returned an `int`, instead of a `float`, and the parameter stacking during the function call then messed up because of that). But I can't manage to reproduce this warning nor find the corresponding `-W` flag that would have helped in such case.
Comment: That was not turned on, but I remember seeing that warning before. Google did not turn up this solution though. Thanks!


jQuery submit form with AJAX problem

Question: Here is my jQuery code:

What I want to do after the submit button is clicked is:

make an AJAX request to the page identified by form's action attribute (which happens to be the same php script with the form... so basically the form should submit to the same page).
replace the HTML of the whole page with the ajax request returned value.

However, I don't know how to do that. There is no html or body tag on the page with the form as the form is getting icnluded in another page with jQuery.
So how to replace the HTML of the page with the HTML ajax returns?
This is how the whole HTML looks like (this is evrything, there is no html or body tag):
<form enctype="application/x-www-form-urlencoded" method="post" action="editDocumentQuestion.php?iqid=-5">

            Otázka:

            <textarea name="questionBody" id="questionBody" rows="4" cols="95" style="border: 1px solid #2278B9; font-family: sans-serif;">Otazka</textarea>

            Odpovede:

<input type="radio" name="questionCorrectAnswer" class="questionCorrectAnswer" value="1" checked="checked" />a)

<textarea name="questionAnswer1" id="questionAnswer1" rows="2" cols="88" style="border: 1px solid #2278B9; font-family: sans-serif;">Odpoved a</textarea>

<input type="radio" name="questionCorrectAnswer" class="questionCorrectAnswer" value="2" />b)

<textarea name="questionAnswer2" id="questionAnswer2" rows="2" cols="88" style="border: 1px solid #2278B9; font-family: sans-serif;">Odpoved b</textarea>

<input type="radio" name="questionCorrectAnswer" class="questionCorrectAnswer" value="3" />c)

<textarea name="questionAnswer3" id="questionAnswer3" rows="2" cols="88" style="border: 1px solid #2278B9; font-family: sans-serif;">Odpoved c</textarea>

            <input type="submit" name="editovatDokumentovuOtazku" id="editovatDokumentovuOtazku" value="Ulož" style="width: 6em; padding: .3em 0;" />

</form>

Answer:
replace the HTML of the whole page
  with the ajax request returned value.

Try modifying your success handler like this:
success: function(data) {
  $('form').after(data).end().remove();
}

What it does is that it inserts ajax data after your current form with .after(data) and end() is used to revert back to the form and finally remove() is used to remove the form.
Answer: Even though there is no body or html tag you should be able to replace it like this:

Firefox 3.6.8, IE 8 and Chrome automatically inserts html and body tags if they are not present (those are the ones I have tested against)

jQuery submit form with AJAX problem


Resolution of Singularities: Base Point

Question: Consider the curve $y^2=4x^3-ax-b$, where $a$ is a fixed constant and $b$ is a free constant. For each value of $b$ we get a family of curves.

Part 1: Show that the family of curves intersect at infinity (the base-point).
My Solution: Using projective geometry (homogeneous coordinates), we have $x=u/w$, $y=v/w$, where $[x,y,1]=[u,v,w]\in\mathbb{CP}^2$. The equation of the level curves is $$\frac{v^2}{w^2}=4\frac{u^3}{w^3}-a\frac{u}{w}-b\qquad\Rightarrow\qquad v^2w=4u^3-auw^2-bw^3$$
For line at infinity, we let $w=0$ such that $0=4u^3\quad\Rightarrow\quad u=0$
Thus the base-point is $[0,1,0]$.
Is this correct?

Part 2: Resolve the base point through blow-ups.
I do not know how to go about answering this question.

Any help with Part 2 will be highly appreciated.
I am relatively new to concepts such as homogeneous coordinates and blow-ups. Are there any recommended books for beginners on these concepts? Thanks.
Answer: I will sketch the argument, since writing all the details would be too tedious, and would certainly include typos...
An important idea about blowups of points in the plane is the following: given two curves passing through a point $P$, the blowup $\operatorname{Bl}_P(\mathbb P^2)$ separates the curves (i.e. their strict transforms do not intersect) iff they have different tangent directions at $P$. The same idea works for germs of curves, which is why repeatedly blowing up a singularity (e.g. a node) desingularizes the curve. Moreover, blowing up reduces the tangency even if the curves hit each other at $P$ with higher order. So the idea is that by doing enough blowups, we can separate all the curves in the linear series for different $b$'s.
Here is how this works. In every blowup that follows there are two charts that glue to give the blowup. Only one chart will really by relevant at each stage, so I will simplify matters by working in that chart. You can check the other chart by mimicking my computations, if you wish. You correctly identified the basepoint $[0:1:0]$, which we should blow up. In the chart $v\neq 0$ the equation becomes
$$0 = 4u^3 - auw^2 - bw^3 - w$$
by substituting $v = 1$. I want to work with variables $x,y$, so let's replace this by $0 = 4x^3 - axy^2 - by^3 - y$, and compute the first blowup at $(x,y) = (0,0)$ in the way explained here. There are two charts. In the first we do
$$0 = 4(x/y\cdot y)^3 - a(x/y\cdot y)y^2 - by^3 - y$$
obtaining
$$0 = y\left(4(x/y)^3y^2 - a(x/y)y^2 - by^2 - 1\right)$$
where $y = 0$ is the local equation of the exceptional divisor of the blowup, and the equation of the strict transform is in brackets. Note that the two equations do not intersect, since $y=0$ implies the equation in brackets equals $1$. This means that the strict transform in this chart doesn't touch the preimage of the basepoint, so we can ignore this chart.
In the second chart, we do
$$0 = 4x^3 - ax(y/x\cdot x)^2 - b(y/x\cdot x)^3 - (y/x\cdot x)$$
which gives
$$0 = x\left(4x^2 - ax^2(y/x)^2 - bx^2(y/x)^3 - y/x\right)$$
where $x=0$ now gives the exceptional divisor. The strict transform has the solution $(x,y/x) = (0,0)$. This does not depend on $b$, so this is a solution of every strict transform. Thus, this point is a basepoint of the blowup linear series. This means we have to repeat the procedure to eliminate the basepoint. Let's work with the equation $$0 = 4x^2 - ax^2y^2 - bx^2y^3 - y$$ instead of using the awkward coordinate $y/x$.
Again, there will be two charts to deal with, but now I'll only work with one. We do
$$0 = 4x^2 - ax^2(y/x\cdot x)^2 - bx^2(y/x\cdot x)^3 - (y/x\cdot x)$$
which gives
$$0 = x\left(4x - ax^3(y/x)^2 - bx^4(y/x)^3 - y/x\right)$$
and again we see that $(x,y/x) = (0,0)$ is a solution of the exceptional and the strict transform. Thus we have a basepoint. We repeat the procedure, using the equation
$$0 = 4x - ax^3y^2 - bx^4y^3 - y$$
as our starting point.
There will be two charts, and I ignore one of them. There is an added twist at this stage. We do
$$0 = 4x - ax^3(y/x\cdot x)^2 - bx^4(y/x\cdot x)^3 - y/x\cdot x$$
which gives
$$0 = x\left(4 - ax^4(y/x)^2 - bx^6(y/x)^3 - y/x\right)$$
and we find that $(x,y/x) = (0,4)$ is a point on the intersection of the strict transform and the exceptional divisor, i.e. is a basepoint. To blow this point up we have to change coordinates so that the basepoint is the origin. E.g. we can take $(x,y) = (x, y/x-4)$, in other words $x = x, y/x = y+4$. We must rewrite the equation of the strict transform before proceeding. We obtain
$$0 = 4 - ax^4(y+4)^2 - bx^6(y+4)^3 - (y+4)$$
in other words
$$0 = - ax^4(y+4)^2 - bx^6(y+4)^3 - y$$
or
$$0 = ax^4(y+4)^2 + bx^6(y+4)^3 + y$$
which we see passes through $(0,0)$. Thus, we can apply the previous techniques and continue on.
I'll let you take it from here. At some point the intersection point of the exceptional divisor and the strict transform will be uniquely determined by $b$, which means that all the curves intersect the exceptional in a different point, i.e. you have separated all the curves of the linear series.
Comment: Dear @Jay, if you compute the other chart for the last blowup (the one that gives the solution $(x,y/x)=(0,4)$), then you'll find the solution $(x/y, y) = (1/4, 0)$. This is the same point of the exceptional curve that we found in the first chart! I.e. $y=0$ says that we're on the exceptional, and $x/y=1/4$ is the value of the coordinate of the exceptional curve, which was $y/x=4$ in the other chart. So the choice of chart here does not really matter, since the basepoint lies in both charts. However, when the solution is $(0,0)$ you can check that there will be no solution in the other chart.
Comment: Dear @Andrew, Thanks. Finished checking for the other charts - everything works out perfectly. I knew that a pencil of cubic curves had 9 base points (due to Bezout's Theorem) but to find these base points was another different story :-)Thanks, once again.
Comment: Dear @Andrew, Thank you very much for the detailed explanation. Provided my computations are correct, after the ninth blow-up I get $(x,y)=(0,64b)$. There are 2 charts for each blow-up. How do you decide which chart is going for work? Is there a connection between the variable with the highest power (or conversely, the variable with the lowest power) and the choice of the chart?
Comment: Dear @Andrew, I needed some clarification/help in regards to why was the chart $v=1$ chosen for the base point $[0,1,0]$ to initiate the blow-up process. What happens if the base point is, say, $[0,1,-1]$? I have asked this a question: http://math.stackexchange.com/questions/878551/blow-up-in-projective-space-choosing-the-appropriate-chart

Resolution of Singularities: Base Point


Python STDIN User Input Issue

Question: Issue
Conflict with STDIN when executing these two functions. What would cause the second function to not read STDIN correctly? If the first function is not executed, the second function has no issue reading the input.
To clear STDIN buffer I've tried:
'sys.stdin.flush'

'tcflush(sys.stdin, TCIOFLUSH)'

Python Code
import sys, select

def stdin_read():

    print "[stdin read] You must answer Y/N and press ENTER"
    sys.stdout.flush()
    response = sys.stdin.read(1)
    print "You said '{}'".format(response)

def stdin_timeout():

    print "[stdin timeout] You must answer YES / NO in 10 seconds and press ENTER"
    sys.stdout.flush()

    sys.stdin.flush()

    i, o, e = select.select( [sys.stdin], [], [], 10 )

    if (i):
        print "You said '{}'".format(sys.stdin.readline().strip())
        exit(0)
    else:
        print "You said nothing!"
        exit(1)

stdin_read()
stdin_timeout()

Python Output Both Functions:
:~# python input.py
[stdin read] You must answer Y/N and press ENTER
n
You said 'n'
[stdin timeout] You must answer YES / NO in 10 seconds and press ENTER
no
You said ''
:~# no
-bash: no: command not found

Python Output Second Function
~# python input.py
[stdin timeout] You must answer YES / NO in 10 seconds and press ENTER
no
You said 'no'

Answer: The problem arises from the behaviour of stdin flushing in unix
I'll answer by commmenting your code:
import sys, select

def stdin_read():

    print "[stdin read] You must answer Y/N and press ENTER"
    # sys.stdout.flush() # not needed
    # you are reading one byte here, but the user enters at least two bytes
    # (e.g 'y' + LF(enter key)) so the LF byte (and possibly additional bytes)
    # remain in the stdin buffer.
    response = sys.stdin.read(1) # (->LF REMAINS)
    print "You said '{}'".format(response)

def stdin_timeout():

    print "[stdin timeout] You must answer YES / NO in 10 seconds and press ENTER"
    #sys.stdout.flush() #  not needed
    # the behaviour of stdin flushing in unix is not defined (see
    # link above)
    sys.stdin.flush()
    # thus the LF still remains in the stdin buffer

    # the select call blocks until the file discriptor is 'ready' for
    # the corresponding i/o operation. DISCLAIMER: assumptions are
    # following.... By default python does a open call which uses
    # buffered reads, so even if you did a read(1) it will likely read
    # more data from stdin and the select call blocks until the next LF
    # arrives.
    i, o, e = select.select( [sys.stdin], [], [], 10 )

    if (i):
        # you are just reading the left over bytes from above (->LF REMAINS)
        print "You said '{}'".format(sys.stdin.readline().strip())
        # Proof: readline() again:
        print "You missed '{}'".format(sys.stdin.readline().strip())
        exit(0)
    else:
        print "You said nothing!"
        exit(1)

stdin_read()
stdin_timeout()

But maybe it would be better to use another approach Keyboard input with timeout in Python

Python STDIN User Input Issue


Erro ao gerar gráfico matplotlib

Question: sou novo com o Python e estou tendo dificuldade com meu algorítimo, a função do mesmo é verificar palavras em um conjunto de arquivos no formato PDF e analisar a recorrência de cada palavra gerando com essas informações um gráfico da lei de zipf(a segunda palavra mais recorrente repete em quantidade a raiz quadrada da primeira palavra mais recorrente) em fim, estou usando a biblioteca matplotlib para plotar gráficos em barras, porém o número de palavras que aparecem no gráfico é muito grande(no eixo x) e estão se sobrescrevendo.
obs: todo crítica é bem vinda, desde já agradeço a todos.
segue o algorítimo e o gráfico gerado.
    #!/usr/bin/env python3.6
import os
import re
from operator import itemgetter
import matplotlib.pyplot as plt
import numpy as np
import math

from tkinter import *
def io_pasta():
        def on_press():
            if not (os.path.exists(entrada.get())):
                lb["fg"]="red"
                lb["text"] = "Pasta inexistente/inacessivél"
                lb["font"]= "Bold"
            else:
                zipf(entrada.get(),janela)

        janela = Tk()
        lb=Label(janela, text = "Onde estão os asquivos?", font = "arial")
        lb.pack()
        entrada = Entry(janela, width = 40)
        entrada.place(x=40,y=40)
        b = Button(janela,text="OK",width = 10, command=on_press)
        b.place(x=150,y=75)

        janela.geometry("400x120")
        janela.title("Distribuição ZIPF")

        janela.mainloop()

def zipf(pasta,win):
    win.destroy()
    if not pasta[-1]=="/":
          pasta+="/"
    palavra=[]
    repetic=[]
    for nome in os.listdir(pasta):
        os.system("pdftotext -enc UTF-8   "+pasta+""+str(nome)+"  "+pasta+""+str(nome)+".txt")
    print("arquivos convertidos ......................ok!")
    os.system("mkdir "+pasta+"arquivos_originais && mv "+pasta+"*pdf "+pasta+"arquivos_originais")
    os.system("mkdir "+pasta+"convertidos_txt && mv "+pasta+"*txt "+pasta+"convertidos_txt/")
    os.system("mkdir "+pasta+"zipf")
    print("pasta ARQUIVOS_MOVIDOS criada .................ok!")
    print("Arquivos Movidos.............................ok!")
    frequency = {}
    for arq in os.listdir(""+pasta+"convertidos_txt/"):
        open_file = open(""+pasta+"convertidos_txt/"+str(arq)+"", "r", encoding='latin-1')
        file_to_string = open_file.read()
        w1 = re.findall(r'(\b[A-Za-z][a-z]{4,20}\b)', file_to_string)
        control = True
        for word in w1:
            count = frequency.get(word,0)
            frequency[word] = count + 1

        for key, value in reversed(sorted(frequency.items(), key = itemgetter(1))):
            if control == True:
                    j=value
                    control=False
            else:
                if abs(math.sqrt(j)-value)<4:
                        palavra.append(key)
                        repetic.append(value)

        plt.title("Distribuição zipf")
        plt.grid(True)
        plt.xticks(repetic,palavra,rotation=90,size='small')
        pos = np.arange(len(palavra)) + .5
        plt.bar(pos,repetic,align='center',color='#b8ff5c')
        plt.savefig(''+pasta+'zipf/grafico_'+str(arq)+'.png')

io_pasta()

Comment: Não é possível gerar um [mcve]?
Comment: vou fazer e logo posto.
Comment: Dei uma olhada no seu código, mas não rodei ele pois ele quer ler, criar e mover arquivos e pastas (meus arquivos). Porém, isso não é diretamente relevante para o problema descrito (problemas com barras, número e palavras). Mesmo se eu resolver rodar, este código, não tenho certeza de vou repetir o seu problema pois são meus pdfs (voltando ao comentário inicial de reproduzir o problema).
Seria bom ter apenas a lista de palavras e repeticões, assim como a parte para plotar do código que reproduz o seu problema.
Comment: Opa, consegui resolver, o meu problema era que não estava passando o parâmetro "palavras" em plt.bar.
Comment: Neste caso, você pode responder a sua pergunta e aceitar a resposta. Colocar uma figura do problema/resultado seria interessante também. Assim tem uma resposta para outros usuários que tenham um problema similar.
Answer: Sugestão 1: use o método tightlayout
Adicione a função
tightlayout antes de
salvar a sua imagem:
plt.bar(pos,repetic,align='center',color='#b8ff5c')
plt.tightlayout()
plt.savefig(''+pasta+'zipf/grafico_'+str(arq)+'.png')

Sugestão 2: instancie uma figure e ajuste seu tamanho

Processe seu texto e tenha ao final um número X de palavras.
Crie uma figura com a função figure (ou função análoga) e especifique
o tamanho dela de acordo com o tamanho do seu número X de palavras:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(0.5 * x, 10))

(ajuste o fator de 0.5 para um número maior/menor).

Erro ao gerar gráfico matplotlib