text:
Q: page transition for app using jquery mobile and phonegap I'm building an app in html/css/javascript and using phonegap to build.
So, I first wanted to have to simple page to page navigation. I tryed this:
index:
<!DOCTYPE HTML>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.css" />

        click me

test.html:
<!DOCTYPE HTML>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.css" />

        New page!

Result: when I click on the button the test.html page loads very slow and the data-transition="slide" seems to be ignored.
I found an article about dynamic page loading: https://www.ibm.com/developerworks/mydeveloperworks/blogs/94e7fded-7162-445e-8ceb-97a2140866a9/entry/dynamic_page_loading_for_phonegap1?lang=en
Which I really don't get. Aren't the HTML files stored locally? So why do a XMLHtppRequest?
My question is: How do I get a good page transition (fast and with effects)?

A: You should remove rel="external" from your  link.
The attribute rel="external" disables the Ajax navigation, skipping the transition effect, and refreshes your page test.html.
Try your code after removing it.
index.html:
<!DOCTYPE HTML>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.css" />

        click me

test.html:
<!DOCTYPE HTML>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="jquery.mobile-1.2.0/jquery.mobile-1.2.0.min.css" />

        New page!

Let me know about your results.

A: Try this solution by Piotr Walczyszyn. Highly recommended for anyone using Jquery mobile and Phonegap together.


text:
Q: Conversion of a currency string in the format "0.0 GBP 0" I'm pulling data from an API and I'm trying to see if there is a decent way of pulling apart the string that's being returned.
Ideally I want to put this into a database as a decimal value.
UPDATE:
I'm interested in the 0.0 and I'd wondered if there was a decimal.parse that could strip it down like I could do with the date/time as noted below:
DateTime updated;
if (DateTime.TryParseExact("Wed Jun 05 08:06:17 UTC 2013",Config.dateTimeFormat,CultureInfo.InvariantCulture,DateTimeStyles.None,out updated))
{
// Yeah!!
}

However what has been noted below is that the trim and strip will do the job. What I'm really after is a high performance solution to the problem as it's part of a delta sync routine.

A: So you just want to parse the first part in the string which represents the numeric value? Then you could use String.Split and take the first:
string text = "0.0 GBP 0";
string value = text.Trim().Split()[0]; // 0.0
decimal pounds = decimal.Parse(value, CultureInfo.InvariantCulture);

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS UIView touchesBegan not getting called I have some UIViews:
Top UIView: MatrixViewController
---- Sub1 UIView
---- Sub2 UIView
---- Subx UIView

In each Sub views I have set self.userInteractionEnabled=YES.
Each Sub UIView do get it's touchesBegan called...
But, when touching beside of any of the Sub views the TopParent's touchesBegan is not getting called?
AppDelegate:
...
self.matrixViewController = [[MatrixViewController alloc] init];
self.window.rootViewController = self.matrixViewController;
[self.window makeKeyAndVisible];
return YES;

The TopParent UIView is created in ViewController / viewDidLoad:
CGRect rect = [[UIScreen mainScreen] applicationFrame];
MatrixViewController matrix = [[MatrixViewController alloc] initWithFrame:rect];
[self setView:matrix];

Thanks


text:
Q: how to use xcrun simctl io to pipe and record an iOS audio stream My iOS app writes a stereo audio stream into a circular buffer at 44.1KHz and outputs successfully to either simulator or iOS device. I want to capture the audio stream while the app is running in Xcode and do it without altering the code or converting the stream to an analogue signal.
Initially I tried using SoundFlower with Audacity and Quicktime. Both work with audio from the internal microphone but unfortunately capture ambient noise and with Soundflower(2ch) input selected no signal activity appears in the monitor on either Audacity or Quicktime.
I am now trying to create an ogg file by capturing a digital audio stream using terminal e.g. copying the stream and piping the copy into a file, a bit like this Linux solution
       arecord -f cd -t raw | oggenc – -r -o out.ogg

The following Unix command line fails to capture audio when it records video according to this Radar community bug report submitted Feb 2018.
       xcrun simctl io booted recordVideo my video.mp4

I have set up command line tools so audio data sent from Xcode to the simulator can be captured. This answer (from 2015) says it is not possible to intercept a background audio stream from another app. But does anyone know a way to pipe an audio stream into a file using xcrun simctl io ?


text:
Q: how to upload video with variable to server? i can get my video to upload to my server fine but when i want to upload it with a variable to use in the PHP then it wont work. I am i doing something wrong? What can i do to upload a variable and then a video so i can name the video what ever is in the variable!
Android code:
try{
    FileInputStream fileInputStream = new FileInputStream(sourceFile);
    URL url = new URL(UploadVideo_URL);
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");

    OutputStream OS = conn.getOutputStream();
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));

    String data = URLEncoder.encode("ProductAccountName", "UTF-8") + "=" + URLEncoder.encode(ProductOwnerEmail, "UTF-8") + "&" +
            URLEncoder.encode("ProductName", "UTF-8") + "=" + URLEncoder.encode(ProductName, "UTF-8");

    bufferedWriter.write(data);
    bufferedWriter.flush();
    bufferedWriter.close();
    OS.close();

    InputStream IS = conn.getInputStream();
    IS.close();

    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("ENCTYPE", "multipart/form-data");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    conn.setRequestProperty("myFile", selectedPath);
    dos = new DataOutputStream(conn.getOutputStream());

    dos.writeBytes(twoHyphens + boundary + lineEnd);
    dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + selectedPath + "\"" + lineEnd);
    dos.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    Log.i("Huzza", "Initial .available : " + bytesAvailable);

    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    dos.writeBytes(lineEnd);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    serverResponseCode = conn.getResponseCode();

    fileInputStream.close();
    dos.flush();
    dos.close();

} catch (Exception e) {
    e.printStackTrace();
    return "Product upload failed";
}

PHP code:
<?php

$ProductOwnerEmail = $_POST['ProductOwnerEmail'];
$Productname= $_POST['Productname'];

if($_SERVER['REQUEST_METHOD']=='POST'){
    $file_name = $_FILES['myFile']['name'];
    $file_size = $_FILES['myFile']['size'];
    $file_type = $_FILES['myFile']['type'];
    $temp_name = $_FILES['myFile']['tmp_name'];

    $location = "/var/www/html/ProductVideos/$ProductOwnerEmail/" . $Productname;//$NewDirectory . '/' . $file_name;

    move_uploaded_file($temp_name, $location);
}
?>

error log:
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:   java.io.IOException: closed
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:     at com.android.okhttp.okio.RealBufferedSink$1.write(RealBufferedSink.java:196)
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:     at java.io.OutputStream.write(OutputStream.java:82)
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:     at java.io.DataOutputStream.writeBytes(DataOutputStream.java:156)
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:     at com.wilsapp.wilsapp.SellerHomePage$ProductUpload.doInBackground(SellerHomePage.java:910)
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:     at com.wilsapp.wilsapp.SellerHomePage$ProductUpload.doInBackground(SellerHomePage.java:740)
03-23 21:34:10.531 15083-15491/com.wilsapp.wilsapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
03-23 21:34:10.532 15083-15491/com.wilsapp.wilsapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-23 21:34:10.532 15083-15491/com.wilsapp.wilsapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
03-23 21:34:10.532 15083-15491/com.wilsapp.wilsapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-23 21:34:10.532 15083-15491/com.wilsapp.wilsapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-23 21:34:10.532 15083-15491/com.wilsapp.wilsapp W/System.err:     at java.lang.Thread.run(Thread.java:818)
03-23 21:34:10.575 776-1345/? W/InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@80a63f attribute=null, token = android.os.BinderProxy@5bc159

Thank you!


text:
Q: One or more points were written more frequently than the maximum sampling period configured for the metric Background
I have a website deployed in multiple machines. I want to create a Google Custom Metric that specifies the throughput of it - how many calls were served.
The idea was to create a custom metric that collects information about served requests and 1 time per minute to update the information into a custom metric. So, for each machine, this code can happen a maximum of 1-time per minute. But this process is happening on each machine on my cluster.
Running the code locally is working perfectly.
The problem

I'm getting this error: Grpc.Core.RpcException:
  Status(StatusCode=InvalidArgument, Detail="One or more TimeSeries
  could not be written: One or more points were written more frequently
  than the maximum sampling period configured for the metric.  {Metric:
  custom.googleapis.com/web/2xx, Timestamps: {Youngest Existing:
  '2019/09/28-23:58:59.000', New: '2019/09/28-23:59:02.000'}}:
  timeSeries[0]; One or more points were written more frequently than
  the maximum sampling period configured for the metric. {Metric:
  custom.googleapis.com/web/4xx, Timestamps: {Youngest Existing:
  '2019/09/28-23:58:59.000', New: '2019/09/28-23:59:02.000'}}:
  timeSeries1")

Then, I was reading in the custom metric limitations that:
Rate at which data can be written to a single time series = one point per minute

I was thinking that Google Cloud Custom Metric will handle the concurrencies issues for me.
According to their limitations, the only option for me to implement realtime monitoring is to put another application that will collect information from all machines and will update it into a custom metric. It sounds to me like too much work for a real use case.
What I'm missing?

A: Now that you add the machine name on the metric and you get the machines metrics.
To SUM these metrics go to Stackdriver > Metric Explorer, and group your metrics  by project-id or label for example, and then SUM the metrics.
https://cloud.google.com/monitoring/charts/metrics-selector#alignment
You can save the chart in a custom dashboard.


text:
Q: What is the relation between Frey's Curve and Fermat's Last Theorem? Can anyone give an overview showing how the elliptic curve $E (a, b) := y^2=x(x-a)(x-b)$ is associated with the solution of $a^n+b^n=c^n$?
In 1969 Hellegouarch performed the elliptic curves $E (a, b)$, which were later named after Gerhard Frey and were constructed from the solutions of the Fermat equation, he reported on the curves in an article in Acta Arithmetica. I have found the article but it is not in English.
I was looking for a document (lecture note, book, blog) that elaborately explains how the elliptic curve $E (a, b) := y^2=x(x-a)(x-b)$ is associated with the solution of $a^n+b^n=c^n$ and asked it on mathoveflow, I got some documents but I could not understand the whole thing. So, I am asking for help of this forum.
What I got so far:
Let $y^2=x^3+ax^2+bx+c$, $\Delta=(ab)^2+4a^3c-4b^3+18abc-27c^3.$
If $c=0$, then $y^2=x^3+ax^2+bx$, $\Delta=(ab)^2-4b^3.$
Now the Frey's curve is , $y^2=x(x-A)(x+B)=(x^2-Ax)(x+B)=x^3-Ax^2+Bx^2-ABx.$
Let, $a=(B-A), b=-AB,$ then $\Delta= \{(B-A)(-AB)\}^2-4(-AB)^3= \{(B-A)^2-4(-AB)\}(-AB)^2=(A^2+B^2-2AB+4Ab)(AB)^2=(A+B)^2(AB)^2.$
Now, let, $A=a^q, B=b^q,$ then, $\Delta=(a^q+b^q)^2(ab)^{2q},$ if $a^q+b^q=c^q$ for $q>2$ (this is Fermat's last theorem) then $\Delta=(c^q)^2(ab)^{2q}=(abc)^{2q}.$
Now whats wrong with   $\Delta=(abc)^{2q} ?$


text:
Q: Clarify why review badge progress doesn't appear to add up I was able to complete some "First Answers" reviews today. After completing three, I took a look to see my progress. It shows as follows:

The page says that I've reviewed 4 review tasks, but the badge progress for Steward somehow says 7. Per Proposal for awarding credit towards First Questions/Answers badges based on First Posts activity, this is because there are three questions being carried over from the former "First Posts" queue, and hovering over the "?" icon confirms this. But this view isn't clear at immediate glance.
Can we please have additional information put into the verbiage of the review queues to better spell out why these numbers do not match up, that isn't hidden behind a hover tooltip?

A: I don't think this is really worth adding more text on this page for.
It's something that you only need to discover once, and the icon seems pretty clear that it's what you should mouse over for questions about the numbers (that is, if, as you say, it "isn't clear at immediate glance").  Once you do that, it has served its purpose, and it just exists if you need to check the number again.  Adding always-visible text would largely add noise to the page, as well as complicate the layout.

A: The verbiage is already provided if you hover over the badge progress bar or click on the question mark icon. We aren't going to be adding further customizations to this. If there are concrete suggestions on how to make the text of either of these elements more clear, we can consider this. But we are not going to be adding any new explanatory elements to the page.


text:
Q: NTFS inherited permissions... from where? I have a folder with special permissions for an user inherited from the "primary object", but the primary object isn't the normal hierarchical folder. How can I know which is the primary object for these permissions?
Example:
\Folder A (no special permissions for user Test)
    \Folder B (inherited special permissions for user Test)

So, inherited from where?
Thanks very much!

A: If you right click on Folder B and select the Security tab, then the Advanced button the Permissions tab displays a grid of permissions with an Inherited From column that should have the answer to your question.


text:
Q: Calling Google IAM generateAccessToken API always returns error I'm facing the issue where I am not able to generate an Access Token for Google IAM Service Account using this method .
I've got my personal OAuth2 access token using:
gcloud auth application-default print-access-token
I've got all the necessary roles (roles/iam.serviceAccountTokenCreator) but when I cURL the API I always get an error response:
{
  "error": {
    "code": 400,
    "message": "Request contains an invalid argument.",
    "status": "INVALID_ARGUMENT"
  }
}

This is how full curl request looks like:
curl -X POST --header 'Content-Type: application/json' --header 'authorization: Bearer ya29.AASDSADASDASDi9C1yAXXXXXXZzLtDDrCAzblqF_qi5sKvMZcHieBADASDASDTNJiOKrqJBffb4Moh3gTgiTbDgMIF1XDQU5JZ31aACs0aUbI4wgeqV2Q' https://iamcredentials.googleapis.com/v1/projects/<PROJECT_NAME>/serviceAccounts/<SA_NAME>@<PROJECT_NAME>.iam.gserviceaccount.com:generateAccessToken -d '{"scope": ["https://www.googleapis.com/auth/cloud-platform"]}'

Thanks

A: You have two problems in your API call.

*

*The Service Account Name is a path parameter and must be URL encoded. The @ character is not valid. Use %40 in its place (as an example of correct encoding).

*The URI specifies a PROJECT_NAME. This is not correct. You need to use a - (hyphen/dash character). Example projects/-/serviceAccounts.

You also need to have the permission iam.serviceAccounts.getAccessToken attached to one of the roles that are assigned to the account that created the request Access Token use in this API request. This will cause a different error if incorrect. Just a tip as you get to the next step.


text:
Q: Couple css bugs when trying to have a Navbar and Sidebar in same layout file (React.js) In my React.js project, I'm trying to implement a common layout file for my components.
Here is that file:
import React from "react";

import SideBar from "./SideBar/SideBar";
import Navbar from "./Navbar/Navbar";

import { useSidebarStore } from "/zustand";

import classes from "./CustomUserLayout.module.css";

const CustomUserLayout = ({ children }) => {
  const sideBarState = useSidebarStore((state) => state.sideBar);
  const toggleSideBar = useSidebarStore((state) => state.toggleSideBar);

  return (

      <SideBar isOpen={!sideBarState} hideSideBar={toggleSideBar} />

        <Navbar isSidebarOpen={sideBarState} toggleSideBar={toggleSideBar} />
        <div className={`${sideBarState ? "container" : ""}`}>

{children}

  );
};

export default CustomUserLayout;

And here is its CSS file:
.container {
  display: flex;
}

.mainWrapper {
  flex: 5;
}

.wrapper {
  background-color: #fff;
  padding-top: 80px;
  padding-bottom: 40px;
}

My Sidebar layout:
const Sidebar = ({isSidebarOpen,toggleSidebar}) => {
   return (

           // contains logout div

   );
}

export default Sidebar

Important part of my sidebar css:
.container {
  flex: 1;
  background-color: #fff;
  box-shadow: 0px 0px 4px 2px rgba(0, 0, 0, 0.1);
}

Here is the reult:

However I'm getting a couple of bugs:
The first is as i'm trying to scroll down my sidebar overflows, I tried solving this by adding position: sticky; top: 0; overflow-y:hidden; to the sidebar container class but that didn't work. Basically what I'm trying to achieve is have that sidebar completely still kind of like as if it had a position sticky however I don't want to use position sticky.
My 2nd problem is the content on the right side of my navbar its overflowing:
My header component:
import Image from "next/image";

const Navbar = ({ isSidebarOpen, toggleSideBar }) => {
   return(

        <div className={`container ${classes.wrapper}`}>

              <Image src={"some-img-src"} alt="alt" layout="fill" />

   );
}

export const Navbar;

Navbar css:
.container {
  position: fixed;
  z-index: 200;
  width: 100%;
  height: 80px;
  background: #ffffff;
  box-shadow: 0px 0px 4px 2px rgba(0, 0, 0, 0.1);
}

.wrapper {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.profile{
  position: relative;
  cursor: pointer;
  width: 23px;
  height: 28px;
}

I believe the problem is cause because I have the position of the nabvar container as fixed and I'm giving it a width of 100%, however I don't know how to fix it


text:
Q: Displaying customised Item in ItemsControl I have created a (slightly) extended Checkbox that has an IsError property (basically used to change the colour of the checkbox to red when some condition is not met) as follows:
public class MyCheckBox : CheckBox
{
    public static readonly DependencyProperty IsErrorProperty = DependencyProperty.Register("IsError", typeof(bool), typeof(MyCheckBox), new UIPropertyMetadata(false));

    public MyCheckBox() : base()
    {
        IsError = false;
        IsCorrect = false;
    }

    public bool IsError
    {
        get { return (bool)GetValue(IsErrorProperty); }
        set { SetValue(IsErrorProperty, value); }
    }
}

This control is associated with the following style:
<Style TargetType="{x:Type local:MyCheckBox}">
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="Margin" Value="0,2,8,2"/>
    <Setter Property="BorderBrush" Value="Yellow"/>
    <Setter Property="BorderThickness" Value="2"/>
    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="LightGray"/>
            <Setter Property="BorderThickness" Value="0"/>
        </Trigger>
        <Trigger Property="IsError" Value="True">
            <Setter Property="BorderBrush" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

All is well, if I create one of these checkboxes the it responds to the IsError binding correctly.
The issue I'm having is when placing these inside an ItemsControl.  If I create a very basic items control and set the values manually then it works - the list of items is displayed and the IsError and IsChecked properties act as expected.
<ItemsControl Grid.Column="3" Grid.Row="8" HorizontalAlignment="Left" VerticalAlignment="Top" BorderThickness="0">
    <local:MyCheckBox Content="Item1"/>
    <local:MyCheckBox Content="Item2" IsChecked="True"/>
    <local:MyCheckBox Content="Item3" IsError="True"/>
    <local:MyCheckBox Content="Item4" IsChecked="True" IsError="True"/>
</ItemsControl>

If, however I use binding for the list of items then the Content and IsChecked properties work as expected, but the IsError property is completely ignored, I cannot get the border to change to red.
<ItemsControl Grid.Column="3" Grid.Row="8" HorizontalAlignment="Left" VerticalAlignment="Top" BorderThickness="0">
              ItemsSource="{Binding MyThings}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:MyCheckBox Content="{Binding Path=ColorName}" IsChecked="{Binding Path=IsPresent}" IsError="{Binding Path=IsError}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

I know that the IsError binding value is correct (I tested by including a Label bound to the same value which displayed the correct True/False information) but I cannot work out how to get the customised Checkbox to display properly; it's as if the displayed item is using a standard Checkbox instead of the customised version.
For reference, the list of items the control is bound to is as follows:
public class Thing : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    #endregion

    private string colorName;
    public string ColorName
    {
        get { return colorName; }
        set { colorName = value; RaisePropertyChanged("ColorName"); }
    }

    private bool isPresent;
    public bool IsPresent
    {
        get { return isPresent; }
        set { isPresent = value; RaisePropertyChanged("IsPresent"); }
    }

    private bool isError;
    public bool IsError
    {
        get { return isError; }
        set { isError = value; RaisePropertyChanged("IsError"); }
    }

    public CastorClip(string colorName)
    {
        ColorName = colorName;
        IsPresent = false;
        IsError = false;
    }
}

private ObservableCollection<Thing> myThings = new ObservableCollection<Thing>();
public ObservableCollection<Thing> MyThings
{
    get { return myThings; }
    set { myThings = value; RaisePropertyChanged("MyThings"); }
}

What am I missing?  How can I make this work?

A: It turns out it was a problem in the constructor of the custom checkbox where the IsError property was being set overwriting the binding expression. I'll let the other possibilities here also so that other people that did get into these common traps of WPF can check them right away.
The property IsError is not bound two way by default, change the:
new UIPropertyMetadata(false)

to:
new FrameworkPropertyMetadata {
    BindsTwoWayByDefault = true,
    DefaultValue = false
}

Also, add this to the static constructor of your checkbox so that it will seek a default style specific to your checkbox:
static MyCheckBox ()
{
    DefaultStyleKeyProperty.OverrideMetadata (typeof (MyCheckBox), new FrameworkPropertyMetadata (typeof (MyCheckBox)));
}

Be sure to check how the resource is being added to your app.


text:
Q: Mixin Method super() call generates a Unresolved Attribute Reference in PyCharm In PyCharm I have some codes that looks like this:
class Mixin:
    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update({'foo': 'bar'})
        return kwargs

The linter is raising an issue that Unresolved attribute reference 'get_form_kwargs' for class 'object' on the super() call.   This issue is 100% true but unhelpful on a mixin.   We have a great many mixins that have this super() pattern.
I'm aware of a solution for attributes but not methods where you are able to declare types for these undefined class attributes.  For example:
class Mixin:
    foo:str

I am curious if there is anything similar for methods that help the linter to recognize the mixins.
Thanks!

A: Try this code:
class Mixin:
    def get_form_kwargs(self):
        get_form_kwargs_method = getattr(super(), "get_form_kwargs")
        if get_form_kwargs_method and callable(get_form_kwargs_method):
            kwargs = get_form_kwargs_method()
        else:
            kwargs = {}
        kwargs.update({'foo': 'bar'})
        return kwargs

Update:
I'd appreciate a comment from those who added - on this answer. This definitely fixes a pylint issute. This is not short and elegant, but you have 2 choices: disable this check in pylint or write a valid code.


text:
Q: Directive/scope inheritance Maybe this is sort of two questions in one.  I know you have to explicitly declare directives to be used inside a Component for Angular 2.  Does this propagate to children Components of the Component, and if not, can it be made to?  Second, do variables declared on the Component propagate to children, or do they have to be explicitly passed to the Component?

A: As of beta.14 you have to explicitly list all used directives in @Component's directives array. For the second part of the question, variables declared on component (eg: this.name) are not propagated to child components. To achieve that you have to pass them explicitly in components template using attributes like <child [item]="parentItem"></child> and child component must contain @Input item property.
EDIT:
To incorporate clarification from comment... It is possible to register directives globally but only in bootstrap function. Directives declared on parent will NOT be inherited by child component.
bootstrap(App, [
    PLATFORM_DIRECTIVES,
    provide(PLATFORM_DIRECTIVES, {useValue: [SomeDirective, SomeComponent], multi:true})
]);


text:
Q: Python - checking if a list is a subset of another list, if not, how do i split it? How do I find the minimal amount of lists that mylist is in, for example,
For the lists below, I can easily find that Sarah's animals all belong in house_animals using set(sarahs_animals) < set(house_animals)
However Johns animals needs split across zoo_animals and house_animals. John_animals could be split a number of ways e.g. it could also be house_animals, big_animals and bird_animals, how would I find the minimal amount of lists that it can be split across? Thanks
johns_animals = ['dog', 'cat', 'rhino', 'flamingo']
sarahs_animals = ['dog', 'cat']

house_animals = ['dog', 'cat', 'mouse']
big_animals = ['elephant', 'horse', 'rhino']
bird_animals = ['robin', 'flamingo', 'budgie']
zoo_animals = ['rhino', 'flamingo', 'elephant']

A: I believe this is a solution (Python3, but easily adaptable to Python2).
from itertools import combinations

johns_animals = {'dog', 'cat', 'rhino', 'flamingo'}

animal_sets = { 'house_animals': {'dog', 'cat', 'mouse'},
                'big_animals': {'elephant', 'horse', 'rhino'},
                'bird_animals': {'robin', 'flamingo', 'budgie'},
                'zoo_animals': {'rhino', 'flamingo', 'elephant'}
}

def minimal_superset(my_set):
  for n in range(1,len(animal_sets)+1):
    for set_of_sets in combinations(animal_sets.keys(), n):
      superset_union = set.union(*(animal_sets[i] for i in set_of_sets))
      if my_set <= superset_union:
        return set_of_sets

print(minimal_superset(johns_animals))

We go through all possible combinations of animal sets, returning the first combination that "covers up" the given set my_set. Since we start from smallest combinations, ie. consisting of one set, and advance to two-set, three-set etc., the first one found is guaranteed to be the smallest  (if there are several possible combinations of the same size, just one of them is found).


text:
Q: Another South "table does not exist" issue: none of the previously posted solutions working I am trying to make an app using Django and am using South to handle migrations. After I define the app's models.py, I include south in the "INSTALLED_APPS" in settings.py. Then I sync my database. When I validate the database, I get 0 errors. Then I execute the following commands on the command prompt:
C:\Users\abagaria\Desktop\IntegrateID\website>python manage.py schemamigration w
ebsite.integrate --initial
Creating migrations directory at 'C:\Users\abagaria\Desktop\IntegrateID\website\
website\integrate\migrations'...
Creating __init__.py in 'C:\Users\abagaria\Desktop\IntegrateID\website\website\i
ntegrate\migrations'...
 + Added model integrate.Publisher
 + Added model integrate.Author
 + Added model integrate.Book
 + Added M2M table for authors on integrate.Book
Created 0001_initial.py. You can now apply this migration with: ./manage.py migr
ate integrate

C:\Users\abagaria\Desktop\IntegrateID\website>python manage.py migrate website.i
ntegrate
Running migrations for integrate:
 - Migrating forwards to 0001_initial.
 > integrate:0001_initial
FATAL ERROR - The following SQL query failed: CREATE TABLE "integrate_publisher"
 ("id" integer NOT NULL PRIMARY KEY, "name" varchar(30) NOT NULL, "address" varc
har(50) NOT NULL, "city" varchar(60) NOT NULL, "state_province" varchar(30) NOT
NULL, "country" varchar(50) NOT NULL, "website" varchar(200) NOT NULL)
The error was: table "integrate_publisher" already exists
 ! Error found during real run of migration! Aborting.

 ! Since you have a database that does not support running
 ! schema-altering statements in transactions, we have had
 ! to leave it in an interim state between migrations.

! You *might* be able to recover with:   = DROP TABLE "integrate_publisher"; []
   = DROP TABLE "integrate_author"; []
   = DROP TABLE "integrate_book"; []
   = DROP TABLE "integrate_book_authors"; []

 ! The South developers regret this has happened, and would
 ! like to gently persuade you to consider a slightly
 ! easier-to-deal-with DBMS (one that supports DDL transactions)
 ! NOTE: The error which caused the migration to fail is further up.
Error in migration: integrate:0001_initial
DatabaseError: table "integrate_publisher" already exists

I know that a lot of people have faced similar problems while using south, but usually in their case, they make the mistake of executing the "--initial" command more than once-- thereby causing south to make more than one __initial file in the migrations directory. But in my case, South thinks that the table already exists even when I make the first migration!
I have also tried:

*

*deleting the migrations directory

*deleting ghost migrations

*making a "fake" migration

*and then running the actual migration

Can someone please tell me how I fix this problem and can start defining my models again?

A: If you already have tables in database, do not use --initial, instead you need convert_to_south command. Delete directory "migrations", all tables from database and run the following commands:
python manage.py syncdb
python manage.py convert_to_south appname
python manage.py syncdb --migrate

http://south.readthedocs.org/en/latest/convertinganapp.html


text:
Q: Heterogeneity test in meta-analysis In a random effect meta-analysis model with one categorical independent variable $\theta_{ij}=\theta_i+s_j+\epsilon_j$, where $\theta_{ij}$ is the observed effect size in category $i$ in study $j$, $\theta_i$ is the mean effect size in category $i$, $s_j$ is the random study effect, and $\epsilon_j$ is the within study error (or sampling error). We often further assume that $s_i$ follows a normal distribution with mean 0 and variance $\tau^2$. $\epsilon_j$ is also normally distributed and its variance ($\sigma^2$) is calculated from primary literature and is assumed to be known when fitting the model.
In a model like this, meta-analysis software, such as metafor in R, can perform two heterogeneity test. The first is testing if among study heterogeneity is 0, that is, $\tau=0$. This is done by computing a Cochran's $Q=\sum w_i(\theta_{ij}-\hat{\theta_i})^2$. Here, $w_i=1/\sigma^2$ and $\hat{\theta_i}$ is the weighted average ($w_i$ as the weight) of all $\theta_{ij}$ within the $i$th group. Meta-analysis text book often says that Q is asymptopically chi-square distributed under the null hypothesis $\tau=0$.
The second homogeneity test is whether all $\theta_i$ are equal. This is done by computing a $Q=\sum w^*_i(\hat{\theta_i}-\hat{\theta})^2$, where $\hat{\theta_i}$ is the weighted ($w^*_i=1/(\hat{\tau^2}+\sigma^2)$) average of all $\theta_{ij}$ within the $i$he category and $\hat{\theta}$ is the weighted overall mean. Again, Q follows a Chi-square distribution.
The questions I have are

*

*In the first test, Why is Q asymptotically chi-square, not exactly Chi-square? We know for a normally distributed random variable, $(n-1)S^2/\sigma^2$ follows chi-square distribution. Q is essentially the same. Is it the weighted average that makes it asymptotically, but not exactly, Chi-square?

*Is the heterogeneity test for $\tau$ still valid in general for a linear mixed effect model? In a linear mixed model, we usually don't know $\sigma$ and have to estimate it using "ML" or "REML". Does this break the Chi-square distribution of Q? I have never seen the Q statistics for testing random effect in a linear mixed model text book. We know that likelihood ratio or Wald test for random effect tends to be conservative. If this Q statistics works in general, why isn't it adopted as a general test for linear mixed models?

*For the second heterogeneity test about the categorical predictor, is it just a Wald test? We know that Wald test or likelihood ratio test are anti-conservative in linear mixed model. Many text book recommends conditional F test (with df corrections) or simulation based inference. Is such anti-conservative nature still a concern for meta-analysis model? I don't know whether the fact that $\sigma$ is given to the model as a known quantity alleviate such problem.
I have read a few meta-analysis textbook and search online but cannot find detailed explanations for these technical details. Any insights or references would be very helpful.

A: I have done more reading on primary literature since posting the questions. I want to post what I have learnt since then and hopefully that might be helpful for someone else. I cannot guarantee that these new findings are absolutely correct. So please feel free to comment and correct any wrong understandings here.

*

*If we treat $\sigma$ as known, $Q$ follows an exact Chi-square distribution. The proof is similar to proving $(n-1)S^2/\sigma^2$ follows Chi-square distribution. Using weighted average in the calculation does not break the Chi-square distribution. However, in practice, $\sigma$ is not actually known. It is calculated based on data in primary literature and treated as known. This is what makes the distribution asymptotic. This 1982 paper by Hedges seems to be the first paper that address the distribution property of the Q statistic.

*It only works in the settings of meta-analysis because $\sigma$ is treated as known. In linear mixed model, $\sigma$ is unknown and has to be estimated. If we use the estimated $\sigma$ in calculating Q, the Q statistics does not have Chi-square distribution any more. In fact, if $\sigma$ is estimated in the absence of any random effect (i.e. in a linear model), Q is actually always n-1.

*It is indeed a Wald test. And Wald test tends to be anti-conservative in linear mixed model. Because Wald test is based on asymptotic theory, sample size influences its performance. I think this is why the anti-conservative problem is less severe in meta-analysis. In a meta-analysis, the random effect $s_j$ is for each $\theta_{ij}$ and thus we have a large sample size to estimate $\tau$. For example, if we compiled 100 effect size estimates for a meta-analysis without any moderator, we have 99 degrees of freedom to estimate $\tau$. In a normal linear mixed model, we often don't have that many samples to estimate random effect. For example, we may do an experiment in a few randomly chosen fields or conduct an experiment in several randomly chosen schools. This makes the anti-conservative property of the Wald test a more severe concern in general for linear mixed model. However, such anti-conservative problem is recognized in meta-analysis literature as well. Adjustments such as the Knapp-Hartung method has been proposed to at least partially resolve this issue.


text:
Q: Oracle DBD Insert and update table using perl script running parallel I have a perl script which is run parallel.
ls -lrt INCOMING | grep .out | head -${PARALLEL_COUNT} |  awk '{print $9}' | parallel "./new_control.pl" {}

Script proccessing csv files which coresponds server data.
When the script is running parallel I have exception
Uncaught exception from user code:
DBD::Oracle::st execute failed: ORA-00001: unique constraint (PRE.SYS_C006373) violated (DBD ERROR: OCIStmtExecute) [for Statement "INSERT INTO DISK
(
    ID,
    RECORD_ID,
    MOUNT_POINT,
    TOTAL_SIZE,
    USED,
    AVALIABLE,
    CAPACITY,
)
VALUES ((SELECT NVL(MAX(ID)+1, 1) FROM DISK), ?, ?, ?, ?, ?, ?, ?, ?, ?)

I suppose that the problem is ID column where is inserting incremented value.
(SELECT NVL(MAX(ID)+1, 1)

and the same id is already also inserting by the other script instance.
I tried to change AutoCommit but without any positive result
our $dbh = DBI->connect("dbi:Oracle:host=$host;sid=$sid;port=$port", $username, $password,
{
    RaiseError => 1,
    AutoCommit => 1 # this will need to call commit manually (if value is 0) after changes in DB.
});

When the script is not run parallel everythink is ok. I don't want to generate those id's before I run the script parallely.

A: Assuming what you're trying todo here is make the data load quicker, you would be better off using the sqlldr tool ( the oracle bulk loading tool ).
Apart from anything else this is almost certainly IO bound, putting insert statements in multiple cores will do nothing to make it faster, and will create new problems like the one you have above.


text:
Q: NotFittedError when using RandomForestRegressor Python newbie. I'm trying to run simple random forest model with 5 features and one label but when I run RandomForestRegressor I get a NotFittedError (Below) which I do not understand.
Any help appreciated...
---------------------------------------------------------------------------
NotFittedError                            Traceback (most recent call last)
<ipython-input-86-b670604a6f52> in <module>()
----> 1 predictions = rf.predict(train_features)

/anaconda3/lib/python3.6/site-packages/sklearn/ensemble/forest.py in predict(self, X)
    677             The predicted values.
    678         """
--> 679         check_is_fitted(self, 'estimators_')
    680         # Check data
    681         X = self._validate_X_predict(X)

/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py in check_is_fitted(estimator, attributes, msg, all_or_any)
    766
    767     if not all_or_any([hasattr(estimator, attr) for attr in attributes]):
--> 768         raise NotFittedError(msg % {'name': type(estimator).__name__})
    769
    770

NotFittedError: This RandomForestRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.

A: First fit data to train model and then predict
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_regression

X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False)
regr = RandomForestRegressor(max_depth=2, random_state=0)
regr.fit(X, y)
regr.predict([[0, 0, 0, 0]])


text:
Q: MVC routing issue which I can't find a solution I have an Area called User. Under that area I have a view called Index.
Area Registration with only one route:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
                "0",
                "user/signup",
                new { action = "Index", controller = "Signup" },
                new string[] { "Company.Web.Areas.User.Controllers" }
            );
}

Path to controller:
Areas\User\Controllers\SignupController.cs

Path to view:
Areas\User\Views\Signup\Index.cshtml

This is how I am trying to generate URL in header with Signup hyperlink:
Signup

This is the url I am getting:
http://www.myserver.com/user/signup?returnUrl=home/main
The url looks correct, the routing has just one route.
But when I click the url it says: The resource cannot be found. user/signup
What am I missing?

A: Try
context.MapRoute(
            "signup",
            "{controller}/{action}", // URL with parameters
            new { controller = "Signup", action = "Index" } // Parameter defaults
        );

That should map to the Signup controller and the Index action


text:
Q: Double negation of existential/universal quantifier $\lnot(\exists x(\lnot A(x))$ I have a (simple) question about the double-negation and existential/universal quantifiers.
When negating the following
$$\lnot\exists x(\lnot A(x)) $$
I believe you just push the negation in (which swaps the quantifier) making it
$$\forall x[\lnot(\lnot A(x))]$$
and then
$$\forall x A(x)$$
Would that be a correct interpretation? Or would I be losing one of the negations on $A(x)$ somewhere earlier?

A: You did that correctly.
Note that going from
$$\lnot\exists x(\lnot A(x)) $$
to
$$\forall x[\lnot(\lnot A(x))]$$
is an example of 'Quantifier Negation', but going from:
$$\forall x[\lnot(\lnot A(x))]$$
to
$$\forall x A(x)$$
is an instance of 'Double Negation'

A: A word of caution. Of course at the final step $\forall x\neg\neg Ax$ entails (or at least, classically entails) $\forall x Ax$, and does so because adjacent double negations (classically) cancel each other out.
BUT
The inference is not strictly an application of a standard double negation rule of the form from $\neg\neg\varphi$ infer $\varphi$. That rule only allows us to remove initial double negations.
SO
To show the entailment in standard proof systems requires a three-step mini-proof:

$\forall x\neg\neg Ax\quad$ (given)
$ \neg\neg Aa\quad\quad$  (universal instantiation with parameter or free variable depending on system)
$ Aa\quad\quad\quad$  (NOW you can apply the DN rule)
$\forall x Ax\quad\quad$ (universal generalization)

So your reasoning is informally just fine, but do be careful about jumping from $\forall x\neg\neg Ax$ to $\forall x Ax$ in formal proofs!

A: As per the answer by Brian M. Scott:

It's also intuitively clear: the first expression says that there is
  no x for which A(x) is false, and the last says that A(x) is true for
  every x, clearly the same thing.


text:
Q: URL path not working, absolute path does I switched hosting providers and now have the following problem.
A function, imagecreatefromjpeg(), is trying to read a file from its URL path (http://mydomain.com/contents/category/certificate/1/template.jpg). This function was working on old setup but fails with the following error on the newer setup.
(104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
Premature end of script headers: index.php

The problem went away once I replaced the URL path with absolute path of the same file.
The differences I can see are

*

*the new setup is using nginx as Apache's reverse proxy.

*the PHP version on new setup is 5.3.3, older setup had 5.3.14

We've tried many things but can't understand how to make URL paths work on the newer setup. Can anybody help?

A: Are you sure you configured your nginx webserver accordingly ? Here are some good tutorials that can explain some of the more relevant nginx and php fastcgi process manager common pitfalls:

*

*Ars Technica: Web Served part 1: Setting up a web server

*Ars Technica: Web Served part 3: Installing PHP Fastcgi Process Manager

*Nginx common pitfalls
I linked these resources because it seems as if you have a missconfiguration of your rewrite engine. In any case, please provide better context !

A: try to change url 'http://mydomain.com/' by a function
    function selfURL(){
    $server1 = $_SERVER['HTTPS'];
    $server2 = $_SERVER['SERVER_PROTOCOL'];
    $server3 = $_SERVER['SERVER_PORT'];
    $server4 = $_SERVER['SERVER_NAME'];

    $s = empty($server1) ? '' : ($server1 == "on") ? "s" : "";
    $protocol = strleft(strtolower($server2), "/").$s;
    $port = ($server3 == "80") ? "" : (":".$server3);
    return $protocol."://".$server4.$port;

    }
function strleft($s1, $s2){
return substr($s1, 0, strpos($s1, $s2));
}
print(selfURL());

you can replace '$port' if it not used

A: i have issues with this on my server when i am running cron.
here is what i can say based on a similar topic.
1)  a page loads at something like ~/.
2)  You reference another page located at ~/../private/hello/derp.php
3)  inside derp.php it is under the assumption that you are running the file from ~/../private/hello/.'
4)  in actuality you are running it from ~/.
5)  file references are wrong because PWD is wrong.
it was annoying for my stuff to figure out but when i was looking at it in depth, i relized it was trying to load stuff from something like ~/../private/hello/images/hi.jpg where in actuality because of PWD, it was looking in ~/images/hi.jpg which didnt exist.
Maybe this helps you.  I hope it does.
Edit You also want to know that a lot of time, the ~/. for YOU can be different then the ~/. of PUBLIC.  That is also something to keep note of.
Try to make proper use of terminal variables via bash scripting.


text:
Q: Issues with jquery post method I'm trying to make a simple hello world app to test connecting front end and back end. The back end is a simple flask app.
This is the JS that executes on button click:
function mouseAction() {
    let helloWorldButton = document.getElementById('btn')
    helloWorldButton.addEventListener("click", function(){
        //post request goes here
        console.log("mouse clicked!")
        $.post({
            url: "http://localhost:5000/hello_world",
            data: {},
            success: function(data){
                formatReturnedData(data)
            },
            dataType: 'string'
        })
        console.log(data)
        console.log('hi bruh')
    })
}

I know the request is received by the server because my daemon logs it:

But the 'hi bruh' or the 'data' never get printed to console, what am I doing wrong? Any help is appreciated.

A: Your request is not formed properly. Your console.logs should be inside of your success callback function. And 'string' is not a valid dataType value.
Try this instead:
$.post({
  url: 'http://localhost:5000/hello_world',
  data: {},
  success: function(data) {
    formatReturnedData(data);
    console.log(data);
    console.log('hi bruh');
  },
  dataType: 'json'
});

For more details see the docs https://api.jquery.com/jquery.post/

A: Data only exists inside the success function
function mouseAction() {
    let helloWorldButton = document.getElementById('btn')
    helloWorldButton.addEventListener("click", function(){
        //post request goes here
        console.log("mouse clicked!")
        $.post({
            url: "http://localhost:5000/hello_world",
            data: {},
            success: function(data){
                formatReturnedData(data)
                console.log(data)
                console.log('hi bruh')
            },
            dataType: 'string'
        })
    })
}

A: By default jquery ajax request works asynchronously. In that case as you putted your console.log after the server request console.log is executing before server response. If you put console.log inside success call back function the problem will resolve. For example

function mouseAction() {
    let helloWorldButton = document.getElementById('btn')
    helloWorldButton.addEventListener("click", function(){
        //post request goes here
        console.log("mouse clicked!")
        $.post({
            url: "http://localhost:5000/hello_world",
            data: {},
            success: function(data){
                formatReturnedData(data)
                console.log(data)
                console.log('hi bruh')
            },
            dataType: 'string'
        })
    })
}


text:
Q: spring - How to set List of java.util.Locale in Spring XML? How can I configure list of java.util.Locale in Spring XML?
This is what I tried (which obviously didn't work..):-
<bean
    class="x.y.z.CommandBean"
    scope="prototype">
    <property name="locales">
        <list value-type="java.util.Locale">
            <value>Locale.US</value>
            <value>Locale.FR</value>
        </list>
    </property>
</bean>

Exception :-
 org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Locale';

Also, is there any way I can move the locale as comma separated values in a .properties file?

A: Try this,
 <property name="locales">
        <list value-type="java.util.Locale">
            <value>java.util.Locale.US</value>
            <value>java.util.Locale.FR</value>
        </list>
    </property>

In your class,
private List<Locale> locales;

    public List<Locale> getLocales() {
        return locales;
    }

    public void setLocales(List<Locale> locales) {
        this.locales = locales;
    }

A: Specifying the values as
<value>java.util.Locale.US</value>
<value>java.util.Locale.FR</value>

should do the trick. Getting them from a properties value seems a bit more work.
You could specify them like
my.app.locales=en_US,de_DE

configuring
<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>file:./config.properties</value>
    </property>
</bean>
<bean
    class="x.y.z.CommandBean"
    scope="prototype">
    <property name="locales">
        <bean class="org.springframework.util.StringUtils" factory-method="tokenizeToStringArray">
            <constructor-arg type="java.lang.String" value="${my.app.locales}"/>
            <constructor-arg type="java.lang.String" value=","/>
        </bean>
    </property>
</bean>

and then you would need
import org.apache.commons.lang3.LocaleUtils;

public void setLocales(String[] localeStrings) {
   List<Locale> locales = new ArrayList<Locale>(localeStrings.length);
   for (String localeName: Arrays.asList(localeStrings)) {
      locales.add(LocaleUtils.toLocale(localeName));
   }
   this.locales = locales;
}

this is a bit gludgy though. As an alternative, you could define a wrapper class that does the conversion above, and wire that as a bean. Then hook your class to that bean.


text:
Q: Exterior 2-form, 1-form, Hodge star operator. In $\mathbb{R}^{2n}$ with coordinates $x_1, x_2, \dots, x_{2n}$, consider an exterior 2-form$$\eta = \sum_{k=1}^n x_{2k-1} \wedge x_{2k}.$$Given a 1-form $\alpha = \sum_{i=1}^{2n} a_ix_i$, what is the 1-form$$\beta = \star\left(\alpha \wedge \underbrace{\eta \wedge \dots \wedge \eta}_{n-1}\right)?$$Many thanks in advance.

A: We have$$\eta^{n-1} = (n-1)! \sum_{j=1}^n x_1 \wedge \dots \wedge x_{2n} \text{ (}x_{2j - 1} \wedge x_{2j} \text{ is missing).}$$Then$$x_{2j - 1} \wedge \eta^{n-1} = (n-1)! \sum_{j=1}^n x_1 \wedge \dots \wedge x_{2n} \text{ (}x_{2j} \text{ is missing)}$$and$$x_{2j} \wedge \eta^{n-1} = (n-1)! \sum_{j=1}^n x_1 \wedge \dots \wedge x_{2n} \text{ (}x_{2j-1}\text{ is missing).}$$Hence, $\star(x_{2j-1} \wedge \eta^{n-1}) = (n-1)!x_{2j}$ and $\star(x_{2j} \wedge \eta^{n-1}) = -(n-1)!x_{2j-1}$.
Therefore,\begin{align}\beta &= \star(\alpha \wedge \eta^{n-1}) = \sum_{j=1}^n (a_{2j-1} \star (x_{2j-1} \wedge \eta^{n-1}) + a_{2j} \star (x_{2j} \wedge \eta^{n-1}))\\
&= (n-1)! \sum_{j=1}^n (-a_{2j} x_{2j-1} + a_{2j-1} x_{2j}).\end{align}Note that these formulas also hold for $n=1$. In this case, $\star(a_1x_1 + a_2x_2) = a_1x_1 - a_1x_2$.


text:
Q: Hide cursor for only one Adobe AIR window I have the following code which hides the cursor for an Adobe AIR app (JavaScript):
window.runtime.flash.ui.Mouse.hide();

However I have two screens displayed when the app is run, and I only want the cursor hidden on one of the windows... How can I do this? As the above code will hide it for all windows!
What I have tried (based on the code posted below by Andrey):
window.nativeWindow.addEventListener(air.MouseEvent.ROLL_OVER, function(){

    window.runtime.flash.ui.Mouse.hide();

});

window.nativeWindow.addEventListener(air.MouseEvent.ROLL_OUT, function(){

    window.runtime.flash.ui.Mouse.show();

});

This code lives inside the ACTUAL HTML that is loaded into the window, so it only runs on the window it exists on... but doesn't work...
Also tried: MOUSE_OVER and MOUSE_OUT
I've also tried to add the mouse hide on the actual window:
var secondWindow = air.HTMLLoader.createRootWindow(false, options, false, largestScreen.bounds);

    secondWindow.window.runtime.flash.ui.Mouse.hide();

Which also doesn't work... Any ideas on how I can achieve this on just one window?

A: Hide mouse on roll over event and show on roll out:
private var window:Window;

private function init():void
{
    window = new Window();
    window.addEventListener(MouseEvent.ROLL_OVER, window_onRollOver);
    window.addEventListener(MouseEvent.ROLL_OUT, window_onRollOut);
    window.open();
}

private function window_onRollOver(event:MouseEvent):void
{
    Mouse.hide();
}

private function window_onRollOut(event:MouseEvent):void
{
    Mouse.show();
}


text:
Q: failing to check if document retrieved from cloud firestore database has data or not I am retrieving data fro my Firestore and I can't seem to get my code to work. I want it to display something when it can't find data in the collection I gave it......................................................................................................................................................
Here is my code:
     StreamBuilder(
                      stream: Firestore.instance.collection("payments").where('participants', arrayContains: userActive).snapshots(),
                      builder: (context, snapshot){

                      return Container ( child:ListView.builder(
                          shrinkWrap: true,
                        itemCount: snapshot.data.documents.length,
                        padding: EdgeInsets.all(0),
                        controller: ScrollController(keepScrollOffset: false),
                        itemBuilder: (context, index){

                           DocumentSnapshot documentSnapshot = snapshot.data.documents[index].data();

                          if(snapshot.data.documents.isEmpty){

                               print("No Data!!!");

                          }else{

                            print("Found Data!!!");
                          }

                     /*   if(documentSnapshot["receiver_name"] == userActive )  {

                            return Container(
                            margin: EdgeInsets.symmetric(horizontal: 32,vertical: 5),
                            padding: EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(20))
                            ),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  decoration: BoxDecoration(
                                      color: Colors.grey[100],
                                      borderRadius: BorderRadius.all(Radius.circular(18))
                                  ),
                                  child: Icon(Icons.attach_money, color: Colors.lightBlue[900],),
                                  padding: EdgeInsets.all(12),
                                ),

                                SizedBox(width: 16,),
                                Expanded(

                                  child: Column(

                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[

                                    Text("Recieved", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.grey[900]),) ,

                                      Text("" + documentSnapshot["currency_received"] + documentSnapshot["amount_received"], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),

                                    ],
                                  ),
                                ),

                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: <Widget>[

                                    Text("+ " + documentSnapshot["currency_sent"] + documentSnapshot["amount_paid"].toString(), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.lightGreen),),

 Text(documentSnapshot["date"].toDate().toString(), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),
                                  ],
                                ),
                              ],
                            ),
                          );

                      } else if (documentSnapshot["sender_name"] == userActive){

                     return Container(
                            margin: EdgeInsets.symmetric(horizontal: 32,vertical: 5),
                            padding: EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(20))
                            ),
                            child: Row(
                              children: <Widget>[
                                Container(
                                  decoration: BoxDecoration(
                                      color: Colors.grey[100],
                                      borderRadius: BorderRadius.all(Radius.circular(18))
                                  ),
                                  child: Icon(Icons.attach_money, color: Colors.lightBlue[900],),
                                  padding: EdgeInsets.all(12),
                                ),

                                SizedBox(width: 16,),
                                Expanded(

                                  child: Column(

                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[

                                    Text("Sent", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.grey[900]),) ,

                                      Text("" +  documentSnapshot["currency_received"] + documentSnapshot["amount_received"], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),

                                    ],
                                  ),
                                ),

                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: <Widget>[

                                    Text("- " + documentSnapshot["currency_sent"] + documentSnapshot["amount_paid"].toString(), style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: Colors.orange),),

                                                 Text(documentSnapshot["date"].toDate().toString(), style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.grey[500]),),

                                  ],
                                ),
                              ],
                            ),
                          );

                      }else{

                                        return Text("Nothng found ",style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: Colors.black));
                      }

*/

                        },
                       )
                      );

 }

   ),

A: There is a new update to Firestore recently and you have to retrieve the value by using .data().
To make your code work, you would have to change this:
DocumentSnapshot documentSnapshot = snapshot.data.docs[index]; //not working code

Add .data() in the end:
DocumentSnapshot documentSnapshot = snapshot.data.documents[index].data(); //working code

A: check your cloud_firestore version, if you're using version cloud_firestore: ^0.14.0
DocumentSnapshot documentSnapshot = snapshot.data.documents[index].data();

if not use
DocumentSnapshot documentSnapshot = snapshot.data.documents[index].data; //this is a getter

data is a getter, not a method and should be called without parenthesis (javascript uses them because its a method there, but not in dart) but only before version 0.14.0. If you're not sure you can run pub outdated to check the current versions of your packages.
Also it could be better to change it like this
StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection("payments").where('participants', arrayContains: 'userActive').snapshots(),
  builder: (context, snapshot){
    if(snapshot.connectionState == ConnectionState.active && snapshot.hasData) {
      if(snapshot.data.documents.isEmpty) return Center(child: const Text('No Data!'));
      print("Found Data!!!");
      return Container ( child:ListView.builder(...)); //your listView here
    }
    return Center(child: const CircularProgressIndicator());
  },
);


text:
Q: How to get all values in a column in table using vaadin SQLContainer Hi Stackoverflow members,
I have one SQLContainer with TableQuery. Now, I want to get all the values in one column. How can I get it? Or Shall I need to go with FreefromQuery?
This is my SQLContainer code
public SQLContainer getMyContainer() {
    //FreeformQuery query = null;
    SQLContainer container = null;
    try {

             connectionPool = new SimpleJDBCConnectionPool(
                    "com.mysql.jdbc.Driver",
                    "jdbc:mysql://localhost:3306/vaadin", "root", "root",
                    2, 5);
             TableQuery query = new TableQuery("components", connectionPool);
            /*query = new FreeformQuery(
                    "SELECT rowNum, colNum, caption, cType FROM items where screenId='"
                            + screenName+"'", connectionPool);
            query.setDelegate(new DemoFreeformQueryDelegate());*/
            container = new SQLContainer(query);

    } catch (Exception e) {

    }
    return container;
}

A: It depends on what you wish to do.
With SQLContainer you could do it this way:
// Returns a list with all ID's (Beware of large resultsets)
Collection<?> itemIDS= conatiner.getItemIds();
for (Object itemID : itemIDS)
{
     Property property= container.getContainerProperty(itemID, "COLUMN");
     Object data= property.getValue();
}

The getItemIds() must fetch all rows from the DB (at least the primary keys),
so this will cause troubles with large resultsets/tables.
https://vaadin.com/api/com/vaadin/data/util/sqlcontainer/SQLContainer.html#getItemIds%28%29


text:
Q: Logging in and using cookies in pycurl I need to download a file that is on a password protected page.  To get to the page manually I first have to authenticate via an ordinary login page.  I want to use curl to fetch this page in script.
My script first logins. It appears to succeed--it returns a 200 from a PUT to /login.  However, the fetch of the desired page fails, with a 500.
I am using a "cookie jar":
C.setopt(pycurl.COOKIEJAR, 'cookie.txt')

In verbose mode, I can see cookies being exchanged when I fetch the file I need.  Now my question: Is there more to using a COOKIEJAR?

A: wds is right on.
for your further edification, the available options are based on those at http://curl.haxx.se/libcurl/c/curl_easy_setopt.html  (see the section on cookie shortcuts).
a 500 is an internal server error...hard to be sure whether this can be blamed on your script without knowing more information about what's going on here.  you could be failing to pass other data the page is expecting (unrelated to cookies) for all we know (and they have not implemented graceful error handling!)
jb

A: I believe Curl will store the cookies but you need to use them explicitly. I've only ever used the command line interface for this though. Scanning the documentation I think you might want to try:
C.setopt(pycurl.COOKIEFILE, 'cookie.txt')

(before the second request)

A: You should store cookie first and then read from it:
C.setopt(pycurl.COOKIEJAR, 'cookie.txt')
C.setopt(pycurl.COOKIEFILE, 'cookie.txt')

Here what curl --help returned:
-b, --cookie STRING/FILE  String or file to read cookies from (H)
-c, --cookie-jar FILE  Write cookies to this file after operation (H)

See this sample:
def connect(self):
    '''
    Connect to NGNMS server
    '''
    host_url = self.ngnms_host + '/login'

    c = pycurl.Curl()
    c.setopt(c.URL, host_url)
    c.setopt(pycurl.TIMEOUT, 10)

    c.setopt(pycurl.FOLLOWLOCATION, 1)
    c.setopt(pycurl.POSTFIELDS, 'j_username={ngnms_user}&j_password={ngnms_password}'.format(**self.ngnms_login))
    c.setopt(pycurl.COOKIEJAR, 'data/ngnms.cookie')

    # c.setopt(c.VERBOSE, True)

    c.setopt(pycurl.SSL_VERIFYPEER, 0);
    session = c
    return session


text:
Q: MacBook Pro 2019 13 inch random shut off So I have a MacBook Pro 2019 13 inch, at the moment it doesn't have macOS on it. Trying to run Internet Recovery gives the prompt: "A software update is required to use this startup disk". Clicking on Update after that just shuts it down and makes it restart.
I have already tried several macOS images (High Sierra, Catalina, Monterey, Ventura) but all of them have the same problem (some do load in but again the device randomly shuts down installation). I think there is a problem with the drivers so that's why it shuts down (kernel panic?). I tried running Apple Diagnostics, but this takes me to Internet Recovery.
Is there some way to fix this? The battery is still good so it's not because of that (even if it was bad, that wouldn't explain the other problems)
If there is any info that's still needed to help me, just tell me.
I hope someone knows how to fix this.


text:
Q: I have my requirements for a CodeIgniter web application, now what? I'm working on a project and have developed the high level user requirements for what the system must do.  This project is a php web application built on the CodeIgniter framework.    Now I'm trying to take those requirements and break them down further into controllers/actions.  What is the best way to do this?
I was thinking of creating a word document with a table that would have four columns.  Column one would be the the name of the controller, column two would have the actions, column three would have the name of the view that is specific to the action, and the fourth column would show which users had access to that action.  Does this sound like a good idea?
I like the interface first approach to building an application, but realistically, I need to know what views I need before I can create a prototype interface.
Could anyone help me out with how to plan the app and any documentation that might help?

A: Your breakdown is a good idea, but it's really the second step.
here's what I'd do:

*

*take your requirements, and turn them into a series of scenarios ("use cases", "user stories").

*Pick one, and sketch, like on paper, the basics of the user interface you'd want if you were to have the Good Code Fairy deliver the perfect system to you.

*separately go through the scenario, and underline all the nouns in the story; those are probably domain objects.  Underline all the verbs in a different color.  Each verb is a method of one of those domain objects.  (In fact the domain object will be the object of the verb.  Cool, huh?)

*Figure out how you would implement that user interface using those domain objects.

*Build it

*Show it to your customer, who will invariably say "I like it but"

*Put the changes and things you learned inot your requirements, and repeat until the check clears.
Peter Coad wrote what I still think is really the best beginners book on this:  Java Design: Building Better Apps and Applets.  It's oriented to Java, but the design part is universal.
Your domain objects are the model, the display of your data is (roughly speaking) the view, and the code attached to actions is the controller.

On Use Cases
The "right way" to do use cases or user stories is subject to immense discussion and religious warfare.  There are zillions of options, from Cockburn's somewhat complex form, to notes scribbled on index cards.
For the kind of application you're describing, I do two things: I try to keep them to 25 words or less, and I think about the SMART acronym.

*

*Twenty-five words or less helps keep them small.  Doing a few small stories is preferable to spending weeks on a big one.

*SMART stands for "Specific, Measurable, Agreement with Responsibilities and Tests."  (Or at least that's how I interpret it.  There are other versions.)

*

*Specific, you have to be comfortable you know what's being asked.

*Measurable, you have to have some way of testing or some kind of statement of what will be acceptable

*Agreement, because it needs to be something you and the customer can both agree satisfies a need — in other words, the "meeting of minds" of a contract

*with Responsibilities, you have to know what you're being given, what the customer or user is responsible for providing, and what you are

*and Tests, in other words, you should have an effective procedure that gives you the answer "it is acceptable" or "it's not acceptable."

The form I use has the pattern

User in a particular role
does something
resulting in some benefit

So, in your example, I would write

*

*Administrator (who?)

*lists all FAQs (does what?)

*to review them for updates. (why?)

The "resulting in some benefit" part is something I emphasize and a lot of other people don't, or don't even mention.  It helps a lot later if you need to prioritize them.
The "test" part is a description of an acceptance test: you're answering the question "Is this done?"  So the acceptance test might be

*

*A logged in administrator selects "list FAQ".  All known FAQs are listed in correct format.

Ideally, you'd set this up so some tool, like expect or a gui test tool, can run this automatically, but especially in a small projects you may end up testing by hand.  You want automated testing, because as you build the system, you want to do regression tests; that is, you want to repeat your tests to make sure nothing has been broken by a later change.

A: What you do is you work user-centered.

*

*You make rough mockups of the screens (use Balsamiq or something), and show them to your client/stakeholder, and walk them through it (as if they were using it). Get them to agree.

*Then you code the thing (I'm sure you can figure that part out)

*Then you show to your client again (have them actually use it in detail), and agree on changes.

*Now you finish it

Good luck!


text:
Q: how to show the radio button is selected is still ticked? my app has 2 radio buttons, when user ticks any of it, the value of the ticked radio button gets saved in the table via ajax, now the problem is, when user gets back to the page, the radio button is not ticked, how to make the selected radio button appear as ticked, so that the user knows which he selected before ?
here's my code

    <input type="radio" id="gallerymenustyle1" class="element radio" name="gallerymenustyle[]" value="1" /> Gallery Link - In the navigation of my website, display one "gallery" link

    <input type="radio" id="gallerymenustyle2" class="element radio" name="gallerymenustyle[]" value="2" /> Category Links - In the navigation of my website, display a separate link to each category.

A: When you are rendering the page for the user in PHP you would need to do a query to where you have saved the selection (presumably a database). If the user has selected that particular radio button then you would display it as selected. Code would be something like:
// Do a database query or something to get the value that the user has stored before (if any)
<input type="radio" id="gallerymenustyle1" class="element radio" name="gallerymenustyle[]" value="1" <?php if ($gallerymenustyleFromDatabaseValue == 1){ echo 'selected'; }/> Gallery Link....

<input type="radio" id="gallerymenustyle1" class="element radio" name="gallerymenustyle[]" value="2" <?php if ($gallerymenustyleFromDatabaseValue == 2){ echo 'selected'; }/> Category Link....

A: If the user is logged in you should query the database to get the value whether the button was ticked.
If the user isn't logged in you could use the session id. Although this only works until the user closes his browser / the session expires.
<?php
$checked = 0;
// this should come from db
$checked = 1;
?>

      <input type="radio" id="gallerymenustyle1" class="element radio" name="gallerymenustyle[]" value="1" <?php if ($checked == 1) print('checked="checked"') ?>/> Gallery Link - In the navigation of my website, display one "gallery" link

      <input type="radio" id="gallerymenustyle2" class="element radio" name="gallerymenustyle[]" value="2" <?php if ($checked == 1) print('checked="checked"') ?>/> Category Links - In the navigation of my website, display a separate link to each category.

Will check the first radio button


text:
Q: Tortoise SVN Show Log from root folder doesn't show all I'm new to SVN (long-time cvs user), and am using Tortoise 1.6 (not allowed to update Tortoise).
My problem is this:  performing the Show Log option from the root folder doesn't show revisions/commits that are correctly displayed when performing Show Log on individual revised/committed files from the sub-folder.
The Repo Browser option shows the same problem.
Tried the following without success:  Disabling Log Caching, un-selecting "Hide unrelated changed paths", "Stop on copy/rename", and selecting "Include merged versions"
Thanks in advance for any help.

A: Maybe those subfolders are externals to the main folder. It doesn't matter if an external points to the same repository as the main folder itself. To view the log you'd have to checkout the working copy in which this folder will not be an external. Or do what you've been doing already, view logs from subfolders.
To find out which folders are externals right-click on main folder and then in menu go to TortoiseSVN > Properties. You will see a list of items. If one of them is svn:externals then that's it. Edit it, and in new window you'll see one or more items consisting of subfolder name and an URL to external repository. URL may be relative, with all kinds of "relativeness". To learn more about externals go to appropriate TortoiseSVN doc page.


text:
Q: Jersey resource with multiple paths I'm trying to migrate the way my resources are named, from Portuguese (and singular) to English (and plural), and I was wondering if Jersey currently supports multiple @Paths for the same resource, so I could make this transition painless to the users of my system.
From:
@Path("/usuario")
public class UsersResource {

    @POST
    public Response create(User user) {
        ...
    }
}

To:
@Path("/users")
public class UsersResource {

    @POST
    public Response create(User user) {
        ...
    }
}

Would really appreciate if someone could help me with this.
Cheers!

A: Yes, there is a way to work with multiple paths:
@Path("/{parameter: path1|path2}")


text:
Q: PostgreSQL does not start: FATAL: xlog flush request is not satisfied --- flushed only to 0 I have a Docker PostgreSQL (TimescaleDB) developer instance with a local Linux volume mapping.
version: '3'
services:
  dex-timeseriesdb:
    image: timescale/timescaledb:latest-pg12
    # https://stackoverflow.com/a/56754077/315168
    shm_size: 1g
    container_name: dex-timeseriesdb
    environment:
      POSTGRES_USER: postgres
    volumes:
       - $PWD/data/postgresql:/var/lib/postgresql/data

After unclean shutdown the instance no longer starts with FATAL:  xlog flush request 0/2CEFA910 is not satisfied --- flushed only to 0/1B48258 error:
dex-timeseriesdb    |
dex-timeseriesdb    | PostgreSQL Database directory appears to contain a database; Skipping initialization
dex-timeseriesdb    |
dex-timeseriesdb    | 2021-06-13 18:50:47.330 UTC [1] LOG:  starting PostgreSQL 12.6 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.2.1_pre1) 10.2.1 20201203, 64-bit
dex-timeseriesdb    | 2021-06-13 18:50:47.330 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
dex-timeseriesdb    | 2021-06-13 18:50:47.330 UTC [1] LOG:  listening on IPv6 address "::", port 5432
dex-timeseriesdb    | 2021-06-13 18:50:47.336 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
dex-timeseriesdb    | 2021-06-13 18:50:47.486 UTC [21] LOG:  database system shutdown was interrupted; last known up at 2021-06-13 18:47:35 UTC
dex-timeseriesdb    | 2021-06-13 18:50:49.629 UTC [21] LOG:  database system was not properly shut down; automatic recovery in progress
dex-timeseriesdb    | 2021-06-13 18:50:49.645 UTC [21] LOG:  redo starts at 0/1B46C68
dex-timeseriesdb    | 2021-06-13 18:50:49.648 UTC [21] LOG:  invalid record length at 0/1B48258: wanted 24, got 0
dex-timeseriesdb    | 2021-06-13 18:50:49.648 UTC [21] LOG:  redo done at 0/1B48220
dex-timeseriesdb    | 2021-06-13 18:50:49.697 UTC [21] LOG:  request to flush past end of generated WAL; request 0/2CEFA910, currpos 0/1B48258
dex-timeseriesdb    | 2021-06-13 18:50:49.697 UTC [21] CONTEXT:  writing block 0 of relation base/13455/16573_vm
dex-timeseriesdb    | 2021-06-13 18:50:49.697 UTC [21] FATAL:  xlog flush request 0/2CEFA910 is not satisfied --- flushed only to 0/1B48258
dex-timeseriesdb    | 2021-06-13 18:50:49.697 UTC [21] CONTEXT:  writing block 0 of relation base/13455/16573_vm
dex-timeseriesdb    | 2021-06-13 18:50:49.701 UTC [1] LOG:  startup process (PID 21) exited with exit code 1
dex-timeseriesdb    | 2021-06-13 18:50:49.701 UTC [1] LOG:  aborting startup due to startup process failure
dex-timeseriesdb    | 2021-06-13 18:50:49.744 UTC [1] LOG:  database system is shut down

This is likely data corruption due to unclean Docker shutdown.
There is nothing important in the database. However, I would still like to learn if it is possible to recover the database in situations like this, instead of rebuilding it from the scratch or restoring from a backup.
I tested that the volume mapping is writable within the Docker instance using shell, so that should not be an issue.
See also similar question regarding FATAL: xlog flush request, but slightly different error.

A: According to the provided log, the problem is related to the data file corrupt - which might be caused by the improper shutdown. One of data files has become corrupted.
The file location should be $PGDATA/base/13455/16573_vm
Recommended Action:
First of all, its important to keep in mind that this error is about the pages written to the data directory, not about the WAL stream. That means the primary aim here, if the data of a table is indeed lost, is to get a copy of the data from the WAL stream.
Before we go into details on how to do that, lets first find out which table or index is affected.
In the log message invalid page in block 0 of relation base/13455/16573_vm we get the following information:

*

*16573 is the pg_class.relfilenode value of the index or table affected

*13455is the database OID, i.e. pg_database.oid

*0 is the block number, from which we can determine the file segment as well as the location within the file

That means we can find the affected table by first doing the following to locate the correct database:
SELECT datname FROM pg_database WHERE oid = 13455;

And then connecting to that database and running the following, which gives us the affected table or index:
SELECT relname, relkind FROM pg_class WHERE relfilenode = 16573;

If the affected database object is an index, it is lucky for you - you could just rebuild the index to fix everything.
If the affected database object is a table - bad luck - the available options are:

*

*Fail over to an HA standby server / follower database

*Replay WAL from an old enough base backup

*Accept that some data is lost, and let Postgres move on. You could try to dump the data of the table (might get error during dumping, and lost some data) , and then truncate the table.


text:
Q: Confirming function calls inside a function I'm unittesting with mock module I have a function I'm writing unit tests for.  I'm trying to assert that a number of functions were called with the proper arguments given the input argument.  For example, the function I'm unit testing is in a file called validate.py
def function_to_test(arg1):
    print 'return2: ', _sub_function_1()
    arg1 = _sub_function_1(arg1)
    arg1 = _sub_function_2(arg1)
    arg1 = _sub_function_3(arg1)
    return arg1

def _sub_function_1(arg1):
    pass

def _sub_function_2(arg1):
    pass

def _sub_function_3(arg1):
    pass

I have my unit tests in a file called dotest.py,
import validate
import unittest
import mock

class TestFunctionToTest(unittest.TestCase):

    @mock.patch('validate._sub_function_1')
    def test_basic(self, m_sub_function_1):
        m_sub_function_1 = mock.Mock(return_value='rv_sf1')
        dum_arg1 = 'dum'
        out = validate.function_to_test(dum_arg1)
        print 'called?: ', m_sub_function_1.called

if __name__ == '__main__':
    unittest.main()

The results of running this test are,
run -i dotest.py
return2:  <MagicMock name='_sub_function_1()' id='4502266128'>
called?:  False
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

For some reason the return value defined for the mock function is not being recognized in the call to _sub_function_1.  I want to check if this function is actually called in function_to_test.  Any insight from the mock gurus?

A: First of all, the self argument seems to be missing in your test_basic. Furthermore, your code doesn't call function_to_test. Personally I write the argument to mock.patch as a string so it would become:
class TestFunctionToTest(unittest.TestCase):

    @mock.patch('validate._sub_function_1')
    def test_basic(self, m_sub_function_1):
        m_sub_function_1.return_value = 'rv_sf1'
        function_to_test(...)

This should print: return2: rv_sf1. You can then assert it has been called with the correct arguments:
m_sub_function1.assert_called_with(...)


text:
Q: how to auto deploy with msbuild correctly? i have triggered a build definition and build succeeded, the build definition is assigned the following parameters which i want to do some auto deploy stuff:
/p:DeployOnBuild=True
/p:Configuration=Debug
/p:SkipExtraFilesOnServer=true
/p:DeployTarget=MSDeployPublish
/p:MSDeployPublishMethod=RemoteAgent
/p:AllowUntrustedCertificate=True
/p:CreatePackageOnPublish=true
/p:DeployIISAppPath=BlueOffice/BlueOfficeService  /*site/application*/
/p:MsDeployServiceUrl=http://10.1.1.4
/p:username=mobiledomain\tfsbuild2
/p:password=Abcd1234!

but when the build finished, the deployment not be done, anything about project or build definition i should notice to modify?thanks in advance!


text:
Q: MVC4 WebApi Knockout JSON Invalid operand to 'in' Hy, I'm stuck with this error message and I can not find an solution.
I get this message error in the Knockout JavaScript library v2.2.0:

Unhandled exception at line 1053, column 5 in
  localhost:port/Scripts/knockout-2.2.0.debug.js 0x800a138f -
  Microsoft JScript runtime error: Invalid operand to 'in': Object
  expected If there is a handler for this exception, the program may be
  safely continued.

It stops at this line of code in knockout-2.2.0.debug.js
 if ((initialValues !== null) && (initialValues !== undefined) && !('length' in initialValues))

I use this WebApi:
public class ProductsController : ApiController
{
  IEnumerable<Product> products = new List<Product>()
    {
        new Product { Id = 1, Name = "Tomato_Soup", Category = "Groceries", Price = 1 },
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
    };

      public IEnumerable<Product> GetAllProducts(){
            return products.AsEnumerable();    }

The scripts that I use are in a header section
@section Testscripts
{

}

And the Knockout code in the footer default script section
@section scripts
{


text:
Q: Is there a standard public URL convention used on a Wordpress site directly to a page listing all of a user's public content? Is there a standard convention for a full direct public URL address that, when visited/clicked on, will show a page list all of user account's public content uploaded on that site.
Background:
I have an account with getmedia.org.uk Podcasting site and here is my home page/user profile page:
http://www.getmedia.org.uk/members/therobyouknow/
However it only lists 'recent content' but I know I have earlier content not shown on that page.
I have recently contacted the site admins but haven't heard back from them yet and not sure if they are in a position to resolve my query so I thought I would ask here.
To further illustrate my point I'm looking for something like:
getmedia.org.uk/members/therobyouknow/content
or
getmedia.org.uk/members/therobyouknow/all
or
getmedia.org.uk/members/therobyouknow/uploads
to list ALL of my content
Update:

*

*I don't want an answer based on search engine results - because:

*

*I want a URL of the site because it's direct and part of the site

*The Google URL is messy

*The google URL could change as they develop their search

*The google URL may include other sites the refer both to the site and me

*The google search results have superfluous and unrelated information (ads, links optiond etc) making it harder to read, if messy for such a

*Just to pre-empt any other unhelpful contribution: This question is not a self-promotion of myself or my content by stealth to readers of wordpress.stackexchange.com. It is a genuine query. That said, I would like to use the URL on profiles of myself but know that others would find a similar solution useful for their posted wordpress content, so it's for me and others.

A: I don't know of a standard wp url, but if you just want to know what pages are attributed to you on a particular website then you could try google - ie:
https://www.google.co.uk/search?q=site%3Agetmedia.org.uk+therobyouknow ?

A: Just wondering .. if you tried to navigate via pages and construct a URL
What I mean is that author page template is basically the archive page template so you can construct a URL with page navigation like so
http://damien.co/author/damiensaunders/page/2
You might also find that http://damien.co/author/damiensaunders?&paged=2 works


text:
Q: HPUX top command out put regarding memory explained While we run top on HP-UX ksh console we can see set of memory related value. Out of that I want to get the total physical memory and free memory.
The output would look like follows on multiple run on same machine

Memory: 3298168K (2220868K) real, 13870752K (11320292K) virtual, 50204K free
Memory: 3370124K (2268140K) real, 13796928K (11299204K) virtual, 28440K free
Memory: 3375964K (2374688K) real, 13829572K (11486128K) virtual, 22584K free

*

*On it what is the total memory?

*What is the free memory?

*What is the value in brackets()?

A: according to man top

       Memory Data
            Reports virtual and real memory used by user processes (with
            the amount of memory considered "active" in parentheses) and
            the amount of free memory.

*

*Virtual is memory you allocate, real is memory you use.

(e.g. I allocate 10 000 int, but use the first 13 and from 1001 to 1024, my virtual would be 10000, and my real 37 (13+24)).


text:
Q: MySQL insert into different databases tables based on PK value Lets assume i have two databases, both having a table 'user_feedback', sharding data between the two databases. My goal is to insert all records where Primary key Id%2=0 goes to db1.user_feedback, and Id%2=1 goes to db2.user_feedback.
Is there a condition in the INSERT statement that can allow me to do this? How can i achieve simply achieve this, both if the two databases are located on the same MySQL server, and when they both reside on a different MySQL server?
** UPDATE **
Ok, what i am trying to achieve is to have several tables in the same MySQL server to shard data and limit one table from becoming too big, hence slowing up queries on this table. The table is expected to grow very large (billion records) with heavy writes. That is the reason we have decided to resort to sharding. The table does not currently exist, but we want to create this shard solution in advance before we hit production with this table.

A: Hi you can try the below query.
insert into db1.user_feedback as select * from db2.user_feedback where < your
conditions>;
insert into db2.user_feedback as select * from db1.user_feedback where < your
conditions>;

A: Use the stored routine:
CREATE PROCEDURE `splitinsert`( IN _param1 INT, ... )
BEGIN
  SELECT max(id) INTO @t1 FROM db1.tbl1;
  SELECT max(id) INTO @t2 FROM db2.tbl2;
  IF @t1 < @t2
    THEN
      INSERT INTO db1.tbl (id, col1, ... )
      VALUES (@t1+2, _param1, ... )
    ELSE
      INSERT INTO db2.tb2 (id, col1, ... )
      VALUES (@t2+2, _param1, ... )
  END IF;
END

And then:
CALL splitinsert(1234, ....);

Sure you have to initialize both tables by seed records.

A: I am extremely dubious that you have the problem you describe, but here goes:
CREATE TEMPORARY TABLE t (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    ...   (the rest of the columns)
    );

INSERT INTO t
    SELECT * FROM source;

INSERT INTO db1.x  SELECT ... FROM t WHERE id % 2 = 0;
INSERT INTO db2.x  SELECT ... FROM t WHERE id % 2 = 1;

If the data is coming from clients that are feeding the data in fast and furious, then I recommend ping-ponging between two temp tables, not between even/odd.  The clients will INSERT into one temp table while a separate task is copying the other temp table into one of the two 'real' tables.  Then that task will TRUNCATE the table it copied, then RENAME TABLE to atomically swap the temp tables.
I discuss that in more detail in http://mysql.rjweb.org/doc.php/staging_table


text:
Q: Wordpress WP_Query with multiple meta_values for a meta_key I'm trying to run a WP_Query in order to search for all the products in my database with multiple meta values.
e.g

*

*Product 1 -> meta_key['key1'] ->meta_value['value1']

*Product 2 -> meta_key['key1'] ->meta_value['value2']

*Product 3 -> meta_key['key1'] ->meta_value['value3']

So i want to get all three products.My arguments are
$args = array(
        'post_type' => 'product',
        'posts_per_page' => 2,
        'orderby'    => 'title',
        'order'      => 'ASC',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'key1',
                'value'   => 'val1',
                'compare' => '='
            ),
            array(
                'key'     => 'key1',
                'value'   => 'val2',
                'compare' => '='
            ),
            array(
                'key'     => 'key1',
                'value'   => 'val3',
                'compare' => '='
            ),
        ),
        'paged' => $paged
        );

The problem is that no products are returned. Instead , if a give only one meta_key => meta_value pair it works fine
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'orderby'    => 'title',
    'order'      => 'ASC',
    'meta_key' => 'key1',
    'meta_value' =>'val1',
    'paged' => $paged
);

A: You should use IN as compare value, like this:
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'orderby'    => 'title',
    'order'      => 'ASC',
    'meta_query' => array(
        array(
            'key'     => 'key1',
            'value'   => array('val1','val2','val3'),
            'compare' => 'IN',
        ),
    ),
    'paged' => $paged
);

Hope it helps!


text:
Q: How to return the next x amount of items in an array? I have an array of objects in js:
[{name:'John',number:1},{name:'Peter',number:2},{name:'Mario',number:3},{name:'Jack',number:4}]

Trying to create a pagination component and wondering how to select the next couple of objects. I tried slice but could not get it to work. So for example :
SelectPage(1) would return nr 3 and 4, SelectPage(0) nr 1 and 2 etc

Is there a lodash function for this?

A: Something along the lines of this?
var list = [{name:'John',number:1},{name:'Peter',number:2},{name:'Mario',number:3},{name:'Jack',number:4},{name:'Mario',number:5},{name:'Jack',number:6}]

function SelectPage(list, index, pageSize) {
    return list.slice(index*pageSize, index*pageSize+pageSize)
}

Updated with improvement, thanks @nnnnnn

A: Here's a sample code to get you running, you can modify it as per your requirement.
// Your dummy data

 var data = [
  {name:'John',number:1},
  {name:'Peter',number:2},
  {name:'Mario',number:3},
  {name:'Jack',number:4}
 ];

// function for pagination

  function page(index,data){
  var count = 2;
  var pageNo = index;
  if(index == 0){
    pageNo = 1;
  }
  var currentCount = count * pageNo;

  return (data.slice(index,currentCount));
}

// call this function and pass page index and the data

page(0,data); // 1st page and data array


text:
Q: Angular фильтрация, контроллеры Не могу разобраться с фильтрацией в angular. А именно:
Есть 2 контроллера, один отвечает за пользователей, другой за их местоположение. На клиентской части нужно сделать чтобы фильтрация была по местоположению с помощью selected(она готова). Проблема в том что я не понимаю как соединить 2 контроллера или какая может быть альтернатива.
Т.е. нужно использовать контроллер с пользователями, а фильтровать по контроллеру местоположению.
В Angular я новичок как и в JS так что не ругайте сильно.
Примеры контроллеров(неполные)
Местоположение:
function DepartmentCtrl(common, $modal, $q, $routeParams, $stateParams, $state, settings, departmentRepository, Department, branchRepository) {
        var vm = this;
        var getLogFn = common.logger.getLogFn;
        var log = getLogFn(departmentCtrlId);
        var logError = common.logger.getLogFn(departmentCtrlId, "error");

Юзеры:
function UserListCtrl(common, dialog, $modal, config, NgTableParams, $resource, $location, $state, branchRepository, userRepository) {
    var vm = this;
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn("UserListCtrl");
    var keyCodes = config.keyCodes;

ро конструкцию "controller as переменная" знаю.
Или как передать функции из одного контроллера в другой путем наследования. Как то так.


text:
Q: recoding a c++ task queue in rust. Is futures the right abstraction? I am rewriting a c++ project in rust as my first non-tiny rust program. I thought I would start with a simple but key gnarly piece of code.
Its a queue of std::packaged_tasks that run at specific times. A client says
running_func_fut_ = bus_->TimerQueue().QueueTask(std::chrono::milliseconds(func_def.delay),
    [this, func, &unit]()
    {
        func(this, &unit);
        Done();
    }, trace);

func is a std::function, but they key point is that as far as the queue is concerned is queuing up a lambda (closure in rust speak )
It returns a std::future which the client can ignore or can hang onto. If they hang onto it they can see if the task completed yet. (It could return a result but in my current use case the functions are all void, the client just needs to know if the task completed). All the tasks run on a single dedicated thread. The QueueTask method wraps the passed lambda up in a packaged_task and then places it in a multiset of objects that say when and what to run.
I am reading the rust docs and it seems that futures encapsulate both the callable object and the 'get me the result' mechanism.
So I think I need a BTreeSet (I need the queue sorted by launch time so I can pick the next one to run) of futures, but I am not even sure how to declare one of those. SO before I dive into the deep end of futures, is this the right approach? Is there a better , more natural, abstraction for rust?

A: For the output, you probably do want a Future. However, for the input, you probably want a function object (Box<dyn FnOnce(...)>); see https://doc.rust-lang.org/book/ch19-05-advanced-functions-and-closures.html.