text:
Q: Query/Replace element in DataFrame with element directly beneath it I have a dataframe in which I need to query and replace 0.00s with a value directly below it if certain conditions are met. I have looked for documentation on such a behavior but have been unable to find an efficient Pythonic solution.
The logic is as follows:
IF [Symbol] = 'VIX' AND [QuoteDateTime] CONTAINS '09:31:00' AND [Close]  = '0.00'
THEN I would like to replace the [Close] value with the [Close] value right below it.
+----+--------+---------------------+---------+
|    | Symbol |    QuoteDateTime    |  Close  |
+----+--------+---------------------+---------+
|  0 | VIX    | 2019-04-11 09:31:00 |    0.00 |
|  1 | VIX    | 2019-04-11 09:32:00 |   14.24 |
|  2 | VIX    | 2019-04-11 09:33:00 |   14.40 |
|  3 | SPX    | 2019-04-11 09:31:00 | 2911.09 |
|  4 | SPX    | 2019-04-11 09:32:00 | 2911.55 |
|  5 | SPX    | 2019-04-11 09:33:00 | 2915.22 |
|  6 | VIX    | 2019-04-12 09:31:00 |    0.00 |
|  7 | VIX    | 2019-04-12 09:32:00 |   15.64 |
|  8 | VIX    | 2019-04-12 09:33:00 |   15.80 |
|  9 | SPX    | 2019-04-12 09:31:00 | 2901.09 |
| 10 | SPX    | 2019-04-12 09:32:00 | 2901.55 |
| 11 | SPX    | 2019-04-12 09:33:00 | 2905.22 |
+----+--------+---------------------+---------+

Expected output would be that Index 0 [Close] is 14.24 and Index 6 [Close] is 15.64. Everything else remains the same.
+----+--------+---------------------+---------+
|    | Symbol |    QuoteDateTime    |  Close  |
+----+--------+---------------------+---------+
|  0 | VIX    | 2019-04-11 09:31:00 |   14.24 |
|  1 | VIX    | 2019-04-11 09:32:00 |   14.24 |
|  2 | VIX    | 2019-04-11 09:33:00 |   14.40 |
|  3 | SPX    | 2019-04-11 09:31:00 | 2911.09 |
|  4 | SPX    | 2019-04-11 09:32:00 | 2911.55 |
|  5 | SPX    | 2019-04-11 09:33:00 | 2915.22 |
|  6 | VIX    | 2019-04-12 09:31:00 |   15.64 |
|  7 | VIX    | 2019-04-12 09:32:00 |   15.64 |
|  8 | VIX    | 2019-04-12 09:33:00 |   15.80 |
|  9 | SPX    | 2019-04-12 09:31:00 | 2901.09 |
| 10 | SPX    | 2019-04-12 09:32:00 | 2901.55 |
| 11 | SPX    | 2019-04-12 09:33:00 | 2905.22 |
+----+--------+---------------------+---------+

A: Create boolean mask by Series.eq for ==, Series.dt.strftime for strings from datetimes and set new values by Series.mask with Series.shift:
#convert to datetimes if necessary
df['QuoteDateTime'] = pd.to_datetime(df['QuoteDateTime'])

mask = (df['Symbol'].eq('VIX') &
        df['QuoteDateTime'].dt.strftime('%H:%M:%S').eq('09:31:00') &
        df['Close'].eq(0))

df['Close'] = df['Close'].mask(mask, df['Close'].shift(-1))
#alternative1
#df.loc[mask, 'Close'] = df['Close'].shift(-1)
#alternative2
#df['Close'] = np.where(mask, df['Close'].shift(-1), df['Close'])
print (df)

   Symbol       QuoteDateTime    Close
0     VIX 2019-04-11 09:31:00    14.24
1     VIX 2019-04-11 09:32:00    14.24
2     VIX 2019-04-11 09:33:00    14.40
3     SPX 2019-04-11 09:31:00  2911.09
4     SPX 2019-04-11 09:32:00  2911.55
5     SPX 2019-04-11 09:33:00  2915.22
6     VIX 2019-04-12 09:31:00    15.64
7     VIX 2019-04-12 09:32:00    15.64
8     VIX 2019-04-12 09:33:00    15.80
9     SPX 2019-04-12 09:31:00  2901.09
10    SPX 2019-04-12 09:32:00  2901.55
11    SPX 2019-04-12 09:33:00  2905.22

A: Not an expert, but you could try using the index:
First get the index with this short line:
idx = df.index[(df['Symbol'] == 'VIX') & (df['QuoteDateTime'].str.contains("09:31:00")) & (df['Close'] == '0.0')]
Then use the index to set the values to the values in the rows below:
df.loc[idx, 'Close'] = df.loc[idx+1, 'Close'].values


text:
Q: how to traverse xml file based on variables with XSL I recently asked a question on which engine to parse my xml and decided to stick to XSL, but I can only get the job half done. (ref: Which language to use to parse xml for navigation)
I've managed to get as far as traversing down <root> --> <menu> -->  but any children under nav and my logic gets totally screwed up.
Question is how do I repeat my logic in xsl to go deeper in the xml child nodes, when the @path is the next child node tier?
Am I even doing this right? I feel like I'm missing something here and should be using templates somehow?
For example here is my xsl style sheet.
<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" />
    <xsl:param name="page" select="default"/>

    <xsl:template match="root">

            <xsl:for-each select="*/nav">
                <xsl:choose>
                    <xsl:when test="$page = '/index.aspx'">

                            <xsl:attribute name="href"><xsl:value-of select="@path" /></xsl:attribute><xsl:value-of select="@name" />

                    </xsl:when>

                    <xsl:when test="@path=$page and $page != '/index.aspx'">

                            <xsl:attribute name="href"><xsl:value-of select="@path" /></xsl:attribute><xsl:value-of select="@name" />

                                <xsl:for-each select="/root/menu/nav[@path=$page]/child::*">

                                        <xsl:attribute name="href"><xsl:value-of select="@path" /></xsl:attribute><xsl:value-of select="@name" />

                                </xsl:for-each>

                    </xsl:when>

                    <xsl:otherwise>

                            <xsl:attribute name="href"><xsl:value-of select="@path" /></xsl:attribute><xsl:value-of select="@name" />

                    </xsl:otherwise>

                </xsl:choose>

            </xsl:for-each>

    </xsl:template>

</xsl:stylesheet>

XML file looks something like this:
<root name="menutest">
  <menu>

  </menu>
</root>

This basically only shows first tier  children based on param "$page".
Example(s) of how the menu works and which nodes selected, basically aligned  nodes are children, indented nodes are child of parents and so on etc etc. xml example http://fraudo.orconhosting.net.nz/xml.png
TIA
Jared
Updated code snippet
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" />
    <xsl:param name="page" select="'index.aspx'"/>

    <xsl:template name="makeUL">

            <xsl:apply-templates/>

    </xsl:template>
    <xsl:template match="nav">

            <xsl:if test=".//@path = $page and $page != '/index.aspx'">
                <xsl:attribute name="class"><xsl:text>children-open current-menu-page</xsl:text></xsl:attribute>
             </xsl:if>

                <xsl:value-of select="@name" />

            <xsl:if test=".//@path = $page and $page != '/index.aspx'">
                 <xsl:call-template name="makeUL"/>
            </xsl:if>

    </xsl:template>
</xsl:stylesheet>

I also echo out "ul" before the xml parsing, but I may have that wrong :).
echo '
'."\n\r";
    echo $xsl->transformToXML($dom);
echo '
'."\n\r";

A: The root cause of your trouble is that you are trying to use "pull" processing - traditional constructs like xsl:for-each and xsl:choose, instead of writing it "the XSLT way" using template rules and xsl:apply-templates. It's usually possible to write your code in "pull" style, but experts avoid it because it tends to lead you into this kind of trouble.
I say "usually", but one case where it isn't possible is when your input data is recursive (nav elements within nav elements, indefinitely nested). You can only process recursive data using recursive code, and in this situation, the apply-templates style of coding becomes essential. Sit down with a tutorial and read some examples until you have understood the concept, and then use it in your coding.

A: If you want to expand the branch of tree containing the identified node, this stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" />
    <xsl:param name="page" select="'menulink1childlink1.php'"/>
    <xsl:template match="menu" name="makeUL">

            <xsl:apply-templates/>

    </xsl:template>
    <xsl:template match="nav">

                <xsl:value-of select="@name" />

            <xsl:if test=".//@path = $page">
                <xsl:call-template name="makeUL"/>
            </xsl:if>

    </xsl:template>
</xsl:stylesheet>

Output:

home

menulink1

menulink1child1

menulink1child1child1

menulink2

menulink3

menulink4

Rendered:

*

*home

*menulink1

*

*menulink1child1

*

*menulink1child1child1

*menulink2

*menulink3

*menulink4

Note: This is the only case where .// abbreviation can be handy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check CPU percentage of computing node used How can I can the CPU percentage used of each node when say job J is submitted to queue Q?
I don't want it specific to a queue which qstat gives, but specific to a job.

A: Assuming that you are using Torque/Moab you should be able to use the checkjob(documentation linked) command to get more detailed information about the job you are interested in.  Something like:
checkjob -v exact:J -n <Insert Node ID here>

Should work to get you more information about the job, the -v, -n and Node ID are optional.
Alternately if you know the node ID/name you can use the checknode command and associated options to get more information about the node the job is being run on.  Hopefully that helps.


text:
Q: installing packages on pycharm issue so i was trying to install pygame, i went to the cmd and did the pip install pygame everything was successfully until i went on pycharm, i did everything: i went to file > setting > pythonProjects > interpreter > searched "pygame" > install package
and then was the problemerorr
i did what they talled me to do, didnt work, i did everything the google said and didnt work. pls help erorr details

A: Are you currently using 3.11? Try rolling back to an earlier version of Python.
*Also, try putting a little more effort into drafting your question. You will be much more likely to get an answer to your question if you make sure you spell everything correctly and use proper grammar. Welcome to stack overflow!
Edit: Here's a link to JetBrains (PyCharm parent company) documentation that covers changing your interpreter: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-reloading-interpreter-paths.html


text:
Q: vcalendar vs icalendar What is the difference between vcalendar and icalendar? Is it only the VERSION difference as  1.0 and 2.0 respectively?
For sending a Meeting Request with iCalendar and vcalendar, I specify the MIME type as text/calendar.
The email sent with iCalendar appears as a Meeting Request while the one with vCalendar appears as an attachment. When I double click the attachment, it opens up as an Appointment.

A: I figured this out myself.
iCalendar is used to display Meeting Requests while vCalendar is used for Appointments. Meeting Requests have attendees while Appointments don't.


text:
Q: Best Strategies for preventing addresses with PO Boxes? I have a client which is shipping via UPS, and therefore cannot deliver to Post Office boxes. I would like to be able to validate customer address fields in order to prevent them from entering addresses which include a PO box. It would be best if this were implemented as a regex so that I could use a client-side regex validation control (ASP.NET).
I realize there's probably no way to get a 100% detection rate, I'm just looking for something that will work most of the time.

A: UPS also has tools that you can integrate to do this... that way you can verify an address exactly as to whether or not they will ship, what the cost would be, schedules, etc. I suggest visiting the UPS IT Solutions page for more information.

A: This should get you started.  Test to see if the Address field matches this regex.
"^P\.?\s?O\.?\sB[Oo][Xx]."

Translation to English:  That's a P at the beginning of the line, followed by an optional period and space, followed by an O, followed by an optional period, followed by a space, followed by "Box", followed by anything else.

A: You might be better off putting a disclaimer on the page warning that you can not ship to post office boxes, opposed to validating the input.
More than likely if you do create a regex that catches most of the P.O. Box scenarios, there's a good chance it'll also catch things you weren't intending (i.e. a customer with a street name containing the letters 'p' 'o' and 'box')

A: Unfortunately, UPS's online software allows P.O. Boxes to go through, but will choke on them once they're in the shipping channel.
In our case, our cart abandonment rate went up when we tried to gracefully prevent P.O. Boxes.  We found it much more cost effective to leave it alone, accept the sale, bring it to the attention of customer service, and let them resolve it.
Of course, if you get a high incidence of P.O Boxes, this may not be the case for you.

A: I'd start with a regex ala Lizard (but use the "ignore case" flag :)), test on historical data, then iterate as you see what invalid inclusions and exclusions you see in testing.

A: Most shipping providers (for example FedEx) will validate the shipping address. For example, with FedEx web services, there is a call to validate a shipping address and get the estimated cost. This not only ensures that the address is not a PO Box, but also makes sure that the rest of the address is valid.

A: Regarding the OP's comment to Jason Coco's answer:
Since you're in a position to add regex validation to the shipping address, I assume that you have control of the application (i.e., you have the source and can modify it).  If that's the case, then you should have the ability to, on reciept of the submitted data, check whether it is to be shipped via USPS, FedEx, or UPS and submit a request to the appropriate shipper-specific address validator, gaining all the benefits suggested in Jason's answer.
By making it shipper-specific, this would also allow you to avoid implementing one-size-fits-all rules, such as "no PO boxes because UPS doesn't deliver to them", even though the user can select non-UPS shippers who do deliver to PO boxes.

A: What if it doesn't start with "PO Box.." or "P.O. Box" ?
Example:
John Schmidt |
Silver Valley PO Box 3901 |
Whereswaldoville, SI. 78946
I used an onblur event for the address field to use a javascript function, indexOf, to recognize the input.toUpperCase "PO BOX" || "P.O" that is >= 0.
If either of these two searches are not found, the return is -1, otherwise, it will return the string's start position which will always be 0 or more.
This will ensure that lazy typing, 'po box,' 'p.o box,' and as well as 'p.o. box' will be recognized.  I suppose you could add 'po. box' as well.
Anyway, the condition triggers an unobtrusive message to show that 'We can't ship to a PO Box address." It's a feature to not see it if it doesn't apply to you.  Otherwise, for users who don't have js or css enabled, they'll just see the message.  The only fail on this graceful degradation is if a user has css, but not js enabled (where they just won't see the message at all).  I only came up with the solution today, but if I think of a better way, I'll come back to post it here.


text:
Q: Can we set minimum value for FrameworkPropertyMetadata default value Here is the code:
new FrameworkPropertyMetadata( (uint) 100,...

We can set in max value here as 100, is there a way to set minimum value too? Let's say I want this default value to be between 5 and 100? I looked all over Google did not find any answers. Can anybody please suggest a solution. Thanks!
Code tried according to Reed Copsey
public static bool IsValidReading(object value)
{
    uint v = (uint)value;
    return (!v.Equals(0));
}

Full code:
public static readonly DependencyProperty Result =
            DependencyProperty.Register(
                "ResultLimit", typeof( uint ), typeof( UI ),
                new FrameworkPropertyMetadata( ( uint )10, new PropertyChangedCallback( ResultChanged ) ), IsValidReading );

A: The value is not the max value - it's the default value.
There is no way to specify the min or max in the metadata directly.  This should be handled via a Callback registered with the Dependency Property.


text:
Q: Парсинг с изменением ссылки Хочу написать программу, которая бы парсила сайт wooordhunt.ru и выдавала бы транскрипцию, например с помощью телеграм бота. Я знаю как передавать информацию в бот, но мне непонятно как правильно парсить целый сайт - раньше я занимался отдельными страницами.
Я заметил, что ссылка на искомое слово имеет следующий вид: wooordhunt.ru/слово, соответственно, при инпуте пользователя необходимо будет парсить конкретно эту страницу. С помощью каких инструментов лучше реализовать такой парсер?


text:
Q: Retrieving id and not position from class to activity using intent displays nothing I am new in developing mobile applications. I am trying to pass a variable from class to a new activity, but it displays nothing. However, this variable is retrieved from the products adapter.
I am new in developing mobile applications. I am trying to pass a variable from class to a new activity, but it displays nothing. However, this variable is retrieved from the products adapter.
The Class
package net.simplifiedlearning.volleymysqlexample;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;
import android.util.Log;
/**
 * Created by Belal on 10/18/2017.
 */

public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductViewHolder> {

    private Context mCtx;
    private List<Product> productList;

    public ProductsAdapter(Context mCtx, List<Product> productList) {
        this.mCtx = mCtx;
        this.productList = productList;
    }

    @Override
    public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.product_list, null);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ProductViewHolder holder, int position) {
        Product product = productList.get(position);

        holder.textViewTitle.setText(product.getTitle());
    }

    @Override
    public int getItemCount() {
        return productList.size();
    }

    class ProductViewHolder extends RecyclerView.ViewHolder {

        TextView textViewTitle;

        public ProductViewHolder(View itemView) {
            super(itemView);

            textViewTitle = itemView.findViewById(R.id.textViewTitle);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent;

                    intent = new Intent(mCtx , Eservice.class);
                    int position = getAdapterPosition();
                    intent  = intent.putExtra("KEY",  productList.get(position).getId());
                    mCtx.startActivity(intent);
                }
            });
        }
    }
}

The activity
package net.simplifiedlearning.volleymysqlexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Eservice extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eservice);

        String id = getIntent().getExtras().getString("KEY");
        TextView access_text = (TextView) findViewById(R.id.access_text);
        access_text.setText(id);
    }
}

Layout for the activity and the other is just a class
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/access"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/access_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#000" />

</LinearLayout>

Th class displaying products
package net.simplifiedlearning.volleymysqlexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.util.ArrayList;

import android.widget.AdapterView;
import android.widget.GridView;

import android.view.*;
import android.widget.*;
import java.util.*;
import android.content.*;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ProductS extends AppCompatActivity {

    //this is the JSON Data URL
    //make sure you are using the correct ip else it will not work
    private static final String URL_PRODUCTS = "https://syncsecser.com/testmob/api-fetch.php";

    //a list to store all the products
    List<Product> productList;

    //the recyclerview
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_s);

        //getting the recyclerview from xml
        recyclerView = (RecyclerView) findViewById(R.id.recylcerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
       // selecting item in recycler view

        //initializing the productlist
        productList = new ArrayList<>();
        loadProducts();
    }

    private void loadProducts() {

        /*
        * Creating a String Request
        * The request type is GET defined by first parameter
        * The URL is defined in the second parameter
        * Then we have a Response Listener and a Error Listener
        * In response listener we will get the JSON response as a String
        * */
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //converting the string to json array object
                            JSONArray array = new JSONArray(response);

                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {

                                //getting product object from json array
                                JSONObject product = array.getJSONObject(i);

                                //adding the product to product list
                                productList.add(new Product(
                                    product.getInt("id"),
                                    product.getString("title")
                                ));
                            }

                            //creating adapter object and setting it to recyclerview
                            ProductsAdapter adapter = new ProductsAdapter(ProductS.this, productList);
                            recyclerView.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);
    }
}

A: Your productList.get(position).getId() is returning Int. Try changing it to String


text:
Q: ng-route get parameters from url I faced an issue while getting param using ng-route
where param value contain '==' that is remove from URL

index.html#/app/test?param=value==

when use $state.params.param
i suppose the result should be 'value==' but it is actual return 'value'

A: Try to use this below code.....
GetEmployeId : function () {//this function will get the last value of current page url.
        var urlPath = $window.location.href;
        var result = String(urlPath).split("/"); //will split the url by forword slash
        if (result != null && result.length > 0) {
           var id = result[result.length - 1]; //will get the last value from url.
            return id;
        }
    },

See here the complete article.

A: it is a bug on angular 1.3

Solve :  I upgrade to 1.6


text:
Q: Android tabs in AlertDialog Can I have tabs in AlertDialog?
I've gone through a lot of online tutorials and they usually place the intent from one activity to another in the tabs. However the alert dialog is all within a single activity.
I want to have two tabs in one alert dialog.

A:
Can I have tabs in AlertDialog?

Presumably you can use TabHost and TabWidget in an AlertDialog, using views for the tabs. This sample shows views-as-tabs in an activity: https://github.com/commonsguy/cw-omnibus/tree/master/WidgetCatalog/Tab In your case, you would use the same sort of layout, but use LayoutInflater to create the View that you then use with AlertDialog.Builder to create the dialog.

I've gone through a lot of online tutorials and they usually place the intent from one activity to another in the tabs.

Those tutorials are obsolete now IMHO. The whole technique of embedding activities in tabs has been deprecated.


text:
Q: Testing of even easy behaviour leads to a jungle of testing functions Until today I had a hard time with unit testing. For this reason I just started to read a book "The art of Unit Testing".
The author states that each "unit of work" has entry and exit points and that there should be a unit test for each exit point.
An "exit point" could be:

*

*A return value of a function (also an exception)

*A state change (for example of a class property)

*A third party system called (E-Mail service)

The entry point is usually a function call.
I was now eager to try this in one of my examples and I was successful. But for a price that I cannot accept.  My tests are a huge amount of functions and I would like to get your opinion about them.
The test class I want to use is easy:
public class RoleAssignement
{
    public string RoleId { get; }
    public string EnterpriseId { get; }
    public List<string> SiteIds { get; }

    public RoleAssignement(string roleId, string enterpriseScopeId)
    {
        Ensure.ThrowIfNull(roleId);
        Ensure.ThrowIfNull(enterpriseScopeId);
        Ensure.ThrowIfIdNotValid(roleId);
        Ensure.ThrowIfIdNotValid(enterpriseScopeId);

        RoleId = roleId;
        EnterpriseId = enterpriseScopeId;
    }

    public RoleAssignement(string roleId, List<string> siteScopeIds)
    {
        Ensure.ThrowIfNull(roleId);
        Ensure.ThrowIfNull(siteScopeIds);
        Ensure.ThrowIfIdNotValid(roleId);
        foreach(var id in siteScopeIds)
        {
            Ensure.ThrowIfIdNotValid(id);
        }
        RoleId = roleId;
        SiteIds = siteScopeIds;
    }
}

You can see that I have just three properties. One of them (RoleId) must be set always. The other two parameters should be exclusively set (if one is null, the other must be set and vice versa).
In the language of the book I have two "entry points" - my two constructors.
But I have ten exit points that are:
1 If roleId is null for the first constructor, an exception should be thrown.
2 If roleId is null for the second constructor, an exception should be thrown.
3 If enterpriseScopeId is null for the first constructor, an exception should be thrown.
4 If siteScopeId is null for the second constructor, an exception should be thrown.
5, 6, 7, 8 If any of the four parameters have an invalid id, an exception should be thrown.
9 If the first constructor was called with the correct parameters, RoleId and EnterpriseId should be set but SiteIds should be null.
10 If the second constructor was called => vice versa.

If I write my unit tests now, I get a long list of testing functions - one of each exit point. I pasted this in the end of my question.
The thing is: Am I really on the right way here? I have a very easy test class now and the tests for it seem to explode in a huge jungle of tests.
Testing each possible exit point with its own function will slow me down in my coding and because the tests are testing such an easy behaviour they are also worthless for me.
Or are they?
But what will happen if I start to test the more complicated things? I will have a project with 1000 lines of production code and 10000 lines of tedious test functions.
I think I misunderstood something, but I don't know what I misunderstood. Or am I okay with my tests and I have to live with this from now?
Here is my testing code - all tests are passing. I even wrote them following TDD:

Testing code: ~100 lines
Production code: ~30 lines
Really?
using CP.Admin.Core.SDK.ValueObjects;
using DataHive.Validations.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace CP.Admin.Tests
{
    [TestClass]
    public class RoleAssignementTests
    {
        [TestMethod]
        public void RoleAssignementFirst_NullRoleIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =>
            {
                var roleAssignement = new RoleAssignement(null, "62500ac55988223c8b9b28fc");
            };
            Assert.ThrowsException<ArgumentNullException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_InvalidRoleIdParameter_ThrowsIdNotValidException()
        {
            Action useConstructor = () =>
            {
                var roleAssignement = new RoleAssignement("invalidId", "62500ac55988223c8b9b28fc");
            };
            Assert.ThrowsException<IdNotValidException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_NullEnterpriseScopeIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =>
            {
                string param = null;
                var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", param);
            };
            Assert.ThrowsException<ArgumentNullException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_InvalidEnterpriseScopeIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =>
            {
                var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", "invalidId");
            };
            Assert.ThrowsException<IdNotValidException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_NullRoleIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =>
            {
                var param = new List<string> { "62500ac55988223c8b9b28fc" };
                var roleAssignement = new RoleAssignement(null, param);
            };
            Assert.ThrowsException<ArgumentNullException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_InvalidRoleIdParameter_ThrowsIdNotValidException()
        {
            Action useConstructor = () =>
            {
                var param = new List<string> { "62500ac55988223c8b9b28fc" };
                var roleAssignement = new RoleAssignement("invalidId", param);
            };
            Assert.ThrowsException<IdNotValidException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_NullSiteScopeIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =>
            {
                List<string> param = null;
                var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", param);
            };
            Assert.ThrowsException<ArgumentNullException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_InvalidSiteScopeIdParameter_ThrowsIdNotValidException()
        {
            Action useConstructor = () =>
            {
                var param = new List<string> { "invalidId" };
                var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", param);
            };
            Assert.ThrowsException<IdNotValidException>(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_ParametersAreOkay_AllValuesAreCorrect()
        {
            var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", "62500ac55988223c8b9b28fc");
            Assert.IsNotNull(roleAssignement.RoleId);
            Assert.IsNotNull(roleAssignement.EnterpriseId);
            Assert.IsNull(roleAssignement.SiteIds);
        }
        [TestMethod]
        public void RoleAssignementSecond_ParametersAreOkay_AllValuesAreCorrect()
        {
            var param = new List<string> { "62500ac55988223c8b9b28fc" };
            var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", param);
            Assert.IsNotNull(roleAssignement.RoleId);
            Assert.IsNotNull(roleAssignement.SiteIds);
            Assert.IsNull(roleAssignement.EnterpriseId);
        }
    }
}

A: As you recognize, going down this road will be very painful. Because wanting to assert for each possible case (every parameter value + every possible combination) will require (as you saw) more work than making the actual production code to work.
All of this because you are orienting tests regarding data.
If you consider testing the behavior of the system instead, you can break free from a lot of implementation details and focus on a higher level.
Considering behavior, the only one that I can eventually see is

The other two parameters should be exclusively set (if one is null, the other must be set and vice versa).

It corresponds to scenarii 9 and 10 according to your numerotation:
[TestMethod]
public void RoleAssignementFirst_ParametersAreOkay_AllValuesAreCorrect()
{
    var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", "62500ac55988223c8b9b28fc");
    Assert.IsNotNull(roleAssignement.RoleId);
    Assert.IsNotNull(roleAssignement.EnterpriseId);
    Assert.IsNull(roleAssignement.SiteIds);
}

[TestMethod]
public void RoleAssignementSecond_ParametersAreOkay_AllValuesAreCorrect()
{
    var param = new List<string> { "62500ac55988223c8b9b28fc" };
    var roleAssignement = new RoleAssignement("62500ac55988223c8b9b28fc", param);
    Assert.IsNotNull(roleAssignement.RoleId);
    Assert.IsNotNull(roleAssignement.SiteIds);
    Assert.IsNull(roleAssignement.EnterpriseId);
}

Now the test codebase has a significant smaller proportion than before comparing to the production codebase, which is a better compromise because it tests the most important thing at a greatly reduced price (both in implementation and maintenance).
Going further
Let me allow you to see something that you may never has thought would be possible. RoleAssignment could require no tests and still enforce the same rules as the one you want by better using the type system.
Consider the following code:
public class RoleAssignement
{
    public Id RoleId { get; }
    public Either<Id, List<Id>> RelatedIds { get; }

    public RoleAssignement(Id roleId, Either<Id, List<Id>> relatedIds)
    {
        RoleId = roleId;
        RelatedIds = relatedIds;
    }
}

I used a pattern called Value Object to get rid of primitive types. These value objects (Id and Either) encapsulate all the validation for a Id to be considered valid. When given to RoleAssignement constructor, you then know for sure that you are handling correct values. No more tests needed for RoleAssignement, the type system already enforce your constraints !
You can then extract tests from your scenarii to test only value object construction once. Which means that even if Id is used everywhere through the codebase, it requires only to test once.


text:
Q: How to combine NSData objects from Bluetooth packet I have the following bluetooth packet which contains these individual values:
value 1: 0x2710
value 2: 0000
value 3: 0xFFF
value 4: 0xFEE
value 5: 0x426
The complete packet looks like this: 0x2710 0 FFF FEE 426
My question is how can I convert these values/the complete packet into an NSData object?


text:
Q: VBA for formatting stops in specific range Well I guess it might be a silly question but i could not figure ir out by myself.
I have a WB that has various macros  within it. One for copy a template(creating a new WS every time it is necessary) that the user fills ups. After, one macro for coping the results to a 'Summary' WS, then another that applies a formula, after that, one that applies a score (good, bad, ok) and the last one that copies the format of scpecifics cells to give a proper formating to print it.
This last one is acting wierd. I created more than 40 WS (copping the template) but the formatting one stops on the 25th line. I don't know why.
I have used the formula to copy till last row, but nothing can make this thing work.
Bellow follows the result and the code. I thought that the problem could be that I compressed all the command in one sub, so I break it in variuos ones and created a 'trigger' button to activate all of this commands.
If my explaniation is not enought, just ask for more info.
In advance, thanks for all the help!
Erro on the formatting

The code I used.
==============
Sub FormatarCab()

Dim sht As Worksheet
Dim LastRow As Long

Set sht = ActiveSheet

'Using Find Function (Provided by Bob Ulmas)
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

'Para o cabeçalho
Worksheets("Descritivo").Range("B50").Copy
Worksheets("Avaliação Todos").Range("A1:E1").PasteSpecial xlPasteFormats

Application.CutCopyMode = False
End Sub

'-------------------------------------
Sub FormatarNome()

Dim sht As Worksheet
Dim LastRow As Long

Set sht = ActiveSheet

'Using Find Function (Provided by Bob Ulmas)
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

'Para os Nomes das Abas
Worksheets("Descritivo").Range("B52").Copy
Worksheets("Avaliação Todos").Range("A2:A" & LastRow).PasteSpecial xlPasteFormats

Application.CutCopyMode = False
End Sub

'-------------------------------------
Sub FormatarConceito()

Dim sht As Worksheet
Dim LastRow As Long

Set sht = ActiveSheet

'Using Find Function (Provided by Bob Ulmas)
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

'Para o Conceito
Worksheets("Descritivo").Range("B54").Copy
Worksheets("Avaliação Todos").Range("E2:E" & LastRow).PasteSpecial xlPasteFormats

Application.CutCopyMode = False
End Sub

'-------------------------------------
Sub FormatarValores()

Dim sht As Worksheet
Dim LastRow As Long

Set sht = ActiveSheet

'Using Find Function (Provided by Bob Ulmas)
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

'Para os valoreso
Worksheets("Descritivo").Range("B56").Copy
Worksheets("Avaliação Todos").Range("B2:D" & LastRow).PasteSpecial xlPasteFormats

Application.CutCopyMode = False
End Sub

==============
The sctructure for the function LastRow
==============
Option Explicit

'Common Functions required for all routines:

Function LastRow(Sh As Worksheet)
    On Error Resume Next
    LastRow = Sh.Cells.Find(What:="*", _
                            After:=Sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByRows, _
                            searchdirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

Function LastCol(Sh As Worksheet)
    On Error Resume Next
    LastCol = Sh.Cells.Find(What:="*", _
                            After:=Sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlFormulas, _
                            SearchOrder:=xlByColumns, _
                            searchdirection:=xlPrevious, _
                            MatchCase:=False).Column
    On Error GoTo 0
End Function

==============

A: Ignoring the LastRow function that you've added to the bottom of the code but don't actually use, you're setting a variable called LastRow with the value of the lowest cell found in sht - which is Set to ActiveSheet.
You then paste down from E2 to E & LastRow - but not necessarily of ActiveSheet - in fact you do this on Worksheets("Avaliação Todos")
You want LastRow to be based on the bottom row of the sheet you're going to paste upon so - it should look like this:
Sub FormatarCab()

    Dim LastRow As Long

    With Worksheets("Avaliação Todos")

        'Using Find Function (Provided by Bob Ulmas)
        LastRow = .Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

        'Para o cabeçalho
        Worksheets("Descritivo").Range("B50").Copy
        .Range("A1:E1").PasteSpecial xlPasteFormats

    End With

    Application.CutCopyMode = False
End Sub

'-------------------------------------

Sub FormatarNome()

    Dim LastRow As Long

    With Worksheets("Avaliação Todos")

        'Using Find Function (Provided by Bob Ulmas)
        LastRow = .Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

        'Para os Nomes das Abas
        Worksheets("Descritivo").Range("B52").Copy
        .Range("A2:A" & LastRow).PasteSpecial xlPasteFormats

    End With

    Application.CutCopyMode = False
End Sub

'-------------------------------------

Sub FormatarConceito()

    Dim LastRow As Long

    With Worksheets("Avaliação Todos")

        'Using Find Function (Provided by Bob Ulmas)
        LastRow = .Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

        'Para o Conceito
        Worksheets("Descritivo").Range("B54").Copy
        .Range("E2:E" & LastRow).PasteSpecial xlPasteFormats

    End With

    Application.CutCopyMode = False
End Sub

'-------------------------------------

Sub FormatarValores()

    Dim LastRow As Long

    With Worksheets("Avaliação Todos")

        'Using Find Function (Provided by Bob Ulmas)
        LastRow = .Cells.Find("*", SearchOrder:=xlByRows, searchdirection:=xlPrevious).Row

        'Para os valoreso
        Worksheets("Descritivo").Range("B56").Copy
        .Range("B2:D" & LastRow).PasteSpecial xlPasteFormats

    End With

    Application.CutCopyMode = False
End Sub

A: If your looking to find the last row or column you can use the below:
Dim lc As Long
Dim lr As Long

'Change the 1 to whatever row you would want to be able to check for the last true column.
lc = Cells(1, Columns.Count).End(xlToLeft).Column 'determines total number of columns

'Change the "A" to whatever row would show the last row and be consistent for all your worksheets
lr = Range("A" & Rows.Count).End(xlUp).Row 'determines total number of rows including header

The above assumes that you have consistent data


text:
Q: Spivak, Ch. 15, Problem *26c: show $\lim\limits_{\lambda\to \infty} \int_a^b f(x)\sin{(\lambda x)}dx=0$ for any $f$ integrable on $[a,b]$. The following problem is from Ch. 15 of Spivak's Calculus. My question is about understanding the solution manual solution to item $(c)$. I've asked a separate question about my own attempt at a solution which differs from the solution manual.

*26. It is an excellent test of intuition to predict the value of
$$\lim\limits_{\lambda\to \infty} \int_a^b f(x)\sin{(\lambda x)}dx$$
Continuous functions should be the most accessible to intuition, but
once you get the right idea for a proof the limit can easily be
established for any integrable $f$
(a) Show that $\lim\limits_{\lambda\to \infty} \int_a^b \sin{(\lambda
 x)}dx=0$, by computing the integral explicitly.
(b) Show that if $s$ is a step function on $[a,b]$, then
$\lim\limits_{\lambda\to \infty} \int_a^b s(x)\sin{(\lambda x)}dx=0$.
(c) Finally, use Problem 13-26 to show that $\lim\limits_{\lambda\to
 \infty} \int_a^b f(x)\sin{(\lambda x)}dx=0$ for any function $f$ which
is integrable on $[a,b]$. This result, like Problem 12, plays an
important role in the theory of Fourier series; it is known as the
Riemann-Lebesgue Lemma.

Item $(a)$ is just the limit of a definite integral
$$\lim\limits_{\lambda\to \infty} \int_a^b \sin{(\lambda x)}dx$$
$$=\lim\limits_{\lambda\to \infty} -\frac{1}{\lambda}\left ( \cos{(\lambda d)}-\cos{(\lambda c)} \right )=0$$
For item $(b)$, note that a step function is defined based on a partition $P=\{t_0,...,t_n\}$ of $[a,b]$. Then
$$\lim\limits_{\lambda\to \infty}\int_a^b s(x)\sin{(\lambda x)}dx=\lim\limits_{\lambda\to \infty} \sum_{i=1}^n s_i\int_{t_{i-1}}^{t_i} \sin{(\lambda x)}dx=0$$
For the items above, my solution coincided with the solution manual. For item $(c)$ my solution was different. For now I'd like to understand the solution manual solution (specifically the last part of it). Here it is
Solution Manual Solution to $(c)$

For any $\epsilon>0$ there is, by Problem 13-16, a step function
$s\leq f$ with
$$\int_a^b [f(x)-s(x)]dx<\epsilon$$
Now
$$\left | \int_a^b f(x)\sin{(\lambda x)}dx-\int_a^b s(x)\sin{(\lambda
 x)}dx \right |\tag{1}$$ $$=\left | \int_a^b [f(x)-s(x)]\sin{(\lambda x)} dx \right
 |$$
$$\leq \int_a^b [f(x)-s(x)]\cdot |\sin{(\lambda x)} |dx$$
$$\leq \int_a^b [f(x)-s(x)]dx<\epsilon\tag{2}$$

So far so good

Part $(b)$ then shows that
$$\lim\limits_{\lambda\to \infty} \left | \int_a^b f(x)\sin{(\lambda
 x)}dx \right |<\epsilon$$
Since this is true for every $\epsilon>0$, the limit must be $0$.

I'd like to understand this last part.
I think what happened is that from $(1)$ we had
$$\left | \int_a^b f(x)\sin{(\lambda x)}dx\right | -\left | \int_a^b s(x)\sin{(\lambda
 x)}dx \right |\leq\left | \int_a^b f(x)\sin{(\lambda x)}dx-\int_a^b s(x)\sin{(\lambda
 x)}dx \right |<\epsilon$$
and then we took the limit
$$\lim\limits_{\lambda\to \infty}\left | \int_a^b f(x)\sin{(\lambda x)}dx\right | -\lim\limits_{\lambda\to \infty}\left | \int_a^b s(x)\sin{(\lambda
 x)}dx \right |<\epsilon$$
But since from $(b)$ we know that $\lim\limits_{\lambda\to \infty}\left | \int_a^b s(x)\sin{(\lambda
 x)}dx\right |=0$ we have
$$\lim\limits_{\lambda\to \infty}\left | \int_a^b f(x)\sin{(\lambda x)}dx\right |<\epsilon$$
Is this filling in of the steps correct?

A: The filling of the missing steps does not look correct because:
$\lim\limits_{\lambda\to \infty}\int_a^b f(x)\sin{(\lambda x)}dx$ is not known to exist so in $\left | \int_a^b f(x)\sin{(\lambda x)}dx\right | -\left | \int_a^b s(x)\sin{(\lambda
 x)}dx \right |<\epsilon$, it is not known if limit of LHS exists.
You could fill in the gaps as follows:
"Part (b) then shows that"
By part $(b)$, there is an $M>0$ such that for all $\lambda>M$, $\left | \int_a^b s(x)\sin{(\lambda
 x)}dx \right |\lt \epsilon$.
So for all $\lambda>M$, $\left | \int_a^b f(x)\sin{(\lambda x)}dx\right|\le\left | \int_a^b f(x)\sin{(\lambda x)}dx - \int_a^b s(x)\sin{(\lambda
 x)}dx \right |+ \left | \int_a^b s(x)\sin{(\lambda
 x)}dx \right |<2\epsilon$


text:
Q: IBM Notes database - Slow I am currently working with IBM notes and I realize that it is sometimes very slow. Our database runs on a Server and my question is: What if 100 users have a Notes client in which they access and edit documents(which are in a database from that server) at the same time. Would that cause slowness because too many people do too many actions on that server?

A:
I got the answers from the comments on my question and posted it as an
  answer. Thank you @Torsten Link and @Richard Schwartz:

Comment from @Torsten Link:
This question is wrong here, belongs to serverfault or superuser. Just one thing: We have servers, they have 2.000 concurrent users, and they are not slow at all (and these are "small environments" for Domino- servers). IF the application is slow, then a) the application is very bad or b) the server configuration is bad or c) the client configuration is miserable
Reply on above comment from me:
@TorstenLink Thank you very much for taking time to anwser, may I know how much servers you got and which is the most active one an how big are the notes databases on that server.
Answer from @TorstenLink:
I am consultant and know everything from single server environments to worldwide environments with 2.000 or more users per server... This question is to broad: The answer is "this is not normal". But a fix for it might involve a lot of analysis for the reasons for the slowlyness.
Comment from @Richard Schwartz:
Torsten is correct. Properly designed Domino applications or perform well under loads from thousands of users as long as the hardware is adequate - and very modest hardware can easily handle 100 users. But if the application is poorly designed, or if the hardware is not up to the job, then of course it can be slow. An experienced Domino consultant would look at all aspects of the problem; there are far too many possible issues to consider and StackOverflow isn't designed for the type of detailed back-and-forth dialogue that would be required to help you narrow it down.


text:
Q: Merge multiple static libraries into one GCC scons I'm building this library, libmyproject.a
I want it to include several other static libraries (libone.a and libtwo.a), so that the application that links with libmyproject doesn't have to link with libone and libtwo as well.
I'm new to the GCC chain. With Visual C++, I would just add all dependencies and it would create a lib which also includes all other libs that I want in it.
How can I accomplish this with GCC ?
A bonus question: I'm using scons to build, is there a way to tell scons to do this ?
Right now it just ignores all the additional libs that I supply and only compiles the .cpp files into the library.

A: You have to use ar (binutils) for operations on archive files. I am using a simple Perl script to do the merging:
#!/usr/bin/perl

use warnings;
use strict;
use File::Temp qw(tempdir);
use File::Basename;
use Getopt::Long;

my %opt;
if (!GetOptions(\%opt,
                "dest=s",
               )) {
  die "Invalid option!";
}

my $tempdir = tempdir( CLEANUP => 1 );

if (!chdir($tempdir)) {
    die "Couldn't change directories to `$tempdir': $!";
}

foreach my $lib (@ARGV) {
    my $subdir = $tempdir . '/' . basename($lib);
    mkdir($subdir) or die "Unable to make $subdir: $!";
    chdir($subdir) or die "Unable to cd $subdir: $!";
    system("ar x $lib");
}
chdir($tempdir) or die "Unable to cd $tempdir: $!";
system("ar cr $opt{dest} */*.o") == 0 or die "'ar cr' failed: $?";
system("ranlib $opt{dest}") == 0 or die "'ranlib' failed: $?";

exit 0;

To invoke the script in SCons:
# this can be put to site_scons/site_init.py
def MergeLibs(env, target, sources):
    """Rapack multiple archive files into one."""
    merge_libs_tool = os.path.join('$TOOLS_DIR', 'merge_libraries.pl')
    lib = env.Command('${LIBPREFIX}' + target + '${LIBSUFFIX}', [merge_libs_tool] + sources,
            '$SOURCE -dest ${TARGET.abspath} ${SOURCES[1:].abspath}')
    return lib

# lib_one = env.StaticLibrary(...)
# lib_two = env.StaticLibrary(...)
# merged_lib = env.MergeLibs('myproject', [libone, libtwo])

Of course, you can merge libraries using Python function inside SCons. I prefer using a separate script, so it can be run from command line as any other build tool.


text:
Q: XMLReader - Blank Page With No Errors I'm trying to get the data from an XML file into an array so that I can import it via 'Magmi'. Using the following code, I'm working with a 3.6GB XML file.
<?php

$z = new XMLReader;
$z->open('wpcatsub.xml');

$doc = new DOMDocument;

// move to the first <App /> node
while ($z->read() && $z->name !== 'App');

// now that we're at the right depth, hop to the next <App/> until the end of the tree
while ($z->name === 'App')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('App');
}

?>

When I load the PHP file, no errors appear -- the page is just blank. My XML data structure is below...
<App action="A" id="1">
    <BaseVehicle id= "17491"/>
    <Note><![CDATA[License Plate Lamp]]></Note>
    <Qty>.000</Qty>
    <PartType id= "10043"/>
    <Part>W0133-1620896</Part>
    <Product>
        <PartNumber>W0133-1620896</PartNumber>
        <BrandID>OES</BrandID>
        <BrandDescription><![CDATA[Genuine]]></BrandDescription>
        <WorldpacCategoryID>P9032</WorldpacCategoryID>
        <Price>29.85</Price>
        <ListPrice>33.17</ListPrice>
        <Available>Y</Available>
        <OEFlag>OEM</OEFlag>
        <Weight>.10</Weight>
        <Height>.7</Height>
        <Width>4.4</Width>
        <Length>4.4</Length>
        <SellingIncrement>1</SellingIncrement>
        <Popularity>D</Popularity>
        <ImageURL><![CDATA[http://img.eautopartscatalog.com/live/W01331620896OES.JPG]]></ImageURL>
        <ThumbURL><![CDATA[http://img.eautopartscatalog.com/live/thumb/W01331620896OES.JPG]]></ThumbURL>
    </Product>
    <ImageURL><![CDATA[http://img.eautopartscatalog.com/live/W01331620896OES.JPG]]></ImageURL>
    <ThumbURL><![CDATA[http://img.eautopartscatalog.com/live/thumb/W01331620896OES.JPG]]></ThumbURL>
</App>

Is it stalling because of the size of the file? If so, isn't XMLReader supposed to work for large XML files? If nothing else, what other options would I have?
I suppose I could load the XML data into a database if needed and then use SELECT queries to build the array for the MAGMI import. Though I'm not sure how to import an XML file into a SQL database. If need be, I'll be happy to get guidance with that.


text:
Q: Как анимировать фигуры из paintevent? Я пытался решить проблему с наследованием переменной и когда мне это удавалось - возникали ошибки в самой библиотеке Qt.
from PyQt5 import QtCore, QtGui, QtWidgets, QtQuick
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys

class MainWindow(QtWidgets.QMainWindow):

    def paintEvent(self, e):
        if self.flagPaintEvent:
            painter = QPainter(self)
            painter.setPen(QPen(QColor(100, 250, 250), 1, Qt.SolidLine))
            painter.setBrush(QColor(250, 250, 250))
            painter.drawRect(90, 110, 340, 280)
        self.update()

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setWindowTitle('Main Window')
        self.setFixedSize(1300, 800)
        self.setUpdatesEnabled(True)

        self.flagPaintEvent = True

    def foo(self):
        self.do_anim2()

    def do_anim2(self):
        self.block2 = QtCore.QPropertyAnimation(painter, b'geometry', self)
        self.block2.setStartValue(QRect(75, 30, 16, 16))
        self.block2.setEndValue(QRect(75, 25, 16, 16))
        self.block2.setDuration(150)
        self.block2.start()

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

A: Я не совсем понял, какие фигуры вы хотите анимировать, но приведу пример, который должен вам помочь.
import sys
from PyQt5 import QtCore, QtWidgets, QtGui

class CustomRect(QtWidgets.QGraphicsObject):
    def boundingRect(self):
        return QtCore.QRectF(20, 20, 340, 280)

    def paint(self, painter, styles, widget=None):
        painter.setPen(QtGui.QPen(QtGui.QColor(100, 250, 250), 1, QtCore.Qt.SolidLine))
        painter.setBrush(QtGui.QColor(250, 250, 150))
        painter.drawRect(self.boundingRect())

class Demo(QtWidgets.QGraphicsView):
    def __init__(self):
        super(Demo, self).__init__()

        self.scene = QtWidgets.QGraphicsScene()
        self.scene.setSceneRect(0, 0, 700, 600)

        self.rect = CustomRect()

        self.ellipse = QtWidgets.QGraphicsEllipseItem()
        self.ellipse.setRect(100, 180, 100, 50)
        self.scene.addItem(self.rect)
        self.scene.addItem(self.ellipse)
        self.setScene(self.scene)

        self.animation = QtCore.QPropertyAnimation(
            self.rect,
            b"pos",
            duration=4000,
            startValue=QtCore.QPointF(0, 0),
            endValue=QtCore.QPointF(340, 280),
            loopCount=-1,
        )
        self.animation.start()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    demo = Demo()
    demo.resize(700, 600)
    demo.show()
    sys.exit(app.exec_())

например перерисовывать qpainter, не могли бы вы показать это в коде?

import sys
from PyQt5 import QtCore, QtGui, QtWidgets, QtQuick
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.flagPaintEvent = True

        self.rect = (90, 110, 340, 280)
        btn = QPushButton("Click me", self, clicked=self.onClick)

        self.how_many_times = 50
        self.timer = QTimer(interval=30)
        self.timer.timeout.connect(self.tick)

    def paintEvent(self, e):
        if self.flagPaintEvent:
            painter = QPainter(self)
            painter.setPen(QPen(QColor(100, 250, 250), 1, Qt.SolidLine))
            painter.setBrush(QColor(250, 250, 250))
#            painter.drawRect(90, 110, 340, 280)
            painter.drawRect(*self.rect)

            self.update()

    def tick(self):
        self.how_many_times -= 1
        if self.how_many_times:
            delta = (50-self.how_many_times)*3
            self.rect = (90 + delta, 110 + delta, 340, 280)
        else:
            self.timer.stop()
            self.how_many_times = 50

    def onClick(self):
        self.timer.start()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow()
    main.setWindowTitle('Main Window')
    main.resize(700, 600)
    main.show()
    sys.exit(app.exec_())


text:
Q: elliptic functions on the 17 wallpaper groups In doubly periodic functions as tessellations (other than parallelograms), we learned about the Dixonian elliptic functions. There are 17 wallpaper groups -- are there elliptic function analogues for the other 15 cases (not covered immediately by Jacobian elliptic functions, or Dixonian elliptic functions, or Weierstrass's $\wp$) (they can be expressed in terms of a rational function of $\wp$) ?

A: This is an old question, but it's still interesting.  Here is a more precise version of it:
Definition.  Let $f\colon\mathbb{C}\to\widehat{\mathbb{C}}$ be a meromorphic function.  A Euclidean isometry $g\colon \mathbb{C}\to\mathbb{C}$ is a symmetry of $G$ if $f(g(z))=f(z)$ for all $z\in\mathbb{C}$.  The symmetry group of $f$ is the group of all such symmetries.
Question.  For each wallpaper group $G$, does there exist a non-constant elliptic function whose symmetry group is $G$.
The answer to this question is NO.  In particular, it is easy to show that all symmetries of a non-constant meromorphic function must be orientation-preserving (i.e. no reflections or glide reflections).  This is because the image of a holomorphic function under an orientation-reversing isometry is an antiholomorphic function, and a function that is both holomorphic and antiholomorphic must be constant on each component of its domain.
Therefore, the only possible symmetry groups $G$ are those wallpaper groups that consist solely of orientation-preserving isometries.  There are five such groups: p1, p2, p3, p4 and p6.  I will demonstrate elliptic functions corresponding to each.  Most of the following results were obtained experimentally, and the conjectures are backed by a limited amount of experimental evidence, which I have not included.
Type p1
This is the wallpaper group that consists solely of translations in the two fundamental directions.  Wikipedia uses the following image to illustrate p1 symmetry:

Intuitively, a "typical" elliptic function should have p1 symmetry.  For example, the following plots show the function $\wp\,'(z)$ for the lattice generated by $1$ and $0.2+i$.

(Note: In this picture and all of the subsequent pictures, dark blue indicates negative values and light blue indicates positive values, while the white regions show the placement of the vertical asymptotes.  All of these contour plots were produced in Mathematica.)
Type p2
This wallpaper groups consists of translations as well as certain $180^\circ$ rotations.  Wikipedia uses the following image to illustrate p2 symmetry:

(The diamonds indicate points with $180^\circ$ symmetry.)
Interestingly, the Weierstrass $\wp$-function always has p2 symmetry.  The following plots show the function $\wp(z)$ for the lattice generated by $1$ and $0.2+i$.

(There is $180^\circ$ symmetry around each of the marked points.)
More generally, let $G$ be the p2 group consisting of the translations together with $180^\circ$ rotations at every point of the lattice generated by the half-periods, including the origin.  Then I would conjecture that an elliptic function will be invariant under the action of $G$ if and only if it can be expressed as a rational function of $\wp(z)$ alone (without involving $\wp\,'(z)$).
This does not include every elliptic function with p2 symmetry, because this set is not closed under translation.  In particular, we can "translate" any function with p2 symmetry by any amount at all to obtain another function with p2 symmetry.  The symmetry group of this translated function will be a conjugate of $G$ (specifically, the conjugate of $G$ by the translation used).
Type p4
This wallpaper group only makes sense for the square lattice.  It involves translations as well as several $90^\circ$ and $180^\circ$ rotations.  Wikipedia uses the following image to illustrate p4 symmetry:

(The red and green squares represent points with $90^\circ$ rotational symmetry, and the purple rhombuses represent points with $180^\circ$ rotational symmetry.)
To get an elliptic function with p4 symmetry, we must use a square lattice, e.g. the lattice generated by $1$ and $i$.  In this case, the square of the Weierstrass $\wp$-function has p4 symmetry.  The following plots show $\wp(z)^2$ for the lattice generated by $1$ and $i$.

(There is $90^\circ$ symmetry around the red and green points, and $180^\circ$ symmetry around the purple points.)
More generally, let $G$ be the p4 symmetry group with a $90^\circ$ rotation at the origin.  Then I would conjecture that an elliptic function for a square lattice is invariant under $G$ if and only if it can be represented as a rational function of $\wp(z)^2$.  (And then every elliptic function with p4 symmetry can be obtained from these by translation.)
Type p3
This wallpaper group only makes sense for the hexagonal lattice.  It involves translations as well as several $120^\circ$ rotations.  Wikipedia uses the following image to illustrate p3 symmetry:

(The triangles represent points with $120^\circ$ rotational symmetry.)
This appears to be the symmetry of the Dixon elliptic functions.  However, it is not hard to make an elliptic function with p3 symmetry directly from Weierstrass $\wp$-functions.  Using the lattice generated by $1$ and $e^{i\pi/3}$, the function $\wp\,'(z)$ has p3 symmetry:

(There is $120^\circ$ symmetry around each of the marked points.)
More generally, let $G$ be the p3 symmetry group of the function above.  Then I would conjecture that an elliptic function for this lattice is invariant under $G$ if and only if it can be represented as a rational function of $\wp\,'(z)$.  (Note that this includes the Dixon function $\mathrm{cm}(z)$, but that $\mathrm{sm}(z)$ is invariant under a translate of $G$.)  Then every elliptic function with p3 symmetry would be obtained from these via translation.
Type p6
This wallpaper group only makes sense for the hexagonal lattice.  It involves translations as well as $60^\circ$ rotations, $120^\circ$ rotations, and $180^\circ$ rotations.  Wikipedia uses the following image to illustrate p6 symmetry:

(The blue hexagons represent points with $60^\circ$ rotational symmetry, the red triangles represent points with $120^\circ$ rotational symmetry, and the purple rhombuses represent points with $180^\circ$ rotational symmetry.)
Again, it isn't too hard to make an elliptic function with p6 symmetry.  We simply use $\wp\,'(z)^2$ for a hexagonal lattice:

(There is $60^\circ$ symmetry around the blue points, $120^\circ$ symmetry around the red point, and $180^\circ$ symmetry around the purple points.)
Again, it seems that $\wp\,'(z)^2$ "generates" the elliptic functions with p6 symmetry, in the sense that every elliptic function with p6 symmetry is a translate of a rational function of $\wp\,'(z)^2$.
Final Thoughts
This certainly isn't all that could be said about the symmetry of elliptic functions.  For one thing, even though a holomorphic function cannot be symmetric under a reflection or a glide reflection, it is reasonable to require the real part of a holomorphic function to have such symmetry.
This leads to the following question.
Question. For each a wallpaper group $G$, does there exist an elliptic function whose real part has symmetry group $G$?
The answer to this question appears to be YES, although I have not checked all of the cases, and it's conceivable that a few of the wallpaper groups are excluded.
Incidentally, when the real part of an elliptic function has a certain wallpaper symmetry, the imaginary part usually seems to have some sort of "harmonic conjugate" symmetry, which may be a different copy of the same wallpaper group, or a different wallpaper group altogether.
Overall, perhaps a more sensible way to talk about the symmetry of an elliptic function is to talk about the symmetry of its graph in $\mathbb{C}\times \widehat{\mathbb{C}}$.  For example, many of the functions above are invariant under a reflection of the domain followed by complex conjugation in the range.  I'm not sure what the discrete groups of symmetries are in $\mathbb{C}\times \widehat{\mathbb{C}}$ — they're not simply the wallpaper groups — but this would certainly be interesting to investigate.


text:
Q: ASP.NET MVC 4 Database connection error on deployment I am trying to deploy my ASP application to a webhosting but i receive the following error
System.ArgumentException: Invalid value for key 'attachdbfilename'.

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

[ArgumentException: Invalid value for key 'attachdbfilename'.]
   System.Data.SqlClient.SqlConnectionString.VerifyLocalHostAndFixup(String& host, Boolean enforceLocalHost, Boolean fixup) +907214
   System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +4116
   System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
   System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +150
   System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value) +59
   System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +4
   System.Data.SqlClient.SqlConnection..ctor(String connectionString) +26
   System.Data.Entity.Infrastructure.SqlConnectionFactory.CreateConnection(String nameOrConnectionString) +236
   System.Data.Entity.Infrastructure.LocalDbConnectionFactory.CreateConnection(String nameOrConnectionString) +281
   System.Data.Entity.Internal.LazyInternalConnection.Initialize() +327
   System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +332
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +56
   System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
   System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +37
   System.Linq.Queryable.OrderByDescending(IQueryable`1 source, Expression`1 keySelector) +66
   georgi_it2.Models.ApplicationController..ctor() +302
   georgi_it2.Controllers.HomeController..ctor() +5

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67

[InvalidOperationException: An error occurred when trying to create a controller of type 'georgi_it2.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +218
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +49
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970436
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

The connection string the company provided me is this:
<add name="SiteSqlServer" connectionString="Server=(127.0.0.1);Database=DATABASENAME;uid=DBUSERNAME;pwd=DBPASSWORD;" providerName="System.Data.SqlClient" />

And the one in my web.config file is the same. I have created a database already, it worked well with the default connection string on my machine.

A: One possible cause:
I have experienced this error when using the WebSecurity classes for authentication.  Check for an attribute class in your filters folder which is used on the account controller.  This class is used to initialize the WebSecurity classes, but has a default constructor call referencing "DefaultConnection".   Change this to the name of the connection string in your web.config's connectionstrings section (in your case, "SiteSqlServer") and it may resolve the problem.


text:
Q: Trade Reconciliation Macro I'm trying to write a macro that will reconcile two trade reports by putting a yellow fill on trades listed on Sheet1 that are missing from Sheet2 and vice versa. I am a beginner to VBA and have been learning as I go along. Basically the approach that I have taken has been to iterate through each row on Sheet1, creating an array for each of the main fields being compared (TradeDate, Ticker, and Quantity). These arrays contain the row numbers of every match with that field in Sheet1 that is found in Sheet2. Once the arrays are created, I would like to compare the arrays and check if the same row number is contained in each. If so, the program should move on to the next trade. If not, that row should be marked with a yellow fill on Sheet1. I keep getting run-time errors for type mismatch, any input as to why?
Sub Reconciliation()

Sheets("Sheet1").Select

Dim LastRow As Long
Dim LastRow2 As Long
Dim rowCounter As Long
Dim isZero As Long

LastRow = ActiveSheet.UsedRange.Rows.Count
With Sheets("Sheet2").Select
    LastRow2 = ActiveSheet.UsedRange.Rows.Count
End With
isZero = 1

'Loops through every row on Sheet 1
For rowCounter = 2 To LastRow
    Dim DateValue As String
   DateValue = ActiveSheet.Cells(8, rowCounter)

    'Search Sheet2 for TradeDate and add matched rows to DateArray
    Dim DateArray() As Long
    ReDim DateArray(0 To LastRow2)

    Sheets("Sheet2").Select
    If Application.WorksheetFunction.CountIf(Range("E2:E" & LastRow2), DateValue) > 0 Then
        isZero = isZero * 0

    Else
        DateArray(0) = Application.Match(DateValue, Range("E2:E" & LastRow2), 0)

        Dim i As Integer
        Dim x As Integer

        x = 1
        For i = 1 To LastRow2
         If Application.Match(DateValue, Range("E" & DateArray(x - 1) & ":E" & LastRow2), 0) = "IsError" Then
            Exit For
         Else
            DateArray(x) = Application.Match(DateValue, Range("E" & DateArray(x - 1) & ":E" & LastRow2), 0)
            x = x + 1
         End If
        Next i

    End If

    Dim tickerValue As String

    tickerValue = ActiveSheet.Cells(4, rowCounter)

    Dim TickerArray() As Long
    ReDim TickerArray(0 To LastRow2)

    Sheets("Sheet2").Select
    If Application.Match(tickerValue, Range("D2:D" & LastRow2), 0) = "IsError" Then
        isZero = isZero * 0
    Else

        TickerArray(0) = Application.Match(tickerValue, Range("D2:D" & LastRow2), 0)

        Dim i1 As Integer
        Dim x1 As Integer

        x = 2
        For i1 = 1 To LastRow2
            If Application.Match(tickerValue, Range("D" & TickerArray(x1 - 1) & ":D" & LastRow2), 0) = "IsError" Then
                Exit For
            Else
                ReDim Preserve TickerArray(0 To x1)
                TickerArray(x1) = Application.Match(tickerValue, Range("D" & TickerArray(x1 - 1) & ":D" & LastRow2), 0)

                x1 = x1 + 1
            End If
        Next i1
    End If

    Dim quantityValue As Long

    quantityValue = ActiveSheet.Cells(3, rowCounter)

    Dim QuantityArray() As Long
    ReDim QuantityArray(0 To LastRow2)

    Sheets("Sheet2").Select
    If Application.Match(quantityValue, Range("E2:E" & LastRow2), 0) = "N/A" Then
        isZero = isZero * 0
    Else

        QuantityArray(0) = Application.Match(quantityValue, Range("E2:E" & LastRow2), 0)

        Dim i2 As Integer
        Dim x2 As Integer

        x2 = 2
        For i2 = 1 To LastRow2
            If Application.Match(quantityValue, Range("E" & QuantityArray(x2 - 1) & ":E" & LastRow2), 0) = "IsError" Then
                Exit For
            Else
                ReDim Preserve QuantityArray(0 To x2)
                QuantityArray(x2) = Application.Match(quantityValue, Range("E" & QuantityArray(x2 - 1) & ":E" & LastRow2), 0)

                x2 = x2 + 1
            End If
        Next i2

    End If

Next rowCounter
End Sub

A: So there's quite a few problems with your code. Some of it is style, some of it is syntax.
First every place that you have a:
Application.Match(...)

It needs to have WorksheetFunction in between Application and Match so it reads:
Application.WorksheetFunction.Match(...)

Second try to avoid dimensioning variables inside your loops. There's no need for it, and if you want to reset your variables after each loop then add something like a var = 0 at the end.
Move DateValue and DateArray out of the For Loop. Dim DateArray once after LastRow(2) since that's the only time you do and LastRow(2) never changes.
The same goes for TickerArray, tickerValue, QuantityArray, and quantityValue.

Third avoid variables with numbers in them, i.e. LastRow2. This is when you need to use either a more descriptive variable name or an Array. Instead of LastRow2 use
Dim LastRow(1 to 2) as Long
LastRow(1) = Sheet1.UsedRange.Rows.count
LastRow(2) = Sheet2.UsedRange.Rows.count

Fourth why are you using
isZero = isZero*0

instead of
isZero = 0

Fifth, don't use the select() method so much. Its slow and clunky compared to just referencing the sheet you want directly
i.e. instead of doing this
LastRow = ActiveSheet.UsedRange.Rows.count
With Sheets("Sheet2").Select
    LastRow2 = ActiveSheet.UsedRange.Rows.count
End With

do this instead
LastRow(1) = Sheet1.UsedRange.Rows.count
LastRow(2) = Sheet2.UsedRange.Rows.count

Sixth you don't need three separate x and i variables, you can dim them once outside of the highest For loop and reuse them for your lower For loops in the If-Else statements.


text:
Q: How to implement this even-odd matrix decomposition efficiently? In connection with solving a partial differential equation numerically, I have come across the following question about how to implement a specific matrix-vector product algorithm efficiently in Matlab. For notational convenience I will formulate the question using Matlab notation.
The background of the question is that I have a matrix, D, which has size NxN (N is even and typical values for N are 4, 6 and 8) and which has the property that
D(i,j) = - D(N+1-i, N+1-j)

for 1 <= i,j <= N. To solve the differential equation, I use a numerical method that requires D to be multiplied onto many different vectors and I therefore want to exploit the above property to make the matrix-vector product as efficient as possible.
The algorithm which utilizes the symmetry of D that I have in mind is the following: Assume we want to compute the product D*f where f is a Nx1 column vector. Moreover, define the column vectors e and o of size N/2x1 by
e(n) = 0.5*(f(n) + f(N+1-n))

o(n) = 0.5*(f(n) - f(N+1-n))

as well as the matrices De and Do of size N/2xN/2 by
 De(n,m) = D(n,m) + D(n,N+1-m)

 Do(n,m) = D(n,m) - D(n,N+1-m).

Using the definition of a matrix-vector product it can be shown that the matrix vector product D*f can be computed as
 Df = [De*e + Do*o; -De*e + Do*o]

and since the products De * e and Do * o each require one quarter as many multiplications as the product D * f I hope that it is possible to reduce the computational time by roughly a factor of 2 using this algorithm.
So far I have, however, not been able to implement the algorithm in a way such that it is faster than the built in matrix-vector product which does not utilize the special property of D. The first hirdle seems to be constructing the vectors e and o. If I do it the straight forward way, i.e.
 e = 0.5*(f(1:N/2) + flipud(f(N/2+1:N)))

 o = 0.5*(f(1:N/2) + flipud(f(N/2+1:N)))

it already takes more than an order of magnitude longer than to compute D * f directly. Forming the sparse matrices eMat and oMat as
 eMat = 0.5*[1, 0, ..., 0, 0, ..., 0, 1;

             0, 1, ..., 0, 0, ..., 1, 0;

             |  |   |   |  |   |   |  |

             0, 0, ..., 1, 1, ..., 0, 0]

 oMat = 0.5*[1, 0, ..., 0,  0, ...,  0, -1;

             0, 1, ..., 0,  0, ..., -1,  0;

             |  |    |   |  |    |   |   |

             0, 0, ..., 1, -1, ...,  0, 0]

where the vertical lines mean that the pattern should be continued, e and o can be computed as
 e = eMat*f

 o = oMat*f

and this takes about a third of the time it takes computing D * f directly. Using the sparse matrices eMat and oMat I can compute De * e and Do * o as
 Dee = De*eMat*f

 Doo = Do*oMat*f

and this also takes roughly a third of the time it takes computing D * f with the built in matrix-vector product. Now the difficulty arises, because carrying out the computation
 Dee + Doo

requires about the same amount of time (and typically even a little more) than computing D * f directly. Needless to say, it also takes more time to compute D * f as
 Df = [Dee + Doo; -Dee + Doo]

than with the built in matrix-vector product.
My question is if anyone can suggest a way of implementing the above algorithm efficiently in Matlab, such that the algorithm in total runs faster than the built in matrix-vector product?


text:
Q: How to display images with a fade in effect in a listview? How is it possible to display images with a fade in effect (i don't know the exact name) in a listview like the app yummly doing.
https://play.google.com/store/apps/details?id=com.yummly.android
Any reference to such libraries or helpful resources?

A: You can use this example
In adapter(extend BaseAdapter or ArrayAdapter):
private int lastPosition = -1;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  //.....inflating and bind view

  setAnimation(convertView, position);
  return convertView;
}

 /**
 * Here is the key method to apply the animation
 */
private void setAnimation(View viewToAnimate, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {
        Animation animation = AnimationUtils.loadAnimation(mContext, android.R.anim.fade_in);
        viewToAnimate.startAnimation(animation);
        lastPosition = position;
    }
}

Or for RecyclerView.Adapter:
@Override
public void onBindViewHolder(final HistoryHolder holder, final int position) {
....
setAnimation(holder.animatedView, position);
}


text:
Q: Page numbering problem when text is there I have a problem with my template. When I use the blindtext package or "lorem ipsum" from an online generator to simulate text everything works exactly as it should. When I write my normal text (pictures, tables and text), it won't work! The problem begins between "normal test" and "appendix".
I'm using the report-KOMA class, so every chapter begins on a right side and the sides between are empty (no header, footer, page numbers) to have every chapter beginning on a right page.
The problem is that there are numbers on empty pages that are there from the report class (to be able to start next chapter on the right page). In addition, my appendix doesn't start on a right side.
Is there another behaviour after appendix in KOMA?
Here, you can download the hole template: https://drive.google.com/open?id=0B1enfawBNB9xMy0tc0JOSWxiQ2c
Unfortunately, I can't provide a MWE, because after trying for one hole day, I can't provide anything. It works without my text with nearly any text. I'm not allowed to show my text here, it's scientific work so it's forbidden. I really hope you can help me, anyway.


text:
Q: I get AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name' (The below code is not mine) Ive been trying to get this ixl math bot to work but everytime i run it i get
AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
Im using selenium 4.3 and the latest python version, if no one can help then at least an explanation of what this error means and how i could fix it would be appreciated,
https://github.com/debaet/IXLMultiBot?adlt=strict&toWww=1&redig=1D778E48B58B4E39B6F7082C77F7F797
this is the original GitHub post (not mine)
I'm fairly new to python so I only tried a few basic things like restated PATH or double "\" not a lot
its supposed to ask for username password grade and lesson link which work but after the selenium chrome windows opens and it gets gives:
AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
`
from selenium import webdriver
import os, time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
import sys
import colorama
from colorama import Fore, Back, Style
colorama.init()

# config

#if trying yourself replace this path with your own path of chromium downloaded (with double back slashes)
PATH = ("C:\\Users\\aashu\Downloads\\chromedriver_win32\\chromedriver.exe")

driver = webdriver.Chrome(PATH)

def main4(argv):
    lesson = input('Enter lesson link for algerba')
    while True:
        driver.get(lesson)
        time.sleep(4)
        driver.refresh()
        time.sleep(4)
        q1 = driver.find_element_by_class_name('yui3-practiceagent-content')
        q2 = q1.text
        print(repr(q2))
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[1]/div/div[2]/button').click()
        time.sleep(4)
        driver.find_element_by_xpath('/html/body/div[1]/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/button[2]').click()
        time.sleep(4)
        #change this
        answer = driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[4]/div[2]/div/div/div[2]')
        ans = answer.text
        print(ans)
        driver.delete_all_cookies()
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[1]/div[2]/button').click()

def main1(argv):
    lesson = input('Enter an 8th grade lesson link')
    while True:
        driver.get(lesson)
        time.sleep(4)
        driver.refresh()
        time.sleep(4)
        q1 = driver.find_element_by_class_name('yui3-practiceagent-content')
        q2 = q1.text
        print(repr(q2))
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[1]/div/div[2]/button').click()
        time.sleep(4)
        driver.find_element_by_xpath('/html/body/div[1]/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/button[2]').click()
        time.sleep(4)
        #change this
        answer = driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[4]/div[2]/div/div/div/div/div[9]')
        ans = answer.text
        print(ans)
        driver.delete_all_cookies()
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[1]/div[2]/button').click()

def main2(argv):
    lesson = input('Please Enter A 7th Grade Lesson Link: ')
    while True:
        driver.get(lesson)
        time.sleep(4)
        driver.refresh()
        time.sleep(4)
        q1 = driver.find_element_by_class_name('yui3-practiceagent-content')
        q2 = q1.text
        print(repr(q2))
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[1]/div/div[2]/button').click()
        time.sleep(4)
        driver.find_element_by_xpath('/html/body/div[1]/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/button[2]').click()
        time.sleep(4)
        answer = driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[4]/div[2]/div/div/div/div/div')
        ans = answer.text
        print(ans)
        driver.delete_all_cookies()
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[1]/div[2]/button').click()
# 6th Grade
def main3(argv):
    lesson = input('Please Enter A 6th Grade Lesson Link: ')
    while True:
        driver.get(lesson)
        time.sleep(4)
        driver.refresh()
        time.sleep(4)
        q1 = driver.find_element_by_class_name('yui3-practiceagent-content')
        q2 = q1.text
        print(repr(q2))
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[1]/div/div[2]/button').click()
        time.sleep(4)
        driver.find_element_by_xpath('/html/body/div[1]/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/button[2]').click()
        time.sleep(4)
        answer = driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[4]/div[2]/div/div/div/div')
        ans = answer.text
        print(ans)
        driver.delete_all_cookies()
        driver.find_element_by_xpath('/html/body/div[9]/section/div[1]/div[1]/div[6]/div/div[8]/div/div[1]/div[1]/div[2]/button').click()

def op1():
    os.system('cls' if os.name == 'nt' else 'clear')
    print('If any of these are incorrect, bot will fail.')
    username = input('Enter Username or Email: ')
    password = input('Enter Password:  ')
    os.system('cls' if os.name == 'nt' else 'clear')

    print('do not touch the window that has just popped up. ')
    print('smart score goes up and down alot, just go afk or do something in background!')
    driver.get('https://www.ixl.com/math/grade-7/add-and-subtract-integers')
    time.sleep(3)
    driver.refresh()
    driver.find_element_by_xpath('//*[@id="qlusername"]').send_keys(username)
    driver.find_element_by_xpath('//*[@id="qlpassword"]').send_keys(password)
    driver.find_element_by_xpath('//*[@id="qlsubmit"]').click()
    driver.execute_script('''window.open('',"_blank");''')
    driver.switch_to.window(driver.window_handles[-1])
    driver.get('https://www.meta-calculator.com/scientific-calculator.php?panel-203-simple-calculator')
    driver.switch_to.window(driver.window_handles[0])

    while True:
        time.sleep(3)
        variable = driver.find_element_by_class_name('old-space-indent').text
        print(variable)
        driver.switch_to.window(driver.window_handles[-1])
        box = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[2]/div[2]/div[4]/div[1]/div[2]/input')
        time.sleep(3)
        driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[2]/div[2]/div[4]/div[1]/div[2]/input').send_keys(variable)

        answer = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[2]/div[2]/div[4]/div[1]/div[2]/input')
        box.send_keys(Keys.BACKSPACE)
        print('the bot will now pause for 150 seconds to generate some time.')
        time.sleep(150)
        box.send_keys(Keys.ENTER)
        answer = driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[2]/div[2]/div[4]/div[1]/div[1]/span[2]').text
        a = (answer)
        c = "="

        for char in c:
            a = a.replace(char, "")

        print(a)
        driver.find_element_by_xpath('/html/body/div[1]/div[3]/div/div[1]/div[2]/div[2]/div[4]/div[1]/div[2]/button[2]').click()
        driver.switch_to.window(driver.window_handles[0])
        driver.find_element_by_class_name('fillIn').click()
        driver.find_element_by_class_name('fillIn').send_keys(a)
        time.sleep(3)
        driver.find_element_by_class_name('fillIn').send_keys(Keys.ENTER)
        driver.refresh()

def op2():
    os.system('cls' if os.name == 'nt' else 'clear')
    grade = input('Are you in 8th Grade? (Y/N): ')
    if grade == "Y":
        main1(sys.argv)
        print('You are In 8th Grade')
        print('You will be asked to Enter Your Lesson Link')
    else:
        grade2 = input('Are you in 7th Grade? (Y/N): ')
        if grade2 == "Y":
            main2(sys.argv)
            print('You are In 7th Grade')
            print('You will be asked to Enter Your Lesson Link')

        else:
            grade3 = input('Are you in 6th Grade? (Y/N): ')
        if grade3 == "Y":
            print('You are In 6th Grade')
            print('You will be asked to Enter Your Lesson Link')
            main3(sys.argv)
        else:
            print('algerba')
            main4(sys.argv)

def op4():
    os.system('cls' if os.name == 'nt' else 'clear')
    print('If any of these are incorrect, bot will fail.')
    username = input('Enter Username or Email: ')
    password = input('Enter Password:  ')
    os.system('cls' if os.name == 'nt' else 'clear')

def op3():
    os.system('cls' if os.name == 'nt' else 'clear')
    print('If any of these are incorrect, bot will fail.')
    username = input('Enter Username or Email: ')
    password = input('Enter Password:  ')
    os.system('cls' if os.name == 'nt' else 'clear')

def op5():
    os.system('cls' if os.name == 'nt' else 'clear')
    print('If any of these are incorrect, bot will fail.')
    username = input('Enter Username or Email: ')
    password = input('Enter Password:  ')
    os.system('cls' if os.name == 'nt' else 'clear')

def main():
    print('Menu: ')
    print('1. Add more time to your account')
    print('2. Scrape Answers (get answers)')
    print('3. Get Teacher Accounts')
    print('4. Auto Answer (some lessons work)')
    print('5. Credits')
    var = input('Enter an Option: ')

    # goes to the specified option
    if var==('1'):
        op1()

    elif var==('2'):
        op2()

    elif var==('3'):
        op3()
    elif var==('4'):
        op4()

    elif var==('5'):
        op5()

    else:
        print('Please enter numbers only. If you did and still got an error, please enter a number which is listed above.')
        time.sleep(4)
        os.system('cls' if os.name == 'nt' else 'clear')
        main()

# end code

print('Welcome to The First Functional IXL BOT.')
print('DO NOT CLOSE THE CHROME WINDOW THAT IS ABOUT TO POP UP.')
print('Please wait..')

time.sleep(3)
os.system('cls' if os.name == 'nt' else 'clear')
main()

`
Thank you to anyone that helps, i will try to respond to any answers within 2-3 days
:D - Aashu,

A: All the find_element_by_* and find_elements_by_* methods are deprecated in current Selenium versions. You need to use driver.find_element(By.CLASS_NAME, " "), driver.find_element(By.XPATH, " ") etc. methods.


text:
Q: Android: how to encapsulate layout.xml in Object I have layout file which I'm inflating dynamically on the screen.
Then in my activity I have to init some UI logic (listeners, etc...).
But now this logic needs to be moved to some class. And I can't decide what way is the best to create view based object that has its layout in xml.
public MyView extends View {
    MyView(Context context) {
        super(context);
        //inflation here...
    }

OR
MyViewFactory {
    View get(Inflater inflater) {

    }

OR something else?
May be someone can also recommend source code where to look for.

A: You probably don't want to do this with a simple view like ImageView. you want it to be a more complex layout like (linear layout containing buttons etc)?
In case you need the first you are best off with a simple view instance like ImageView img = new ImageView(context); or a factory if you have more parameters involved if you think its simpler setting them in xml.
As far as more complex layouts go i prefer using a custom class extending some of the viewGroups(Like: MyView extends LinearLayout)
create a function called init();
call the function from each constructor
implement inside it something like:
LayoutInflater.from(context).inflate(R.layout.my_layout,this,true);

this + true would mean that the layout will be attached to the root, in this case linearLayout and you can use findViewById directly on the viewgroup)
ImageView img = findViewById(R.id.myView);

i find it really important to create custom views since they always include logic that is specific to them and can be reused and also expose some public methods to invoke from the activities that include the custom view.


text:
Q: Mockito stubbing a method to return value for all instances of class Scenario:
I am testing a Spring MVC controller using a standalone setup.
The controller takes parameters from the JSON object in the request.It calls a service after converting the JSON object to java object.The service saves it to DB using JPA and it then updates the Id field of entity and returns back to controller.The controller returns the JSON response to the caller after converting the entity to JSON.
I have mocked the service in my test class and injected to the controller using @InjectMocks
The mocked service has no access to the private setId method of the JPA entity as it is populated by hibernate in the real scenario.
Now when I mock the service, how can i stub the getId method of the created entity?
Code to test mockservice:
@Test
public void thatAccountCreationRendersAsJson() throws Exception {

    doAnswer(new Answer<Boolean>() {
        @Override
    public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable {
    Account account = (Account) invocationOnMock.getArguments()[0];
    account.setEnabled(true);
    account.setFirstName("bca123");
        return Boolean.TRUE;
    }
    }).when(mockAccountService).registerAccount(any(Account.class),
            anyString(), any(BindingResult.class));

Now how to stub the getId method of Account class so that controller gives the Id in the JSON response.
I cannot create a mock account object as it is created by the controller from JSON and sent to the mocked service. my mock account object is not used.
I tried to use
Account spier = spy(account);
doReturn(new Long(22)).when(spier).getId();
spier.setFirstName("cba123");

in the above doAnswer method but it is not effective.
Is there any way we can return a constant value like 22 for all invocations of getId method of Account.class for any instance ?
http://code.google.com/p/mockito-python/wiki/Stubbing gives a section
Instance, Class-level and Static Methods
which exactly fits my needs where they stub a instance method for all instances
but it is on python.
Thanks for answering my question.

A: Make your setId() method public, and add account.setId(whatever). The setId() method has no real reason to be private. Just because Hibernate can set private fields doesn't mean that you shouldn't have a public setter for it, especially if it's needed for your tests. If you really want to keep it private, then do the same thing as Hibernate, and set it using reflection. But I wouldn't do that.

A: I have moved this test to integration testing as i had the full spring container along with a in memory database to set the id by hibernate.
Vam