text:
Q: how to save map containing markers into image file using phantomjs I am trying to save a map containing markers and also heatmap.
Here is the code to display the map.
import folium
m_f = folium.Map(location= [39.76258, 254.994682],
                 zoom_start=8)

m_f.save('f_map.html')
m_f

I then use phantomjs to save the image.
import selenium.webdriver
import time

from selenium import webdriver

driver = webdriver.PhantomJS(executable_path='/Users/path/Downloads/PhantomJS/bin/phantomjs')

driver.set_window_size(4000, 3000)  # choose a resolution
driver.get('f_map.html')
# You may need to add time.sleep(seconds) here
time.sleep(1)
driver.save_screenshot('f_map.png')

There is no problem until here.
However,  when I add some markers on the map, I get the correct html file, which I can open also in the browser, but its screenshot is a blank file (content).
Here is the code of the new map
import folium
m_f = folium.Map(location= [39.74258, 254.993682],
                 zoom_start=12)

arr_test1 = [39.74258, 254.993682]
arr_test2 = [39.75258, 254.994682]
arr_test3 = [39.76258, 254.994682]

all_loc = [arr_test1, arr_test2, arr_test3]

for cur_loc in all_loc:
    point = folium.Circle(
        radius=200,
        location=cur_loc,
        popup='The Waterfront',
        color='red',
        fill=False,
    )
    point.add_to(m_f)

    time.sleep(0.001)

m_f
m_f.save('f_map_marker.html')

and its phantonjs code lines
import selenium.webdriver
import time

from selenium import webdriver

driver = webdriver.PhantomJS(executable_path='/Users/path/Downloads/PhantomJS/bin/phantomjs')

driver.set_window_size(4000, 3000)  # choose a resolution
driver.get('f_map_marker.html')

time.sleep(1)
driver.save_screenshot('f_map_marker.png')

So, the f_map_marker.png file is blank.
Does anyone has an idea, why it behaves this way, and how I can solve the issue ?
Any hints will be welcome.

A: I checked your code with Firefox (geckodriver) instead of PhantomJS and I have the 3 circles on the map in the "f_map_marker.png" file. Maybe it is because the PhantomJS project is not maintained anymore. You can have look to the Github comment on the PhantomJS repository : https://github.com/ariya/phantomjs/issues/15344


text:
Q: cell height depending on a label text I get the object from CoreData like this self.name = [[abc anyObject] valueForKey:@"name"]
and display it:
cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.name];
cell.nameLabel.numberOfLines = 0;
cell.nameLabel.lineBreakMode = NSLineBreakByWordWrapping;

How can I get the correct height for my cell to return it in
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

A: This is the solution:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize constraintSize = CGSizeMake(286.0f, CGFLOAT_MAX);
    UIFont *theFont  = [UIFont systemFontOfSize:14.0f];
    CGSize theSize;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        CGRect frame = [[self.mArray objectAtIndex:indexPath.row] boundingRectWithSize:constraintSize options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:theFont} context:nil];
    theSize = frame.size;
    }
    else
    {
        theSize = [[self.mArray objectAtIndex:indexPath.row] sizeWithFont:theFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    }

    return theSize.height;
    }

Also in - (UITableViewCell )tableView:(UITableView )tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath I used cell.label.numberOfLines = 0
If you are using more than one Label in row - in CGSizeMake(286.0f, CGFLOAT_MAX) use lower value than 286.0f (for example 150.0f)

A: Just implement a static method in your UITableViewCell class that is able to calculate cell height basing on provided string and a width. Cell should know how it is constructed and how much space it will occupy.
For example:
+ (CGFloat)heightForWidth:(CGFloat)width text:(NSString *)text {

    CGFloat height = ... ;

    return height;
}

A: Try to disable auto layout in your storyboard and then call sizeToFit.
cell.nameLabel.text = [NSString stringWithFormat:@"%@",self.name];
cell.nameLabel.numberOfLines = 0;
cell.nameLabel.lineBreakMode = NSLineBreakByWordWrapping;
[cell.nameLabel sizeToFit];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring boot stops after starting on server When I trying to deploy jar file on server at that time it is deployed successfully and then I execute startup.sh file after that spring boot application is start the execution but after execute bellow logs server is not responding any more.
[2016-07-15 11:01:38.714] boot - 14956  INFO [main] --- TomcatEmbeddedServletContainer: Tomcat started on port(s): 8084 (http)
[2016-07-15 11:01:38.723] boot - 14956  INFO [main] --- Application: Started Application in 64.717 seconds (JVM running for 67.138)
[2016-07-15 11:01:44.688] boot - 14956  INFO [Thread-4] --- AnnotationConfigEmbeddedWebApplicationContext: Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@64375c2a: startup date [Fri Jul 15 11:00:38 EDT 2016]; root of context hierarchy
[2016-07-15 11:01:44.692] boot - 14956  INFO [Thread-4] --- DefaultLifecycleProcessor: Stopping beans in phase 0
[2016-07-15 11:01:44.752] boot - 14956  INFO [Thread-4] --- AnnotationMBeanExporter: Unregistering JMX-exposed beans on shutdown
[2016-07-15 11:01:44.810] boot - 14956  INFO [Thread-4] --- LocalContainerEntityManagerFactoryBean: Closing JPA EntityManagerFactory for persistence unit 'default'

Also attached screenshot here.

Please Guide,
Thanks.

A: If you are using Maven add this to your pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

It should work.


text:
Q: Prevent hanging of "echo STRING > fifo" when nothing is reading that FIFO When I echo something to a named pipe made with mkfifo, it hangs if no process is reading from that pipe. How can I prevent that, i.e., stop that from hanging?
And by the way, why is that hanging echo process not listed in ps -e or pstree?

A: It's not totally clear what your desired end result is from the question, so I will assume that your desire is to continue the program, but still have the write occur when possible. In that case, just background the operation:
echo foo > fifo &

As for why echo is not listed in the process table, it's because echo is a shell builtin.


text:
Q: Taylor series representation of a function I'm given a function and asked to represent it as a Taylor series, but it seems that taking derivatives of this function gets more and more tedious.  Is there an alternative way to solve this problem?

A: The trick is to let $u = x+2$ so that we want a power series in $u$. Note $x=u-2$ so that $1-2x = 1-2(u-2) = 5 - 2u$ so that we have the expression
$$\frac{5}{5 - 2u} = \frac{1}{1 - \frac{2}{5}u} = \sum \left(\frac{2}{5}\right)^n u^n =  \sum \left(\frac{2}{5}\right)^n (x+2)^n$$
(remember the basic geometric series $\sum_{n\geq 0} x^n = \frac{1}{1-x}$)

A: Also, calculating derivatives is easy:
$$f(x)=5(1-2x)^{-1}\\
f'(x)=5\cdot 2(1-2x)^{-2}\\
f''(x)=5\cdot 2\cdot 2(1-2x)^{-3}\\
f'''(x)=5\cdot 2^2\cdot 2\cdot 3(1-2x)^{-3}\\
...\\
f^{(n)}(x)=5\cdot 2^n\cdot n!(1-2x)^{-n-1}$$
For $x=-2$
$$f^{(n)}(-2)=5\cdot 2^n\cdot n!(5)^{-n-1}=\left(\frac{2}{5}\right)^n n!$$


text:
Q: Excel add in (Content app) How to get rid of top right arrow Excel add in (Content app) How to get rid of top right arrow.

This element(div) is auto created by app development template.

A: This is "by design", so there is nothing you can do on your end to get rid of it (I think it actually sits above the web content, and is inaccessible to the DOM altogether).  But there had been some discussion of possibly finding an alternate pattern, at least in task panes.  Let me talk to my team about this.

A: The top right icon is a Personality Menu button per documentation. As Michael said, it is placed there "by design" and can not be removed.
The browser version of the Excel doesn't have it but Mac and Windows do.
You can conditionally move the content that is hidden by the button using the Office.PlatformType enum.


text:
Q: How should you schedule tasks in a web api .NET 5 vNext I am in need of scheduling tasks that need to run every hour daily.  I also ideally need to "fire and forget" a task, although i could handle this by creating another task to run every 5 minutes instead.
I have created a WebApi and ideally would like to run a scheduler within this, rather than having to create another application, such as a console app and then setup a windows schedule task. I see that there is a nuget package called Quartz.net that can deal with this.
Quartz sounds good to me, because code is all in one place.  Plus because i will have multiple copies of this webApi running, Quartz could run for each instance.
But overall i want stablility! I have been reading sites and they say because your application pool is recycled by default every X hours, scheduling in a webApi is not a good idea.
Has anyone done this before, and which option did they go for and why?


text:
Q: How get paypal transaction detail in angular2? I am using paypal transaction for my site which is built in angular2. Here code of my paypal form. Component function.
paypalPayment(cartArr) {
    var form = document.createElement("form");
    form.method = "POST";
    form.action = "https://www.sandbox.paypal.com/cgi-bin/webscr";
    this.createElement(form, 'charset', 'utf-8');
    this.createElement(form, 'cmd', '_xclick');
    //this.createElement(form, 'cmd', '_cart');
    this.createElement(form, 'upload', '1');
    this.createElement(form, 'currency_code', 'USD');
    this.createElement(form, 'business', "my_business@mail.com");
    this.createElement(form, 'email',"user_email@test.com");
    this.createElement(form, 'custom', '{ "order_id": ' + this.order_id + ' }');
    this.createElement(form, 'item_name', "Item");
    this.createElement(form, 'amount', "10");
    this.createElement(form, 'quantity', 1);
    this.createElement(form, 'return', 'sitename.com/purchase/close_verified_order/' + this.order_id);
    this.createElement(form, 'cancel_return', 'sitename.com/purchase/cancel/' + this.order_id);
    this.createElement(form, 'notify_url', 'sitename.com/purchase/close_invalid_order/' + this.order_id);

    document.body.appendChild(form);
    form.submit();
  }

In above form when i use _xclick then it returns basic detail like transaction id in URL but i need all transaction detail. Below is code of return page.
ngOnInit() {
    let transactionId = this.route.snapshot.queryParams['tx'];
    this.order_id = this.route.snapshot.params['id'];
  }

How paypal provide all transaction detail ? I have read about IPN but i don't know how to use it in angular2.
I want to know what should i have to change in my notify_url or in return to get all transaction detail. ?
If paypal send transaction detail in POST data then how can i handle that in angular2 code ?
If i need to use IPN then how can i get auth_token from paypal and then how to call it's api from angular2 ?

A: Don't work with Angular, but in general, you need to set up a 'listener' to respond to IPN results. That 'listener' should include code that uses the $_POST data (returned to the 'listener') to do what you need with the info.
IPN docs start here https://developer.paypal.com/docs/classic/products/instant-payment-notification/ . Set up a Sandbox account, and use that for testing.
There is also an IPN 'tester' that you can use to test your code against various types of IPN responses.


text:
Q: sharepoint rendering templates set attributes from fields I'm trying to write a custom rendering template for use in the DisplayForm of a list whose fields include Title, HeaderImageUrl, Body.  I've got the following so far:
<SharePoint:RenderingTemplate ID="NewsListForm" runat="server">
 <Template>

<SharePoint:FieldValue FieldName="Title" runat="server"/>

          <SharePoint:UrlField FieldName="HeaderImageUrl" runat="server"></SharePoint:UrlField>
          <SharePoint:RichTextField FieldName="Body" runat="server" />

 </Template>
</SharePoint:RenderingTemplate>

The HeaderImageUrl field is configured to be an Image URL, but when I use the UrlField control, it renders a link.
I was thinking there might be a way to grab field values and put them in attributes, so something like this:
<asp:Image ImageUrl="<% FieldValue["HeaderImageUrl"] %>" runat="server"/>

If this kind of thing isn't possible, then is there another control in Microsoft.SharePoint.WebControls that would render an image from a URL?

A: All the examples I've seen of calling a URL field to be displayed as an image have been through C# code. Which is quite annoying since most of web part bits can be written without using C# code. You might also need to go down that road here... perhaps a custom field control or user control.
Even if your code above did get the value for HeaderImageUrl, it wouldn't work as Url values are (confusingly):
[the actual url specified][some wierd delimeter string][the description field of the url (usually the actual url again if your don't specify it)]
So you would need to split the string with te delimeter values and use the [0] (the first) as what you inject into your image url.
Please do post if you find a way to do this without writing C# code.
p.s. Have you considered using a DataFormWebPart which has a xsl section in which you might be able to do extractly what you need?!
Example: You can stick the following syntax into any aspx / ascx file:
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register tagprefix="WebPartPages" namespace="Microsoft.SharePoint.WebPartPages" assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<WebPartPages:DataFormWebPart runat="server" IsIncluded="True" FrameType="None"
NoDefaultStyle="TRUE" ViewFlag="0" Title="My List Display"
 Default="FALSE" ID="dfwp_MyListDisplay"
 DisplayName="My List Display">
 <DataSources>
        <SharePoint:SPDataSource runat="server" DataSourceMode="List" UseInternalName="true"
        selectcommand='<View><Query><Where><Eq><FieldRef Name="Category"/><Value Type="Text">Header</Value></Eq></Where></Query></View>' id="Utility_x0020_Navigation1"><SelectParameters><WebPartPages:DataFormParameter Name="ListName" ParameterKey="ListName" PropertyName="ParameterValues" DefaultValue="My List Display"/>
        <asp:Parameter Name="ListName" DefaultValue="LIST NAME" />
        <asp:Parameter Name="WebUrl" DefaultValue="<% $SPUrl:~SiteCollection/ %>" />
        </SelectParameters>
        </SharePoint:SPDataSource>
    </DataSources>
    <ParameterBindings>
    <ParameterBinding Name="dvt_apos" Location="Postback;Connection"/>
    <ParameterBinding Name="PageURL" Location="ServerVariable(URL)" DefaultValue=""/>
    <ParameterBinding Name="SiteUrl" Location="ServerVariable(SERVER_NAME)" DefaultValue=""/>
</ParameterBindings>
    <datafields>@Title,Title;@URL,URL;@Category,Category;@Parent_x0020_item,Parent_x0020_item;@Sort_x0020_Order,Sort Order;@ID,ID;@ContentType,Content Type;@Modified,Modified;@Created,Created;@Author,Created By;@Editor,Modified By;@_UIVersionString,Version;@Attachments,Attachments;@File_x0020_Type,File Type;@FileLeafRef,Name (for use in forms);@FileDirRef,Path;@FSObjType,Item Type;@_HasCopyDestinations,Has Copy Destinations;@_CopySource,Copy Source;@ContentTypeId,Content Type ID;@_ModerationStatus,Approval Status;@_UIVersion,UI Version;@Created_x0020_Date,Created;@FileRef,URL Path;</datafields>
    <xsl>
    YOUR XSLT HERE
    </xsl>

</WebPartPages:DataFormWebPart>

A: The following code will get you the url of an imagefield:
SPListItem item = GetItem();
string imagefieldhtml = item["HeaderImageUrl"].ToString();
ImageFieldValue imagefield = new ImageFieldValue(imagefieldhtml);

var url = imagefield.ImageUrl;

So maybe altering your to something like this will help you, or maybe help you out atleast...?
<asp:Image ImageUrl="<% (ImageFieldValue ["HeaderImageUrl"]).ImageUrl %>" runat="server"/>

A: Unable to test it atm (no environment) but I am quite sure I did this before.
Try these:
<SharePoint:FieldValue FieldName="HeaderImageUrl" runat="server"/>

or:
<img src="<SharePoint:FieldValue FieldName="HeaderImageUrl" runat="server"/>" />

I'll check back on this one and do an actual test by monday if those didn't work and you still need help.

A: Turns out that my problem was simply that I didn't have that image column set up to render as an image, rather than as a link.  The builtin Microsoft.SharePoint.UrlField control worked just fine, as it turned out.


text:
Q: Search phase execution exception with reason all shards failed I am working on elastic search in spring boot REST API. I am getting the following exception while executing search query with ElasticSearch Java Client.
org.elasticsearch.ElasticsearchStatusException: Elasticsearch exception [type=search_phase_execution_exception, reason=all shards failed]
Following is my code:
        String query = path + "\"" + path + "\"";
        SearchRequest request = new SearchRequest();
        request.indicesOptions(IndicesOptions.fromOptions(true, true, true, true));
        String [] indices = new String[]{"index1", index2"};
        request.indices(indices);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(query);
        sourceBuilder.size(1);
        sourceBuilder.fetchSource("field_1", null);
        sourceBuilder.query(queryBuilder);
        request.source(sourceBuilder);
        SearchResponse searchResponse = elasticsearchClient.getRestClient().search(request, RequestOptions.DEFAULT); ---> This line is throwing error.

And this issue seems intermittent during initialisation of ES and when indices are being created. Once after creation of indices, this issue is not occurring.
Can anyone help me on how we can eat this issue smoothly. Thank you in advance.

A: are you trying to query the index which is being created
if that is the case try to query without specifying the index
which will avoid error or wait until the index creation is over which may resolve your issue


text:
Q: Using iconv to convert utf-8 characters to the closest ASCII character I can use the iconv command to "translit" a utf-8 string to an ASCII-only string with characters being replaced with their closest ASCII character. However, my problem is that I need the resulting string to contain exactly the same number of characters (code points) as the source string. For example the British pound (£) character is being replaced with three characters (GBP) or the character æ with the two characters ae. Instead, I want these characters to be replaced with a single character (for example, L or ? or a or e). Is there a method / option for this?

Overview
I am trying to develop an "ASCII-based" find routine for Latin-based text. For example, find 'uco' in '£Húçôz' should return position 3 (I am counting from 1 for the first position) and not 5 (because£ is expanded to 3 characters and not one). Please, note that, what I am trying to develop is much more complex; I have tried to simplify my question as much as possible here.
Also note that, this find routine need not be perfect in matching non-ASCII Latin-based text strings, but the (first) position of the match (if there is one) should point to the correct character (code point) position.


text:
Q: Neyman allocation and proportional allocation
Suppose that a city has 90,000 dwelling units, of which 35.000 are houses, 45,000 are apartments,
  and 10,000 are condominiums. We want to estimate the overall proportion (p) of households
  in which energy conservation is practiced, with a bound on the error of estimation equal 0.1.
  The cost for obtaining an observation is \$9 for houses, \$10 for apartment, and \$16 for
  condominiums. Suppose that from an earlier study, we know that 47% of house dwellers, 23%
  of apartment dwellers, and 3% of condominium residents practice energy conservation.
(a) (4 marks) Using a proportional allocation, find the strata sample sizes, $n_1$, $n_2$, and $n_3$,
  and the sample size n.
  (b) (4 marks) Using a optimal allocation, find the strata sample sizes, $n_1$, $n_2$, and $n_3$, and
  the sample size n.
  (c) (4 marks) Using a Neyman allocation, find the strata sample sizes, $n_1$, $n_2$, and $n_3$, and
  the sample size n.

Neyman allocation is used when the cost of obtaining an observation is the same for all strata, while proportional allocation is used when costs are unequal among strata but variances are equal in all strata. But in this question, neither cost or variance are equal, then how can I apply the formula for Neyman and proportional allocation? Just ignore the cost and variance and set them equal or is there another formula for that?

A: Proportional allocation is exactly that - proportional. Sampling cost does not matter here, the only information you need to calculate $n$ is the stratum weights, a bound, and stratum variances or variance estimate.
The stratum weights are $W_h= \frac{N_h}{N}$ where $h=1,2,3$. $N_h$ is the size of stratum $h$ and $N$ is the population size. In this case, $N= 90,000 $ and $W_1=\frac{35,000}{90,000}$, for example.
Your bound is B=0.1, which is fine.
You don't have a variance or variance estimate of each strata, so use the earlier study's information for this. For example, a variance estimate for stratum 1 would be $\hat{S}_1^2 = \hat{p}_1\hat{q}_1 = (0.47)(0.53)$.
Now, use the formula $$n= \frac{\sum_h W_h\hat{S}^2_h }{\frac{B^2}{4} + \frac{1}{N}\sum_h W_h\hat{S}^2_h}$$ and then calculate each $n_h = nW_h$, rounding where required.
Neyman Allocation ignores costs for these calculations as well because we assume they are equal. The calculation for $n$ is $$n= \frac{\sum_h W^2_h\frac{\hat{S}^2_h}{w_h} }{\frac{B^2}{4} + \frac{1}{N}\sum_h W^2_h\frac{\hat{S}^2_h}{w_h}}$$ Where $$w_h = \frac{W_h\hat{S}_h}{\sum_h W_h\hat{S}_h}$$
Note that the $\hat{S}$'s are not squared. Finally, we can calculate $n_h=nw_h$ and then you're done, since it sounds like you have optimal allocation covered.


text:
Q: Apply style on mouseover and when class variable is true I come from a web background, so I'm really struggling with this one.
I have a style that I need applied when both IsMouseOver is true and a class variable (called _isLinking) is true within my Linking class is true also. I have the style built and functioning with the IsMouseOver, but I'm not sure how to get the second condition with the _isLinking in there.
<Path.Style>
    <Style>
        <Setter Property="Path.Stroke" Value="Black" />
        <Setter Property="Path.Fill" Value="LightGray" />
        <Style.Triggers>
            <Trigger Property="Canvas.IsMouseOver" Value="True">
                <Setter Property="Path.Stroke" Value="Blue" />
                <Setter Property="Path.Fill" Value="LightBlue" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Path.Style>

A: You should use MultiDataTrigger (msdn).
Example:
<Canvas>
    <Path>
        <Path.Data>
            <PathGeometry Figures="M 10,100 C 10,300 300,-200 300,100" />
        </Path.Data>
        <Path.Style>
            <Style>
                <Setter Property="Path.Stroke" Value="Black" />
                <Setter Property="Path.Fill" Value="LightGray" />
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Canvas}}" Value="True" />
                            <Condition Binding="{Binding IsLinking}" Value="True" />
                        </MultiDataTrigger.Conditions>
                        <MultiDataTrigger.Setters>
                            <Setter Property="Path.Stroke" Value="Blue" />
                            <Setter Property="Path.Fill" Value="LightBlue" />
                        </MultiDataTrigger.Setters>
                    </MultiDataTrigger>
                </Style.Triggers>
            </Style>
        </Path.Style>
    </Path>
</Canvas>

In the above example DataContext is set to object of type Linking.
 this.DataContext = new Linking { IsLinking = true };


text:
Q: LAN connection not working when cable plugged after removal I am facing a weird problem recently. When I reboot my computer with the LAN cable plugged in, it's connected and everything works fine. But when I remove the cable and plug it in again, it detects LAN but shows no internet access (And in 1 or 2 cases, it didn't detect LAN too).
Each time I plug out my LAN cable I have to reboot my system to get connected again. I even tried disabling and re-enabling the LAN adapter, but the problem still persists. My OS is Windows 7. Can someone help me out on this?
We use static IPs only. Each LAN cable is assigned a static IP. ipconfig /renew has no effect.

A: the solution is going into the network setting in the control panel and right-click on ur ethernet adapter and go into the properties-configure-power management-uncheck the option to shut down to save power option (or whatever it says with regards to saving power) and that's it. problem solved.


text:
Q: Puppet-Agent fails to resolve RPM from YUM-Repo I´m trying to resolve RPMs additional from an our own YUM-Repository. I declared the additional Yum-Repo in "/etc/yum.repos.d/" and running the command "yum install JDK-jdk.x86_64" the rpm installs succesfully.
But when using the following manifest from Puppet, Puppet doesn`t seem to look in the declared additional YUM-repository:
class tomcat7_rhel {
  package { "sun-JDK-1.6.0":
    ensure => latest,
    require => Yumrepo["JDK-jdk.x86_64"]
    #require => Package["JDK-jdk.x86_64"]
  }
}

Running the agent with:
puppet agent --test --environment det

the Error looks as follows:

Error: Could not retrieve catalog from remote server: Error 400 on
  SERVER: Invalid relationship: Package[sun-JDK-1.6.0] { require =>
  Yumrepo[JDK-jdk.x86_64] }, because Yumrepo[JDK-jdk.x86_64] doesn't
  seem to be in the catalog Warning: Not using cache on failed catalog
  Error: Could not retrieve catalog; skipping run

Currently I´m completly stuck, so any help would be appreciated.

A: try requiring a yum update on package installation to make sure you're getting your latest additions:
exec {"yum_update":
  command => "yum update -y",
}

package { "sun-JDK-1.6.0":
    ensure => latest,
    require => [ Yumrepo["JDK-jdk.x86_64"], Exec["yum_update"] ],
}


text:
Q: Perform ifelse() on every element of a data frame, but different test for each column in R I've got a large data frame [4000,600] and I'd like to convert elements to 0 if they are smaller than three orders of magnitude less than each column maximum.  So each element would need to be compared to the maximum value of its column and if the element < 0.001*$column_max then it should be converted to 0 and if it isn't, it should remain the same.
I am having a tough time getting apply() to let me use an ifelse() function.  Is there a better approach or function I am missing??  I'm fairly new to R.

A: Use lapply to loop over each column with a replace call:
dat <- data.frame(a=c(1,2,1001),b=c(3,4,3003))
dat
#     a    b
#1    1    3
#2    2    4
#3 1001 3003

dat[] <- lapply(dat, function(x) replace(x, x < max(x)/10^3, 0) )
dat
#     a    b
#1    0    0
#2    2    4
#3 1001 3003

A: This should work with ifelse if you use apply column-wise:
df <- data.frame(a = c(1:10, 4000), b = c(4:13, 7000))

apply(df, 2, function(x){ifelse(x < 0.001*max(x), 0, x)})

A: We could do this without using ifelse
library(dplyr)
dat %>%
    mutate_each(funs((.>= 0.001*max(.))*.))
#     a    b
#1    0    0
#2    2    4
#3 1001 3003

data
dat <- data.frame(a=c(1,2,1001),b=c(3,4,3003))


text:
Q: PHP February date: "2015-01-31" +1 month: "2015-03-30". How to fix? If I use this code I get strange results:
$datetime = new DateTime('2015-01-31');
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "
";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "
";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "
";

I get this:
2015-03-31
2015-04-30
2015-05-31

And not 2015-02-28.
How to fix?

A: The way DateTime works, + 1 month increases the month value by one, giving you 2015-02-31. Since there are only 28 or 29 days in February, that will evaluate to the first few days of March. Then, as you know, asking for Y-m-t will give you the last day of March.
Since you're already using t to get the last day of the month, you could avoid this problem by starting with a date that falls at the beginning of a month instead:
$datetime = new DateTime('2015-01-01');

Reference: PHP DateTime::modify adding and subtracting months

A: If you want to get the last day of the next month, you can use:
$datetime->modify('last day of next month');

A: You can try this function to add months to a datetime object
    /**
 *
 * @param \DateTime $date DateTime object
 * @param int $monthToAdd Months to add at time
 */
function addMonth(\DateTime $date, $monthToAdd)
{
    $year = $date->format('Y');
    $month = $date->format('n');
    $day = $date->format('d');

    $year += floor($monthToAdd / 12);
    $monthToAdd = $monthToAdd % 12;
    $month += $monthToAdd;
    if ($month > 12) {
        $year ++;
        $month = $month % 12;
        if ($month === 0) {
            $month = 12;
        }
    }

    if (! checkdate($month, $day, $year)) {
        $newDate = \DateTime::createFromFormat('Y-n-j', $year . '-' . $month . '-1');
        $newDate->modify('last day of');
    } else {
        $newDate = \DateTime::createFromFormat('Y-n-d', $year . '-' . $month . '-' . $day);
    }
    $newDate->setTime($date->format('H'), $date->format('i'), $date->format('s'));

    return $newDate->format('Y-m-d');
}

echo addMonth(new \DateTime('2015-01-30'), 1); //2015-02-28
echo addMonth(new \DateTime('2015-01-30'), 2); //2015-03-30
echo addMonth(new \DateTime('2015-01-30'), 3); //2015-04-30

A: Fix it like this.
$datetime = new DateTime('2015-01-31');
$datetime->modify('28 days');
echo $datetime->format('Y-m-t') . "
";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "
";
$datetime->modify('+1 month');
echo $datetime->format('Y-m-t') . "
";

You will get
2015-02-28
2015-03-31
2015-04-30


text:
Q: HttpClient4.5 throw exception on connecting server I am want to hit the one rest service using httpclient. But facing problem. Here is my program to hit server. If I run this program from my local machine then it hit server fine and get the response as well.
But When I host this program to server and then hit the Rest Server then it thows and exception. I really not able to understand what is different between local and server enviornment.
HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(se);

            HttpResponse resp = null;
            String url = "http://gigilitytest.cloud.cms500.com/MMServer/mycircle/saveuserinfo";
            URI uri = null;
            RequestResult reqResult = new RequestResult();
            try {
                uri = new URI(url);
                httpPost.setURI(uri);
                System.out.println("***********************************----------1");
                resp = httpClient.execute(httpPost);
                System.out.println("***********************************----------2");
                System.out.println("resp:" + resp);

                Reader reader = new InputStreamReader(resp.getEntity().getContent());
                reqResult = gson.fromJson(reader, RequestResult.class);
                reader.close();
                httpPost.releaseConnection();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

Exception is :
"preferedGenderType":"","imgUrl":"https%253A%252F%252Fscontent.xx.fbcdn.net%252Fv%252Ft1.0-1%252Fp50x50%252F16194964_10208251611276804_5467876133040299192_n.jpg%253Foh%253D63a59ee0a5dc9cdb0771135ffa7fab2d"} org.apache.http.conn.HttpHostConnectException: Connect to gigilitytest.cloud.cms500.com:80 [gigilitytest.cloud.cms500.com/10.101.4.223] failed: Connection refused at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) at com.gigility.rs.UserProfileRS.saveUserProfile(UserProfileRS.java:93) at com.controller.AjaxController.saveUserProfile(AjaxController.java:113) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:622) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134) ... 51 more


text:
Q: In my Shiny app, why does my sample generator result in the same exact sample without any randomization? Although I am able to generate the correct amount of samples, and these samples are each of the right size, each one is exactly the same.
Currently, I am trying to create a Shiny app that demonstrates the Central Limit Theorem, specifically for the case regarding the distribution of the sample mean. I expected the app to generate a proper sampling distribution when I realized that the histogram had the same exact value on the x-axis, indicating that the mean was exactly the same for each sample.
Based on my own testing, I think that the issue lies with the sample_i() reactive expression, given that the latter reactive expressions work well.
Would I have to implement another reactive expression in order to fix the issue?
library(shiny)

ui <- fluidPage(
  titlePanel("Demonstration of the Central Limit Theorem"),
  fluidRow(
    column(4, selectInput("dist", "Distribution",
                          c("Normal", "Uniform", "Poisson", "Binomial"))),
    column(4, numericInput("n_sample", "Number of samples", value = 50)),
    column(4, numericInput("size", "Sample size", value = 100))
  ),
  tabsetPanel(
    id = "params",
    type = "hidden",
    tabPanel("Normal",
             numericInput("mean", "Mean", value = 0),
             numericInput("sd", "SD", value = 1)
    ),
    tabPanel("Uniform",
             numericInput("min", "Min", value = 0),
             numericInput("max", "Max", value = 1)
    ),
    tabPanel("Poisson",
             numericInput("r", "Rate", value = 1)
    ),
    tabPanel("Binomial",
             numericInput("p", "Probability of success", value = 0.5),
             numericInput("n", "Number of trials", value = 10)
    )
  ),
  plotOutput("hist"),
  verbatimTextOutput("length")
)

server <- function(input, output, session) {
  observeEvent(input$dist, {
    updateTabsetPanel(inputId = "params", selected = input$dist)
  })

  sample_i <- reactive({
    switch(input$dist,
      Normal = rnorm(input$size, input$mean, input$sd),
      Uniform = runif(input$size, input$min, input$max),
      Poisson = rpois(input$size, input$r),
      Binomial = rbinom(input$size, input$n, input$p))
  })
  sample_dist <- reactive({
    replicate(n = input$n_sample, sample_i())
  })
  sample_dist_mean <- reactive({
      apply(sample_dist(), MARGIN = 2, mean) |>
        unlist() |>
        as.numeric()
  })

  output$hist <- renderPlot(hist(sample_dist_mean()))
  output$length <- renderPrint(head(sample_dist(), n = 5))
}

shinyApp(ui, server)

Note that the console generates the output below (which was done through the length component of the output) when the number of samples is set to 12.
           [,1]       [,2]       [,3]       [,4]       [,5]       [,6]
[1,]  0.5953571  0.5953571  0.5953571  0.5953571  0.5953571  0.5953571
[2,]  0.8323953  0.8323953  0.8323953  0.8323953  0.8323953  0.8323953
[3,] -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900
[4,]  2.1517537  2.1517537  2.1517537  2.1517537  2.1517537  2.1517537
[5,] -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259
           [,7]       [,8]       [,9]      [,10]      [,11]      [,12]
[1,]  0.5953571  0.5953571  0.5953571  0.5953571  0.5953571  0.5953571
[2,]  0.8323953  0.8323953  0.8323953  0.8323953  0.8323953  0.8323953
[3,] -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900 -1.0366900
[4,]  2.1517537  2.1517537  2.1517537  2.1517537  2.1517537  2.1517537
[5,] -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259 -1.2565259

A: EDIT: Found a new solution.
server <- function(input, output, session) {
  observeEvent(input$dist, {
    updateTabsetPanel(inputId = "params", selected = input$dist)
  })

  samples <- reactive({
    switch(input$dist,
      Normal = replicate(n = input$n_sample, rnorm(input$size, input$mean, input$sd)),
      Uniform = replicate(n = input$n_sample, runif(input$size, input$min, input$max)),
      Poisson = replicate(n = input$n_sample, rpois(input$size, input$r)),
      Binomial = replicate(n = input$n_sample, rbinom(input$size, input$n, input$p)))
  })

  sample_dist_mean <- reactive({
      apply(samples(), MARGIN = 2, mean) |>
        unlist() |>
        as.numeric()
  })

  output$hist <- renderPlot(hist(sample_dist_mean()))
}


text:
Q: How can we display both label and value on a pieSliceText on an 3d pie chart using google charts? Iam using Google Chart in Angular 6
I am using
pieSliceText: 'value'
But I need to display both label and value on the pie slice,
I tried using
pieSliceText: 'label-and-value'
similar to
pieSliceText: 'value-and-percentage'
But this doesnt work for me

A: a couple options...

1) use the following option to label the slices...
legend: {
  position: 'labeled'
}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work',     11],
    ['Eat',      2],
    ['Commute',  2],
    ['Watch TV', 2],
    ['Sleep',    7]
  ]);

  var options = {
    height: 400,
    is3D: true,
    legend: {
      position: 'labeled'
    },
    pieSliceText: 'value'
  };

  var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
  chart.draw(data, options);
});

2) use the following option to display the value of the slice...
pieSliceText: 'value'

with the above option, the slice will display the formatted value by default.
using object notation, we can provide both the value v: and formatted value f: in the data table.
{v: 11, f: 'Work: 11'}

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],
    ['Work', {v: 11, f: 'Work: 11'}],
    ['Eat', {v: 11, f: 'Eat: 2'}],
    ['Commute', {v: 11, f: 'Commute: 2'}],
    ['Watch TV', {v: 11, f: 'Watch TV: 2'}],
    ['Sleep', {v: 11, f: 'Sleep: 7'}]
  ]);

  var options = {
    chartArea: {
      height: '100%',
      width: '100%',
      top: 12,
      left: 12,
      right: 12,
      bottom: 12
    },
    height: 400,
    is3D: true,
    legend: {
      position: 'none'
    },
    pieSliceText: 'value'
  };

  var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
  chart.draw(data, options);
});


text:
Q: ASP.NET server controls overview I am looking for a chart overview of the different server control classes. I have seen it once somewhere but can not locate it anymore. Can someone please provide me with a link?

A: You mean like:
http://www.w3schools.com/aspnet/aspnet_refwebcontrols.asp
or:
http://www.asp.net/%28S%28dfjoah55n4ywsy45zregske4%29%29/community/control-gallery/
Or are you looking for something more like:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7b645f3a-6d22-4548-a0d8-c2a27e1917f8&displaylang=en
but just for ASP .NET server controls?  I guess it depends a lot on the version of the .NET framework (and Visual Studio, if you're using that).

A:
ASP.NET Server Controls Hierarchy
Web Server Controls Hierarchy


text:
Q: expectation of the sign of product of bivariate normal variables Let $X$ and $Y$ be two normal random variables with mean zero, variance 1 and correlation $\rho$. Let $Z=sign(XY)$ with $sign(x)=1$ if $x>0$ and $sign(x)=0$ otherwise.
Now, I calculate $\mathbb{E}[Z]$ as follows
\begin{eqnarray}\label{exp}
\mathbb{E}\left[Z_{t}\right]
&=&\mathbb{P}\left( X\geq 0, Y\geq 0\right)+\mathbb{P}\left( X\leq 0, Y\leq 0\right)\notag\\
&=& 2\mathbb{P}\left( X\geq 0, Y\geq 0\right)\notag\\
&=&2\sqrt{1-\rho^{2}}\frac{1}{2\pi}\int_{0}^{+\infty}\int_{0}^{+\infty}
\frac{uv}{|u||v|}e^{-\frac{1}{2}(u^{2}+v^{2}-2uv\rho)}dudv\notag\\
&=&2\sqrt{1-\rho^{2}}\bigg[\frac{1}{\sqrt{2\pi}}\int_{0}^{+\infty}\frac{1}{\sqrt{2\pi}}
\int_{0}^{+\infty}
e^{-\frac{1}{2}(u-\rho v)^{2}}du e^{-\frac{1}{2}(v^2-\rho^2 v^2)} dv\bigg] \notag\\
&=&2\sqrt{1-\rho^{2}}\bigg[\frac{1}{\sqrt{2\pi}}\int_{0}^{+\infty}
\frac{1}{\sqrt{2\pi}}\int_{-v\rho}^{+\infty}
e^{-\frac{x^{2}}{2}}dx e^{-\frac{1}{2}(v^2-\rho^2 v^2)} dv\bigg]\notag\\
&=&2\sqrt{1-\rho^{2}}\bigg[\frac{1}{\sqrt{2\pi}}\int_{0}^{+\infty}
\Phi(v\rho) e^{-\frac{1}{2}(v^2-\rho^2 v^2)} dv\bigg]\notag\\
&=&2\sqrt{1-\rho^{2}}\bigg[\frac{1}{\sqrt{2\pi}\rho}\int_{0}^{+\infty}
\Phi(y) e^{-\frac{y^{2}}{2}(\frac{1-\rho^2}{\rho^2})} dy\bigg]\notag\\
&=&2\sqrt{1-\rho^{2}}\left[\frac{1}{\sqrt{2\pi}\rho}
\left[\frac{\rho}{\sqrt{2\pi(1-\rho^{2})}}\arctan\left(\frac{\rho}
{\sqrt{1-\rho^{2}}}\right)
+\frac{\sqrt{2\pi}\rho}{4\sqrt{1-\rho^{2}}}\right] \right]\notag\\
&=&\frac{1}{\pi}\arctan\left(\frac{\rho}
{\sqrt{1-\rho^{2}}}\right)+\frac{1}{2}\,.
\end{eqnarray}
However, the solution is $\frac{1}{\pi} \arccos (-\rho)$.
Is any step wrong? Thanks for your kindely helps.

A: Your answer is correct. You only need some inverse trigonometric formulas to get there, see https://en.wikipedia.org/wiki/Inverse_trigonometric_functions.
In particular, since $\tan(\arcsin(x)) = \frac{x}{\sqrt{1-x^2}}$,
$$
\frac{1}{\pi} \arctan \left(\frac{\rho}{\sqrt{1-\rho^2}}\right) + \frac{1}{2} = \frac{1}{\pi}\arcsin(\rho)+\frac{1}{2} =\frac{1}{\pi}\left(\arcsin(\rho)+\frac{\pi}{2}\right),
$$
and since $\arcsin(x)=-\arcsin(-x)$ and $\arccos(x)=\pi/2-\arcsin(x)$, we get
$$
\frac{1}{\pi} \arctan \left(\frac{\rho}{\sqrt{1-\rho^2}}\right) + \frac{1}{2} = \frac{1}{\pi}\left(\arcsin(\rho)+\frac{\pi}{2}\right) = \frac{1}{\pi}\left(\frac{\pi}{2}-\arcsin(-\rho)\right) = \frac{1}{\pi} \arccos(-\rho).
$$


text:
Q: How do I create an object with a default value if none is passed in the parameter? I'm trying to create a table that will default to size 500 if no value is passed to the constructor.
Example
Table object; //sets table size to 500 by default
Table object(10000); //sets table size to 10000

This is how I currently have my header set up:
Class Table{
public:
    Table();
    //other functions excluded
private:
    static const int tableSize = 500;
    std::vector<int> A[tableSize];
};

How can I do this?

A: This is likely what you're looking for, assuming you wanted a table and not just a sequence. You code made no mention of the size of each row in that table, so I'm going with what you had:
class Table
{
public:
    Table(size_t n = tableSize) : A(n) {};

    //other functions excluded
private:
    static const size_t tableSize = 500;
    std::vector< std::vector<int> > A;
};

If that size of your row buffers is fixed (say 100 columns), you could use a std::array<> for your row buffers, and thus this instead:
class Table
{
public:
    Table(size_t n = tableSize) : A(n) {};

    //other functions excluded
private:
    static const size_t tableSize = 500;
    std::vector< std::array<int,100> > A;
};

EDIT: Growing Your Hash Table
it appears from comment this is to provide a hash table implementation, and in so doing the need to expand the hash table is required (probably one reason for this in the first place). In that, you can expand the original directly by doing this in conjunction with the first snippet:
void Table::expand()
{
    size_t new_size = 2*A.size() + 1;
    std::vector< std::vector<int>> tmp(new_size);
    for (auto& x : A)
    {
        std::hash<int> hfn;
        for (auto y : x)
            tmp[hfn(y) % new_size].push_back(y);
    }
    std::swap(A,tmp);
}

or something similar. Your hash function would obviously need proper integration as well as potentially taking an optional size factor, etc, but you can hopefully get the idea.

A: You can do it like so:
Class Table{
public:
    Table(int size = 500): A(size) { }
private:
    std::vector<int> A;
};

(note that it's shown this way for brevity.  You could/should separate the interface from its implementation and define Table::Table in a source file, and the initializer list should go with it.)


text:
Q: NPM/Node Error that I cannot resolve I am trying to install my packages for a bot (that work on another vps I own) using npm 5, ubuntu 16.04, and node.js 8. The issue seems to be with sodium/libsodium. Here is the error:

I've tried deleting all the node modules and reinstalling, nothing seems to be working. Any ideas?

A: Install libtool. The log is saying it doesn't find libsodium so it has to build it with libtool which it can't find on your system.
sudo apt-get update
sudo apt-get install libtool

While you add at it, make sure you have automake and autoconf
sudo apt-get update
sudo apt-get install libtool automake autoconf

Then try npm install again. Remove node_modules first to be safe.
Hope this is of help.


text:
Q: How to save object in grails I have grails 2.0.4 app, I have new domain class as below, which contains around 50 properties
class Test{
  int testField1
  int testField2
  int testField2
   .
   .
  int testFieldN
}

And I want to do as follows,
 Display Value         Value to Save in DB

'Excellent'             10
'Good'                  8
'Average'               6
'Poor'                  4
'Pathetic'              2

I have a html form which contains all these properties.
If testField1 value is any of the value of  "Display Value" then the value to be saved will be the corresponding value listed in  "Value to Save in DB"
For example If testField1 value is 'Excellent'  then value to be saved is 10.
This particular mapping applies to around 30 properties in the domain class.
Like this I have different mappings for different properties.
How to achieve this in grails.

A: I suggest to use enums.
class Test{
  enum Scales{
    Excellent(10), Good(8), Average(6), Poor(4), Pathetic(2)
    private final int value
    Scales(int v){ this.value = v}
    int getValue(){ this.value}
  }

  int testField1
  int testField2
  int testField2
   .
   .
  int testFieldN
}

GSP
<g:select name='testField1' from="${Test.Scales}" optionKey="value"/>

But better use enum as a type of property
class Test{
  enum Scales{
    Excellent(10), Good(8), Average(6), Poor(4), Pathetic(2)
    private final int value
    Scales(int v){ this.value = v}
    int getValue(){ this.value}
  }

  Scales testField1
  ....
}

and then
GSP
<g:select name='testField1' from="${Test.Scales}"/>


text:
Q: Acumatica - PrimaryView property doesn't populate on page datasource control I am following instructions to add a Customized page but cannot get any values to populate the PrimaryView property.
I've followed these steps a few times along with Clean/Build project and closing Visual Studio, but nothing is working.  I'm just missing something.
In this order:
1- Created new table in Sql called INMerchandiseGroup with similar makeup as Country table.
2- Defined my graph by creating a PXGraph called MerchandiseGroupMaint.
3- Created axpx page called IN201000 using a ListView control.
4- Bind graph to aspx page by setting datasource TypeName to graph.
5- Generated Data Class through aspx page datasource control, loading new table INMerchandiseGroup, selecting GroupCD and description;  set GroupCD IsKey = true and removed string defaults (""), saved and rebuild
6- Added PXSelect actions (alone and with PXDelete, PXCancel) in graph.
7- !!!Problem!!! I go to Properties for datasource to set PrimaryView and nothing is there to select.
Graph:
public class MerchandiseGroupMaint : PXGraph<MerchandiseGroupMaint>
{
    PXCancel<INMerchGroup> Cancel;
    PXSave<INMerchGroup> Save;

    PXSelect<INMerchGroup> MerchandiseGroups;
}

Dataclass:

[System.SerializableAttribute()]
public class INMerchGroup : PX.Data.IBqlTable
{
    #region GroupCD
    public abstract class groupCD : PX.Data.IBqlField
    {
    }
    protected string _GroupCD;
    [PXDBString(10, IsUnicode = true, IsKey = true)]
    [PXDefault]
    [PXUIField(DisplayName = "Group ID")]
    public virtual string GroupCD
    {
        get
        {
            return this._GroupCD;
        }
        set
        {
            this._GroupCD = value;
        }
    }
    #endregion
    #region Description
    public abstract class description : PX.Data.IBqlField
    {
    }
    protected string _Description;
    [PXDBString(256, IsUnicode = true)]
    [PXDefault]
    [PXUIField(DisplayName = "Description")]
    public virtual string Description
    {
        get
        {
            return this._Description;
        }
        set
        {
            this._Description = value;
        }
    }
    #endregion

I don't get any error messages...if i manually add the PrimaryView to aspx Source code I get an error that view isn't found.
What am I not doing?

A: A new screen can be configured this way,look maybe missed something

To Create a Custom Form Template

A: The problem was so silly, I don't know how i didn't see it.  I was missing the "public" access modifier.
public class MerchandiseGroupMaint : PXGraph<MerchandiseGroupMaint>
{
    public PXCancel<INMerchGroup> Cancel;
    public PXSave<INMerchGroup> Save;
    public PXSelect<INMerchGroup> MerchandiseGroups;
}


text:
Q: Why the devise user instance does not get stubbed? i have a @user instance that i use for logging a devise user. It's a macro as Devise wiki proposes :
module ControllerMacros
  def login_user
    before(:each) do
      @request.env["devise.mapping"] = :user
      @user = Factory(:user)
      sign_in @user
    end
  end
end

Generally, i do different things to stub methods, but i don't understand why this stub does not work : (note that @user is indeed logged in, i use it successfully for testing attributes and stuff)
@user.stub(:has_tavern_quest?).and_return(true)

It seems that the stub works(i checked with @user.has_tavern_quest should true), but i just get back :
 Failure/Error: flash[:error].should == I18n.t('error.has_quest')
   expected: "You already have a quest to finish !"
        got: nil (using ==)

The whole controller method is :
quest_type = params[:quest_type]
@quest_minutes = TavernQuest.get_quest_minutes_from_quest_type(quest_type)

flash[:error] = I18n.t('error.invalid_post') and redirect_to tavern_url and return unless [1,2,3,4].include? quest_type.to_i
flash[:error] = I18n.t('error.has_quest') and redirect_to tavern_url and return if current_user.has_tavern_quest?
flash[:error] = I18n.t('error.no_adv_points') and redirect_to tavern_url and return if current_user.adventure_points < @quest_minutes

current_user.reduce_adventure_points(@quest_minutes.to_i)
TavernQuest.create(:user_id => current_user.id, :start_time => Time.now, :end_time => Time.now + @quest_minutes.minutes,
                             :duration => @quest_minutes, :quest_type => quest_type)

redirect_to tavern_url

end
And the whole spec is :
    it "should redirect to '/tavern' with an error if user already has a tavern quest" do
        @user.stub(:has_tavern_quest?).and_return(true)
        post :create, :quest_type => 3
        flash[:error].should == I18n.t('error.has_quest')
        response.should redirect_to tavern_url
    end

Anybody knows why and what is the way to make it work ?

A: Solved :
  def login_user
    before(:each) do
      @user = Factory(:user)
      controller.stub(:current_user) { @user }
      sign_in @user
    end
  end


text:
Q: I need to know how to update the UI in the bootstrap hamburger menu I am having an issue finding a way to change the hamburger dropdown from slide down to slide right and use the same elements. I've seen samples where they swap out one menu for the other at breakpoints but I want to use just one menu to achieve both. I have the basic code here.

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> Toggle navigation

            </button> Bootstrap theme

Home

About

Contact

 Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

I am looking everywhere for a solution for this. The reason I cannot swap menus is because the menu items will have to be updated regularly and I don't want to have to do it in two spaces.
https://fiddle.jshell.net/qw93eLy6/2/

A: I check it my local Its Working fine please check it, and you should include this head file.
If you have your jquery,css file then include that file

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.min.css">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">Bootstrap theme Toggle navigation

Home

About

Contact

 Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link


text:
Q: How do you organize js files so that you can require from them within one npm package? I have a couple of nodejs files I want to group together in one folder, because they fit together logically.
Say they're called a.js, b.js, c.js
In my app, I have code that imports from these files like:
require('a')
 require('b')
 require('c').
How do I package those files together so that I don't have to change my individual requires? Is there an option in package.json file so that I can make those files exportable on a global scale without relying on the directory that contains those files?

A: You could always create a project (package.json) and include the js files and then manually move it to your corresponding's OS NPM global modules path. For windows this is %AppData%\Roaming\npm\node_modules. After than you can confirm using npm list -g that your package is globally installed

A: You could create packages a, b, c separately. Like this:
|Custom checks' packages
|- package a
|-- package.json
|-- index.js // with the code of your a.js
|- package b
|-- package.json
|-- index.js // with the code of your b.js
|-package c
|-- package.json
|-- index.js // with the code of your c.js

On each package.json, you define its entry file by setting the main property, so it could be:
{
  "name": "a",
  ... some properties
  "main" : "index.js",
  ... some other properties
}

Then within each package folder, you run in your console:
npm install .

Finally in any local project, you can do
require('a')
require('b')
require('c')


text:
Q: Components in Angular are kind Of Directives? As said,

Directives are instructions in the DOM

so as components work as the instructions in DOM too.
So that Means Components are Directives too but with a template
is it right to said so?
i am having difficulty in clearing the difference and comparison of both.
(Preparing for First Angular Job Interview)


text:
Q: webpack resolves CSS/SASS imports in wrong order When using css and sass imports in the same file, the order of the generated css is not correct.
the full example can be seen and reproduced here: https://github.com/p0wl/webpack-jimdo-example/tree/master/sass-order
Given we have the following setup:
@import 'some.sass';

.legacy_bundle {
    content: 'legacy_bundle';
}

@import 'middle.css';
@import 'other.sass';

output:
.middle {
    content: 'middle';
}.some {
  content: 'some'; }

.legacy_bundle {
  content: 'legacy_bundle'; }

.other {
  content: 'other'; }

/*# sourceMappingURL=new_cms_classes.css.map*/

.middle is the first rule, although it is not the first import. .some needs to be the first rule, as it is the first import.
webpack.config.js (extract):
    entry: {
        "new_cms_classes.css": "legacy_bundle.css"
    },
    module: {
        loaders: [
            [
                {
                    test: /\.sass$/,
                    // Passing indentedSyntax query param to node-sass
                    loader: "sass?indentedSyntax"
                },
                {
                    test: /legacy_.+\.css$/,
                    loader: ExtractTextPlugin.extract("style-loader", "css-loader?root=~!sass")
                },
                {
                    test: /\.css$/, loaders: ["style", "css?root=~"]
                }
            ]
        ]
    },

webpack and all loaders are at the latest release.

A: This issue is opened here
Possibly it may be the cause of using CommonChunkPlugin.
In my case, the reason was in using ExtractTextPluginto compress classNames in stylesheets, like this

  if (isProd) {
     config.module.loaders[1].loader = ExtractTextPlugin.extract('style',
                                                                 'css?modules&sourceMap&localIdentName[local]_[hash:base64:10]!sass!css');
  }

Actually, in my case, stylesheets was not mixed, but had other classes, so reset.scss file had main priority. Check out your webpack.config.js file, the place, where you compress styles in prod mode.


text:
Q: How does the Finder refresh in OS X Mountain Lion? I just batch edited some pictures with Preview and changed the name of one file in the Preview window.
Minutes later, Finder still didn't show the changed file sizes (not even when opening the Info dialog) and changed names. Switching from list view to icon view or so didn't fix it.
I restarted Finder and then the names changed.
How come, is there an update or refresh command? Thought it'd be in the View menu but it isn't.

A: A "Refresh" feature can be added to Finder by 3rd-party software like XtraFinder (free).

A: Alt click and select "Get info." This will refresh the folder. I have this problem with ftp folders mounted as a drive via Transmit.

A: The Finder's information should be refreshing automatically and instantly as files and information is changing that is the goal and why Apple does not provide a "Refresh" option, although in practice things sometime don't work for whatever reason.
If the information is not automatically updating changes to files etc, it may be the result of a bug or Finder preferences corruption, or other corruption.

*

*Make sure you are running the latest version of OS X, as the issue may be a bug that has been fixed already.

*Additionally for folders where the contents are not updating properly it might be a good idea to try and remove the .DS_Store file for that directory, and see if that has an effect. (restarting the finder to verify)

*The next option would be to reset the Finder's preferences. Try removing the the file named com.apple.finder.plist located at ~/Library/Preferences/com.apple.finder.plist (restarting the finder to verify)

*If the problem is consistently occurring contact Apple and show them the issue and how to repeat it, you may have found a bug.

A: Just go to the parental directory and into the specific folder again and it refreshes the content. Or use the back and forward button.


text:
Q: Log user actions in PostgreSQL In PostgreSQL 12+ is it possible to have a log with all actions performed by a user/role?
Eg: If that user executes a query, delete, create table, pg_dump, etc, store what he did in a log.

A: You can set parameters per role:
ALTER ROLE user_to_log SET log_min_duration_statements = 0;


text:
Q: Incomplete response received from application - Passenger & NGINX I have successfully installed rails with Passenger+Nginx but am experiencing an Incomplete response error via the web browser:
http://tenklakes.northcentralus.cloudapp.azure.com/
I have tried rake secrets to generate a new secret_key_base for production in my secrets.yml file with no luck.
Secrets.yml :
development:
secret_key_base:c70c590cfe799087c47528016ab49a1a8e57fe2eb851639e27e2ea66f92f241a0400b3d4247e3d61a6c82818dd3988825deeb66e783ba90cfccfbc0c500d6dbd
test:
secret_key_base: 08b1ebf5defee2eb1ad196e9780ae118f256c9f40f40f76674451dac4dfb1c42b75f04d22ee264644711de4e547ac8f58031e88f09c5c7223834b99230fb205c
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

when I run curl http:0.0.0.0:3000 I receive the following from Passenger:
Started GET "/" for 127.0.0.1 at 2016-10-09 04:52:43 +0000
Processing by Rails::WelcomeController#index as */*
  Parameters: {"internal"=>true}
  Rendering /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/templates/rails/welcome/index.html.erb
  Rendered /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/templates/rails/welcome/index.html.erb (2.5ms)
Completed 200 OK in 10ms (Views: 6.2ms | ActiveRecord: 0.0ms)
NGINX error.log :

[ 2016-10-09 04:49:44.8271 45647/7fe3b30d4700 age/Cor/Con/InternalUtils.cpp:112 ]: [Client 1-3] Sending 502 response: application did not send a complete response
  App 45674 stderr: [ 2016-10-09 04:49:56.0108 45754/0x0000000092d678(Worker 1) utils.rb:87 ]: *** Exception RuntimeError in Rack application object (Missing secret_key_base for 'production' environment, set this value in config/secrets.yml) (process 45754, thread 0x0000000092d678(Worker 1)):
  App 45674 stderr:       from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:513:in validate_secret_key_config!'
  App 45674 stderr:       from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:246:inenv_config'
  App 45674 stderr:       from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:693:in build_request'
  App 45674 stderr:       from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:521:inbuild_request'
  App 45674 stderr:       from /home/garrett/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:521:in call'
  App 45674 stderr:       from /usr/lib/ruby/vendor_ruby/phusion_passenger/rack/thread_handler_extension.rb:97:inprocess_request'
  App 45674 stderr:       from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:152:in accept_and_process_next_request'
  App 45674 stderr:       from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler/thread_handler.rb:113:inmain_loop'
  App 45674 stderr:       from /usr/lib/ruby/vendor_ruby/phusion_passenger/request_handler.rb:416:in block (3 levels) in start_threads'
  App 45674 stderr:       from /usr/lib/ruby/vendor_ruby/phusion_passenger/utils.rb:113:inblock in create_thread_and_abort_on_exception'

I am out of ideas to get this working - is there anything else I should be checking?
EDIT: Here is what I get when running 'grep -r ENV *'
garrett@10klakes:~/lakemag$ grep -r ENV *
bin/bundle:ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
config/database.yml:  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
config/database.yml:#     url: <%= ENV['DATABASE_URL'] %>
config/database.yml:  password: <%= ENV['LAKEMAG_DATABASE_PASSWORD'] %>
config/puma.rb:threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
config/puma.rb:port        ENV.fetch("PORT") { 3000 }
config/puma.rb:environment ENV.fetch("RAILS_ENV") { "development" }
config/puma.rb:# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
config/environments/production.rb:  # config.secret_key_base =   ENV["SECRET_KEY_BASE"]
config/environments/production.rb:  config.secret_key_base = ENV["SECRET_KEY_BASE"]
config/environments/production.rb:  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config/environments/production.rb:  if ENV["RAILS_LOG_TO_STDOUT"].present?
config/boot.rb:ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
config/secrets.yml:  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

test/test_helper.rb:ENV['RAILS_ENV'] ||= 'test'

A: For production mode you have to set all ENV (environment) variables named in any ruby or config file. For example within secrets.yml Rails expects an environment variable SECRET_KEY_BASE. You didn't set this variable and now Rails does not start up in production mode.
You are using asure as hosting provider. So you can follow this post
to setup environment variables for azure. In short:

Add a app setting in "App settings" section

You can use rake secret to generate a new key and use it for the environment variable.
One more hint. secrets.yml has its name for a reason. You should not post secrets from this file.

A: After much research the problem was in the hba_config file. md5 permissions needed to be set to "trust" instead.
I am not sure if this solution is a "complete" fix, but it worked in my case.


text:
Q: How to access my bitbucket repository if I rename it I have a git project on bit bucket which I access via:
git@bitbucket.org:amm/witmachine.git

I would like to access as:
git@bitbucket.org:amm/masterwit.git

Do I need to create a new repository?
I have an existing checkout - if I rename the repository how to I make my checkout use the correct project on bitbucket instead of the old one?

A: So you want to change the URL of a remote?
git remote set-url origin git@bitbucket.org:amm/masterwit.git


text:
Q: MYSQL select all expired subscribers I have two database tables:
subscribers: (ID, name, email_address etc)

And
    subscriptions: (subsc_id, user_id, subsc_start, subsc_end)
My question is how can I get a result of all expired members? I wrote an SQL query:
SELECT *
FROM subscriptions
LEFT JOIN subscribers
ON subscriptions.user_id = subscribers.ID
WHERE DATE(subscription.subsc_end) < DATE(NOW())
GROUP BY subscriptions.user_id

The problem is if a subscriber has an active subscription but also has an earlier expired subscription, then that subscriber will be also added to the expired list.
Can anybody help me to write the proper query?
Thank you

A: So you want to find users whose expiry date is in the past AND their start date is before their expiry date - so try this:
SELECT * FROM subscriptions
LEFT JOIN subscribers
ON subscriptions.user_id = subscribers.ID
WHERE DATE(subscriptions.subsc_end) < DATE(NOW())
AND DATE(subscriptions.subsc_start) < DATE(subscriptions.subsc_end)
GROUP BY subscriptions.user_id
HAVING MAX(DATE(subscriptions.subsc_end)) < DATE(NOW())

A: You can probably try using a having clause:
SELECT * FROM subscriptions
  LEFT JOIN subscribers
    ON subscriptions.user_id = subscribers.ID
GROUP BY subscriptions.user_id
  HAVING MAX(DATE(subscriptions.subsc_end)) < DATE(NOW())

A: Why don't you "soft delete" old subscriptions anytime someone renews his?
add a "renewed" field to your second table, and anytime someone renews his subscription, push your timestamp to the renewed field of his old one so that you can exclude it in your queries?

A: Do this with a php script, so you can display all expired users.
$get_exp = mysql_query("SELECT * FROM subscriptions LEFT JOIN subscribers ON subscriptions.user_id = subscribers.ID GROUP BY subscriptions.user_id") or die(mysql_error());;

    while($row=mysql_fetch_assoc($get_exp)){
       $now = time();
       $end_date = strtotime($row['subsc_end']);
       $exp_date = ($end_date - $now);
       $totDays = floor($datediff/(60*60*24));
        if($totDays < 0){
            //display user, he/she expired
        }
     }

A: Probably easiest to do a LEFT OUTER JOIN of non expired subscriptions to subscribers, and check in the WHERE clause that no non expired subscription is found.
Saves any aggregate functions.
SELECT *
FROM subscribers
LEFT JOIN subscriptions
ON subscriptions.user_id = subscribers.ID
AND DATE(subscription.subsc_end) > DATE(NOW())
WHERE subscriptions.subsc_id IS NULL


text:
Q: Unable to use assert function in a class I am trying to use this function
class AClass(cls):
    def add_entry(self):
        year = input('Please enter the movie in which entry was made: ')
        if not isinstance(year, int) or year < 1900 or year > 2021:
            raise ValueError('Please enter a valid year between 1900 and 2021')
        else:
            return year

However when I input any year, for example: 1980 I get the value error. Please suggest how to rectify this.


text:
Q: Function Alignment in C What is the default function alignment for C? I know C has 4 bytes aligment for variables... is it the same for functions or are functions 16 bytes aligned? I cant find any information on that.

A: The C standard does not impose any requirements on the alignment of functions.
C implementations typically align functions as required by the target processor's requirement for instruction alignment. In Intel's IA-32 architecture, instructions have diverse lengths and may start at any address, so functions might not have any alignment requirement (other than byte boundaries). In many architectures, instructions are 32 bits and must start at four-byte boundaries, so C implementations start functions at four-byte boundaries.
An implementation could align the entry point of a function more strictly than the hardware requires because it benefits performance.


text:
Q: Cramer-Rao bound for $\chi^2$ distribution parameter estimates I've struck an unpleasant problem with the noncentral $\chi^2$ distribution.
I work with random variables, distributed as $\chi^2_{\nu}(\lambda)$, where $\nu$ is the degree of freedom and $\lambda$ is non-centrality parameter (which should be somehow estimated).
In "Continuous Multivariate Distributions Vol.2 by S. Kotz, N. Balakrishnan, N. L. Johnson) it is said that the Cramer-Rao bound for variance of unbiased estimators of $\hat{\lambda}$ is (page 453, eq. 29.39b):
 $$CRB_{\hat{\lambda}}=4(\theta\lambda^{-1}-1)^{-1}n^{-1},$$ where $n$- is the sample size, $\lambda$-true value of the noncentrality parameter that is under estimation and $\theta$ is the parameter which has the following upper and lower estimates (page 452, eq. 29.36a):
$$1+\lambda^{-1}-\frac{1}{2}\nu\lambda^{-2}+\frac{1}{4}\nu^2\lambda^{-3}\leq \theta\lambda^{-1}\sigma^{-2}\leq 1+\frac{5}{4}\lambda^{-1}-\frac{20\nu-13}{39}\lambda^{-2},$$ and $\sigma$ is the noise variance.
I tried to analyse the behavior of $CRB_{\hat{\lambda}}$ when $\lambda \to 0$. But the problem is that it goes to zero to!
But in my opinion it is not what we should get. I use an analogy from physics or mathematical statistics . For example this problem arises when one estimates the square of the Euclidean distance between some determined vector and its empirical sample contaminated by additive white Gaussian noise with zero mean and equal variances for all the points of the vector. And the result that I've got ($CRB_{\hat{\lambda}}\to 0$ when $\lambda \to 0$) pushes me to conclude that for a fixed level of noise ($\sigma=\mbox{const}$) it is possible to estimate infinitely close vectors with practically infinite precision (almost with zero variance of estimation).
But that shouldn't be true. It should be the opposite way. So where's the problem?

A: For small $\lambda$, lower bound for $\theta$ is  $1/4 \times\nu^2 \lambda^{-3} \le \theta \lambda^{-1} \sigma^{-2}$
simplifying, $\theta$ varies with $\sigma^2 / \lambda^2$, thus $\theta\lambda^{-1}$ varies with $\sigma^2/\lambda$.
The inverse of $\theta  \lambda^{-1} - 1$ will thus still increase with a lower value for $\lambda$.


text:
Q: vue idb format variable Hello I'm making a web app using vuex and vue idb.
In one of my view I have a table with filter fields.
My data are stored using vue-idb and filter fields call applyFilter methods function using the input text box event and the header name of the column's cell
Here is my html
...some html

               0'>
                <input type='checkbox' @change='updateCheckboxList(-1)' :checked='checkAllCheckbox'>

              -1'>
                <input @keyup="applyFilter(header,$event )" :disabled="thinking" :placeholder='header +" filter"'>

Here is my component
some code ...

applyFilter (header, e) {
      // apply filter after enter key has been pressed
      if (e.keyCode === 13) {
        console.log('Filtering column ' + header + ' with ' + e.target.value)
        // not working unsing dynamical variable, but it does while using static variable like uid
        store.dispatch('tasksSetFilter', {header: e.target.value}) // this doesn't works
        // store.dispatch('tasksSetFilter', {id: e.target.value}) // this works

My issue is that I'm unable to use header variable (a string)  as key of dict passed with tasksSetFilter, but if I replace it by a variable having the same name it works.
Is there a way to transform string to variable name to solve my problem?

A: Try this:
store.dispatch('tasksSetFilter', {[header]: e.target.value})

What this syntax does is set the parameter to an object where the key will be whatever the value of header is. This is a newer syntax that came about with ES2015.
If you could not support ES2015, you could build the parameter this way:
let filter = {}
filter[header] = e.target.value
store.dispatch('tasksSetFilter', filter)


text:
Q: Solving a PDE with constant initial and boundary conditions Consider the PDE:
$$ u_t + (1-2u) u_x =0 \text{, where } x<0 \text{ and } t>0,$$
with initial and boundary data given by
$$u(x,0) = \frac{1}{4} \text{ for } x<0, \text{ and } u(0,t) = 1, \text{ for } t>0.$$
I tried solving it by method of characteristics, but it merely gives a trivial solution, since the initial condition function $u(x,0)$ is simply a constant in this case. Any other suggestions of how to solve this PDE?

A: $$u_t+(1-2u)u_x=0$$
Applying the method of characteristics :
$$\frac{dt}{1}=\frac{dx}{1-2u}=\frac{du}{0}$$
which gives $du=0$ hense the characteristics $(u)$ and $\left(x-(1-2u)t\right)$
Thus the general solution, on implicit form, is :
$$F\left(u\:,\:x-(1-2u)t\right)=0$$
The function $F(X,Y)$ with $X=u$ and $Y=x-(1-2u)t$ is not a solution of the PDE. The solutions of the PDE are the functions $u(x,t)$ which are solutions of the equation $F\left(u\:,\:x-(1-2u)t\right)=0$
Verification, any derivable function $F(X,Y)$:

In addition : Look at the Boundary conditions :
$$
$$\begin{cases}
    u(x,0)=\frac{1}{4}       & \quad \text{for } x<0 \\
    u(0,t)=1  & \quad \text{for } t>0 \\
  \end{cases}
The implicit equation $F\left(u\:,\:x-(1-2u)t \right)=0$ can be transformed to :
$$u=f\left(x-(1-2u)t \right)$$
where $f$ is a function to be determined according to the boundary conditions.
$$  \begin{cases}
    u(x,0)=\frac{1}{4}=f\left(x-(1-2u(x,0))0 \right)=f(x) & \quad  x<0\\
    u(0,t)=1=f\left(0-(1-2*1)t \right)=f(t)  & \quad \text t>0 \\
  \end{cases}
$$
So, the function $f$ is defined by
\begin{cases}
    f(\chi)=\frac{1}{4}       & \quad \text{for } \chi<0 \\
    f(\chi)=1  & \quad \text{for } \chi>0 \\
  \end{cases}
Hense
$$f(\chi)=\frac{1}{4}+\frac{3}{4}H(\chi)$$
where $H(\chi)$ is the Heaviside step function.
Finally, the solution expressed on implicit form is :
$$u=\frac{1}{4}+\frac{3}{4}H\left(x-(1-2u)t \right)$$


text:
Q: Mongo Aggregation filter on collection 2 fields Hi I am working with mongoDb I have two collections as below:
Owners

*

*name

*address

*familySize

*petId

[
  {
    "name": "Johnsons",
    "address": "Lambert Street",
    "familySize": 4,
    "petId": "p153ATjs54"
  },
    {
    "name": "Markinsons",
    "address": "Pebble Street",
    "familySize": 2,
    "petId": "G34hts94"
  }
]

Pets

*

*animal_Id  // the foreign key if you may for petId

*petName

*preferredPlayToy

*vaccinationInfo

[
  {
    "animal_Id": "G34hts94",
    "petName": "Oscar",
    "preferredPlayToy": "Ball",
    "vaccinationInfo": {
      "vacId": "a-984KA",
      "dosage": 3
    }
  },
  {
    "animal_Id": "p153ATjs54",
    "petName": "Piggy",
    "preferredPlayToy": "Bone",
    "vaccinationInfo": {
      "vacId": "G-397B",
      "dosage": 1
    }
  }
]

Now I am actually trying to find all Owners who have pet that have preferredPlayToy as "ball"
Below is what I have in the pipeline but I can't seem to get it right:
db.owners.aggregate([
    {
        $lookup: {
            from: 'ms_pets',
            localField: 'petId',
            foreignField: 'aniId',
            as: 'petMaster'
        }
    },
    {
        name: 1,
                    address: 1
        'petMasterData': {
            $filter:{
                input: "$petMaster",
                as: "master",
                cond: { $eq: [ "$$master.preferredPlayToy", 'ball' ] }
            }
        }
    }
])

It'll also be great if I can pull out the pet name and vaccinationInfo from the Pets table as part of the response.

Sample Expected:
{
    "name": "Markinsons",
    "address": "Pebble Street",
    "petId": "G34hts94",
    "petMasterData":{

        "petName": "Oscar",
        "vaccinationInfo": {
            "vacId": "a-984KA",
            "dosage": 3
        }
    }

}

A: You can run $lookup with custom pipeline to apply both filtering conditions and projection. To convert an array into single subdocument you can use $unwind which will also remove owners with empty petMasterData
db.owners.aggregate([
    {
        $lookup: {
            from: "ms_pets",
            let: { pet_Id: "$petId" },
            pipeline: [
                { $match: {
                    $expr: {
                        $and: [
                            { $eq: [ "$$pet_Id", "$animal_Id" ] },
                            { $eq: [ "$preferredPlayToy", "Ball" ] } ]
                        }
                    }
                },
                { $project: { petName: 1, vaccinationInfo: 1, _id: 0 } }
            ],
            as: "petMasterData"
        }
    },
    { $unwind: "$petMasterData" }
])


text:
Q: Combination with partial constraint We have a group of 15 people and want to find out how many possibilities there are to choose a subgroup of 5 people. This is pretty easy, we can just calculate $15 \choose 5$.
But now suppose we have a constraint where two people don't want to be in the subgroup together. My first guess would have been to calculate how many possibilities there are that these two are in the same subgroup (which would be $15 \choose 3$, right?) and then subtract that, so my solution to this problem would look like this:
${15 \choose 5} - {15 \choose 3} = 3003 - 455 = 2548$
Is this the correct way to approach this problem? If now, what would be the right answer?

A: There are three possible types of subgroups:
a) None of the two persons are in the subgroup
b) Only the first one is in the subgroup
c) Only the second one is in the subgroup
For a) is the same to choose $5$ people out of $13$, i.e. ${13}\choose{5}$
For b) is the same to choose $4$ people out of $13$ (because you have already one and you don't want the other), i.e. ${13}\choose {4}$
For c) is the same as b)
Thus the solution is ${13}\choose {5}$ +$2 $${13}\choose{4}$ $=1287+2 \cdot 715=1287+1430=2717$


text:
Q: Is the following relation $R$ reflexive, symmetric, antisymmetric, and/or transitive? I am currently studying for an exam and one of the problems I am working on is asking me about relations.
Consider the set of all students at a school. We define a relation $R$ on this set.
Statement: $(a,b)\in R$ if students $a$ and $b$ take exactly the same set of classes in the semester.
I need to state whether $R$ is or is not reflexive, symmetric, antisymmetric, and/or transitive.
Initially, I ruled out that $R$ is not antisymmetric. After some time working through it, I am thinking that $R$ is reflexive, symmetric, and transitive. Since the students are taking the same set of classes, it is clear that $R$ would be symmetric and reflexive. However, I am unsure if transitivity can be applied to $R$. Am I on the right track? If not, can someone explain why my initial answer is incorrect?


text:
Q: Finding the right SE site for a problem I am not sure how to make a suggestion. I will position the problem and then a solution/idea. Even if my idea would be adopted there may still be a problem, but I am just trying to close the gap.
Problem:
As a new user it is not obvious how to use SE. As an intermediate user it is not obvious which site to use in each situation, and also probably the same for even an advanced user, somewhat of an impossible problem to solve. Sure photography/physics/math to name a few are easy to find which site to use.
My issue was in Office 365 & OneDrive, there is no 365/MS/OneDrive SE.
So I came to this link.
https://stackexchange.com/sites#
and found all sites, and this did not offer me any help for my Office 365 OneDrive issue.
Ideas:

*

*When hovering over a site load a word cloud of the site tags inside the site (bubble).

*Make the tags searchable, filterable, to help find the site which uses that word the most.

This way the punters can find a good site, easier, when trying to be diligent SE users.
However I just searched for these tags:

*

*"office365" SO=7k tags used, and SU=1k

*"onedrive" SO=2.5k, SU=750

This would suggest SO would be my best place to ask my question, however I got told to take my question to SU.
So maybe my theory is wrong, maybe SO is naturally higher because of the larger usergroup?
My question: Was this the right content to post here?

A:
when hovering over a site load a word cloud of the site tags inside the site (bubble).

Would this really help more than searching for tags? Just some numbers I got from looking at the tags pages on three sites: SO has ~64.3k tags, SU has ~6.4k tags, even a 'small' site like Interpersonal Skills has almost 300 tags. There's no way you can show all of those in a bubble of tags, and still clearly convey what a site is about.
For example, Stack Overflow has a java tag. But questions about Java would be off-topic. A tag alone does not convey the topic of a site.

Make the tags searchable, filterable, to help find the site which uses that word the most.

I also don't think this would help. After all, you manually did the same and still picked the 'wrong' site. I wrote a bit about thist before: The number of questions in a tag doesn't say much about the site's suitability for your question, without taking into account the size of site it's on, and without taking into account the actual topic of the site.
SO may indeed have more questions in a tag just because there are more questions on SO in general. That doesn't mean everything that could be tagged with such a tag would automatically be on-topic on SO.
While word clouds with relation to a site are a nice idea (they can give more information about a site's topic than  "Q&A for professional and enthusiast programmers" or "Q&A for computer enthusiasts and power users" does), they should be based on more than just the tags used on a site.

A: One way of implementing this in accordance with what you are asking, (but without making a lot of modifications), is to add a new Search Bar to the Stack Exchange main All Sites - Grid View:

That webpage normally displays different sized site logos based on the site's size.
It wouldn't be too difficult to resize the logos based on the number of search hits returned; giving an indication of the site's popularity for a given search.
You could tap/mouseover on one of the sites to see what sort of results were being returned, and possibly tweak the terms used, to narrow down the search and redisplay the icon cloud:


text:
Q: Select item from typeahead with enter Good day, I'm trying to add an event to my typeahead. Please check my script first
JavaScript
$("#itemid").typeahead({
source: function(query, process) {
     $.ajax({
         async:true,
         url: '<?=base_url();?>do_mutasi/ItemList/'+$("#tipenya").val()+'/'+ $("#itemid").val().replace(/ /g,"_"),
         dataType: 'JSON',
         success: function(data) {
                  process(data);
                }
        });
    },
  minLength: 3
});

PHP
public function ItemList($tipe="",$itemid=""){
            extract(populateform());
            $newitemid = str_replace("' '",'_',$itemid);
            $hasil = $this->modelmodel->showdata("SELECT ItemCode,ItemName from Item
                                                where status = 1
                                                and (ItemCode like '%".$itemid."%' or ItemName like '%".$newitemid."%') and ItemType like '%".$tipe."%'
                                                ");
            $data = array();
            foreach ($hasil as $hsl)
                {
                    $data[] = $hsl->ItemCode .' [ '. $hsl->ItemName . ' ] ' ;
                }
            echo json_encode($data);
        }

and my HTML

                    Tipe

                    <select required size="1" class="form-control" id="tipenya">
                        <?php
                        if(isset($tipeitem->ItemType)){
                            if(rtrim(ltrim($tipeitem->ItemType)) == "MERCHANDISE"){
                                echo " <option value='MERCHANDISE'>MERCHANDISE</option>";
                            }else if(rtrim(ltrim($tipeitem->ItemType)) == "GENERAL"){
                                echo " <option  value='GENERAL'>GENERAL</option>";
                            }
                            else{
                            echo    "<option  value='MERCHANDISE'>MERCHANDISE</option>
                                    <option value='GENERAL'>GENERAL</option>";
                            }
                        }
                            else{
                            echo    "<option  value='MERCHANDISE'>MERCHANDISE</option>
                                    <option value='GENERAL'>GENERAL</option>";
                            }
                        ?>
                    </select>

                          Kode Item

                              <input required type="search" autocomplete="off" name="dest" id="itemid" class="form-control" placeholder="Search..." data-provide="typeahead" />

Data example from php result from my browser console.
["F160048 [ FLT SHOES L27506 BLUE ] ","F160049 [ FLT SHOES L27506 GREEN ] ","F160050 [ FLT SHOES L27506
 ORANGE ] "]

There isn't any problem with my script above. I just want to adding enter event. How can i achieve that ? Sorry for my bad english
I found the problem my problem is because my Js below. Which is the function from my script below for change textfield if i press enter
$('body').on('keydown', 'input, select, textarea', function(e) {
var self = $(this)
  , form = self.parents('form:eq(0)')
  , focusable
  , next
  ;
if (e.keyCode == 13) {
    focusable = form.find('input,a,select,button,textarea').filter(':visible');
        next = focusable.eq(focusable.index(this)+1);
        if (next.length) {
            next.focus();
        } else {
            form.submit();
        }
        return false;
    }
});

can i fix that , without delete my last js


text:
Q: Respuesta a una llamada http angularjs Cuando ejecuto esta función:
 $scope.Login = function (callback) {
            var httpreq = {
                method: 'POST',
                url: 'Inicio.aspx/Iniciar',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    'dataType': 'json'
                },
                data: { usuario: $scope.usuario, password: $scope.password }
            }
            $http(httpreq).success(function (data) {

            })
        };

La función iniciar devuelve un tipo bolean, el cual quiero recuperar en la parte de success para evaluar su valor pero el código no siempre accede a dicha parte.

A: Si analizamos la documentacion
$http angularjs
capturar el success utiliza el then para tomar la promise
$http(httpreq).then(function(response){
   //aqui codigo sucess
   console.log(response.status);
}, function(response){
  //aqui codigo error
  console.log(response.status);
});


text:
Q: Pass Parameters from Grape::API to Serializer I am getting a parameter e.g: member_id in Grape::API like
   desc 'Return Events'
         params do
             requires :member_id, type: Integer, desc: 'Member'
         end
         get 'all' do
              #some code
         end
     end

and I want to pass it to ActiveModel::Serializer so that I can perform some functionality.
Is there any way that I can pass it to ActiveModel::Serializer?

A: When you serialize an object using ActiveModel::Serializers, you can pass along options which are available inside the serializer as options (or instance_options, or context, depending on which version of AMS you're using).
For instance, in Rails you would pass a foo option like so:
# 0.8.x or 0.10.x
render @my_model, foo: true
MyModelSerializer.new(@my_model, foo: true).as_json

# 0.9.x
render @my_model, context: { foo: true }
MyModelSerializer.new(@my_model, context: { foo: true }).as_json

In your serializer you access options (or instance_options) to get the value:
class MyModelSerializer < ActiveModel::Serializer
  attributes :my_attribute

  def my_attribute
    # 0.8.x: options
    # 0.9.x: context
    # 0.10.x: instance_options
    if options[:foo] == true
      "foo was set"
    end
  end
def