text:
Q: How to capture some values using xml-rs (if it's possible) I'm using xml-rs 0.4 and I need to capture several fields and values:

*

*name

*"visible"

*True

From this sample XML file:
<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <requires lib="rsTest+" version="1.00"/>
  <object class="rsTestWindow" id="window1">
    <property name="can_focus">False</property>
  </object>
</interface>

After looking at the xml-rs code in Github, I was able to capture name and "visible":
for att in attributes {
    // test
    let temp_name_local_name = att.name.local_name.clone();
    let temp_value= att.value.clone();

    println!("{}+{}+{}", temp_name_local_name, temp_value);
}

Stdout:
name+visible

I could not figure out how to capture True.
This is my complete code:
extern crate xml;

use std::fs::File;
use std::io::BufReader;

use xml::reader::{EventReader, XmlEvent};
use xml::name::{Name, OwnedName};

fn indent(size: usize) -> String {
    const INDENT: &'static str = "    ";
    (0..size)
        .map(|_| INDENT)
        .fold(String::with_capacity(size * INDENT.len()), |r, s| r + s)
}

fn main() {
    let file = File::open("./src/sample.xml").unwrap();
    let file = BufReader::new(file);

    let parser = EventReader::new(file);
    let mut depth = 0;

    for e in parser {
        match e {
            Ok(XmlEvent::StartElement {
                   name,
                   attributes,
                   namespace,
               }) => {

                /* //test
                    let n: xml::namespace::Namespace = namespace;

                    if n.is_empty() {
                        println!("empty");
                    }else{
                        println!("no empty");
                    }
                    */

                let t: String = name.local_name;
                println!("{}", t);

                if name.prefix.is_some() == true {
                    println!("{}", name.prefix.clone().unwrap().clone());
                }
                if name.namespace.is_some() == true {
                    println!("{}", name.namespace.unwrap().clone());
                }

                if attributes.is_empty() == true {
                    //"test".to_string()
                } else {

                    for att in attributes {

                        //let tet: xml::name::OwnedName = att.name;
                        let temp_name_local_name = att.name.local_name.clone();
                        let temp_value = att.value.clone();

                        println!("{}+{}", temp_name_local_name, temp_value);

                        /* //test
                            if att.name.namespace.is_some() == true {
                                 println!("{}", att.name.namespace.unwrap().clone());
                            }
                            if att.name.prefix.is_some() == true {
                                 println!("{}", att.name.prefix.unwrap().clone());
                            }
                            */
                    }
                }
                depth += 1;
            }
            Ok(XmlEvent::ProcessingInstruction { name, data }) => {
                /* //test
                    if data.is_some() == true {
                        println!("{}", data.unwrap().clone());
                    }
                    println!("{}", name );
                    */
            }
            Ok(XmlEvent::EndElement { name }) => {
                //println!("{}-{}", indent(depth), name);
            }
            Err(e) => {
                //println!("Error: {}", e);
                break;
            }
            _ => {}
        }
    }
}

And my dependencies in Cargo.toml:
[dependencies]
xml-rs = "0.4"

A: As xml-rs is a pull parser, each structural part of an XML element is captured by multiple events, in this case of type XmlEvent. Namely, XmlEvent::StartElement is triggered after parsing an opening (or bodiless) XML tag, and provides the element's name, namespace and list of attributes.
On the other hand, XmlEvent::Characters captures text between XML tags. This is the event that is missing in your pattern matching.
In your case, this means that you must keep track of the last entered element in order to assign that text to the entry. One possible solution is to keep a mutable record and use it at the end of an element, where it will be complete.
let mut record = MyStruct { /* ... */ };

for e in parser {
    match e {
        Ok(XmlEvent::StartElement { name, attributes, namespace }) => {
           record.name = name;
           // ...
        }
        Ok(XmlEvent::Characters(text)) => {
            record.value = text; // or something else
        }
        Ok(XmlEvent::EndElement { .. }) => {
           // record is finished, use it or save it here
           // ...
        }
        // ...
    }
}

Ideally, you could build your own iterator type that abstracts XMLEvent away, and provides iteration over complete records. Here's an example from one of my projects.


text:
Q: WSO2 Custom Connector Build Failure by using apache-maven-3.8.4 I have tried to create custom connector by following this WSO2 Documentation
Prerequisites of apache-maven-3.8.4-bin installation done.
Connector:

maven build:

ERROR:

partial pom.xml:
<properties>
        <connector.name>googleBooks</connector.name>
        <integration.base.version>1.0.2</integration.base.version>
        <product.ei.version>6.1.1</product.ei.version>
        <carbon.kernel.version>4.4.17</carbon.kernel.version>
        <automation.framework.utils.version>4.4.2</automation.framework.utils.version>
        <automation.framework.version>4.4.3</automation.framework.version>
        <emma.version>2.1.5320</emma.version>
        <synapse.version>2.1.7-wso2v19</synapse.version>
        <carbon.mediation.version>4.6.19</carbon.mediation.version>
        <json.version>2.0.0.wso2v1</json.version>
        <org.testng.version>6.1.1</org.testng.version>
        <jets3t.version>0.9.4</jets3t.version>
        <bouncycastle.version>1.55</bouncycastle.version>
        <rampart.apache.version>1.6.1-wso2v18</rampart.apache.version>
        <rampart.wso2.version>1.6.1.wso2v18</rampart.wso2.version>
        <skip-tests>true</skip-tests>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.synapse</groupId>
            <artifactId>synapse-core</artifactId>
            <version>${synapse.version}</version>
        </dependency>

Note: synapse-core dependency is presented in above pom.xml
What tried so far:
As per this answer i tried to delete below mentioned folder and run mvn install which also not resolving issue.
.m2\repository\org\apache\synapse\synapse-core\2.1.7-wso2v19

Can anyone please let me know the solution to resolve this?

A: You need to change in pom.xml file, in the repository nodes, url adresses. You can use find/replace like below.
from: <url>http://maven.wso2....
to: <url>https://maven.wso2....
From the Maven 3.8.1, it is blocking http mirror repositories, and uses only https adreses. More in this Release Notes – Maven 3.8.1

redpajama_set_name: RedPajamaStackExchange


text:
Q: MvxTableViewCell not disposed I have a memory leaks issue.
I basically have a MvxTableViewController databound to a observablecollection.  I create a MvxTableViewController and add it to my Controller as a child and I add the view as a subviews.
Problem is, the Cell in the table never gets disposed, leaking memory.
// When the view gets removed from the stack, the cells disposed method is never called and I can see the memory not going away, using the Xcode Instruments tool.  The table dispose gets called as expected. but not the cell
public partial class ParticipantTableViewCell : MvxTableViewCell
{
    readonly UILabel _nameLabel = new UILabel();
    readonly UILabel _locationLabel = new UILabel();
    readonly PictureContainer _pictureView = new PictureContainer(7.0f);

    public ParticipantTableViewCell (IntPtr handle) : base(handle)
    {
        BackgroundColor = UIColor.Clear;
        SelectionStyle = UITableViewCellSelectionStyle.None;

        ContentView.AddSubviews(new UIView[] {_nameLabel, _locationLabel, _pictureView});
        _pictureView.TransparentBackground = true;

        SetupConstraints();

        // Since this view is readonly, I've removed the actual binding code
        // and instead manually init each views.
        this.DelayBind(() => {
            _nameLabel.Text = ((ParticipantViewModel)DataContext).Name;
            _locationLabel.Text = ((ParticipantViewModel)DataContext).Location;
            IsSelected = ((ParticipantViewModel)DataContext).IsSelected;
            _pictureView.AvatarImage.Image = UIImage.FromFile ("Media/" + ((ParticipantViewModel)DataContext).AvatarUrl);
        });
    }

    void SetupConstraints ()
    {
        ContentView.Subviews.ForEach(v => v.TranslatesAutoresizingMaskIntoConstraints = false);

        ContentView.AddConstraints(
            _pictureView.Height().EqualTo().HeightOf(ContentView),
            _pictureView.Width().EqualTo().HeightOf(ContentView),
            _pictureView.WithSameCenterY(ContentView),
            _pictureView.Left().EqualTo(6.0f).LeftOf(ContentView),

            _nameLabel.Left().EqualTo(10.0f).RightOf(_pictureView),
            _nameLabel.Right().EqualTo().RightOf(ContentView),
            _nameLabel.Bottom().EqualTo(2.0f).CenterYOf(ContentView),

            _locationLabel.Left().EqualTo(10.0f).RightOf(_pictureView),
            _locationLabel.Right().EqualTo().RightOf(ContentView),
            _locationLabel.Top().EqualTo(4.0f).CenterYOf(ContentView)

        );
    }

    // never called
    protected override void Dispose (bool disposing)
    {
        base.Dispose(disposing);
    }

}

    class FriendsView : MvxTableViewController
{
    protected new FriendsViewModel ViewModel { get { return (FriendsViewModel) base.ViewModel; } }

    public FriendsView ()
    {
    }

    public override void ViewDidLoad ()
    {
        base.ViewDidLoad();
        TableView.BackgroundColor = UIColor.Clear;
        TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
        TableView.RowHeight = 60;
        TableView.ScrollEnabled = false;

        var source = new MvxSimpleTableViewSource(TableView, typeof(ParticipantTableViewCell));
        TableView.Source = source;

        var set = this.CreateBindingSet<FriendsView, FriendsViewModel>();
        set.Bind(source).To(vm => vm.YuFitFriends);
        set.Apply();
    }
}

Anybody got an idea as to why my cells are leaking ?
thanks
pat

A: **// never called**
protected override void Dispose (bool disposing)
{
    base.Dispose(disposing);
}

Do you expect this will be called magically? NO!
Dispose is just a another method in your class which you should call when you don't want its instance anymore.
And also, you should dispose all the disposable instances in your class (eg: PictureContainer) in this Dispose method. Also, make sure you unsubscribe from any event subscriptions. Just calling base.Dispose doesn't release any reference in this class.

A: I got a working solution... The bugs seems to be with how MvvmCross register cells for reuse.  If I derive my own class from MvxBaseTableSource  instead of using MvxSimpleTableSource and I create the cells differently, I get everything to dispose properly:
class MySource : MvxTableViewSource
{
    public MySource (UITableView tableView) : base(tableView)
    {

    }

    protected override UITableViewCell GetOrCreateCellFor (UITableView tableView, NSIndexPath indexPath, object item)
    {
        var cell = tableView.DequeueReusableCell (ParticipantTableViewCell.Key) as ParticipantTableViewCell;
        if (cell == null)
            cell = new ParticipantTableViewCell ();

        return cell;
    }
}

and in my tableviewcontroller, I use MySource
    var source = new MySource(TableView);

Now everything gets collected fine!


text:
Q: How can I download deb from a PPA? How can I download deb package from a PPA?

A: Thanks to "A.B." - this is useful - an easier way is to just construct the URL from the PPA, so for ppa:inkscape.dev/stable
the URL is:
https://launchpad.net/~inkscape.dev/+archive/ubuntu/stable/+packages
This gives the list of packages where you can choose the package for your distribution.
You can do this with a script - example: create script ppa.sh containing:
echo $* | awk -F/ '{
    sub(".*ppa:","",$0)
    print "https://launchpad.net/~"$1"/+archive/ubuntu/"$2"/+packages"
    }'

Any of the following will then work:
./ppa.sh inkscape.dev/stable
./ppa.sh ppa:inkscape.dev/stable
./ppa.sh apt-add-repository ppa:inkscape.dev/stable
./ppa.sh sudo apt-add-repository ppa:inkscape.dev/stable

to give:
https://launchpad.net/~inkscape.dev/+archive/ubuntu/stable/+packages

A: This is an example to download a deb file.
This can be done. But it need not be, if you add a PPA to the system.
e.g.:
sudo apt-add-repository ppa:inkscape.dev/stable

But let's go on with the example of downloading.
Go to the PPA page, e.g. "Inkscape Developers" team

*

*Use the link eg. Inkscape Stable

*Use the link View package details

*Use the link eg. inkscape - 0.91.0+47~ubuntu15.04.1

*Use the link eg. inkscape_0.91.0+47~ubuntu15.04.1_amd64.deb

A: I just needed this too, but wanted an automated way to get the latest version of the .deb, without needing a browser every time.
Here's a full list of commands that you can put in a script and which always gets you the latest version .deb from the phpmyadmin ppa, whatever the latest version is at the time (replace nijel/phpmyadmin with the source of the ppa you're interested in):
sudo add-apt-repository -y ppa:nijel/phpmyadmin
sudo apt-get update
cd /tmp
apt-get download phpmyadmin
sudo add-apt-repository -y -r ppa:nijel/phpmyadmin
sudo apt-get update

You will then have some phpmyadmin*.deb file in /tmp. The above will add and then remove the phpmyadmin ppa source from your system. If you don't want it removed, then just comment the last two lines.


text:
Q: Is this map surjective? Let $B^1(\mathbb{R},\mathbb{R})$ be the set of all locally integrable functions $f:\mathbb{R}\to \mathbb{R}$ such that
$$\sup_{t\in \mathbb{R}} \int_t^{t+1}|f(x)|dx<\infty.$$
  Consider the map $A:B^1(\mathbb{R},\mathbb{R})\to L^\infty(\mathbb{R},L^1([0,1],\mathbb{R}))$ defined by
$$(Af)(t)(s)=f(t+s).$$
Is $A$ surjective ?

A: Certainly not. If $g$ is in the image of $A$, it has the property that $x\mapsto g(x)(1-x)$ is constant, which not all elements of $L^\infty(\mathbb R,L^1([0,1],\mathbb R))$ have


text:
Q: How to get MAX date for currency conversion across multiple periods using MDX Summary
I'm new to MDX but have been asked to enhance currency conversion
functionality in a cube. The problem itself seems simple.
For any given selected period, get the last date, and use that as the Reporting date for FX currency conversion.
For example, user selects periods Jan 2018 through to Oct 2018. The last date would be 31-Oct-2018.
The currency conversion is many to one reporting currency so we would take rates from the 31-Oct-2018.
Methods Tried
I have tried various methods to get the last date using:

*

*MAX (with and without existing)

*ClosingPeriod

*Separate FX Rate Measure Group and Date Dimension

These work fine if the user selects one period and the calculation is only for that period.
However the problem is that across multiple periods (think YTD or LTD calculations) then end rate is taken from each month.
For example, each line item here in the corresponding month would be converted using the rate at period value for that month (Jan 7.285) rather than using the Oct 2018 value of 7.027.
Period  | Rate at Period    | LastDate  | LastDateExisting
Jan 2018    | 7.285 | 20191231  | 20180131
Feb 2018    | 7.273 | 20191231  | 20180228
Mar 2018    | 7.275 | 20191231  | 20180331
Apr 2018    | 7.201 | 20191231  | 20180430
May 2018    | 7.146 | 20191231  | 20180531
Jun 2018    | 7.118 | 20191231  | 20180630
Jul 2018    | 7.116 | 20191231  | 20180731
Sep 2018    | 7.102 | 20191231  | 20180930
Oct 2018    | 7.027 | 20191231  | 20181031
Example Code
Here is an example of the MAX method I have found in various MDX cookbooks to get the last Date. I am assuming that due to the CurrentMember I am getting results per period. I realise this is normal MDX behaviour but due to the requirement would need to break this.
The MAX example without existing is the closest as it returns the same date but I am not sure if this can be filtered for the actual closing period easily?
WITH

MEMBER Measures.[LastDate] AS

MAX( [Accounting Date].[Year – Quarter – Month – Date].[Date].MEMBERS,
IIF( [Measures].[Rate at Period] = 0,
NULL,
[Accounting Date].[Year – Quarter – Month – Date].CurrentMember.Member_Key
)
)

MEMBER Measures.[LastDateExisting] AS

MAX( EXISTING [Accounting Date].[Year – Quarter – Month – Date].[Date].MEMBERS,
IIF( [Measures].[Rate at Period] = 0,
NULL,
[Accounting Date].[Year – Quarter – Month – Date].CurrentMember.Member_Key
)
)

Expected Results
I would like to see the last date column as all '20181031' as below.
Period  | Rate at Period (overridden)   | LastDate
Jan 2018    | 7.027 | 20181031
Feb 2018    | 7.027 | 20181031
Mar 2018    | 7.027 | 20181031
Apr 2018    | 7.027 | 20181031
May 2018    | 7.027 | 20181031
Jun 2018    | 7.027 | 20181031
Jul 2018    | 7.027 | 20181031
Sep 2018    | 7.027 | 20181031
Oct 2018    | 7.027 | 20181031
Any help appreciated and happy to provide more information should you need it.

A: Looks like you already figured this bit:
WITH
MEMBER Measures.[LastDate] AS
MAX(
  [Accounting Date].[Year – Quarter – Month – Date].[Date].MEMBERS,
  IIF(
     [Measures].[Rate at Period] = 0,
     NULL,
     [Accounting Date].[Year – Quarter – Month – Date].CURRENTMEMBER.MEMBER_KEY
   )
)

So to get the Rate at Period (overridden) you can just use the date you've found and make a measure using a tuple - only slight change is that you will need to add the LastDate member to a hierarchy other than Measures - you can take your pick: in our cubes I usually pick the Langauges hierarchy as it is hardly ever used:
WITH
MEMBER <OtherHierarchy>.[LastDate] AS
MAX(
  [Accounting Date].[Year – Quarter – Month – Date].[Date].MEMBERS,
  IIF(
     [Measures].[Rate at Period] = 0,
     NULL,
     [Accounting Date].[Year – Quarter – Month – Date].CURRENTMEMBER.MEMBER_KEY
   )
)
MEMBER Measures.[Rate at Period (overridden)] AS
(
  <OtherHierarchy>.[LastDate],
  [Measures].[Rate at Period]
)


text:
Q: How to compare two values which are structs but returned as interface I am really new with programming in Go and got stuck here.
I have a function A which creates a struct from 3 different values a, b, c.
func A() interface{} {
    s := new(struct{
        a, b, c int
    })
    //fill the values in s
    return s
}

Now when I am testing this function, how will I compare the returned interface with some expected result?
I cannot move the struct definition global
If someone have a better way of doing this type of testing, please suggest.

A: Although it's possible what you want, this comparison looks really "hackish", you should redesign to not require such comparison.
But let's see how to do it. Let A()'s implementation be like this:
func A() interface{} {
    return &struct {
        a, b, c int
    }{1, 2, 3}
}

If you want to compare the result, you have to first specify the value to compare to. One way is to use an anonymous struct:
got := A()
exp := struct {
    a, b, c int
}{1, 2, 3}

Now since A() returns a pointer (wrapped in an interface{}), you can't really compare that. Comparing pointers compares the pointer value, not the pointed value. So first we should get the pointed value. For that, we may use reflection:
gotNoptr := reflect.ValueOf(got).Elem().Interface()

Now we have 2 struct values, and they are comparable if all their fields are comparable (which is true in this case):
if gotNoptr == exp {
    fmt.Println("Match")
} else {
    fmt.Printf("Mismatch")
}

This will output (try it on the Go Playground):
Match

If you would change a number in the exp value, output would turn into Mismatch.
An alternate way would be to declare exp to be a pointer too:
exp := &struct {
    a, b, c int
}{1, 2, 3}

And use reflect.DeepEqual() to compare the pointed struct values:
if reflect.DeepEqual(got, exp) {
    fmt.Println("Match")
} else {
    fmt.Printf("Mismatch")
}

Try this one on the Go Playground.


text:
Q: Issue with saving RDD as a JSON file, considering that size of each RDD never exceeds 10 Mb I am reading DStream of JSON strings from Kafka using Spark Streaming. I need to save the input data on S3 in JSON format. This is the way I do it, however when the amount of data in batch is around 5Mb, it takes very long time to execute this code. Can it be optimized?
I need to save data in JSON files (*.json), because there is another program that uses these files and reads them as follows:
var df = sqlContext.read.json("s3n://" + bucketNameData + "/" + directoryS3 + "/*.json")
So, in order to save RDD as a sinlge JSON file, I tried rdd.map(lambda x :json.loads(x))
.coalesce(1, shuffle=True).saveAsTextFile('examples/src/main/resources/demo.json'), but it saves the data in a hadoopish way, and as far as I understand, I want be able to later read them as I shown above (to get df from json files). Therefore I switched to amazonS3Client, however I feel like it might be optimized. Maybe I should convert rdd to DataFrame or so, and then save it in some way as JSON?
val mySet = ssc.sparkContext.broadcast(Map("metadataBrokerList"->metadataBrokerList,
                                           "bucketNameData"->bucketNameData,
                                           "bucketNameCode"->bucketNameCode))

dstreamdata.foreachRDD(rdd => {
      if (!rdd.isEmpty()) {
      rdd.foreachPartition { iter =>
        val producer = UtilsTest.createProducer(mySet.value("metadataBrokerList"))
        val amazonS3Client = UtilsTest.createS3()
        iter.foreach { msg =>
          if (msg.nonEmpty) {
            // Save messages to S3
            val CONTENT_TYPE = "application/json"
            val fileContentBytes = msg.getBytes(StandardCharsets.UTF_8)
            val fileInputStream = new ByteArrayInputStream(fileContentBytes)
            val metadata = new ObjectMetadata()
            metadata.setContentType(CONTENT_TYPE)
            metadata.setContentLength(fileContentBytes.length)
            val datetime = Calendar.getInstance.getTime
            val formatter = new SimpleDateFormat("yyyy-MMM-dd-HH-mm-ss")
            val setID = formatter.format(datetime)
            val filePath = mySet.value("bucketNameData") + "/file_" + setID + ".json"
            val putObjectRequest = new PutObjectRequest(mySet.value("bucketNameData"), filePath, fileInputStream, metadata)
            amazonS3Client.putObject(putObjectRequest)

//---

A: your direct putObject() will be more efficient as there's no copy in the rename() normally used to commit work. You may have problems when dealing with failure and replay of work though.
If you do use newHadooopRDD, you can significantly reduce the overhead with commit algorithm 2:

spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version 2


text:
Q: Why is there a negative sign in the time evolution operator when defining in/out states? (Peskin/Schroeder) This relates to Peskin & Schroeder's QFT book, equation 4.70 on page 104.
To define in and out states we take our initial state and evolve it far into the past, and do the same for our final state. Peskin & Schroeder write this:
$$_{out}\langle p_1p_2...|k_\mathcal Ak_\mathcal B\rangle_{in}=\lim_{T\rightarrow \infty}\langle p_1p_2...|e^{-iH(2T)}|k_\mathcal A k_\mathcal B\rangle \tag{4.70},$$
in which the time evolution operator has a negative sign. However, in my attempt to explain this I have written the following:
$$|k_\mathcal Ak_\mathcal B\rangle_{in}=\lim_{T\rightarrow\infty}e^{iHT}|k_\mathcal Ak_\mathcal B\rangle,$$
since $U(T,0)=e^{-iHT}$ is the forward time evolution operator and $U(0,T)=e^{iHT}$ is the backward time evolution operator (or rather, the inverse), since we are evolving the initial state back to the far past this (perhaps naively) seems like the correct choice. I would then expect an analogous statement to hold for the out state, and combining the two would give:
$$_{out}\langle p_1p_2...|k_\mathcal Ak_\mathcal B\rangle_{in}=\lim_{T\rightarrow \infty}\langle p_1p_2...|e^{+iH(2T)}|k_\mathcal A k_\mathcal B\rangle,$$
in which there is a $+$ sign in the exponential. What have I done wrong?

A: The 'in' and 'out' states are the (asymptotically free) initial and final states of particals interacting at $t=t_0$:
$$|k_1k_2...\rangle_{in/out}=|k_1k_2...(t=\pm\infty)\rangle_{interacting}$$
The 'in' and 'out' states are independent on time, however the interacting states are not.
$$
|k_1k_2...(t)\rangle_{interacting} = e^{-iH(t-t_0)}|k_1k_2...(t_0)\rangle_{interacting}
$$
What we are interested in is e.g. an initial state $|k_1k_2...(t=-T)\rangle_{interacting}$ long before ($-T\ll t_0$) the particles in it interact with each other and we want to know how this states looks like long after ($T\gg t_0$) the interaction $|p_1p_2...(t=+T)\rangle_{interacting}$. The overlap is
$$
S_{fi} = \langle p_1p_2...(t_0)|k_1k_2...(t_0)\rangle =
\langle p_1p_2...(T)|e^{-iH2T}|k_1k_2...(-T)\rangle
$$
If we take the limit $T\rightarrow\infty$, we can relate these interacting states to the 'in' and 'out' states.
$$
S_{fi}\rightarrow {}_{out}\langle p_1p_2...|k_1k_2...\rangle_{in}
$$
The reason for wanting to relate the transition amplitude of interacting states to those of free states is, that we know the explicit form of the creation and annihilation operators only for free theories. Another important subtlety is that $a_{in}(p)\neq a_{out}(p)$, which means, that the overlap of the asymptotically free states does not simply produce a bunch of delta functions, but is instead more complicated and can be calculated e.g. using the LSZ reduction formula.


text:
Q: Double jQuery entry in wordpress file I have 2 jquery script tags on this page and I am trying to find where they are inserted from. I have located one which comes from header.php, but cannot find the second one. Is there a browser developer tool that could help me with this?

A: A browser developer toolbar will not tell you what WordPress item is asking for another jQuery script.
Often plugins and themes will want to include their own version...and it can cause conflicts.
The version of jQuery installed with your wordpress version is 1.10.2, and "something" is calling jQuery 1.8.2.
You may want to try removing the reference to 1.8.2 from your theme file (header.php)

A: Just try the following mini plugin:
<?php
/** Plugin Name: Debug Scripts */
add_action( 'wp_enqueue_scripts', function() {
    var_dump( current_filter(), $GLOBALS['wp_filters'], $GLOBALS['wp_scripts'] );
}, 999 );

This will tell you

*

*The name of the current filter (wp_enqueue_scripts)

*All registered filters

*All registered scripts

Then search for your script, search for the callback and then search for the plugin or theme causing it. You got all the tools.


text:
Q: PG::UndefinedTable - Next troubleshooting step? I've got a Rails app that works fine in development and testing, but in production, where it is configured to use a remote Postgresql database, it is failing to create its table. The database is setup and working. I can connect to it via psql as the app, from the production server, using the same configuration that I specify in my database.yml, and then I can create and query tables with commands, no problem.
When I execute database-related rake tasks, everything looks good:
$ rake db:reset
-- create_table("users", {:force=>true})
   -> 0.0293s
-- add_index("users", ["username"], {:name=>"index_users_on_username", :unique=>true})
   -> 0.0428s
-- initialize_schema_migrations_table()
   -> 0.0212s
-- create_table("users", {:force=>true})
   -> 0.0097s
-- add_index("users", ["username"], {:name=>"index_users_on_username", :unique=>true})
   -> 0.0058s
-- initialize_schema_migrations_table()
   -> 0.0092s

No errors. But the table has not been created.
I discovered this by investigating the Nginx error log, but the easiest way to reproduce the error is to fire up the console and do anything with with the app's only model:
$ rails console production
Loading production environment (Rails 4.2.0.beta4)
2.1.3 :001 > all_users = User.all
PG::UndefinedTable: ERROR:  relation "users" does not exist
LINE 1: SELECT "users".* FROM "users"
                          ^

I've also ssh'd into the database server and inspected the database  with \z, and it isn't there.
I think the app is connecting to the database server properly, because earlier I was getting permissions errors, and I resolved those. But I don't know how to make sure. And if I do confirm that I am connecting properly, where do I go from there?
Thanks!

A: Following mu's suggestion, I ran rake db:reset, explicitly specifying the environment.
rake db:reset RAILS_ENV=production --trace

This revealed the error at the heart of the problem:
PG::ObjectInUse: ERROR:  database "database_name" is being accessed by other users
DETAIL:  There are 1 other session(s) using the database.

I ssh'd to the database server, killed all active connections, and restarted the service.
Back on the web server, I reran the rake task above, and it worked.  Thanks mu and harmic!


text:
Q: How To Install APC Via Pecl
*

*here is the output im getting.
showing output  after running this command : pecl install apc
 downloading APC-3.1.13.tgz ...
 Starting to download APC-3.1.13.tgz (171,591 bytes)
   .....................................done: 171,591 bytes
  could not extract the package.xml file from "/build/buildd/php5-5.5.9+dfsg/pear-  build-download/APC-3.1.13.tgz"
  Download of "pecl/apc" succeeded, but it is not a valid package archive
  Error: cannot download "pecl/APC"
  Download failed
  install failed.

*

*I have to  install apc via cmd.

*problem  im facing is installation failure.

A: Try using the default system apc install:
sudo apt-get install php-apc

A: Here is how I install PHP APC:
Download latest stable Version
PHP APC-3.1.9 (stable) can be found on PECL page. Download and save (to desktop).
Begin installation
Untar APC, move into extracted directory
tar xvzf APC-3.1.9.tgz
cd APC-3.1.9/

Now, we want to phpize current directory. Because I use LAMPP PHP installation, its phpize is located in /opt/lampp/bin. Then, new .configure file will be created (your php-config may differ).
/opt/lampp/bin/phpize
./configure --with-php-config=/opt/lampp/bin/php-config

Then,
make
sudo make install

Configure php.ini file
Next, we want to configure APC for use. Edit your php.ini file. (mine was located in /opt/lampp/etc/php.ini).
vim /opt/lampp/etc/php.ini

Add these lines (preferably under Dynamic Extension section, but you can place it anywhere):
extension=apc.so
apc.enabled=1
apc.shm_size=40M
apc.ttl=7200
apc.user_ttl=7200
apc.enable_cli=1
apc.max_file_size=5M

also edit extension_dir on php.ini file
extension_dir = "/opt/lampp/lib/php/extensions/no-debug-non-zts-20100525/"

your extension_dir refers to make install result.
Now, look at phpinfo() page to verify your APC installation.
References:
Install guide


text:
Q: Webpack worker-loader silently fails on errors I'm using CRA to configure my projects, then eject and add whatever else I need. In this case I simply added worker-loader to module rules:
    {
      test: /\.worker\.js$/,
      loader: 'worker-loader'
    },

The problem is that if there are compilation errors in worker code, it still reports production build as successful, but the output folder only has a handful of files (development builds work fine). The only way to get error messages is to rename the worker script so it's imported as a regular module.
How do I get it to properly report errors?
Webpack 4.29.6, worker-loader 2.0.0.
If it matters, the errors come from eslint, which isn't aware of some worker-specific globals and requires comments to disable errors for specific lines.


text:
Q: Trouble with java vlcj 1.2.2 RTSP client example (Mac OSX 10.6) I'm trying to get their tutorial code running to connect to a rtsp stream from my webcam and display the feed on a JFrame.  I modified their example code to make a simple client rtsp viewer. When I specify the directory location in the playMedia method,  I can play mp3s, mpegs, avi's just fine.
e.g. mediaPlayerComponent.getMediaPlayer().playMedia("/Volumes/dl/The Lord Of The Rings - The Two Towers/The Lord Of The Rings - The Two Towers - Disc 1.mp4"); //works
When I enter a working RTSP mrl, it breaks.  It works in the VLC standalone application running live555.  With this client code, I just get a black screen.
    import uk.co.caprica.vlcj.binding.LibVlc;
    import uk.co.caprica.vlcj.runtime.RuntimeUtil;

    import com.sun.jna.Native;
    import com.sun.jna.NativeLibrary;
    import uk.co.caprica.vlcj.binding.LibVlc;
    import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
    import uk.co.caprica.vlcj.runtime.RuntimeUtil;
    import javax.swing.SwingUtilities;
    import com.sun.jna.NativeLibrary;
    import javax.swing.JFrame;
    import uk.co.caprica.vlcj.mrl.RtspMrl;

    public class Tutorial1B {

        private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
        public static void main(String[] args) {

            if (com.sun.jna.Platform.isMac()) {
                final String jnaLibraryPath = System.getProperty("jna.library.path");
                final StringBuilder newJnaLibraryPath = new StringBuilder(jnaLibraryPath != null ? (jnaLibraryPath + ":") : "");
                newJnaLibraryPath.append("/Users/Huy/Downloads/vlc-vlckit-x86_64-20120131-2049/VLCKit/VLCKit.framework/Versions/A/lib");
                System.setProperty("jna.library.path", newJnaLibraryPath.toString());
            }

            SwingUtilities.invokeLater(new Runnable() {
            @Override
             public void run() {
              new Tutorial1B();
             }
             });
            }

    private Tutorial1B() {
       JFrame frame = new JFrame("HUY vlcj");

       mediaPlayerComponent = new EmbeddedMediaPlayerComponent();

       frame.setContentPane(mediaPlayerComponent);

       frame.setLocation(100, 100);
       frame.setSize(1050, 600);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setVisible(true);
       String mrl = new RtspMrl().host("192.168.0.191")
                       .port(554)
                       .path("/live/ch01_0/")
                       .value();

    //mediaPlayerComponent.getMediaPlayer().playMedia("/Volumes/dl/The Lord Of The Rings - The Two Towers/The Lord Of The Rings - The Two Towers - Disc 1.mp4");
        mediaPlayerComponent.getMediaPlayer().playMedia(mrl);
       }
    }

I'm out of ideas, and I scoured this site and their tutorials for examples to no avail.  Thanks for the help!

A: Hi It is working well for me on Snow Leopard.
For the MRL you have to specify as @ee said.


text:
Q: How to hide savefiledialog box c# I want to save my pictures in silent. I mean without showing the save file box
here is save picture code.
string path = textBox1.Text.ToString();
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "jpg|*.jpg";
saveFileDialog1.InitialDirectory = path;
saveFileDialog1.AddExtension = false;
saveFileDialog1.FileName = fileName;
saveFileDialog1.OverwritePrompt = false;
saveFileDialog1.DefaultExt = ".jpg";
this.Invoke(new MethodInvoker(delegate ()
{
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
    Uri realLink = new Uri(link);
    WebClient wc = new WebClient();
    wc.DownloadFileAsync(realLink, saveFileDialog1.FileName);
  }
}));

A: From the code you posted it seems you already know the path and file name. So you can simply:
string destination = Path.Combine(textBox1.Text.ToString(), fileName);
Uri realLink = new Uri(link);
WebClient wc = new WebClient();
wc.DownloadFileAsync(realLink, destination);


text:
Q: PHP doesn't execute query after long processing I have a weird problem with a query that is not being executed under certain circumstances. I'm pretty sure that it's not a problem with they query itself, since I inserted a very simple query right before it, that can't be wrong but isn't executed as well.
Here's a short explanation of what this script does: The script is being executed by a cronjob every minute. It checks a list of uploaded PDF-files and splits them into separate files, if they haven't already been split, followed by a JPG-preview generation.
It works perfectly fine for average PDF-files. However uploading a large PDF-file (e.g. 30MB, 28 Pages), will make the script stop at some point for no reason (see inline comments). I have error_logged the PDF-splitting process ($pdf->process) and it works perfectly fine.
A friend suspected that this weird bug may be caused by insufficient memoryspace on the server or a reached maximum of connections to the database, but we both don't have much of a clue with those kind of things. Maybe one of you has?
ignore_user_abort(0);
set_time_limit(0);
error_reporting(-1);

if($_SERVER['SERVER_ADDR'] == '127.0.0.1')
    include_once("../config.php");
else
    include_once("/home/httpd/docs/myproject/inc/config.php");

include_once(ROOT."inc/db.class.php");
include_once(ROOT."inc/functions.php");
include_once(ROOT."inc/generate_previews.class.php");

$db = DB::getInstance();
$select_file_name_query = "SELECT * FROM z_tmp_preview_files WHERE id > '0' AND status = '0' AND file_name != ''";
$result = $db->query($select_file_name_query);

while($job_preview = $db->fetchNextObject($result)){

    $job_id = $job_preview->rel_job_id;
    $file = $job_preview->file_name;

    $set_inprocess_file_name_query = "UPDATE z_tmp_preview_files SET status = '1' WHERE id = '".$job_preview->id."'";
    $set_inprocess_file_name_result = $db->execute($set_inprocess_file_name_query);

    $file_info = explode('.',$file );
    $file_name = $file_info[0];
    $jpg_file = str_replace(".pdf", ".jpg", $file);

    // =======================================================================================
    // PDF-file is split into separate pages and JPG-previews are generated with the McPdf Class
    // This works just fine, even with very large files, but may take some minutes.
    // =======================================================================================
    $pdf = new McPdf($job_id);
    $pdf->process();

    $files_burst = LoadFiles("".ROOT."intern/jobs/".$job_id."/burst/");
    $page_count = sizeof($files_burst);

    error_log("\nTEST:",3,ERROR_DIR);
    $sql = "SELECT annotation_type FROM annotations";
    $value = $db->queryUniqueValue($sql);

    // =======================================================================================
    // This is where the PHP-script just stops. Non of the following error_logs are shown,
    // nor will the UPDATE-query be executed. The previous SELECT-query probably hasn't been executed as well.
    // =======================================================================================
    error_log($value,3,ERROR_DIR);

    $remove_file_name_query = "UPDATE z_tmp_preview_files SET status = '2' WHERE id = '".$job_preview->id."'";
    error_log("\n\ncheck query:",3,ERROR_DIR);
    error_log(" ".$remove_file_name_query,3,ERROR_DIR);
    $remove_file_name = $db->execute($remove_file_name_query);

    error_log("\npossible error:".$remove_file_name."\n",3,ERROR_DIR);
}

The db.class works just fine, I use it everywhere in my project, but if you're wondering what queryUniqueValue does, here's the code:
function queryUniqueValue($query, $debug = -1){
    $query = "$query LIMIT 1";

    $this->nbQueries++;
    $result = mysql_query($query) or $this->debugAndDie($query);
    $line = mysql_fetch_row($result);

    $this->debug($debug, $query, $result);

    return $line[0];
}

Edit: Here's another guess: Maybe this is some kind of mysql timeout? The problem only occurs, when the McPdf class takes a very long time to process. As far as I can tell, after executing $pdf-process() the first mysql-query will abort the execution of the PHP-script.

A: Maybe you're hitting PHPs "maximum script execution time" ? I believe it is set to 30secs by default. Try increasing the maximum execution time at the beginning of your script:
ini_set('max_execution_time',2*60); // will set it to 2 minutes

HTH


text:
Q: Getting DISTINCT values from 3 columns I have 1 single table with 3 columns say col1,col2,col3
VALUES:
col1 with values (in individual 3 rows) as a, b, c
col2 with values (in individual 3 rows) as b, c, d
col3 with values (in individual 3 rows) as c, d, e

AIM:
To get distinct list to populate in html drop down box (i.e i want a,b,c,d,e) in alphabetical order ?

A: Pseudocode:
Select col1 from table
UNION
Select col2 from table
UNION
Select col3 from table


text:
Q: Swift wrapper class I was watching a talk on swift optimization earlier and they were using an example of a struct with 5 variables 3 strings an array and a dictionary. They said to lower your reference count you could use a wrapper class. Can someone just make a dummy one to I might be able to understand it better.

A: A wrapper class would be used if you have performance issues with a struct which has many properties which are reference types.
A generic wrapper class:
class Wrapper<T> {
    var value: T // or "let" instead of "var"
    init(_ value: T) { self.value = value }
}

This is because if you assign it to another variable all pointers of the properties get copied and therefore all reference counts (see ARC) get incremented (and decremented at the end).
This problem mainly occurs when you are looping over large arrays of such structs where at each iteration a new variable gets created.
With a wrapper class only its reference count gets incremented and decremented once.
Example:
struct Big {
    // "n" properties which have reference semantics
    ...
    ...
}

// "m" count
let hugeArray = [Big(), Big(), Big(), ...]

// m * n reference count operations (+1, -1)
for element in hugeArray {
    // do something
}

// if huge array is of type [Wrapper<Big>]
// m * 1 reference count operations (+1, -1)
for element in hugeArray {
    // do something
}

Side note: Such a class could improve performance. Use it with care if you write to it, assign it or pass it as parameter since it "changes" the semantics of your wrapped type and is no value type.


text:
Q: Convert data frame with dummy variables into categorical variables I need to convert dummy into categorical variables. Being new to R i just know how to do it the other way round. Can someone point me in the right direction?
The dataframe is:
data <- data.frame(id=c(1,2,3,4,5,6,7,8,9),
               red=c("1","0","1","0","1","0","0","0","0"),
               blue=c("1","1","1","1","0","1","1","1","0"),
               yellow=c("0","0","0","0","0","0","0","1","1"))

and expected output is:

A: One option with lapply by ignoring the first column (id), we check which columns have value 1 in it and replace them with the corresponding column names and others can be changed to NA.
data[-1] <- lapply(names(data[-1]), function(x) ifelse(data[x] == 1, x, NA))

data
#  id  red blue yellow
#1  1  red blue   <NA>
#2  2 <NA> blue   <NA>
#3  3  red blue   <NA>
#4  4 <NA> blue   <NA>
#5  5  red <NA>   <NA>
#6  6 <NA> blue   <NA>
#7  7 <NA> blue   <NA>
#8  8 <NA> blue yellow
#9  9 <NA> <NA> yellow

Another approach without using lapply loop
data[-1] <- ifelse(data[-1] == 1, names(data[-1])[col(data[-1])], NA)

data
#  id  red blue yellow
#1  1  red blue   <NA>
#2  2 <NA> blue   <NA>
#3  3  red blue   <NA>
#4  4 <NA> blue   <NA>
#5  5  red <NA>   <NA>
#6  6 <NA> blue   <NA>
#7  7 <NA> blue   <NA>
#8  8 <NA> blue yellow
#9  9 <NA> <NA> yellow

A: As the 'red', 'blue', 'yellow' columns are factor, we coerce it to numeric and use the index to replace with the corresponding column names within Map
data[-1] <- Map(function(x, y) c('None', y)[as.numeric(x)],
                  data[-1], names(data)[-1])
names(data)[-1] <- paste0("c", 1:3)
data
#  id  c1   c2     c3
#1  1  red blue   None
#2  2 None blue   None
#3  3  red blue   None
#4  4 None blue   None
#5  5  red None   None
#6  6 None blue   None
#7  7 None blue   None
#8  8 None blue yellow
#9  9 None None yellow

Or another option by changing the levels
data[-1] <-  Map(function(x, y) {levels(x) <- c('None', y)
                    x},data[-1], names(data)[-1])

Or with lapply, we loop through the sequence of columns, extract the columns, change it to numeric, and use the index to change the values to column names and 'None'
data[-1] <- lapply(seq_along(data[-1]), function(i)
         c("None", names(data)[-1][i])[as.numeric(data[-1][[i]])] )

NOTE: Gives the expected output.

Or using a vectorized approach, we create a logical matrix, multiply with column index and change the index to column names
data[-1] <-  `dim<-`(names(data)[-1][col(data[-1]) *
                       (NA ^(data[-1] == 0))], dim(data[-1]))

Or another option with replace
data[-1] <- replace(as.matrix(data[-1]), data[-1]==1,
               rep(names(data)[-1], colSums(data[-1] == 1)))

Or using tidyverse
library(tidyverse)
imap(data[-1], ~ c('none', .y)[as.numeric(.x)]) %>%
         bind_cols(data[1], .) %>%
         rename_at(2:4, ~ paste0("c", 1:3))
#  id   c1   c2     c3
#1  1  red blue   none
#2  2 none blue   none
#3  3  red blue   none
#4  4 none blue   none
#5  5  red none   none
#6  6 none blue   none
#7  7 none blue   none
#8  8 none blue yellow
#9  9 none none yellow

Or with gather/spread
data %>%
    gather(key, val, -id) %>%
    mutate(val = case_when(val == 1 ~ key),
    key = factor(key, levels = unique(key), labels = paste0("c", 1:3))) %>%
    spread(key, val)

Benchmarks
Here are some benchmarks
data1 <- data[rep(seq_len(nrow(data)), 1e5),]
system.time({
  Map(function(x, y) c('None', y)[as.numeric(x)],
                   data1[-1], names(data1)[-1])

 })
#   user  system elapsed
#  0.065   0.014   0.078

system.time({
 `dim<-`(names(data1)[-1][col(data1[-1]) *
                       (NA ^(data1[-1] == 0))], dim(data1[-1]))

})
# user  system elapsed
#  0.387   0.036   0.422

system.time({
   imap(data1[-1], ~ c('none', .y)[as.numeric(.x)])
})
# user  system elapsed
# 0.047   0.006   0.054

 system.time({
   lapply(names(data1[-1]), function(x) ifelse(data1[x] == 1, x, NA))
  }
  )
 # user  system elapsed
 #  0.555   0.067   0.621

system.time({
    ifelse(data1[-1] == 1, names(data1[-1])[col(data1[-1])], NA)

  })
# user  system elapsed
#  0.711   0.060   0.770

On a 1e6 dataset
data1 <- data[rep(seq_len(nrow(data)), 1e6),]
system.time({Map( function(x, y) {levels(x) <- c('None', y)
              x},data1[-1], names(data1)[-1])})
#   user  system elapsed
#    0.123   0.016   0.139

system.time({
   Map(function(x, y) c('None', y)[as.numeric(x)],
                   data1[-1], names(data1)[-1])

  })
#   user  system elapsed
#  0.328   0.074   0.402
 system.time({
    lapply(names(data1[-1]), function(x) ifelse(data1[x] == 1, x, NA))
   }
   )
#   user  system elapsed
#  7.125   0.463   7.561

with microbenchmark
library(microbenchmark)
microbenchmark(ak = Map(function(x, y) c('None', y)[as.numeric(x)],
                 data1[-1], names(data1)[-1]),
         ak2 = Map( function(x, y) {levels(x) <- c('None', y); x},data1[-1], names(data1)[-1]),
          rs = lapply(names(data1[-1]), function(x) ifelse(data1[x] == 1, x, NA)), unit = 'relative', times = 10L)
#Unit: relative
#expr      min        lq      mean    median       uq      max nev
#ak  6.14964  4.048205  2.401768  1.741373  2.47268  2.43698    10
#ak2  1.00000  1.000000  1.000000  1.000000  1.00000  1.00000    10
#rs 70.73601 45.468868 23.020272 20.408306 18.63263 16.01278    10

data
data <- structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9), red = structure(c(2L,
1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L), .Label = c("0", "1"), class = "factor"),
blue = structure(c(2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L), .Label = c("0",
"1"), class = "factor"), yellow = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 2L, 2L), .Label = c("0", "1"), class = "factor")),
 class = "data.frame", row.names = c(NA,
-9L))

A: This perhaps?
library(tidyverse)

data <- data %>%
  mutate(red = case_when(
    red == 1 ~ "Red", red == 0 ~ "None")) %>%
  mutate(blue = case_when(
    blue == 1 ~ "Blue", blue == 0 ~ "None")) %>%
  mutate(yellow = case_when(
    yellow == 1 ~ "Yellow", yellow == 0 ~ "None"
))

data


text:
Q: Upgraded a retina SSD, now I get random crashes/shutdowns with code 3. Why? I recently upgraded an early-2015 13" Macbook Pro (A1502) from a 128GB SSD to a 256GB ssd. I used Carbon Copy Cloner to clone the original drive to an external 500GB, then booted off of that and cloned to the 256GB SSD.
Now, random shutdowns are happening, and upon logging back in I get a "you shut your computer down because of a problem" message.
The output of log show --predicate 'eventMessage contains "Previous shutdown cause"' --last 24h is as follows:

As you can see, I'm getting the shutdown cause of 3 consistently. With some research, I figured out this is the code for a "forced shutdown" (e.g. pressing and holding the power button), but it is crashing all by itself. It seems to happen consistently if I leave the laptop idle, and let it go to sleep. It seems to crash when it sleeps.
Where should I begin debugging this? Is my new SSD defective somehow? Or is this a software issue that could be fixed by reinstalling macOS? Is there anything I should check before I reinstall the OS?
Thanks for any help here!


text:
Q: Android - Send imageView to X Y position i have an imageView A that starts at right screen.
I want to set X and Y position programatically. To move the imageView near the top left corner, i have to set a X = -1497 Y = 20. What i dont understand is why X = -1497. I think because it tooks the (0,0) position where the imageView starts, but how to catch the (0,0) at top left screen?
This is because, for all screen i have to calculate a % to move the imageView to same place always, but how to do it with negative values.
Point origImagePos = new Point(-1460, 20);

public void moveImageView(View view){
  ObjectAnimator objectX;
  ObjectAnimator objectY;
  AnimatorSet animatorXY;

  objectX = ObjectAnimator.offFloat(view, "translationX", origImagePos.x);
  objectY = ObjectAnimator.offFloat(view, "translationY", origImagePos.y);
  animatorXY.playTogether(objectX, objectY);
  animatorXY.setDuration(500);
  animatorXY.start();
}

Greets

A: Actually you could cut most your code using ViewPropertyAnimator instead of ObjectAnimator.
public void moveImageView(View view){

    view.animate().translationX(0).translationY(0).setDuration(500);

}

thats all the code you need and should move your View to the top left corner.
You could always enhance your method for later animations like this for example  :
// You should also always use Interpolators for more realistic motion.

public void moveImageView(View view, float toX, float toY, int duration){

     view.animate()
        .setInterpolator(new AccelerateDecelerateInterpolator())
        .translationX(toX)
        .translationY(toY)
        .setDuration(duration);
}

and then call it like :
moveImageView(yourImageView, 0, 0, 500);

To get the coordinates of the device dynamically so you know where to move   :
float screenWidth = getResources().getDisplayMetrics().widthPixels;
float screenHeight = getResources().getDisplayMetrics().heightPixels;

screenWidth + screenHeight would be the coordinates of the right bottom corner.
Top Left corner coordinates are simply 0, 0.
Center of screen coordiantes are logically (screenWidth / 2) + (screenHeight / 2).
Hope that makes your life easier in the future.

A: translationX works relative to view. Try this,
objectX = ObjectAnimator.offFloat(view, "X", 20);
objectY = ObjectAnimator.offFloat(view, "Y", 20);


text:
Q: VB.Net MariaDB Sql Server i want to ask about Inserting data from my SqlDb into MariaDb. My trouble is when i success insert the data, i have double data with same TimeStamp and Status. i explain little about inserting process. Every one AWB have many Status Likes SD,AR,OD,UN,RT,UN,UN and OK. i have insert the data using windows services schedule. i make the schedule every 30 seconds. the trouble is every data that i have ever insert before into MariaDb always drawn again in database so there's a many double data about one AWB in database. how can i deny every data that has been insert before with same status and timestamp  cannot longer go into my MariaDB?
this my 'Select Query and Insert Code'
Private Sub getStatus()
    Try
        Dim con As New SqlConnection(DesktopGeneral.koneksiTTM)
        buka2(con)
        Querysend = "Declare @AWB as varchar(50) "
        Querysend += "Select @AWB=Pick_Cust.AWB from Pick_Cust inner join PICKUP_DETIL On Pick_Cust.TrNo=PICKUP_DETIL.TrNo where ComName LIKE '%Lazada%' "
        Querysend += "Select PICKUP_DETIL.AWB,PICKUP_DETIL.RefNo,PICKUP_DETIL.Date,PICKUP_DETIL.time,PICKUP_DETIL.Origin As Station,PICKUP_DETIL.CP2 As Status,'' as Recipient,'' as Relation,'' as Remarks,PICKUP_DETIL.Login,'' as ReasonCode,'' as ReasonNote,'Data Entry' as Comment from PICKUP_DETIL "
        Querysend += "inner join RECEIVED r on PICKUP_DETIL.AWB=r.AWB where pickup_Detil.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select PICKUP_DETIL.AWB,PICKUP_DETIL.RefNo,PICKUP_DETIL.PUdate as Date,PICKUP_DETIL.PUtime as Time,PICKUP_DETIL.Origin as Station,PICKUP_DETIL.CP as Status,'' as Recipient,'' as Relation,'' as Remarks, c.CouName,'' as ReasonCode,'' as ReasonNote,'Pick-Up' as Comment from PICKUP_DETIL "
        Querysend += "inner join COURIER c on PICKUP_DETIL.Pic=c.CouRoute where AWB=@AWB "
        Querysend += "union "
        Querysend += "Select BABY.AWB,p.RefNo,BABY.DATE,BABY.TIME,BABY.STN as Station,BABY.CP as Status,'' as Recipient,'' as Relation,BABY.BABY as Remarks,BABY.LOGIN,'' as ReasonCode,'' as ReasonNote,'Sotir Departement/Destination' as Comment from BABY "
        Querysend += "inner join PICKUP_DETIL p on BABY.AWB=p.AWB where baby.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select ARRIVAL.Code,p.RefNo,CONVERT(char(10),arrival.Date,120) as Date,CONVERT(char(5),arrival.Date,114) as Time,STN as Station,arrival.CP as Status,'' as Recipient,'' as  Relation,'' as Remarks, arrival.PIC,'' as ReasonCode,'' as ReasonNote,'Arrival at Destination HUB' as Comment from ARRIVAL "
        Querysend += "inner join PICKUP_DETIL p on ARRIVAL.Code=p.AWB where code=@AWB "
        Querysend += "union "
        Querysend += "Select DELIVERY.AWB,p.RefNo,CONVERT(char(10),delivery.Date,120) as Date,CONVERT(char(5),delivery.Date,114) as Time, STN as Station,delivery.CP as Status,'' as Recipient,'' as Relation,'Kurir:' +COURIER.CouName + '.Note:'+Note + ' Cycle:'+CYCLE as Remarks,delivery.PIC,'' as ReasonCode,'' as ReasonNote,'On Delivery' as Comment from Delivery "
        Querysend += "inner join COURIER on DELIVERY.CouRoute=COURIER.CouRoute inner join PICKUP_DETIL p on DELIVERY.AWB=p.AWB where delivery.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select UNDELIVERED.AWB,pd.RefNo,CONVERT(char(10),undelivered.date,120) as Date,CONVERT(char(5),undelivered.date,114) as Time,STN as Station,undelivered.CP as Status,'' as Recipient,'' as Relation,Note+'>' as Remarks,c.CouName,Other as ReasonCode,a.Remarks as ReasonNote,'Undelivered' as Comment from UNDELIVERED "
        Querysend += "inner join COURIER c on UNDELIVERED.PIC=c.CouRoute inner join RMK_RET a on UNDELIVERED.Other=a.Code inner join PICKUP_DETIL pd on UNDELIVERED.AWB=pd.AWB where undelivered.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select RECEIVED.AWB,pd.RefNo,CONVERT(char(10),received.Date,120) as Date,CONVERT(char(5),received.Date,114) as Time,STN as Station,received.CP as Status,Recipient as Recipient,Relation as Relation,Note as Remarks,received.PIC,'' as ReasonCode,'' as ReasonNote,'Delivery Success' as Comment from RECEIVED "
        Querysend += "inner join PICKUP_DETIL pd on RECEIVED.AWB=pd.AWB where received.AWB=@AWB "
        Querysend += "union "
        Querysend += "Select [RETURN].AWB,pd.RefNo,CONVERT(char(10),[return].date,120) as Date,CONVERT(char(5),[return].date,114) as Time,STN as Station,[return].CP as Status,'' as Recipient,'' as Relation,Note as Remarks,[return].PIC,returnCode as ReasonCode,a.Remarks as ReasonNote,'Return Shipper' as Comment from [RETURN] "
        Querysend += "inner join RMK_RET a on [RETURN].returnCode=a.Code inner join PICKUP_DETIL pd on [RETURN].AWB=pd.AWB where [return].AWB=@AWB "
        Dim ds As New DataSet
        Dim cmd As New SqlCommand(Querysend, con)
        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds, "joe")
        tutup2(con)

        If ds.Tables(0).Rows.Count > 0 Then
            Dim cn As New MySqlConnection(DesktopGeneral.koneksiAPI)
            buka(cn)
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Querysend = "Insert into api_status(AWB,TrackingNumber,Status,TimeStamp,Comment,Station,Recipient,Relation,ReasonCode,ReasonNote,Attempt,Username,RequestID,Flag) "
                Querysend += "VALUES(@AWB,@TrackingNumber,@Status,@TimeStamp,@Comment,@Station,@Recipient,@Relation,@ReasonCode,@ReasonNote,@Attempt,@Username,@RequestID,@Flag) "
                Dim mycmd As New MySqlCommand(Querysend, cn)
                mycmd.Parameters.Add("AWB", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("AWB").ToString
                mycmd.Parameters.Add("TrackingNumber", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("Refno").ToString
                mycmd.Parameters.Add("Status", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("Status").ToString
                mycmd.Parameters.Add("TimeStamp", MySqlDbType.DateTime).Value = CDate(ds.Tables(0).Rows(i).Item("Date").ToString).ToString("yyyy-MM-dd") & " " & ds.Tables(0).Rows(i).Item("Time").ToString
                mycmd.Parameters.Add("Comment", MySqlDbType.VarChar, 100).Value = ds.Tables(0).Rows(i).Item("Comment").ToString
                mycmd.Parameters.Add("Station", MySqlDbType.VarChar, 50).Value = ds.Tables(0).Rows(i).Item("Station").ToString
                mycmd.Parameters.Add("Recipient", MySqlDbType.VarChar, 150).Value = ds.Tables(0).Rows(i).Item("Recipient").ToString
                mycmd.Parameters.Add("Relation", MySqlDbType.VarChar, 10).Value = ds.Tables(0).Rows(i).Item("Relation").ToString
                mycmd.Parameters.Add("ReasonCode", MySqlDbType.VarChar, 10).Value = ds.Tables(0).Rows(i).Item("ReasonCode").ToString
                mycmd.Parameters.Add("ReasonNote", MySqlDbType.VarChar, 100).Value = ds.Tables(0).Rows(i).Item("ReasonNote").ToString
                mycmd.Parameters.Add("Attempt", MySqlDbType.Int16).Value = 1
                mycmd.Parameters.Add("Username", MySqlDbType.VarChar, 50).Value = "Joe"
                mycmd.Parameters.Add("RequestID", MySqlDbType.VarChar, 50).Value = ""
                mycmd.Parameters.Add("Flag", MySqlDbType.Int16).Value = 0
                mycmd.ExecuteNonQuery()
                mycmd.Dispose()
            Next
            tutup(cn)
        End If
    Catch ex As Exception
        Dim err As String
        err = ex.Message
    End Try
End Sub

Please Help. Thank You before :)

A: Use except statement at the last in the Querysend string like
except
select AWB,TrackingNumber,Station,Status,CONVERT(char(10),TimeStamp,120) as
Date,CONVERT(char(5),TimeStamp,114) as Time,Station,Status,Recipient,Relation,
ReasonCode,ReasonNote,Comment from [MariaDb].[dbo].[api_status] where AWB=@AWB

You can link the server using sp_addlinkedserver() if it is from a different server
http://msdn.microsoft.com/en-us/library/ms190479.aspx
Example:
exec sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
[ , [ @provider= ] 'provider_name' ]
[ , [ @datasrc= ] 'data_source' ]
[ , [ @location= ] 'location' ]
[ , [ @provstr= ] 'provider_string' ]
[ , [ @catalog= ] 'catalog' ]

then
to use your MariaDb Table [server].[MariaDb].[dbo].[api_status]


text:
Q: Youtube Upload Code suddenly prompt Credential Exception I wrote a program to upload our racing videos continuously (loop through every five minutes to see whether a video is finished upload, if finished then start upload another race video)
It all works fine and just from yesterday, it suddenly give a credential exception. First I though it might be the google blocked me cause I uploaded too many videos?
So I tried our testing google account use the program to upload one video and it comes with the same error again?
Some body know anything might go wrong? To me the code is absolutely fine, It works for nearly a year and no body touched it.
I'm confused!
Crash point is --> call service.setUserCredentials( username, the_password)
Java exception thrown: com.google.gdata.client.GoogleService$InvalidCredentialsE
xception: Invalid credentials.

A: It magically works today. I still don't know why, I think its google's problem down there end, so if anybody met this problem in the future, don't panic, go home and have tea, try tomorrow~~~


text:
Q: После использования tqdm пропадает символ После использования tqdm прогресс бара пропадает первый символ выведенный в консоль. Как исправить это?
И как реализовать такое условие:
pbar = tqdm(total=len(data))
for item in data:
    pbar.update(1)

# как проверить завершился прогресс бар или нет
if pbar == 100% или завершен

UDP:Пример с пропаданием символа на каждой итерации:
import tqdm
from time import sleep
list = [1,2,3]
for i in tqdm.tqdm(list, 'Test'):
    sleep(1)
    print(str(i))

print("Result")

В данном примере, вывода внутри цикла не будет, так как он состоит из одного символа, который исчезает чудесным образом.
Но обычно, у меня пропадает символ после всех итераций. В данном примере у меня пропала бы буква "R". Если получится, постараюсь привести пример

A: Насчёт символа не понял, покажите пример. А проверку на 100% можно сделать например так:
from tqdm.auto import tqdm

data = range(1000)

with tqdm(total=len(data)) as pbar:
    for item in data:
        pbar.update(1)

if pbar.n == len(data):
    print('100%')

Только нужно не забывать делать pbar.close() и лучше с помощью with ....


text:
Q: What is the syntax for accessing PHP object properties? How do you access a PHP object's properties?
Also, what is the difference between accessing an object's property with
$this->$property1 vs. $this->property1?
When I try to use $this->$property1 I get the following error:

'PHP: Cannot access empty property'.

PHP's documentation on object properties has one comment which mentions this, but the comment doesn't really explain in depth.

A: *

*$property1 // specific variable

*$this->property1 // specific attribute

The general use on classes is without "$" otherwise you are calling a variable called $property1 that could take any value.
Example:
class X {
  public $property1 = 'Value 1';
  public $property2 = 'Value 2';
}
$property1 = 'property2';  //Name of attribute 2
$x_object = new X();
echo $x_object->property1; //Return 'Value 1'
echo $x_object->$property1; //Return 'Value 2'

A: property1 is a string while $property1 is a variable. So when accessing $this->$property1 PHP looks for contents of the variable named $property1 and because it (probably) doesn't exist it's empty so that's why you get the Cannot access empty property error.

A: $this->property1 means:
use the object and get the variable property1 bound to this object
$this->$property1 means:
evaluate the string $property1 and use the result to get the variable named by $property1 result bound to this object


text:
Q: UPS configuraton -- master/slave I recently bought a Eaton 5PX1500RTN UPS(1440VA/1440W) with a Network-MS card. I connected it via ethernet and can now see the Web UI for Eaton. This thread here gave me confidence that the UPS would work via the network instead of using the USB or Serial cable/driver. Now comes the part where I configure it with FreeNAS and pfSense router in order for it to gracefully shutdown in case of a power outage.
I want to achieve the following in case of a power outage:

*

*60 seconds into the power outage -- initiate graceful shut down of Main NAS and backup NAS.

*Keep the pfSense router, unmanaged switch, modem and DD-WRT Access Point running until the battery is 5% remaining. At that point, gracefully shut everything down including the UPS.

Given what I want to achieve, here are some questions I have:

*

*Do I still need to connect the "control cable" (usb or serial) even though the UPS has a network card and is visible on my network?

*Should I make FreeNAS as the master or pfSense as the Master?

*What is the advantage of making FreeNAS as master or vice-a-versa?

*In what order would a device shut down if it is a master vs a slave?

*Since my switch is a dumb switch, I believe that when the UPS shuts down at 5% battery, the switch and modem will just die due to lack of power and I am ok with that. However can the DD-WRT access point be configured to shutdown gracefully?

Note: all of the devices listed are connected to a PDU which is connected to the UPS.


text:
Q: Cannot disable CompactStrings Java 9 using Netbeans I am trying to disable the CompactStrings feature of Java 9 using the VM option: -XX:-CompactStrings, but it does not work.
When I tried to debug my application, the COMPACT_STRINGS variable in String class is always true (with or without the VM option)
I have the latest version of Java 9: jdk-9+181
And the Netbeans IDE Build 201709070001
I tried various options to set the VM option and none of them works.
What I tried is:
setting the VM option in app.conf, setting it in project.properties, running netbeans by ./netbeans -XX:-CompactStrings, setting the JVM option in Project->Properties->Run->VM Options

Is this a bug in Netbeans? Or am I doing something wrong?

A: I tried to reproduce your problem using a trivial "Hello World" Java application. However, toggling the CompactStrings feature in the project properties settings worked fine for me, and caused COMPACT_STRINGS to be set appropriately, so this is not a bug in NetBeans.
Although I am using the same version of Java (181) as you, I have a more recent Dev Build of NetBeans (Build 201709220002), and there are several discrepancies between my project properties screen and yours. For example, mine shows the Runtime Platform field but yours does not:

Something else to check is that you really do have the environment you expect. I find it easy to mess things up when multiple versions of Java and Netbeans are installed.
This is what I see when I do Help -> About:

If your environment looks fine then I can only suggest that you download the latest DEV Build of NetBeans and try again.


text:
Q: How do I set it so that everyone uses the /bin/bash shell? It doesn't seem to work for some reason if I do this in /etc/profile:
export SHELL="/bin/bash/"

A: The chsh $USER command changes users' shell.
If you want to change them all at once, you can modify the /etc/passwd file.
You don't want a trailing slash when attempting to execute a binary file.

A: To set the default shell when you create a new user, it depends how you create new users. For useradd in Linux (Ubuntu, at least), edit /etc/default/useradd and change the SHELL variable.

A: I'm not sure if it's universal across Linux distros, but in most Unix implementations the file /etc/shells lists the shells that users can choose from.  So if you don't want the users to be able to use chsh to change to something else, make sure bash is the only shell listed there.


text:
Q: Getting multiple errors when trying to use Prepared statements in PHP/MySQL I am trying to use prepared statements as a best practice but I keep getting these errors.
1) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES (?, ?, ?, ?, ?,?, ?, ?, ?, ?)'
2) Undefined index: finalExamGrade in C:\wamp64 (this goes for all the superglobal variables)
3) Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\
Any fixes? Ideas?
PHP/MySQL
 require_once("DBCONNECT.php");
    $id = $_REQUEST['studentID'];
    $last = $_REQUEST['lastName'];
    $first = $_REQUEST['firstName'];
    $grade1 = $_REQUEST['test1Grade'];
    $grade2 = $_REQUEST['test2Grade'];
    $grade3 = $_REQUEST['test3Grade'];
    $grade4 = $_REQUEST['test4Grade'];
    $final = $_REQUEST['finalExamGrade'];

    $stmt = $connect->prepare("SELECT * FROM students) VALUES (?, ?, ?, ?, ?,?, ?)");
    $stmt->bind_param("issiiiii", $id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);

    $stmt->execute();

    var_dump($id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);

    $stmt->close();
    $connect->close();

A: $stmt = $connect->prepare("SELECT * FROM students) VALUES (?, ?, ?, ?, ?,?, ?)");

The above code is the root of all of your problem.

*

*You use SELECT to insert data. It should be INSERT.

*There is an extra bracket after students table.

*The total parameters doesn't match with the bind_param one. There are 7 ?
in your code when you want to store 8 variables.

Change into this code
$stmt = $connect->prepare("INSERT INTO students(col1, col2, col3, col4, col5, col6, col7, col8) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("issiiiii", $id, $last, $first, $grade1, $grade2, $grade3, $grade4, $final);

I don't explain this code any further because it has been discussed on comments.


text:
Q: Ruby algorithm solving So I have a basic problem that needs to be solved. I need to take the following nested array [1, 2, ["str", 1], [[2]]] and return [1,2,"str",1,2]. Ultimately removing all nested arrays. The following is my incomplete solution:
test = [1, 2, ["str", 1], [[2]]]

def remove_array(array)
    new_array = []
    array.each do |item|
        if item != Array
            puts "you are here"
            new_array << item
        else
            remove_array(item)
        end
    end
end

remove_array(test)

This is a classic recursion method. However, I cant seem to think of how to maintain new_array. Every time I pass the item that is an array to it, new_array doesn't maintain its state. I would also like to point out that I am aware of the built in method flatten as I am trying to solve the solution without said method. Any advice would be greatly appreciated.

A: def my_flatten(arr)
  result = []

  arr.each do |el|
    if el.is_a?(Array)
      result.concat(my_flatten(el))
    else
      result << el
    end
  end

  result
end

You generally had the right idea, but you were never adding the inner array elements into your result.

A: def remove_array(array)
  new_array = []
  array.each do |e|
    if e.is_a?(Array)
      new_array += remove_array(e)
    else
      new_array << e
    end
  end
  new_array
end

A: In Ruby, there is a convenient built-in method called flatten
It will "flatten" your array so that all the inside arrays disappear, and it returns one array with all elements inside
Edit:
Sorry editing this. Forgot that you were using recursion for your solution. Since you're essentially creating a new array each recursion, I'm not exactly sure how I would fix your solution at this moment.

A: You can call flatten on you array.
a = [1, 2, ["str", 1], [[2]]]
=> [1, 2, ["str", 1], [[2]]]
   a.flatten
=> [1, 2, "str", 1, 2]

A: just use the flatten! :) keep it simple..
test = [1, 2, ["str", 1], [[2]]]

def remove_array(array)
   array.flatten!
   return array
end

remove_array(test)

2.2.1 :024 >   remove_array(test)
=> [1, 2, "str", 1, 2]

I hope this helps everybody! Thanks


text:
Q: django error in my code ,what does i do from django.core.management import setup_environ
from register2 import settings
setup_environ(settings)

from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import ugettext_lazy as _

class AuthenticationRememberMeForm ( AuthenticationForm ):

            """
            Subclass of Django ``AuthenticationForm`` which adds a remember me checkbox.

            """

            remember_me = forms.BooleanField (
                label = _( 'Remember Me' ),
                initial = False,
                required = False,
                )

print AuthenticationRememberMeForm.remember_me

Traceback (most recent call last):
  File "D:\zjm_code\register2\b.py", line 26, in <module>
    print AuthenticationRememberMeForm['remember_me']
TypeError: 'DeclarativeFieldsMetaclass' object is unsubscriptable

A: The django forms module uses a metaclass to facilitate declarative syntax for form fields. As a consequence, you should consider remember_me to be a field of your form instance, not a class attribute. So accessing the field as so makes sense:
form = AuthenticationRememberMeForm()
field_obj = form.fields['remember_me']

or, similarly, the value:
form = AuthenticationRememberMeForm(data)
if form.is_valid():
    remember_me_value = form.cleaned_data['remember_me']

Obviously, django.forms is doing a bit of work behind the scenes to make this happen. If you want to understand how, check out the relevant code. If you just want to make your forms work, try to follow the usage outlined in the docs.


text:
Q: Why is the Lanczos method only good for solving the extremal eigenvalues? It is a folklore that the Lanczos method is good for looking for the smallest or largest few eigenvalues, but not useful for looking for those in the middle of the spectrum. Actually, this seems a general rule for many similar algorithms, like the Davidson method.
Is there any general reason for this general limitation?

A: In general Krylov-subspace methods such as the Lanczos method yield an approximation of the "dominant space" of a matrix, i.e. you approximate the largest or smallest eigenvectors. The advantage of this method is that the computation of a small number of eigenvectors (compared to the size of the matrix) is much cheaper than computing a factorization of the matrix. For many applications the computation of the largest or smallest eigenvalues is sufficient.
It is not possible to directly approximate the middle of the spectrum using Lanczos method. If you would want to approximate the middle of the spectrum with the Lanczos method, you would need to approximate a "dominant space", which contains approximations for all eigenvectors from the largest/smallest up to the ones in the middle, i.e. more than $n/2$ for a $n \times n$ matrix. This is not efficient any more and might lead to numerical instabilities.
If you can estimate a value close the the middle eigenvalue, you can use the inverse iteration to compute the eigenvalues closest to a prescribed value. Otherwise, you will have to compute at least half of the eigenvalues, which might be very expensive.
In the latter case, it might be better to directly compute all eigenvalues using a suitable algorithm (see https://en.wikipedia.org/wiki/List_of_numerical_analysis_topics#Eigenvalue_algorithms). These direct eigensolvers typically involve computing a tridiagonal form or Schur decomposition, from which you obtain the eigenvalues (see also https://en.wikipedia.org/wiki/Eigenvalue_algorithm).

To better understand why most algorithms compute the largest or smallest eigenvalue, it might be good to start by looking at the power method. By computing $A^kx$ for $k\to \infty$ you obtain an approximation of the largest eigenvalue. In Krylov methods you project your matrix onto the Krylov-subspace $\{ x, Ax, A^2x, A^3x, A^4x, \dots\}$. By construction this subspace tends to contain approximately the larger eigenvectors.
To get the smallest eigenvalue you compute $A^{-k}x$ which is related to the Krylov-subspace $\{ x, A^{-1}x,A^{-2}x,\dots\}$.
You can not directly builds a Krylov-subspace for the middle eigenvalues.


text:
Q: Companion object cannot access private variable on the class A rather weird behavior coming from the Scala REPL.
Although the following compiles without a problem:
class CompanionObjectTest {
    private val x = 3
}
object CompanionObjectTest {
    def testMethod(y:CompanionObjectTest) = y.x + 3
}

the private variable does not seem to be accessible from the companion object in REPL:
scala> class CompanionObjectTest {
     |
     | private val x = 3;
     | }
defined class CompanionObjectTest

scala> object CompanionObjectTest {
     |
     | def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
<console>:9: error: value x in class CompanionObjectTest cannot be accessed in CompanionObjectTest
       def testMethod(y:CompanionObjectTest) = y.x + 3
                                                 ^

Why is that happening?

A: This is indeed a little weird. To work around this problem, you should enter paste mode first with :paste, then define your class and your companion object and exit paste mode with CTRL-D. Here is a sample REPL session:
Welcome to Scala version 2.9.0.1 (OpenJDK Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class A { private val x = 0 }
object A { def foo = (new A).x }

// Exiting paste mode, now interpreting.

defined class A
defined module A

scala>

A: What is happening is that each "line" on REPL is actually placed in a different package, so the class and the object do not become companions. You can solve this in a few ways:
Make chain class and object definitions:
scala> class CompanionObjectTest {
     |   private val x = 3;
     | }; object CompanionObjectTest {
     |   def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
defined class CompanionObjectTest
defined module CompanionObjectTest

Use paste mode:
scala> :paste
// Entering paste mode (ctrl-D to finish)

class CompanionObjectTest {
    private val x = 3
}
object CompanionObjectTest {
    def testMethod(y:CompanionObjectTest) = y.x + 3
}

// Exiting paste mode, now interpreting.

defined class CompanionObjectTest
defined module CompanionObjectTest

Put everything inside an object:
scala> object T {
     | class CompanionObjectTest {
     |     private val x = 3
     | }
     | object CompanionObjectTest {
     |     def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
     | }
defined module T

scala> import T._
import T._


text:
Q: Inheriting istream operator>> I have a function in class PhoneNumber:
class PhoneNumber
{
protected:
    int area;
    long number;
public:
    istream& operator>>(istream& is, PhoneNumber &p){
        cout << "Enter area code : ";
        is >> p.area;
        cout << "Enter number telephone number : ";
        is >> p.number;
        return is;
    }
};

and another function in class like this :
class IntPhoneNumber::public PhoneNumber
{
    int reg;
    public
    friend istream& operator>>(istream& is, IntPhoneNumber &p);
};

I want class IntPhoneNumber to inherit and use operator>> in class PhoneNumber.

A: A nicely scalable way of doing this is to delegate from operator>> to a virtual member function of PhoneNumber, and then provide overloads in derived classes - which can call back into the parent class if they wish.
class PhoneNumber {
protected:
    int area;
    long number;
public:
  friend istream& operator>>(istream& is, PhoneNumber &p);

  virtual void getFromStream(istream& is) {
        cout << "Enter area code : ";
        is >> area;
        cout << "Enter number telephone number : ";
        is >> number;
  }
};

istream& operator>>(istream& is, PhoneNumber &p) {
   p.getFromStream(is);
}

Now you can overload like this:
class IntPhoneNumber::public PhoneNumber {
    int reg;
    virtual void getFromStream(istream& is) {
      PhoneNumber.getFromStream(is);
      cout << "Enter reg :";
      is >> reg;
    }
};

A: First you have to declare your extractor as friend:
class PhoneNumber
{
protected:
    int area;
    long number;
public:
    ...
    friend istream& operator>>(istream& is, PhoneNumber &p);
};

You then defined operator>> outside of the class:
istream& operator>>(istream& is, PhoneNumber &p)
{
        cout << "Enter area code : ";
        is >> p.area;
        cout << "Enter number telephone number : ";
        is >> p.number;
        return is;

};

Now with this construct already, you could use the same operator>> for the derived IntPhoneNumber, if you wouldn't care for the region code:
struct IntPhoneNumber:public PhoneNumber
{
protected:
    int reg;
public:
    ...
};

This code will compile and handle IntPhoneNumber exactly as PhoneNumber:
PhoneNumber n;
cout<< "Request phone number"<<endl;
cin >> n;
cout<< "Request phone int number"<<endl;
IntPhoneNumber ni;
cin>>ni;

Now if you would like to override operator>> for IntPhoneNumber, but reuse what you've already written for PhoneNumber, it's not a problem either.  Just define another friend and use casting:
class IntPhoneNumber:public PhoneNumber
{
protected:
    int reg;
public:
    ...
    friend istream& operator>>(istream& is, IntPhoneNumber &p);
};

istream& operator>>(istream& is, IntPhoneNumber &p)
{
    cout << "Enter area code : ";  // do the specific
    is >> p.reg;
    return is >> static_cast<PhoneNumber&>(p);  // and call the general one
};

Here a live demo on ideone applying this for input and output.
Remark: It's ok for a proof of concept.  But normally for an extractor overload (i.e. operator>>) you shouldn't display on cout:  if the same extractor would be used for reading data from a file, the screen would be submerged by messages for the user and the reading operation would be slowed down.  This is why I've added some if (is==cin) in the live demo.


text:
Q: "IDs do not match" error when extracting raster values at SpatialLines I want to extract a raster's values where a spatialLines object crosses its cells, and am hitting an error. This illustrates:
> require(maptools); require(raster)
> data(wrld_simpl)
> nepal = as(wrld_simpl[wrld_simpl$NAME == 'Nepal',], 'SpatialLines')
> r = raster(volcano)
> extent(r) = c(79,90,26,31)
> plot(r); plot(nepal, col='red', add=T)

The extraction:
> border_values = extract(r, nepal, sp=T, fun=median)
Error in SpatialLinesDataFrame(y, res[, -1, drop = FALSE]) :
  row.names of data and Lines IDs do not match

Any idea what's causing this?  My raster package is v2.5-8.

A: That is a bug that needs to be fixed in the raster package, but here is a work around:
row.names(nepal) <- '1'
border_values <- extract(r, nepal, sp=TRUE, fun=median, match.ID=FALSE)

or more generally, (if you have multiple features)
row.names(nepal) <- as.character(1:length(nepal))


text:
Q: Apparently inconsistent segmentation fault? WARNING: I know I'm not giving any context to this code, and in general this is extremely necessary, but I think that due to the nature of the error/situation it's not necessary and it would unnecessarily obscure things. That being said, if you suggest me to edit the question to add context and definitions to my code, I will of course do it.
In the following code
    Person *root = list[0];
    Element start = {root, NULL};
    Stack Q = {&start};
    i = 0;
    Element *next_elem = NULL;
    Element *first = NULL;
    int cn;
    Person *p = NULL;
    puts("Starting stack process...");
    while(Q.start != NULL)
    {   // process the first element, look at their info and children
        printf("Name: %s\n", Q.start ->prsn ->name);
        cn = Q.start ->prsn ->cn;
        printf("Nº of children: %i\n", cn);
        // look at their children and put them in the stack
        first = Q.start;

        for(i = 0; i < cn; i++)
        {   if((next_elem = (Element*)malloc(sizeof(Element))) == NULL) return 1;
            next_elem ->prsn = first ->prsn ->children[i];
            first -> next = next_elem;
            first = next_elem;
        }
        Q.start = Q.start -> next;
    }

I get the following error
Process 5864 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x30)
    frame #0: 0x0000000100000de0 GTree_DFS`main at GTree_DFS.c:101:32
   98           first = Q.start;
   99           for(i = 0; i < cn; i++)
   100          {   if((next_elem = (Element*)malloc(sizeof(Element))) == NULL) return 1;
-> 101              next_elem ->prsn = first ->prsn ->children[i];
   102              first -> next = next_elem;
   103              first = next_elem;
   104          }
Target 0: (GTree_DFS) stopped.

Which is solved by changing the for loop condition from  i < cn to  i < cn - 1. So this should mean that the problem is that I'm going out of bounds right? Well no, because if I modify the code adding a line like p = first ->prsn ->children[3]; before the for loop, it does not raise any error:
Process 5897 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x30)
    frame #0: 0x0000000100000ddf GTree_DFS`main at GTree_DFS.c:101:32
   98           p = first ->prsn ->children[3]; // No segfault here
   99           for(i = 0; i < cn; i++)
   100          {   if((next_elem = (Element*)malloc(sizeof(Element))) == NULL) return 1;
-> 101              next_elem ->prsn = first ->prsn ->children[i]; // Segfault here
   102              first -> next = next_elem;
   103              first = next_elem;
   104          }
Target 0: (GTree_DFS) stopped.

If the segfault is not due to the i index, then why would the change i < cnto  i < cn - 1 solve it? Isn't this error inconsistent?

A: I may be completely confused but the loop seems wrong.
You allocate next_elem in line 100,
and it seems to have a member which is
a pointer, called prsn
But during allocation, that pointer has no value, so during the next pass through the loop
it will be used     (look at line 101, LHS) via the first variable, which leads to unpredictable results...


text:
Q: ajax response: unexpected non-whitespace character after JSON data I send an ajax request with jquery like this:
 $.post("ajax/myFile.php", {
    myValue: "test"
    }, function(response) {
      console.log($.parseJSON(response))
    })

content of myFile.php
myFunctionA();
myFunctionB();

function myFunctionA() {
   echo json_encode(array('error' => 0, 'message' => "Hello World"));
}

function myFunctionB() {
    echo json_encode(array('error' => 0, 'message' => "Hello again"));
}

my console.log result:
Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 44 of the JSON data

how can I handle this? :/

A: You can't return multiple JSON values from your script. You need to combine them into a single value.
echo json_encode([myFunctionA(), myFunctionB()]);

function myFunctionA() {
   return array('error' => 0, 'message' => "Hello World");
}

function myFunctionB() {
    return array('error' => 0, 'message' => "Hello again");
}

This will return both results as elements of an array in JavaScript.


text:
Q: Pycharm : conditionally run integration test In Pycharm, I would like to conditionally run integration tests, but always run unit tests.
Integration tests are named like this: itest_<module name>.py.
Unit tests are named like this: test_<module name>.py

Can this be accomplished with some kind of run / debug configuration or some other configuration / code trick?

A: the way that I handled this was that I named tests as test_ and integration tests as itest_.  Then I used discovery with the pattern *test_.


text:
Q: analytical geometry We have an affine coordinate system and $3$ points given: $A=(1,0,0)$, $B=(0,1,0)$, $C=(0,0,1)$, $D=(1,1,1)$. I have to find a linear transformation, which depicts the points $A$, $B$, $C$ and $D$ accordingly into $B$, $C$, $A$ and $D$.

A: Besides observing that you need a permutation matrix, another option is to write your matrix $\mathbf{A} = \left[\begin{array}{ccc} a_{11} & a_{12} & a_{13} \\ a_{21} & a_{22} & a_{23} \\ a_{31} & a_{32} & a_{33} \end{array}\right]$ explicitly, and use the given data.
Using the fact that you should map your point $A$ to point $B$, you get
$\mathbf{A}\left[\begin{array}{c} 1 \\ 0 \\ 0\end{array}\right] = \left[\begin{array}{c} 0 \\ 1 \\ 0\end{array}\right]$
or equivalently,
$a_{11} = 0$, $a_{21} = 1$, $a_{31} = 0$.
Now use the rest of the data to find the other entries.


text:
Q: Error sharing directory /etc/prometheus Docker Desktop for mac I'm trying to build a docker stack in portainer with this compose file:
version: '3'

volumes:
  prometheus-data:
    driver: local
  grafana-data:
    driver: local

services:
  prometheus:
    image: prom/prometheus:latest
    container_name: prometheus2
    ports:
      - "9090:9090"
    volumes:
      - /etc/prometheus:/etc/prometheus
      - prometheus-data:/prometheus
    restart: unless-stopped
    command:
      - "--config.file=/etc/prometheus/prometheus.yml"

  grafana:
    image: grafana/grafana:latest
    container_name: grafana2
    ports:
      - "3001:3001"
    volumes:
      - grafana-data:/var/lib/grafana
    restart: unless-stopped

  node_exporter:
    image: quay.io/prometheus/node-exporter:latest
    container_name: node_exporter
    command:
      - '--path.rootfs=/host'
    pid: host
    restart: unless-stopped
    volumes:
      - '/:/host:ro,rslave'

I had no issues with it in Linux, but i'm trying to build it on my mac m2.
I'm getting an error that the path /etc/prometheus/ is not shared from OSX (I'm using legacy osxfs, but i've tried in virtioFS as well.).
I have the entire drive shared (bad practice, I know) but it still access that directory. The directory exists and I have the prometheus.yml in it.
screenshots:
https://imgur.com/a/vWZN8Ad
anyone run into this issue with docker desktop and know how to fix it? I've tried sharing both /etc/prometheus and /private/etc/prometheus and it still cant access it.**
I've tried changing the file system from VirtioFS to osxfs and still get the same error


text:
Q: ORA-00933: SQL command not properly ended (When trying to generate a table query, then ordering it by date) So I'm reuploading this question (as I have a new format now)
The new code:
SELECT * FROM "Sales Orders"
ORDER BY "EMPLOYEE_LASTNAME" DESC;
SELECT "SALES_ORDER_NUMBER","SALES_ORDER_DATE", "EMPLOYEE_LASTNAME",
"DELIVERY_DUE_DATE", "DELIVERY_CHARGE" FROM "Sales Orders"
WHERE "SALES_ORDER_DATE" BETWEEN '05/09/2016' AND '12-12-2016';
The code works separately, but not together (and I can't figure out why).
The error message

A: In your second Insert statement for DELIVERY_DUE_DATE single quotes is missing
INSERT INTO "Sales Orders" ("SALES_ORDER_NUMBER", "SALES_ORDER_DATE", "EMPLOYEE_IDENTIFIER", "DELIVERY_DUE_DATE", "DELIVERY_CHARGE")
VALUES (1000175110, '12-12-2016', '1', '01-12-2017', 8);
                                     --^here


text:
Q: How do I insert the first line of one file into the first line of another? I've got a head command to get the first line of a file and a sed command to insert before the first line of a file. How do I combine these so I can insert the extracted first line of one file before the first line of another file.
Get first line of a file
head -n 1 file_to_get_first_line_from

Insert before first line
sed -i '1 i\insert_this_in_the_first_line' file_to_intert_into

A: If your file_to_insert_into does not end with trailing newline:
$ cat <<IN > file_to_insert_into
$(head -n1 file_to_get_first_line_from; cat file_to_insert_into)
IN

A: The most portable way to do this is by using POSIX specified features of ex.
$ cat file1
Jack and Jill
Went up the hill
To fetch a pail of water.

$ cat file2
Nursery Rhymes:
Epic Poems:
Classic Literature:

$ printf '%s\n' '0r !head -n 1 file2' x | ex file1

$ cat file1
Nursery Rhymes:
Jack and Jill
Went up the hill
To fetch a pail of water.

*

*printf is used to send commands to ex.

*0 is the address given to the read command; it tells ex to read in the specified text "after line 0" (i.e. before line 1).

*!head -n 1 file2 means that instead of reading text directly from a file (a whole file), the head command is executed first and its output is read in (at the specified position, line 0).

*x means save and exit.
This is fully POSIX compliant and portable.

If you were scripting this it would be good practice to check your assumptions: That file2 exists and is readable, and that file1 is readable and writable if it exists.
if [ -r file2 ] && [ -f file2 ] && { ! [ -e file1 ] || { [ -r file1 ] && [ -w file1 ];};}; then
  printf '%s\n' '0r !head -n 1 file2' x | ex file1
fi

A: Updated: Thanks to @Wildcard for pointing out GNU Sed difference
BSD sed
Try on your terminal:
sed -i '' "1i\
$(head -n 1 file_to_get_first_line_from)" file_to_insert_into

*

*This means start typing sed -i '' "1i\, then hit enter to continue the rest of the command

Explanation

*

*Helps combine your two original commands via Bash command substitution $( ). Replaces whatever bash commands are inside $( ), with its output

*We change ' literal quotes to " quotes in order to allow Bash to act while still using quotes for sed to properly see one sed command

GNU sed
Or if you have GNU sed:
sed -i "1i $(head -n 1 file_to_get_first_line_from)" file_to_insert_into

*

*Tested with sed (GNU sed) 4.2.2. To see your sed version: sed --version

*GNU sed can omit the \ and newline. info sed, under sed Programs, Common Commands:

As a GNU extension, if between the 'a' and the newline there is other than a whitespace-'\' sequence, then the text of this line, starting at the first non-whitespace character after the 'a', is taken as the first line of the TEXT block.  (This enables a simplification in scripting a one-line add.)  This extension also works with the 'i' and 'c' commands.

Additional info

*

*Optionally, there is a shorter version of the head command: head -1. However info head claims this is a obsolete option syntax -[NUM]... that head supports, and recommends for "standard hosts" to use the -n NUM syntax instead, so we can just continue to use your original head -n 1 syntax here

A: With Vim and head:
vim -Nesc '0r !head -n1 file_to_get_first_line_from' +wq file_to_insert_into

*

*-Nes starts no-compatible, silent, ex-mode, which is useful when you want to script tasks with Vim.

*-c '0r !<cmd>' inserts the output of the command <cmd> before the first line. The command here is, of course, the head command.

*+wq saves and closes the file.


text:
Q: msal angular get a picture of the user I'm using with azure/msal-angular Library. and I'm trying to get a picture of the user profile.
This is me code in app.module.ts
MsalModule.forRoot( new PublicClientApplication({
  auth: {
    clientId: 'xxx',
    authority: 'https://login.microsoftonline.com/xxx/',
    redirectUri: 'http://localhost:4200',
  },
  cache: {
    cacheLocation: 'localStorage',
    storeAuthStateInCookie: isIE,
  }
}), {
  interactionType: InteractionType.Redirect,
  authRequest: {
    scopes: ['user.read']
    }
}, {
  interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
  protectedResourceMap: new Map([
      ['https://graph.microsoft.com/v1.0/me', ['user.read']],
  ])
})


text:
Q: How to display wordpress login form on index.html home page? I have an existing HTML website. And then Wordpress installed on a separate folder. Wordpress has login, and content .. How can I display the Wordpress login form on my main index.HTML page ? and so once logged in from home, it would redirect to the Wordpress logged in sections ???

A: You should be using an index.php instead of an index.html file. That will allow you to use WordPress functions outside of WordPress. That would then allow you to put <?php wp_login_form(); ?> wherever you want the form to go.
Otherwise you'll have to copy the HTML output of the current login form and paste it into the html file.


text:
Q: Is there any way to make this flat array more compact? I'm sure there is some way to make it shorter:
someObj.array1
  .map((item) => item.array2)
  .flat()
  .map((item) => item.array3)
  .flat()
  .map((item) => item.array4)
  .flat();

A: You could take a recursive approach by handing over the initial array and the wanted keys.
function flat(array, [key, ...rest]) {
    return key
        ? flat(array.map(item => item[key]).flat(), rest)
        : array;
}

console.log(flat(someObj.array1, ['array2', 'array3', 'array4']));


text:
Q: Give an Example of diffeomorphism from unit circle to plane without circle.
Give an Example of diffeomorphism from  circle to plane without
  circle.

Any Ideas?

A: You could try $(x,y) \to (1/(x+101),1/(y+101))
.$ Then each coordinate of image is positive and at most $1/100$ so image strictly inside unit circle.
Added: A much simpler map is $(x,y) \to (rx,ry)$ where $r$ is positive and not $1.$ That maps the unit circle $x^2+y^2=1$ to the concentric (distinct) circle $x^2+y^2=r^2.$


text:
Q: When does a static variable is really initialized I have a Java class:
Class A {
  static Object a = new Object();
  Object getObject() {
    return a;
  }
}

In above code. I want to ask when object a is really initialized. I have two answers for my question:

*

*When Java program is started. a will automatically initialize, although we will never use it.

*the very first time we call getObject(). So, I think this will be more optimize.
I don't know which really true behind the scene.

A: When the JVM loads class A, it executes "static" block of code and initializes static variables as well.


text:
Q: AttributeError: 'NoneType' object has no attribute 'group' problem hello guys i have a problem with my code this isn't running:
from napalm import get_network_driver

driver = get_network_driver('ios')
device = driver('192.168.112.130', 'abc', '123')
device.open()

device.load_merge_candidate(filename='IOSConfig.txt')
print(device.compare_config())

if len(device.compare_config()) > 0:
    choice = input('\nWould you like commit these changes? [y/n]: ')
    if choice == 'y':
        print('Committing ...')
        device.commit_config()
    else:
        print('Discarding ...')
        device.discard_config()
else:
    print('No difference')

# close the session with the device.
device.close()
print('Done.')

and the error is:
AttributeError: 'NoneType' object has no attribute 'group'

A: Script is okay , but you need to make sure your cisco device must have real flash and should be enable with SCP server. In Simulation sometime cisco image doesn't have flash.
Try below with router which have flash. Make sure you have user credentials in place already.
!
aaa new-model
!
!
aaa authentication login default local
aaa authorization exec default local
!
ip scp server enable
!
archive
path flash0:
Script will do below task so your router
CMD: 'terminal width 511' 19:23:52 UTC Fri Sep 3 2021
CMD: 'terminal length 0' 19:23:52 UTC Fri Sep 3 2021
CMD: 'dir' 19:23:52 UTC Fri Sep 3 2021
CMD: 'dir flash0:' 19:23:52 UTC Fri Sep 3 2021
CMD: 'dir flash0:/merge_config.txt' 19:23:53 UTC Fri Sep 3 2021
CMD: 'verify /md5 flash0:/merge_config.txt' 19:23:53 UTC Fri Sep 3 2021
CMD: 'show archive config incremental-diffs flash0:/merge_config.txt ignorecase' 19:23:53 UTC Fri Sep 3 2021