Q:

Unexpected namespace prefix xmnls found for tag RelativeLayout

    ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"   //here's the error
    tools:context=".MainActivity4" >

<android.support.v4.view.ViewPager
      android:id="@+id/view_pager"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

<RelativeLayout
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Divisoria"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/divisoria" />

        <TextView
            android:id="@+id/TextView02"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Divisoria is a bargain hunter’s haven. Filipinos visit Divisoria all year round to scour each nook for great bargain finds and to buy needed business supplies in bulk. The crowd gets heavier come Christmastime, especially when most of the streets in the place are converted into Night Market areas. For those who seek a cooler shopping place, malls such as 168 Mall, Meisic Mall, and Divisoria Mall are available."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView03"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Location: Recto Ave, Tondo, Manila, Metro Manila"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView04"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Quiapo Church"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/quiapo" />

        <TextView
            android:id="@+id/TextView05"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Pinoy private drivers are often advised not to use Quiapo’s main thoroughfares on a Friday. Devotees of the Black Nazarene fill the area around Quiapo Church to hear mass and seek the services of fortune tellers and herbal medicine peddlers. Aside from this, the whole stretch of R. Hidalgo Street is packed with shoppers buying from its many street vendors and legitimate establishments."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView06"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Quiapo Location: Quiapo Church, Quezon Boulevard, Manila, Metro Manila- Quipo"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView07"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Ongpin Street"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/ongpin" />

        <TextView
            android:id="@+id/TextView08"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Ongpin Street is where Pinoys and Tsinoys troop to find anything Chinese, as it is found in Chinatown itself. The ten-block-long street is rich in jewelry shops selling high-carat gold, as well as Chinese fast food joints, hardware shops, and Chinese herbal drugstores. Its close proximity to Divisoria and Quiapo makes it a favorite shopping destination come Christmas gift-buying season."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView09"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Ongpin Location: Ongpin St, Manila, Metro Manila"
            android:textSize="30px" />

         <TextView
            android:id="@+id/TextView10"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Intramuros"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/intramuros" />

        <TextView
            android:id="@+id/TextView1"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Intramuros, the Walled City, is the oldest district of Manila and is rich in culture and tradition. Spanish-era churches, convents, schools, and other old buildings speak of historical value. Presently, the district is maintained by the Intramuros Administration Office. The agency oversees the maintenance and operation of the place and its many museums."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView12"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Intramuros Location: Intramuros, Manila, Metro Manila"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView13"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Rizal Park"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/rizalpark" />

        <TextView
            android:id="@+id/TextView14"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Rizal Park, also called the Luneta, is located next to Intramuros. It was built as a tribute to the national hero, Dr. Jose Rizal, who was shot in the same place in 1896. The park is divided into the Agrifina Circle along Taft Avenue, the 22-hectare park covering the block in between Taft Avenue and Roxas Boulevard, and the Quirino Grandstand fronting Manila Bay. On normal days, visitors crowd the place to relax or visit the smaller areas such as the Orchidarium and Butterfly Pavilion. During special events, Quirino Grandstand transforms into a theater with a sea of people facing it."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView15"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Rizal Park Location: Rizal Park, Roxas Blvd Ermita, Barangay 666 Zone 72, Manila, 1000 Metro Manila, Philippines"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView16"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Manila Baywalk"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/baywalk" />

        <TextView
            android:id="@+id/TextView17"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="The Manila Baywalk is the long stretch of beautifully paved and lighted sidewalks covering the area between the US Embassy and the Cultural Center of the Philippines. In the morning, the area is often full of joggers, walkers, and bicycle riders going through their exercise routines. As the sun sets, people stop and sit by the benches or on the sea wall to appreciate the sight."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView18"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Manila Baywalk Location: Manila Baywalk, Roxas Blvd, Malate, Manila, Metro Manila"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView19"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Malate"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/malate" />

        <TextView
            android:id="@+id/TextView20"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Malate is another spot in Manila that is rich in history. During the American Period, Malate was developed as a prime residential spot for American families, which accounts for the proliferation of buildings displaying American architecture. Present-day Malate is known for its colorful nightlife. Night clubs and bars are situated along M. H. del Pilar, Mabini, M. Adriatico, and Remedios to cater to those in search of a fun night out."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView21"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Malate Location: Malate, Manila, 1004 Metro Manila"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView22"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Manila Zoo"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView8"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/manilazoo" />

        <TextView
            android:id="@+id/TextView23"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="On 25 July 1959, the Manila Zoo was opened to the public to serve as a venue for educational trips geared towards discovering the Philippines’ various flora and fauna. The zoo covers 5.5 hectares of land and has a population of over 500 animals. Aside from viewing the animals in the zoo, visitors also get to enjoy the place’s souvenir shop and playground, and may rent a boatin order to go on the lagoon."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView24"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Manila Zoo Location: Manila Zoological and Botanical Garden, Adriatico Street, Malate, Manila, Metro Manila"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView25"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Manila Ocean Park"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView9"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/oceanpark" />

        <TextView
            android:id="@+id/TextView26"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="The Manila Ocean Park is an oceanarium in Manila, Philippines. It is owned by China Oceanis Philippines Inc., a subsidiary of China Oceanis Inc., a Singaporean-registered firm that has operated four oceanariums in China. It is located behind the Quirino Grandstand at Rizal Park. It opened on March 1, 2008. In terms of floor space, the 8,000 square metres (86,000 sq ft) oceanarium is larger than the Sentosa Underwater World oceanarium in Singapore, and features a 25-metre (82 ft) underwater acrylic tunnel."
        android:textSize="30px" />

        <TextView
            android:id="@+id/TextView27"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Manila Ocean Park Location: Manila Ocean Park, 666, Behind Quirino Grandstand, Luneta, Manila, Metro Manila 1000"
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView28"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Avenida Rizal"
            android:textSize="30px" />

        <ImageView
            android:id="@+id/imageView10"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/avenidarizal" />

        <TextView
            android:id="@+id/TextView29"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Rizal Avenue also known as 'Avenida' or 'Avenida Rizal; is one of Manila's main thoroughfares. Named after the national hero José Rizal, it is a part of Radial Road 9 (R-9). The LRTA's LRT Line 1 elevated railroad is built above the street in its entire length, and several jeepneys ply the area taking passengers from Caloocan and Quezon City. Most of the street is within the Sta. Cruz district."
            android:textSize="30px" />

        <TextView
            android:id="@+id/TextView30"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dip"
            android:text="Avenida Rizal Location: Genesis Avenida, Doroteo Jose Street, Santa Cruz, Manila, Metro Manila"
            android:textSize="30px" />
             </LinearLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>

A:

Your ScrollView/> tag is not well formed.
You should add a <.


Q:

Partial Layout in Rails 3.0.0

I have a collection of partials being rendered using a layout for each element (wrapping in a container). However, when rendering the collection, an outer 'container' is also added (it appears to be adde to each render, despite no layout being specified.
Example:
# index.html.erb
<%= render :partial => 'sprockets' %>

# _sprockets.html.erb
<%= render :partial => 'sprocket', :layout => 'container' %>
<%= render :partial => 'sprocket', :layout => 'container' %>
<%= render :partial => 'sprocket', :layout => 'container' %>

# _sprocket.html.erb
...

# _container.html.erb

<%= yield %>

Gives:

    ...

    ...

    ...

I seem to remember being able to do this in Rails 2.3.8. Note the above is a simplification of my code (I'd like to keep the layouts and multi-partial format).  Any ideas what I'm doing wrong? Thank!

A:

You are probably exploiting a quirk in ActionView. To the best of my knowledge, layouts are not meant to be used with partials like that. My guess is, every time you do :layout => 'container', it sets the same instance variable. Since ActionView renders partials inside-out (innermost partial gets rendered first), the last used value for :layout also gets used higher up the chain.
Maybe doing something like
# index.html.erb
<%= render :partial => 'sprockets', :layout => false %>

will help.
Still I'd say this is not a proper way to get the results you want.


Q:

Instagram Auth Broken?

We just noticed that our app which relies on Instagram as the primary login is no longer working. In investigating this further, it appears the callback URL for Instagram stopped working. Now whenever anyone logs in via Instagram or signs up via Instagram, they are taken to the Instagram app instead of being asked to authenticate or taken into our app experience.
I checked another app that I know if, called "Print Studio" and the same thing is happening to them.
Is this issue happening to anyone else? Any clue as to what is causing it and has anyone heard from Instagram on a possible fix?

A:

Yes. seems to effect all applications (at least the apps that are using the approved 3rd party API). I saw this issue few days ago and it got resolved by itself. I assume Instagram engineers are rolling some updates and broke something.
I suggest reporting an issue from the developer portal. https://www.instagram.com/developer/clients/manage/. as many reports as they receive, the better.
UPDATE:
The issue seems to be related to cookies / session persistent changes made on Instagram side.
To workaround the issue, redirect the user to the original auth url when you detect the user got to the Instagram homepage. Because the user is already logged in, this should pass the user to the correct redirect url without logging in again.
for example, in swift:
  // MARK: - WKNavigationDelegate
  override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

   if let urlString = navigationAction.request.url?.absoluteString {

     if urlString == "https://instagram.com" || urlString == "https://instagram.com/" ||
      urlString == "https://www.instagram.com" || urlString == "https://www.instagram.com/" ||
      urlString == "http://instagram.com" || urlString == "http://instagram.com/" ||
      urlString == "http://www.instagram.com" || urlString == "http://www.instagram.com/" {

        decisionHandler(.cancel)
        self.refresh(nil) // reloads the original auth url
        return
      }
    }

    super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)
  }


Q:

Has the Occupy Wall Street movement had significant influence on policy?

In September 2011 and onwards, Occupy Wall Street and its many spinoffs occupied squares all over the world. The meetings shared some degree of dissatisfaction with present systems, but clear aims were not really formulated, nor were there any clear leaders.
Now, we are more than a year further, and the question is: has anything changed? Apart from initiating limited debate on the financial system and related issues (for example, it triggered me to move part of my savings to an ethical credit union), has the Occupy movement had any lasting political influence?
For example, from this Huffington Post article: Rep. Peter King (R-N.Y.) said:

"[W]e have to be careful not to allow this to get any legitimacy," he warned. "I'm taking this seriously in that I'm old enough to remember what happened in the 1960s when the left-wing took to the streets and somehow the media glorified them and it ended up shaping policy," he said. "We can't allow that to happen."

Indeed, the civil rights movement in the 1960's did influence policy. Is there any evidence that Occupy Wall Street has shaped any policy?

A:

In a purely subjective way, based on my impressions from several visits to the NYC site, I do not think the various OWS happenings changed the minds of a significant number of people. In most instances, there were more curious onlookers and gawkers than actual occupiers. The occupiers did not seem to have coherent agendas. They seemed more to be gathering places for barely connected islands of opinion.
People who were already inclined to think that somehow, somewhere, someone owes them some money did not change their opinion. People who did not think that a sociology major with a concentration of revolutionary organizing was going to pay for $200K in student loans were not impressed.
They did form useful props for politicians who already espoused or supported similar views in the first place.


Q:

DataContractJsonSerializer parse boolean string

I'm working on a wp7 app and I have a function that sends an http web request to the server and the server returns a json string as a response. Suppose the string is like this:
{"products" :
[
{"PRODUCT_ID" : "1", "PRODUCT_NAME" : "product1","IS_PAID" : "F"},
{"PRODUCT_ID" : "30","PRODUCT_NAME" : "product2","IS_PAID" : "T"},
{"PRODUCT_ID" : "36","PRODUCT_NAME" : "product3","IS_PAID" : "F"}
]}

and my product class is like this:
[DataContract]
public class Product
{
    [DataMember(Name = "PRODUCT_ID")]
    public long productId { get; set; }

    [DataMember(Name = "PRODUCT_NAME")]
    public string productName { get; set; }

    [DataMember(Name = "IS_PAID")]
    public bool isPaid { get; set; }
}

in my code, when I'm trying to parse the json response:
DataContractJsonSerializer serailizer = new DataContractJsonSerializer(typeof(Product[]));
MemoryStream reader = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
SynchronizeResponse mResponseObject = (Product[])serailizer.ReadObject(reader);

I get an exception:

There was an error deserializing the object of type MyNameSpance.Product. FormatException

After a lot of debugging I found out that the problem is in the boolean attribute "isPaid" and that the value must be "True" or "False"; not "T" and "F". But I can't change the server response so what can I do? Any ideas ?

A:

Obviously, "T" is not a valid value for a bool.
So, the answer is: don't use a bool. Use a string instead.
[DataMember(Name = "IS_PAID")]
public string isPaidString { get; set; }

public bool isPaid
{
    get {return isPaidString == "T";}
    set {isPaidString = value ? "T" : "F";}
}


Q:

Avoid Loop over Arrays in VBA?

my goal is to write a function that converts returns to prices.
I have a vector of returns stored inside a range in excel like this:
r1
r2
...
rn

Now suppose that these returns are stored in Column B.
In VBA wrote the following code
Dim r As Range

Set r = ThisWorkbook.Sheets("Foglio1").Range("B2:B" & _
ThisWorkbook.Sheets("Foglio1").Range("B" & Rows.Count).End(xlUp).Row)

Dim temp() As Variant
temp = r

So I succesfully assigned the value r1, r2, ..., rn to an array that I called temp.
Now if I were in R or MATLAB I would have done the following, in order to convert return to prices:
temp = cumprod(1 + temp)

with one line of command I would have converted returns to prices
(1 + temp) should sum 1 to each element of array and cumprod should return me a vector with the cumulative product.
Is it possible that to achieve the same result I am forced to use for loop in VBA?
thank you very much for your time
have a great week end

A:

Yes the only way to do this directly in VBA is with loops.
It is also possible to do it indirectly in VBA by using Excel Worksheet functions, but its actually usually faster to copy the range into a VBA array as you are doing and then process it with loops.
You can also write (or find and download) libraries that have callable functions and subroutines to hide the Loops from you, but they're still doing the loops.
As one comment said "Learn to love the loops".  That's just how it works in VBA.

Ironically, I think the actual fastest way to do this would be to add a new column, let's say starting at Z2 that had Z2=B2+1 and every other row/cell was Z*=(B*+1)*Z[*-1].


Q:

Why doesnt ImageView work for me? Android

My code is the following:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //landscape
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        setContentView(R.layout.activity_game);

        //initialize arks
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                initializeArks();
            }
        }, 2000);
    }

Nothing special there, here comes the initializeArks():
    public void initializeArks(){
        iv= (ImageView) findViewById(R.id.imageView);
        tw= (TypeWriter) findViewById(R.id.textView);
CountDownTimer timer = new CountDownTimer(10, 1000) {

            public void onTick(long millisUntilFinished) {

            }

            public void onFinish() {
                iv.setImageResource(R.drawable.loading);
            }
        }.start();

    }

Keep in mind that this code is only for debugging, it doesnt do anything specific, but as I found out the problem is with the ImageView
Also i have my variables declared STATIC for the purpose of using them in my other classes:
    public static ImageView iv;
    public static TypeWriter tw;

My XML is a basic one:
<ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

I would be grateful if somebody explained me why this doesnt work or would send me a working code snippet for me to use for only one purpose: displaying images.
Once i install the app on my phone and open it I wait exactly 4 seconds (thats how much im delaying it by yhe code above) and it simply crashes

A:

I couldnt find a way to achive what I wanted so I looked in the big picture, and my scenario allowed me to not have an ImageView. Fortunately changing the layout background does the trick for me and it doesnt have any negative effects for my project. Thank you for your wasted time here


Q:

How to report "foreign tax paid" from 1099-DIV?

Is it correct to report Foreign tax paid in 1099-div to line 47 Foreign tax credit in 1040 form?
But here http://voices.yahoo.com/how-report-amounts-form-1099-div-2439-11819489.html?cat=3 it says that

Any foreign tax paid by the mutual fund or REIT would be reported in
  box 6. You could claim this tax as an itemized deduction on Schedule A
  or as a credit on Form 1116.

Thanks!

A:

You can always take deduction for foreign tax paid on Schedule A, or calculate foreign tax credit using form 1116. Credit is usually more beneficial, but in some cases you will be better of with a deduction.
However, in very specific cases, you can claim the credit directly on your 1040 without using the form 1116. Look at the 1040 instructions for line 47:

Exception.   You do not have to complete Form 1116 to take this credit
  if all of the following apply.

All of your foreign source gross income was from interest and dividends and all of that income and the foreign tax paid on it were
  reported to you on Form 1099-INT, Form 1099-DIV, or Schedule K-1 (or
  substitute statement).
The total of your foreign taxes was not more than $300 (not more than $600 if married filing jointly).
You held the stock or bonds on which the dividends or interest were paid for at least 16 days and were not obligated to pay these
  amounts to someone else.
You are not filing Form 4563 or excluding income from sources within Puerto Rico.
All of your foreign taxes were:

Legally owed and not eligible for a refund or reduced tax rate under a tax treaty, and
Paid to countries that are recognized by the United States and do not support terrorism.

For more details on these requirements, see the Instructions for
  Form 1116.


Q:

What is the best strategy to support .NET 3.0 and .NET 4.0?

I would like to support .NET 3.0 and .NET 4.0 for my project.
My current solution is to have two project files - one for each version of .NET.
Is there a better / more convenient way?

A:

See my answer to this question: Build System for Targeting Multiple .NET Versions
The short answer is that there isn't an easy way to do this. The best I've found is to use separate projects (with #define's set up appropriately) and use "Add as Link" to share code.


Q:

PowerBuilder window close event

I have a MDI window containing multiple tabs. What I want to do is to disabled the close event every time the user clicked the exit button on the tab. But I didn't know how to accomplish those. Can anyone please help me with this? Thank you.
Here is the sample tab and exit button I was referring from my question above.

and this is what I have so far. Still the window is closing every time i clicked the exit button.
integer ext
ext = MessageBox("","You are not allowed to close this tab",(Exclamation!),(OK!))

if (ext = 1) then
Open(w_main)
end if

A:

That's not easy.
You should handle with user32.dll api and remove, modify and draw the menubar.
Open Global External Functions tab and insert:

Function uLong GetSystemMenu(object hwnd, boolean bRevert ) LIBRARY
  "user32.dll" Function uLong RemoveMenu(object hMenu, long nPosition,
  long wFlags ) LIBRARY "user32.dll" Function uLong DrawMenuBar(object
  hwnd) LIBRARY "user32.dll"

And now:
menu = GetSystemMenu(window, false) // to disable X
RemoveMenu(menu, HF060, H0)
DrawMenuBar(window)


Q:

Comparison using modifiable signs (python)

In Python, is there a way of comparing values using a variable comparison sign? For example, I want to be able to change the sign to be < or >, and have the if statement still work.
The code below shows the idea, but it is not valid in Python:
sign = <
if 1 sign 2:
    print("This works")

A:

Python's operators like < and > aren't values, so you can't assign them to variables. However, functions are values in Python, so you can assign them. The operator module has functions named lt and gt respectively:
>>> from operator import lt, gt
>>> lt(1, 2)
True
>>> gt(1, 2)
False
>>> sign = lt
>>> sign(1, 2)
True

So you could write:
from operator import lt, gt

sign = lt

if sign(1, 2):
    print('This works')


Q:

variadic methods: Check, if a argument is a typedef'ed block

I created a veriadic Category method on NSArray to filter it into a dictionary with given blocks and keys
typedef BOOL (^TestBlock)(id element);
- (NSDictionary *)dictionaryByFilteringWithBlocksAndKeys:(TestBlock)firstBlock, id firstKey,... NS_REQUIRES_NIL_TERMINATION;

Usage:
NSArray *array = [NSArray arrayWithObjects:@"a", @"aa", @"ab", @"cc", @"cd", @"dd", nil];
NSDictionary *dict = [array dictionaryByFilteringWithBlocksAndKeys:
                                    ^BOOL(id element) {return [element hasPrefix:@"a"];},@"a",
                                    ^BOOL(id element) {return [element hasPrefix:@"c"];},@"c",
         nil];

It works quite good, but I wonder, how I can check, if a given block (other then the first) has the typedef'ed signature.
I get the blocks from the va_list with TestBlock block = va_arg(args, TestBlock);, but it also eats non-sense blocks like
NSDictionary *dict = [array dictionaryByFilteringWithBlocksAndKeys:
                                    ^BOOL(id element) {return [element hasPrefix:@"a"];}, @"a",
                                    ^(id element) {;}, @"c",
                          nil];

without complaining.
Is there a way to check, if a block has the same signature as a typedef at runtime?

A:

No, there is no way to check.   This would require new syntax in the compiler.  Effectively, you want "these arguments are optional/variadic, but must follow this type pattern".
Also note that treating a specifically typed argument list as a va_list is not technically correct, either.  It will mostly work by coincidence on most ABIs, but not all.  (Not that you are doing that, but it often comes up in these contexts).

can you give me an example of what you mean with specially typed
  argument list?

Sure, consider:
id objc_msgSend(id,SEL,...);

That is a var-args argument list.   Now, you might think you can do this:
objc_msgSend(mutableArray, @selector(addObject:), anObject);

But, technically, you can't.  varargs are not compatible with specifically typed argument lists, by the C spec.   Thus, you need to typecast:
void (*func)(id,SEL,id) = (void*)objc_msgSend;
func(mutableArray, @selector(addObject:), anObject);

That is, if the called API is not also varargs, then the call site must be compiled against a declaration of the call that has full argument type info...


Q:

Adjusting level of significance

What if I used one - way ANOVA set at 0.05 level of significance, and the computed p - value is 0.058, can I adjust the level of significance to 6% instead of 10% so that it will result to significant difference? Is it sensible to do so?

A:

It may seem logical to you but your suggested change of the criterion goes against the idea of statistical testing. The threshold of 0.05 is an a priori determined rate of type I error (rejecting the null hypothesis when it should not be rejected). It's set before the test and it's to stay. Once the test is performed, we conclude with either reject the null or not.
Two related issues:
If the sample size you have right now was based on a certain computation process, that process would have specified the rates of type I and type II error, by toying with the threshold after the test, you may render the results useless. For example, if the original sample size calculation had used type I error rate of 0.10, you might have a lower sample size, and all these ANOVA results could have been different.
The p-value is just one of many facets of quantitative comparison. Do not put too much undeserved attention to it as it's not a be-all end-all answer. Also, evaluate the actual mean difference across groups and their corresponding variability (e.g. group SD or 95%CI) as well. Forcing your p-value from not significant to significant would not make your findings more/less useful.


Q:

JDialog Not Displaying When in Fullscreen Mode

I have an application that runs in fullscreen mode and has been working fine.  Now I need to add a simple, undecorated dialog and I'm running into trouble.  If I run the application maximized but not in fullscreen, the dialog displays and functions as expected.  When I switch back to fullscreen, the dialog will not display.
The dialog extends JDialog and only contains a JSlider and a couple of buttons.  It is undecorated and not modal.  (I disabled modality for testing purposes -- it was a pain to force exit the app every time the dialog blocked input.)  I'm entering full screen mode using setFullScreenWindow(), passing in the main JFrame for the app.  It doesn't make a difference if I set that very JFrame as the owner of the JDialog or not.  Nor does it seem to help if I call toFront() on the dialog.
The dialog seems to be active -- especially since it blocks input if I make it modal -- but just not showing or being hidden.  So, is there any obvious trick to displaying a JDialog in fullscreen mode?  Something I might be overlooking or omitting?
If there's no obvious solution, I can post some code later.  Unfortunately, I don't have time right now.

A:

JOptionPane.showInternalXXXDialog()
methods render dialogs as JInternalFrames.
Maybe you could consider using a JIternaFrame to simulate the dialog box.

A:

And in fact, as M1EK alluded in his answer and I mentioned in a comment, Java applications in full screen mode will not allow other windows to show over them.  The Javadoc API for GraphicsDevice reads:

Windows cannot overlap the full-screen window. All other application windows will always appear beneath the full-screen window in the Z-order.

In the end, I reconfigured my application so that it doesn't enter full screen mode until a bit later.  This still gives me a fairly class presentation at the start and allows my JDialog to function as it should.  The transition to full screen mode is quick and smooth, even in the "middle" of my app.


Q:

Why is 'pip install json' showing version error

While I wrote 'pip install json' on my command prompt, it is giving an error - ERROR: Could not find a version that satisfies the requirement json (from versions: none)
ERROR: No matching distribution found for json
What should I do

A:

Json is a standard library in python there's no need to install it.
Just include it in your python script as the following
import json


Q:

how to reshape data in r with reshape package

I have data that look like this:
Id    date         result
1     12/2/1997    1
1     04/5/2000    0
2     06/4/1998    1
2     18/6/1999    1
2     20/3/2000    0

And I want it to look like:
Id date.1    result.1 date.2     result.2 date.3    result.3
1  12/2/1997 1        04/5/2000  0        na        na
2  06/4/1998 1        18/6/1999  1        20/3/2000 0

A:

You can try
df$indx <- with(df, ave(seq_along(Id), Id, FUN=seq_along))
df1 <- reshape(df, idvar='Id', timevar='indx', direction='wide')
df1
#   Id    date.1 result.1    date.2 result.2    date.3 result.3
#1  1 12/2/1997        1 04/5/2000        0      <NA>       NA
#3  2 06/4/1998        1 18/6/1999        1 20/3/2000        0

Update
If you want to add  a new column using the indx
 df1$newCol <- tail(unique(df$indx), nrow(df1))
 df1
 #  Id    date.1 result.1    date.2 result.2    date.3 result.3 newCol
 #1  1 12/2/1997        1 04/5/2000        0      <NA>       NA      2
 #3  2 06/4/1998        1 18/6/1999        1 20/3/2000        0      3

data
df <- structure(list(Id = c(1L, 1L, 2L, 2L, 2L), date = c("12/2/1997",
"04/5/2000", "06/4/1998", "18/6/1999", "20/3/2000"), result = c(1L,
0L, 1L, 1L, 0L)), .Names = c("Id", "date", "result"), class = "data.frame",
row.names = c(NA, -5L))


Q:

jQuery move multiple DOM elements into other elements using their classes (not IDs)

I'm working on a page with multiple blog articles and due to constraints of the current platform/template can't move the comment count in the HTML.
I would like to move the .reaction-count elements from one part of each article into another part.
I've read the solutions on this thread: How to move an element into another element? but I'm still not sure how to translate that into what I need.
Here's what I've tried so far. It's not quite working since it moves all the .reaction-count elements into all the .post-title elements instead of just the .reaction-count for that particular article.
One attempt:
http://jsfiddle.net/DanEvans/jbgC4
Another attempt:
http://jsfiddle.net/DanEvans/jbgC4/5/
Here's some simplified example HTML that mimics the situation:

        Post #1

Lots of other text and elements

Post #1 Comments

        Post #2

Lots of other text and elements

Post #2 Comments

One of the first things I tried:
$('.reaction-count').appendTo('.post-title');

Thanks in advance for any help!

A:

If you are just trying to move the reaction counts into the post-title of the same entry content..
$('.reaction-count').each(function(){
    $(this).parent().find('.post-title').append($(this));
});

(My traversing was wrong).
Would move the reaction-count into the post title within it's parent entry-content on an individual basis.
Fiddle with your CSS included


Q:

Why does this code raise a 'does not exist in namespace' error when it compiles fine?

I'm working on a XAML-based app for Windows 10. I'm running into issues when trying to implement a binding in Setters, as per this answer. Here is my code:
namespace Sirloin.Helpers
{
    internal class Binding
    {
        public static readonly DependencyProperty ContentProperty = // ...

        public static string GetContent(DependencyObject o) => // ...
        public static void SetContent(DependencyObject o, string value) => // ...
    }
}

And here is my XAML:
<Page
    x:Class="Sirloin.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Sirloin"
    xmlns:h="using:Sirloin.Helpers"> <!--Some designer stuff omitted for clarity-->

    <Page.Resources>
        <ResourceDictionary>
            <Style x:Key="MenuButtonStyle" TargetType="Button">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="h:Binding.Content" Value="Symbol"/> <!--The XAML parser chokes on this line-->
                <Setter Property="FontFamily" Value="Segoe MDL2 Assets"/>
            </Style>
        </ResourceDictionary>
    </Page.Resources>
</Page>

For some reason, the VS designer seems to be throwing an error when it reaches the lines with the special binding syntax; namely, the one that sets h:Binding.Content to Symbol. Here is a screenshot of the message:

Strangely enough, though, the code seems to be compiling fine. When I hit Ctrl + B in Visual Studio, it builds with no errors and successfully outputs the binary. Of course, the drawback to this is I can't use the designer, which claims the XAML to be 'Invalid Markup' every time I build the project.
Can someone recommend me a solution to this problem? I tried the suggestion here of restarting Visual Studio and deleting the cached binaries, but it doesn't seem to be working.
Thanks!

A:

Turns out Uchendu was right: one of my problems was that the class was marked as internal rather than public. I also had to mark it as sealed, and change the dependency properties from fields to properties. For example, this:
public static readonly DependencyProperty BlahProperty = /* ... */;

had to be refactored to this:
public static DependencyProperty BlahProperty { get; } = /* ... */;

since WinRT components don't allow exposing public fields.
After those modifications I was able to get the library to build successfully.


Q:

Does MyISAM run a risk of actually losing data?

I have a series ofMyISAM database tables and was reading a few points about how it's not as good as InnoDB with respect to integrity. Specifically though, the post went on and seemed to suggest there is a possibility you could lose data. I can't find the link of course (typical luck eh?) but I do remember the takeaway suggesting the above.
Is it possible that you could lose actual rows during inserts? My assumption is this is not true, but would be interested in what the community has to say.
Thanks!

A:

MyISAM has zero support for transactions and because of that, it cannot ensure transactional integrity. It has no journal it can use to recover from a crash. It is, in short, brittle and prone to spectacular failure, especially if your system is abruptly terminated in the middle of a big write.
There is a very high possibility you could lose data during a write. InnoDB is different in that the write itself is not actually committed until it is complete, there's a mechanism for preserving database integrity during a modification so that if there's a failure there it can "roll back" to the previous state. MyISAM has no such mechanism and is at the mercy of the filesystem to save it from total corruption.
I'd strongly recommend not using MyISAM for anything critical, or anything at all if you can avoid it. It was useful in the 1990s when memory was at a premium and CPU power was scarce, a typical high-end MySQL server might have had 512MB of memory, two 200MHz processors, and a pair of 9GB disks in RAID1 configuration. Every little bit of performance counted. InnoDB has gotten a lot faster, and the performance penalty for journaling has shrunk dramatically, especially on SSD.
You wouldn't use a filesystem without a journal, so you really shouldn't use a database without one either.


Q:

Pass arguments list to sass mixin and compose one value from it

Sry for confusing title, don't know how to write it in simple manor.
What I want is something like this:
.someClass {
  @include transition(color, background);
}

to be transpiled to:
.someClass {
  transition: color 200ms ease-in-out, background 200ms ease-in-out;
}

I couldn't find this in documentation.
Any help appreciated.

A:

There are some ways of doing this, what you are looking for is a sass mixin.
Although it is a good solution for simple use cases, it's not always the easiest.
Here I leave one example. I hope it's useful:
@mixin transition($duration, $ease, $props){
  $value: '';
  @if(type-of($props)=='string'){
    $value: $props $duration $ease;
  }
  @if(type-of($props)=='list'){
    $i: 0;
    @each $prop in $props{
      $i: $i + 1;
      $value: #{$value} $prop $duration $ease if(length($props) == $i, unquote(''), unquote(','));
    }
  }
  transition: $value;
}

.someClass {
    @include transition(200ms, ease-in-out, $props: color background);
}


Q:

Is the behavior of XSLT/XQuery regex output implementation-dependent?

Using the regular expression specifications defined for XPath and XQuery, is it possible for two different implementations of fn:analyze-string, given as inputs the same regex and match strings, to return different results and still be considered conforming to the W3C Recommendation? Or should the same inputs always return the same results across different XQuery and XSLT processors?
Specifically, I am asking about the content of match, non-match, group, and @nr values, not the base URIs or node identities (which are clearly defined as implementation dependent).

A:

There are one or two very minor aspects in which the spec is implementation-dependent:

The vendor is allowed to decide which version of Unicode to adopt as the baseline. There are some changes between versions of Unicode, for example changes to character categories, that can affect the outcome of expressions like \p{Cn} or \p{IsGreek}, or the question of whether two characters are considered case-variants of each other.
The rules for captured substrings are not quite precise in edge cases. The spec gives an example: For example given the regular expression (a*)+ and the input string "aaaa", an implementation might legitimately capture either "aaaa" or a zero length string as the content of the captured subgroup.

Beyond that, the results should be the same across processors. But of course, this is one area where processors might decide that 100% conformance is just too hard - for example in Saxon-JS, we decided to do the best we could using the Javascript 6 regex engine, which certainly leaves us short of 100% conformance with the XPath rules.


Q:

Batch - Removing parent section of a specific child in an XML file

I'm trying to remove a parent section using a string in a child's tag.
Section of the XML file (original.xml)
<Mods>
    <ModItem>
        <Name>296707746.sbm</Name>
        <PublishedFileId>296707746</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>294620323.sbm</Name>
        <PublishedFileId>294620323</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>295393216.sbm</Name>
        <PublishedFileId>295393216</PublishedFileId>
    </ModItem>
</Mods>

I need to remove the parent section of a child that matches <Name>numbers.sbm</Name> tags Like this:
<ModItem>
    <Name>294620323.sbm</Name>
    <PublishedFileId>294620323</PublishedFileId>
</ModItem>

to produce this:
<Mods>
    <ModItem>
        <Name>296707746.sbm</Name>
        <PublishedFileId>296707746</PublishedFileId>
    </ModItem>
    <ModItem>
        <Name>295393216.sbm</Name>
        <PublishedFileId>295393216</PublishedFileId>
    </ModItem>
</Mods>

Current code i'm using:
FOR /f "tokens=1 delims=:" %%L in ('FINDSTR /n "<Name>294620323.sbm</Name>"      sandboxxml.txt ') do set /a line=%%L-2

BREAK> "%temp%\empty"

FC "%temp%\empty" "sandboxxml.txt" /lb %line% /t | MORE +4 |FINDSTR /b /e /v "*****" >temp.xml

(the code is a modified answer from a different topic)
It adds everything before the section to temp.xml
How would i get the rest of the original.xml into temp.xml, excluding the removed section?
and is there a different/simpler way to achieve this?
( this is my first question on stackoverflow, sorry if i did something wrong!)

A:

The Batch file below use the same method of your example:
@echo off
setlocal

for /F "delims=:" %%L in ('findstr /N "<Name>294620323.sbm</Name>" original.xml') do set /A start=%%L-1, end=%%L+2
(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" original.xml') do (
   if %%a lss %start% echo(%%b
   if %%a gtr %end% echo(%%b
)) > new.xml

Note that this method works on this file only, with this specific format.


Q:

Can I click tab in TabLayout by coding or method?

I have problem when Toolbar collapse. The CoordinatorLayout is not collapse. This problem is cause by I call keyboard. but when I click Tab in TabLayout the CoordinatorLayout is working correct again.
That is why I want to click tab in TabLayout by coding or method.
UPDATE: This question is relate with this LINK

A:

You might have to elaborate on how you're using a tab layout, but if you have your TabLayout setup with a ViewPager like this:
    mTabLayout.setupWithViewPager(mViewPager);

then you can call .setCurrentItem(int) on the ViewPager like this:
    mViewPager.setCurrentItem(1);

to programatically set the page number. When you have your TabLayout setup with a Viewpager as shown, this will also change your tab in the TabLayout. Here I've set it to 1. Hope this helps!


Q:

Use Fitch system to proof ((p ⇒ q) ⇒ p) ⇒ p without any premise. ONLY FOR FITCH SYSTEM.

I know here has few similar questions, but I cannot figure out with those answer. Since for Fitch system, I can only use And Intro, And Elim, Or Inro, Or Elim, Neg Intro, Neg Elim, Impl Intro, Impl Elim, Biconditional Intro, and Biconditional Elim.
I know I need to assume (p=>q)=>p then for next I need to prove p, at the end I can use Imlo Intro. But I don't know how to prove p...
I saw some answers like:
(p=>q)=>p  assume 1
p          assume 2
~p         assume 3
q          neg Elim with 2 or 3
I stop at this step..NOt sure why I can get q from 2 and 3? Since Neg Elim follows this form ( ~~p get p) and also Neg Intro follows (p=>q, p=>~q, get ~p). But from what I learn I can not get the q from just assume 2 and 3...
I tried in Fitch system, But it doesn't work with the answer from other questions. So that's right I post here again. Wish someone can help me.

A:

$\def\fitch#1#2{\begin{array}{|l}#1 \\ \hline #2\end{array}}$
Maybe this works for your rules?
$\fitch{}{
\fitch{
1. (p \rightarrow q) \rightarrow p \quad Assumption}{
\fitch{
2. \neg p \quad Assumption}{
\fitch{
3. p \quad Assumption}{
\fitch{
4. \neg q \quad Assumption}{
5. p \quad Reiteration \ 3}\\
6. \neg q \rightarrow p \quad \rightarrow  Intro \ 4-5\\
\fitch{
7. \neg q \quad Assumption}{
8. \neg p \quad Reiteration \ 2}\\
9. \neg q \rightarrow \neg p \quad \rightarrow Intro \ 7-8\\
10. \neg \neg q \quad \neg  Intro \ 6,9\\
11.   q \quad \neg Elim \ 10}\\
12. \quad \quad p \rightarrow q \quad \rightarrow Intro \ 3-11\\
13. \quad \quad p \quad \rightarrow  Elim \ 1,12}\\
14. \quad \neg p \rightarrow p \quad \rightarrow  Intro \ 2-13\\
\fitch{
15. \quad \quad \neg p \quad Assumption}{
16. \quad \quad \neg p \quad Reiteration \ 15}\\
17. \quad \neg p \rightarrow \neg p \quad \rightarrow  Intro \ 15-16\\
18. \quad \neg \neg p \quad \neg Intro \ 14,17\\
19. \quad p \quad \neg Elim \ 18}\\
20. ((p \rightarrow q) \rightarrow p) \rightarrow p \quad \rightarrow Intro \ 1-19
}$


Q:

Polypropylene 55 gallon drum

Can a polypropylene 55 gallon drum previously filled with chemicals used in the chrome plating process (possibly Nickel Sulfate) ever really be "cleaned out" for re-use? Can polypropylene ever absorb and retain such chemicals, or are these drums practical for this use because they do not?

A:

Polypropylene is hydrocarbon and does not adsorb polar and ionic compounds. So, several treatments with mild hydrochloric acid followed with several treatments with clean water should work. However, I wouldn't store drinking water there without a proven test. For example, leave water there for several weeks and then perform analysis of the water for metal ions. If all concentrations are within safe levels, it should be alright.

A:

Many of the chemicals used in metal plating are extremely poisonous (cyanide), cause severe allergies (Ni), and are carcinogenic (Cr(VI)).
I'd consider it as extremely unprofessional (besides violating many laws and regulations), to re-use anything that has been in contact with these materials for any purpose that requires a 'clean' container, regardless of the theoretical possibility of cleaning everything off.
To use such a drum for food or drinking water would be criminal negligence.
I'd only consider it ok if it was thoroughly cleaned (my myself) and only used by myself as a trashcan in my machine shop outside of my home.
I would even disallow to use it as a trashcan in the machine shop at work. Why risk it?
Even if PP does not absorb ions in principle, there is always the real world:

The guy who does the cleaning gets lazy and thinks you are an idiot requiring him to clean something off he doesn't see and only rinses the drum with water.
The plating bath contained organics that made the ions stick to the drum.
Some stuff precipitated from the plating bath and stuck to the bottom of the drum.
During the cleaning process cleaned and contaminated drums get mixed up.
Some plating solution dried in a crack, or under the rim, or wherever you can't clean in off.
Cleaning is itself a hazardous action that creates a lot of contaminated wastewater.
You don't know where the drums might end up. Of course the risk of using them as a trashcan in the machine shop is minuscule, agreed. But what if a machinist takes them home to his home shop? What if his kids use them to play with? I'd have been delighted as a kid to have a 55-gallon drum as a toy. Maybe the machinist's wife will take them to store food.

There are hundreds of accidents where contaminated containers have been improperly cleaned and re-purposed. Please don't do it, even if it is actually safe.
Even if the drums can be cleaned, imagine anything happening, like some kid being admitted to the ER with a Nickel allergy.
You'd be in a tough position proving that no one got injured from your unprofessionally cleaned drums. The people who used the drums in the first place will have all the paperwork to 'prove' that it wasn't them.
Btw. we had an accident with a metal plating bath that was not properly cleaned and injured a technician who had do do some modifications to it.
It might not hurt anyone, but it's better not to do it.


Q:

CGPath trouble?

Having a little bit of trouble with the code below. The points array is a set of points provided by a pathfinding algorithm which gives the shortest path between start and end CGPoints made in the method below. Having debugged this code I know it works.
I think its the CGPath that is causing me issues, it doesn't seem to be clearing? Whenever I generate a new path from the algorithm, the player always moves back to the position he first started in, he will then move along the distance of every path created so far within the application. This happens every time I try generate a new path.
Any ideas?
-(void)doubleTap:(UITapGestureRecognizer *)touchPoint
{
    CGPoint touchLocation = [touchPoint locationInView:touchPoint.view];
    touchLocation = [self convertPointFromView:touchLocation];

    //on double tap take the location of the player and the location tapped and pass it to the path finder.
    CGPoint start = CGPointMake((int)(player.position.x/SPACING), (int)(player.position.y/SPACING));
    CGPoint end = CGPointMake((int)(touchLocation.x/SPACING), (int)(touchLocation.y/SPACING));
    NSMutableArray *points = [NSMutableArray arrayWithArray:[self reverseArray:[pathFinder findPath:start End:end]]];

    //convert path to moveable path for sprite, move sprite along this path.
    CGMutablePathRef path = CGPathCreateMutable();

    if (points.count > 0)
    {
        PathFindingNode *firstNode = [points objectAtIndex:0];
        CGPathMoveToPoint(path, NULL, firstNode.position.x, firstNode.position.y);

        for (int i = 1; i < points.count; i++)
        {
            firstNode = [points objectAtIndex:i];
            CGPathAddLineToPoint(path, NULL, firstNode.position.x, firstNode.position.y);
        }
    }

    SKAction *hover = [SKAction followPath:path asOffset:NO orientToPath:YES duration:2.0];
    [player runAction: [SKAction repeatAction:hover count:1]];
    [points removeAllObjects];
    CGPathRelease(path);
}

There is a memory leak somewhere when passing the path to this code:
 //convert path to moveable path for sprite, move sprite along this path.
    CGMutablePathRef path = CGPathCreateMutable();

    if (points.count > 0)
    {
        PathFindingNode *firstNode = [points objectAtIndex:0];
        CGPathMoveToPoint(path, NULL, firstNode.position.x, firstNode.position.y);

        for (int i = 1; i < points.count; i++)
        {
            firstNode = [points objectAtIndex:i];
            CGPathAddLineToPoint(path, NULL, firstNode.position.x, firstNode.position.y);
        }
    }

    SKAction *hover = [SKAction followPath:path asOffset:NO orientToPath:YES duration:2.0];
    [player runAction: [SKAction repeatAction:hover count:1]];
    [points removeAllObjects];
    CGPathRelease(path);
}

If I comment this code out then the memory stays around 50mb on an iPad. If it's not commented out then it just keeps going higher and higher until it crashes around 1.5gb.

A:

The code you posted will create a new path and populate it with the points in your array of points. Either your array of points always contains the previous points PLUS your new points, or the scene kit method followPath:asOffset:orientToPath:duration: is appending the new path to the old. (I haven't actually used scene kit yet, so I don't know about that last possibility.)
In any case, your CGPath-handling code looks good. You remembered to CGRelease the CGPath, which lots of people who only know ARC don't do.


Q:

Problem with choosing the right string gauge - switch from medium to extra light?

I am beginner acoustic guitar player ..
My current guitar' strings are "medium" ,, but I found them hard to play, they make buzzing sound, that's why I hate my guitar now -_- and i'm thinking of changing them to Extra light.
I play both strumming and fingerpicking.  So what advice do you have for me guys? Will the extra light gauge sound nice and is it good to change from medium to extra light?
My guitar is Yamaha f310 :)

A:

The short answer is that lighter gauge strings will be easier to play and easier to get clear tone when you fret the notes.  Most beginners and even many seasoned guitarist prefer lighter gauge strings.
But going from medium gauge to extra light gauge will probably create the need for a new set up.  So let's talk a little about "set up" for acoustic guitar.
Every guitar will sound better and be easier to play with a proper set up. The first step in any set up is deciding what gauge strings you want the guitar set up for.  Different gauge strings will tune up at differing amounts of tension and the width of the nut slots may be optimized for a particular gauge.
A set up performed by a trained guitar technician or luthier will include among other things - adjusting the action to your preference while eliminating any fret buzz on open strings.  Generally, beginners will find it easier to play a guitar that has a lower action because it will make the strings easier to press down.
The action is adjusted in several ways including setting the saddle height (by shimming or sanding to raise or lower the saddle on most acoustics including the Yamaha F310) according to the action specified.  All set up's on a steel string acoustic with a truss rod will include a truss rod adjustment as part of the overall set up.  If your guitar was originally set up from the factory for medium strings, the nut slots may be a little too wide for extra light strings - although it will most likely still play (less than optimal intonation) even if you don't have this issue addressed by replacing the nut.
I would encourage you to seek the advice of a professional who can evaluate your guitar to determine if any modifications may be needed to be able to properly set up your guitar for extra light gauge strings.  With guidance from the guitar expert, select the string set you want to have your guitar set up for.  You will find that a proper set up will help as much or more as going to a lighter string gauge - but you can certainly do both at the same time.
Extra light strings while easier to play, will give you less volume and have a different feel than regular light or certainly medium gauge strings.  They will be a little looser and floppier and finger picking may feel a little less controlled to some guitarist.  You may find that you prefer the feel afforded by lower tension lighter strings.  Just know that it may take getting used to the new feel.
Of course if you switch to ultra light strings until you build more strength in your fretting hand, you can always go back to a heavier gauge later.  Just be aware that the guitar will need to be set up again any time you make a significant change in string gauge - particularly if you want to keep the action as low as possible.
For rank beginners who play a steel string guitar, I usually recommend a custom set of strings that tend to be easier to play than any commercially available stock set.  To learn how to procure and create this custom finger friendly string set click here:  Finger Friendly Custom String Set
Learning to play the guitar is quite challenging in the beginning.  A properly set up easy to play guitar will go a long way towards making the learning process more rewarding and enjoyable.
Good luck.  And most of all - have as much fun as possible while you continue to improve your skills.

A:

The buzzing might because the strings are tuned too low or the guitar is not properly set up (refer to Rockin Cowboy's answer).  But it might also be because your fingers don't yet have enough strength to push the string hard enough into the fret.  Light strings can help with that, since they have lower tension.  However, as a beginner I was quite averse to light strings because they cut into my fingers; you might need to build up calluses before you find them comfortable to play.
So as an alternative, you could try tuning down your medium strings a semitone or two, and put a capo on the first or second fret accordingly.  That'll make the strings have less tension so they're easier to press, with the added benefit of the higher frets being easier to stretch to when learning chord shapes and the like.


Q:

No drive letter assigned to USB drive on windows 8.1

Not long before, I executed dd on my USB drive, but later when I needed it. I found it could not be formatted in Windows Disk Management, which said "The system cannot find the file specified." So I had my USB drive formatted on Linux.
now issue occur. Windows 8.1 does not assign a drive letter, making it unable to be accessed in Windows Explorer, and though it is shown in WDM, any operation returned message mentioned above. But there is no problem when on Linux on my machine and on Windows on another machine.

A:

As we found out through the comments the problem may be solved using Windows' diskpart. Obviously the Linux tools somehow created a MBR and/or partition table Windows couldn't read properly (or had some other issue with).
If you're using these instructions, do so with care! Making mistakes might mean you're losing all data on one more more disks. If you're unsure, let someone else who's more experienced do this!

Open the start menu and type diskpart. You should get one hit, launch it and confirm the UAC prompt in case you're asked.
Wait for the console window to show an input cursor (flashing horizontal line behind DISKPART>).
Type list disk and confirm with Return.
Locate the disk you'd like to format/reset. Double check you pick the right one. Remember its number (listed under ###) for the next step.
Now type select disk # where # is replaced with the number from the last step.
Once again type list disk and the correct disk should be marked with a * in front of it.
Type clean, confirm if asked and wait for the operation to finish.
Leave diskpart using exit.
Windows Explorer should now ask you what to do with the uninitialized/empty disk. If it doesn't, have a look at disk management (open the start menu and run diskmgmt.msc). You should find the uninitialized drive and be able to create new partitions and format them.

A:

I had exactly the same issue and the Mario's solution did not fix my problem.
Additionally to Mario's solution do the following:

after 'clean' do not leave diskpart using 'exit'
type 'create partition primary'

This will create primary FAT32 partition (which was not possible from the Disk Manager as described in comment of 'Stanislav Mamontov' to Mario solution). This partition will be recognized, directly mounted and available. Now you can reformat to e.g NTFS if needed.


Q:

Which layer of an application should keep security logic (permissions, authorization)?

Since the most similar questions are related to ASP MVC I want to know some common right choice strategies.
Lets try to decide, will it go into the business layer or sit on the service layer.
Considering service layer to have a classical remote facade interface it seems to be essential just to land permission checks here as the user object instance is always here (the service session is bound to the user) and ready for .hasPermission(...) calls. But that looks like a business logic leak.
In the different approach with an implementation of security checks in the business layer we pollute domain object interfaces with 'security token' arguments and similar things.
Any suggestions how to overcome this tradeoff or maybe you know the only true solution?

A:

I think the answer to this question is complex and worth a bit of thought early on. Here are some guidelines.
The service layer is a good place for:

Is a page public or only open to registered users?
Does this page require a user of a specific role?
Authentication process including converting tokens to an internal representation of users.
Network checks such as IP and spam filters.

The business layer is a good place for:

Does this particular user have access to the requested record? For example, a user should have access to their profile but not someone else's profile.
Auditing of requests. The business layer is in the best situation to describe the specifics about requests because protocol and other details have been filtered out by this point. You can audit in terms of the business entities that you are setting policy on.

You can play around a bit separating the access decision from the enforcement point. For example, your business logic can have code to determine if a user can access a specific role and present that as a callback to the service layer. Sometimes this will make sense.
Some thoughts to keep in mind:

The more you can push security into a framework, the better. You are asking for a bug (and maybe a vulnerability) if you have dozens of service calls where each one needs to perform security checks in the beginning of the code. If you have a framework, use it.
Some security is best nearest the network. For example, if you wish to ban IP addresses that are spamming you, that definitely shouldn't be in the business layer. The nearer to the network connection you can get the better.
Duplicating security checks is not a problem (unless it's a performance problem). It is often the case that the earlier in the workflow that you can detect a security problem, the better the user experience. That said, you want to protect business operations as close to the implementation as possible to avoid back doors that bypass earlier security checks. This frequently leads to having early checks for the sake of UI but the definitive checks happening late in the business process.

Hope this helps.


Q:

How to Fix Error ata1.00: failed to enable AA (0x1 = error_mask

I have a lenovo z 480 and half of the time ubuntu will not boot, only displays this error message
Error ata1.00: failed to enable AA (error_mask = 0x1

and sometimes the screen goes black with blinking cursor. I've tried several distros (kde and gnome and always equals the start and end times others do not. All use the grub 2, the only distro that starts 100% all the time is mageia not if using the old grub but it is very annoying not to be able to use the distro that you like best.

A:

Error ata1.00: failed to enable AA (error_mask = 0x1)

This point to a problem with your hardware, be the cables, the hard drive or the motherboard. The only way to fix it, is diagnostic each piece of hardware. Since you said is random, you may test the memory and the Hard Disk first. Ubuntu includes the memtest86+ to do heuristics test to the memory, for the Hard Drive, you should do a full backup of all your important data then replace it.

A:

The hard drive incorrectly advertises the ATA_FLAG_FPDMA_AA flag (the FPDMA FIS Auto Activate bit) but when this is activated it does not seem to have this capability. See http://download.intel.com/support/chipsets/imsm/sb/sata2_ncq_overview.pdf
Generally, the best fix is for drivers/ata/libata-core.c to be quirked to fix this for the specific drive series. A workaround may be do disable NCQ using the kernel parameter libata.force=noncq but this will make performance suck.
To do this, edit /etc/default/grub
and change:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash libata.force=noncq"

and run:
sudo update-grub


Q:

Docker, Nginx. PHP-fpm Upload progress bar not work

I use docker-compose (php 7.2 FROM phpdockerio/php72-fpm:latest )
services:
    webserver:
      image: nginx:alpine

nginx.con
user nginx;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /dev/stdout  main;

    #sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;

 server {

     listen 80 default;

     client_max_body_size 208M;

     access_log /var/log/nginx/application.access.log;

     root /application/public;

     rewrite ^/index\.php/?(.*)$ /$1 permanent;

     try_files $uri @rewriteapp;

     location @rewriteapp {
         rewrite ^(.*)$ /index.php/$1 last;
     }

     # Deny all . files
     location ~ /\. {
         deny all;
     }

     location ~ ^/(index)\.php(/|$) {
         fastcgi_pass php-fpm:9000;
         fastcgi_split_path_info ^(.+\.php)(/.*)$;
         fastcgi_index app_dev.php;
         send_timeout 1800;
         fastcgi_read_timeout 1800;
         fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
         fastcgi_param PHP_VALUE "error_log=/var/log/nginx/application_php_errors.log";
         fastcgi_buffers 16 16k;
         fastcgi_buffer_size 32k;
         include fastcgi_params;
     }

     # Statics
         location /(bundles|media) {
         access_log off;
         expires 30d;
         try_files $uri @rewriteapp;
     }}

}

i create test controller to update progressbar
 /**
     * @Route("/progressTest", name="progressTest")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function progressAction(){

        ob_start();
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');

        $total = 10;
        for($i=0;$i<$total;$i++)
        {

            $percent = intval($i/$total * 100)."%";

            sleep(1); // Here call your time taking function like sending bulk sms etc.

            echo '';

            ob_flush();
            flush();

        }
        echo '';

        return new Response('OK '.$i);

    }

run it in template

but have pending to end of loop, then get
OK 10

How i can update progressbar ?

A:

You are most probably missing a header X-Accel-Buffering, as described in Streaming a Response section of official documentation. Basically, your FPM does not buffer anything, but NGINX does, so at the end you will get everything in a bulk.
Try setting that header to no and see it it helps.
On a side note, returning a


Q:

Find the minimum value that data could have had before it was rounded

I have this function in R:
Minimum <- function(data) {
    answer <- numeric(length(data))

    diference <- c(0, diff(data, lag = 1, differences = 1)) #Padded initially =0

    answer[1]=data[1]
    for (i in 2:length(diference)) {
        if (diference[i]==0) {
            answer[i]=answer[i-1]
        } else {
            answer[i]=data[i]-diference[i]/2
        }
    }
    return(answer)
}

Its purpose is to find the minimum value which "data" could had before it was rounded.
The minimum possible value is the average of the values which "data" had at the last change of value in "data"
This code works, but since for loops are inefficient in R, it is advised to vectorize the function.
The problem is that the "answer" vector depends on the former values in "answer", so I cannot use a lambda function.

A:

You can firstly change by difference != 0 and then use na.locf to replace NAs by last available value recursively.
minimum_new <- function(data) {
  answer <- rep(NA, length(data))
  difference <- c(0, diff(data, lag = 1, differences = 1)) / 2
  answer[1] <- data[1]
  answer[difference != 0] <- data[difference != 0] - difference[difference != 0]
  answer <- zoo::na.locf(answer, na.rm = FALSE)
  answer
}

This version is faster for me by at least 2 times.
> data <- sample(10, 10000, replace = TRUE)
> check <- function(values) all(sapply(values[-1], function(x) identical(values[[1]], x)))
> bench <- microbenchmark::microbenchmark(loop = Minimum(data), vectorised = minimum_new(data), check=check)
Unit: microseconds
       expr      min       lq     mean   median       uq      max neval cld
       loop 1401.959 1415.552 1665.816 1457.274 1586.407 4620.835   100   b
 vectorised  742.325  758.183 1111.202  796.507 1383.268 2587.940   100  a

With check it's also checks the equality of output.


Q:

How to implement C-Style callback functions using swift?

I found an example for IOKit:
var notification:io_object_t

let matching:NSDictionary = IOServiceNameMatching("IODisplayWrangler").takeRetainedValue()
let displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, matching)
let notificationPort = IONotificationPortCreate(kIOMasterPortDefault)
    IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, nil, &notification)

CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
   IOObjectRelease (displayWrangler);

The above example is clear to me - so far. But IOServiceAddInteresNotification wants a callback function. In  it's simple to do this, by implementing the C-Style function somewhere in the .m-file.
The documentation says that I have to use a callback of type IOServiceInterestCallback.
In C-Style it is defined as follows:
typedef void ( *IOServiceInterestCallback)( void *refcon, io_service_t service, uint32_t messageType, void *messageArgument );

And on objC everything seems to work out perfectly.
What is the equivalent solution in swift? How do I declare the callback function without creating a C or objC file for this?
Any ideas?
Cheers,
Jack

A:

You cannot create C function like callbacks in Swift as closures are not compatible with CFunctionPointer. You can implement some workaround in Objective-C or C. Example is describe in Objective-C Wrapper for CFunctionPointer to a Swift Closure


Q:

How to specify many ids and their variable name in a REST API request?

What is the most common and wise way to specify many entities' ids in an API request?
For a singular entity request I have:
GET /v1/entities/{entity_id}

My suggestions for requesting many entities:
GET /v1/entities?entity_ids={entity_id1},{entity_id2}

With the same variable name entity_id:
GET /v1/entities?entity_id={entity_id1},{entity_id2}

More looks like for singular endpoint:
GET /v1/entities/{entity_id1},{entity_id2}

Or is there any other way to design for such endpoints?

A:

I'm afraid the standard thing to do is not to search multiple ids like this using REST.  If you're loading several specific entities by id, then you should ask yourself why you're doing so.  Perhaps these entities are customer orders belonging to a specific customer and you're loading the details of each order.  In that case, you should have a URL more like /customer/{id}/orders which returns all orders belonging to a customer with id {id} rather than knowing the ids beforehand and loading them each individually.
Otherwise if the user is attempting to load several entities from a list to view its details, simplify the display to show one entity detail at a time, and you load each one as the user moves forwards or backwards.  In other words, you shouldn't be in a situation where you'd specifically need multiple entities loaded by their ids with no obvious link between them that you'd need a way to call the REST service with each individual id listed.


Q:

Add shape to a UIButton in Swift

I have a UIButton and I wanna add a circle shape in the middle of it.
how can I do that?
Here's what I want to achieve.

Thanks/

A:

Insert a subview in your button
let circleFrame = CGRect(x: 0, y: 0, width: circleDimension, height: circleDimension)
let circle = UIView(frame: circleFrame)
circle.backgroundColor = UIColor.clear
circle.layer.borderWidth = circleWidth
circle.layer.borderColor = UIColor.white.cgColor
circle.layer.cornerRadius = circleDimension/2

Just add that as a subview to your button and set centerX and centerY anchors equal to your button. Then, if you want to make it square, just do
circle.layer.cornerRadius = 0


Q:

Function on the set of limit countable ordinals

Let $\Lambda$ be the set of all countable limit ordinals. Does there exist an injective function $f:\Lambda\to\omega_1$ with the properties:

$\forall \lambda\in\Lambda:~f(\lambda)<\lambda$
$\forall\alpha<\omega_1~~\exists\beta<\omega_1~~\forall\lambda>\beta:~f(\lambda)>\alpha$ ?

A:

No.  The first property is known as $f$ being regressive.  Fodor’s Lemma says that any regressive function on a stationary set is constant on a stationary subset.  In particular, because $\Lambda$ is club (and thus stationary), such $f$ cannot be injective.


Q:

Android BackStack clear but keep root

I am currently writing a chat app. It is basically very similar to WhatsApp:
On Startup there is last conversation overview.
When I want to start a new conversation with somebody I have to do/pass

last conversations overview activity (click on + to look for conversation partner)
courses activity (choose a course)
course participants activity (chooser partner)
Conversation Activity

So that is Basically the stack: [A1, A2, A3, A4]
Now the user had a nice chat with some course member and wants to get back to the last conversation overview but when he presses the back button he will get to A3, the "course participants activity".
I want the user to get back to A1 by pressing the back button in A4.
WRONG: [A1, A2, A3 , A4] -> back -> [A1, A2, A3]
RIGHT: [A1, A2, A3 , A4] -> back -> [A1]
alternatively I could imagine
RIGHT: [A1, A2, A3] -> start A4 -> [A1, A4]
Thanks in advance.
[edit]
THE ANSWER
It turned out to be a combination of these two.
in onOptionsItemSelected() I put this (in a switch case of course) because of the given google conventions.
final Intent intent = new Intent(this, MainPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

and

Define Activity A1's android:launchMode as singleTop at your
  manifest.

Why a combination? Just adding the Flat Intent.FLAG_ACTIVITY_CLEAR_TOP kills activity A1. As this was my fist activity it had some registration/checking implementation included. When I started this activity again after it has been destroyed onCreate was called unnecessarily.
The launchmode singletop prevents this.

A:

Define Activity A1's android:launchMode as singleTop at your manifest.
Handle back button press at Activity A4 and start your Activity A1 like below:
Intent intent = new Intent(A4.this,  A1.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

With this your A2, A3 will be cleared from stack.
See more for intents.
Edit: This will work for your [A1, A2, A3 , A4] -> back -> [A1] requirement


Q:

How to add product picture, in order to create bundle product programmatically

I need to create function that is creating bundle product, I already created my function and it works great, I mean its creating the bundle product for me, my problem is how can I add product's image, (image, small-image and thumbnail), I did some searches cannot find any good way to implement it, will be appreciate if anyone can help, Thanks :)
The following is my code that create the bundle product :
$productsId = array(6,8);
        $categoryId = array();
        $sum = 0;
        $skuSum = 0;
        $ProductsName = array();

        for($i=0,$j=count($productsId);$i<$j;$i++)
        {
            $productCheck = Mage::getModel('catalog/product');
            $categoryId[] = $productCheck->load($productsId[$i])->getCategoryIds();
            $productPrice = $productCheck->load($productsId[$i])->getPrice();
            $productSku = $productCheck->load($productsId[$i])->getSku();
            $ProductsName[] = $productCheck->load($productsId[$i])->getName();
            $sum += $productPrice;
            $skuSum +=  $productSku;
        }

        $bundleProductName = implode('-', $ProductsName);
        $categoryIDs = call_user_func_array('array_merge', $categoryId);
        $uniqueCategoryIDs = array_unique($categoryIDs);

        require_once('includes/config.php');
        require_once('app/Mage.php');

        $storeID = 1;
        $websiteIDs = array(1);
        //$cats = array(8,11,9);
        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

        $p = array(
            'sku_type' => 1,
            'sku' => $skuSum,
            'name' => $bundleProductName,
            'description' => 'Pendant chian created by user',
            'short_description' => 'Pendant chian created by user',
            'type_id' => 'bundle',
            'attribute_set_id' => 4,
            'weight_type' => 0,
            'visibility' => 4,
            'price_type' => 1,
            'price_view' => 0,
            'status' => 1,
            'created_at' => strtotime('now'),
            'category_ids' => $uniqueCategoryIDs,
            'store_id' => $storeID,
            'website_ids' => $websiteIDs,
            'price' => $sum
        );

        $productCheck->setData($p);

        Mage::register('product', $productCheck);
        $optionRawData = array();

        $optionRawData[0] = array(
            'required' => 1,
            'option_id' => '',
            'position' => 0,
            'type' => 'multi',
            'title' => 'pendant chain',
            'default_title' => 'pendantChain',
            'delete' => '',
        );

        $selectionRawData = array();
        for($i=0,$j=count($productsId);$i<$j;$i++)
        {
            $selectionRawData[0][] = array(
                'product_id' => $productsId[$i],
                'selection_qty' => 1,
                'selection_can_change_qty' => 1,
                'position' => 0,
                'is_default' => 1,
                'selection_id' => '',
                'selection_price_type' => 0,
                'selection_price_value' => 0.0,
                'option_id' => '',
                'delete' => ''
            );
        }
        /*$selectionRawData[0] = array();
        $selectionRawData[0][] = array(
            'product_id' => 7,
            'selection_qty' => 1,
            'selection_can_change_qty' => 1,
            'position' => 0,
            'is_default' => 1,
            'selection_id' => '',
            'selection_price_type' => 0,
            'selection_price_value' => 0.0,
            'option_id' => '',
            'delete' => ''
        );*/

        Mage::register('productCheck', $productCheck);
        Mage::register('current_product', $productCheck);
        $productCheck->setCanSaveConfigurableAttributes(false);
        $productCheck->setCanSaveCustomOptions(true);
        // Set the Bundle Options & Selection Data
        $productCheck->setBundleOptionsData($optionRawData);
        $productCheck->setBundleSelectionsData($selectionRawData);
        $productCheck->setCanSaveBundleSelections(true);
        $productCheck->setAffectBundleProductSelections(true);
        $productCheck->save();

        if($productCheck->save()){
            return true;
        }
        else
            return false;

A:

use this code to save picture for bundle product,
$filepath is your location for the picture
$bundleProduct->addImageToMediaGallery($filePath, array('image', 'small_image', 'thumbnail'), false, false);

Hope this helps,


Q:

Display names instead of coordinates in DB scan algorithm

Python newbie here, I got this code from the internet(can't remember the source), and I am unable to understand how it works. What I want is to replace the output in a way so that it shows the name of the cities instead of the coordinates. Are they even linked ? Meaning once we input the values into the DB scan algorithm, do they lose their identity ? Is there any way to keep that so I can display the city names ? Any help or suggestion or edit to the question is appreciated
Here is a colab link.
kms_per_radian = 63.710088
epsilon = 1.500 / kms_per_radian
db = DBSCAN(eps=epsilon, min_samples=1, algorithm='ball_tree', metric='haversine').fit(np.radians(coords))
cluster_labels = db.labels_
num_clusters = len(set(cluster_labels))
clusters = pd.Series([coords[cluster_labels == n] for n in range(num_clusters)])
print('Number of clusters: {}'.format(num_clusters))

clustersList = clusters.tolist()

def get_centermost_point(cluster):
    centroid = (MultiPoint(cluster).centroid.x, MultiPoint(cluster).centroid.y)
    centermost_point = min(cluster, key=lambda point: great_circle(point, centroid).m)
    return tuple(centermost_point)

lats, lons = zip(*centermost_points)
rep_points = pd.DataFrame({'lon':lons, 'lat':lats})
rs = rep_points.apply(lambda row: df[(df['lat']==row['lat']) & (df['lon']==row['lon'])].iloc[0], axis=1)

centermost_points = clusters.map(get_centermost_point)

A:

clusters1 = pd.Series([names[cluster_labels == n] for n in range(num_clusters)])
clusters = pd.Series([coords[cluster_labels == n] for n in range(num_clusters)])
print(clusters1)
print(clusters)
print(df)

I went through your code, I found this clusters coordinates are grouped based on the labels. Instead of that see clusters1 there I have grouped the cluster names based on the coordinates. Hope I answer your question.


Q:

Django: How to get parameters from QuerySet

Consider the following Django model:
class SomeModel(models.Model):
    some_var = models.IntergerField()

Whats the best way to get an array of a models parameters from a search results?
Example (not working of course):
a = SomeModel.objects.all().some_var

would give something like [3, 4, 1, 9, 1, 2]

A:

There is existing queryset method called values_list https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list
a = SomeModel.objects.all().values_list('some_var', flat=True)

We are using flat=True so that it will give flat list
Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]
Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]


Q:

Making sense of angles in $\mathbb{R^n}$

One of the definitions of the dot product of two vectors is the following
$$\vec{a} \bullet \vec{b}\ \  \stackrel{\text{def}}{=} \ \ \|\vec{a}\| \,\|\vec{b}\|\cos(\theta)$$
Where $\theta$ denotes the angle between the vectors $\vec{a}$ and $\vec{b}$. But for that angle $\theta$ to 'make sense', both $\vec{a}$ and $\vec{b}$ must lie in the same plane correct? i.e. There must exist some two-dimensional space, e.g. $\mathbb{R^2}$, that both $\vec{a}$ and $\vec{b}$ are an element of.
Now we can always find a plane that both $\vec{a}$ and $\vec{b}$ fall in. But now the question arises, are we finding the angle $\theta$ with respect to the plane that they lie in (what I'm trying to say is: Is $\theta$ denoting the angle between $\vec{a}$ and $\vec{b}$ in a plane that they both fall in?), or is it with respect to the basis vectors of of the original vector space that they lie in initially.
Here's an example that will hopefully get across what I'm asking:
Take $\vec{a}, \vec{b} \in \mathbb{R^4}$.
If we can find a plane that both $\vec{a}$ and $\vec{b}$ both lie in, then 'the angle between them', $\theta$, makes sense. If not then what essentially is being said is $\theta$ is the angle between two vectors in four-dimensional space, and I'm not sure that an angle in $\mathbb{R^4}$ has any sort of meaning.
My question then essentially boils down to the following.

Are angles only defined (or do they only have meaning) in $\mathbb{R^2}$?
If we have two vectors in $\mathbb{R^n}$, is the only way to find the 'angle between them' by first finding a plane (a two-dimensional vector space) that they both lie in, and then solving for the angle with respect to that plane?

A:

Yes, $\theta$ is the angle with respect to the plane containing $\vec a$ and $\vec b$. If $\vec a$ and $\vec b$ are non-zero, this plane is unique unless $\vec b$ is a multiple of $\vec a$ (in which case $\theta=0$). So $\theta$ is well-defined.
But another approach is to define the dot product of vectors $\vec{a}=(a_1,\ldots,a_n)$ and $\vec{a}=(a_1,\ldots,a_n)$ as
$$\vec{a} \bullet \vec{b} = \sum_{i=1}^na_ib_i$$
Then you can define the angle between then as
$$\theta = \arccos \left(\frac{\vec{a} \bullet \vec{b}}{|\vec a||\vec b|}\right)$$
This gives you the same answer as finding a plane containing $\vec a$ and $\vec b$ and then finding the angle with respect to that plane.
So to answer your two questions:

Are angles only defined (or do they only have meaning) in $\mathbb R^2$?

That is really up to which definition of 'angle' you prefer.

If we have two vectors, is the only way to find the 'angle between them' by first finding a plane that they both lie in, and then solving for the angle with respect to that plane?

No. Usually a much simpler method is to calculate the dot product and use the second formula above.


Q:

Text is not going on a new line

When I try to add text that exceeds the width of my div it doesn't go on a new line but starts the same as the previous text and starts overlapping. Can someone see the issue and explain to me how I can make go to the next line instead?
EDIT: I've located the problem to be within my CSS reset part of my stylesheet. But I can't tell which part creates this problem and how I will be able to solve it. I've included it as my css instead.

    html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

body {
  line-height: 0;
}

article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
  display: block;
}

nav ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}

a {
  margin: 0;
  padding: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

/* change colours to suit your needs */
ins {
  background-color: #ff9;
  color: #000;
  text-decoration: none;
}

/* change colours to suit your needs */
mark {
  background-color: #ff9;
  color: #000;
  font-style: italic;
  font-weight: bold;
}

del {
  text-decoration: line-through;
}

abbr[title], dfn[title] {
  border-bottom: 1px dotted;
  cursor: help;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* change border colour to suit your needs */
hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #cccccc;
  margin: 1em 0;
  padding: 0;
}

input, select {
  vertical-align: middle;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at metus tincidunt, finibus massa a, faucibus arcu. In nec dignissim purus. Etiam auctor ullamcorper velit aliquam aliquam. Sed aliquam sit amet urna in pharetra. Cras orci ante, lobortis
      vitae erat et, efficitur interdum mi.”

A:

The issue is that line-height has been set to 0.
Remove this:
body {
    line-height: 0;
}


Q:

Python Django Global Variables

I'm looking for simple but recommended way in Django to store a variable in memory only.  When Apache restarts or the Django development server restarts, the variable is reset back to 0.  More specifically, I want to count how many times a particular action takes place on each model instance (database record), but for performance reasons, I don't want to store these counts in the database.  I don't care if the counts disappear after a server restart.  But as long as the server is up, I want these counts to be consistent between the Django shell and the web interface, and I want to be able to return how many times the action has taken place on each model instance.
I don't want the variables to be associated with a user or session because I might want to return these counts without being logged in (and I want the counts to be consistent no matter what user is logged in).  Am I describing a global variable?  If so, how do I use one in Django?   I've noticed the files like the urls.py, settings.py and models.py seems to be parsed only once per server startup (by contrast to the views.py which seems to be parsed eache time a request is made).  Does this mean I should declare my variables in one of those files?  Or should I store it in a model attribute somehow (as long as it sticks around for as long as the server is running)?  This is probably an easy question, but I'm just not sure how it's done in Django.
Any comments or advice is much appreciated.
Thanks,
Joe

A:

Why one mustn't declare global variables? O_o. It just looks like a propaganda. If the author knows what he wants and what side-effects will be, why not. Maybe it's just a quick experiment.
You could declare your counter as a model class-member. Then to deal with race condition you have to add a method that will wait if some other client, from another thread works with counter. Something like this:
import threading

class MyModel(ModelBase):
    _counter = 0
    _counter_lock = threading.Lock()

    @classmethod
    def increment_counter(cls):
        with cls._counter_lock:
            cls._counter += 1

    def some_action(self):
        # core code
        self.increment_counter()

# somewhere else
print MyModel._counter

Remember however: you have to have your application in one process. So if you've deployed the application under Apache, be sure it is configured to spawn many threads, but not many processes. If you're experimenting with ./manage.py run no actions are required.

A:

You mustn't declare global variables. Settings (constants) are OK if done right. But variables violate with shared-nothing architecture and might cause a lot of trouble. (best case they'll be inconsistent)
I would simply store those statistics in the cache. (Well, actually I would store them in the database but you made clear you believe it will have a negative impact on performance, so...)
The new incr() and decr() methods are especially suitable for counting. See  docs for more info.


Q:

Rails Active Record Count Across Calculated Field

Using the AREL / Rails calculations I'm trying to execute the following:
SELECT to_char(timestamp, 'YYYY-MM-DD') AS segment, COUNT(*) AS counter
FROM pages
GROUP BY segment
ORDER BY segment

I can run something like:
Page.order(FIELD).count(group: FIELD)
{ a: 1, b: 4, c: 1 }

However, I can't get this working across calculated fields. Any thoughts?

A:

Came up with this:
Page.count(:all, from: "(SELECT to_char(#{SEGMENT}, 'YYYY-MM-DD')  AS segment FROM pages) AS pages", group: "segment", order: "segment")
> SELECT COUNT(*) AS count_all, segment AS segment FROM (SELECT to_char(created_at, 'YYYY-MM-DD') AS segment FROM pages) AS pages GROUP BY segment ORDER BY segment


Q:

How do I turn this into "will" form?

I am trying to say "You will not feel good if you eat such food" and this has been my attempt so far:

そんな食べ物を食べれば、君はいい感じない

How can I express "will not" in this case? Also, any corrections in general are very much appreciated.

A:

Tenses generally do not correspond well between English and Japanese.  Japanese-speakers usually just use the present tense to talk about near future events and we could always tell from the context.
Natural-sounding Japanese sentences for "You will not feel good if you eat such food." would be:

　「そんなもの[食]{た}べてると[元気]{げんき}になれないよ。」
　「そんなのばかり食べてると元気になれないぞ。」
　「そんなの食べてると[身体]{からだ}に[悪]{わる}いぞ。」

As usual, one could not arrive at a natural-sounding phrase if one TRANSLATED from another language.  If you find my English understadable, that is because I am not translating from Japanese.