text:
Q: How to implement click listener in recyclerview? I am new in android and learning about RecyclerView. I am working with json so that i can get data from server. I followed this tutorial for this. I am not getting how to implement onclicklistner on my recyclerview.

A: Item click listeners for RecyclerView
See the answer
you should use ItemClickSupport library :
    ItemClickSupport.addTo(recyclerView)
            .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                @Override
                public void onItemClicked(RecyclerView recyclerView, int position, View v) {
               /* do your thing */
                }
            });

A: @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
       holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //TODO
            }
        }
   }

A: If you are talking about onItemClickListener of ListView , unfortunately there is no such method in RecyclerView. What you can do is, give an id to your parent view of RecyclerView item, and set an onClickListener  on that in onBindViewHolder.

A: Following your tutorial, on the "bind data" method you can set a click listener. It will as easy as writing:
holder.itemView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        // write your code here
        }

    });

You will also need to change the
int position

to final, like:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder,final int position) {


text:
Q: How to delete id from one table and id from another table if they are connected to one object? I have these two tables:
Table: REASON
id | name
---|------------
1  | gold_sell
2  | gold_buy
4  | Silver_sell

Table: REASON_TO_TRANSACTION
reason_id | transaction_type
----------|-------------------
1         | sell
2         | buy
4         | pko

where id from table reason is linked with reason_id from reason_to_transaction.
I want to delete all rows with id = 1 from these two tables.
Can someone help me?
I'm using SQL Server(phpmyadmin).
Variable name is for getting the current activeItem and delete it.
I have written following SQL command:
DELETE rt
  FROM reason_to_transaction rt
  INNER JOIN reasons r
    ON id=reason_id
  WHERE reasons.id=reason_to_transaction.reason_id
    AND name = 'gold_sell'

I also have this angular code:
$scope.deleteItem = function(){
        console.log($scope.activeItem);
        var objectToSave = {
            name: $scope.activeItem.name,
            id: $scope.activeItem.id
        };

        if($scope.activeItem.id){

                defaultAdapter.query('DELETE rt FROM reason_to_transaction rt INNER JOIN reasons r ON r.id = tr.reason_id WHERE name = :name',
              { replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
            ).then(projects => {
              console.log(projects);
              $scope.editMode = false;
                $scope.activeItem = false;
                $scope.refresh();
            });
        } else {
                defaultAdapter.query('DELETE rt FROM reason_to_transaction rt INNER JOIN reasons r ON r.id = tr.reason_id WHERE name = :name',

              { replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
            ).then(projects => {
              console.log(projects);
              $scope.editMode = false;
                $scope.activeItem = false;
                $scope.refresh();
            });

        }
    };

And also have html submit form:

<form ng-submit="saveItem(reasonsForm.$valid)" name="reasonsForm">

                Име на основание
                <input type="text" class="form-control" required ng-model="activeItem.name" placeholder="Име на основание за редактиране" />

    <button class="btn btn-primary" ng-disabled="reasonsForm.$invalid" type="submit">Save</button>
    <button class="btn btn-primary" type="submit" ng-click="deleteItem()">Delete</button>

    <button class="btn btn-primary" id="cnlbtn" type="button">Cancel</button>

</form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing url arguments to http get request in angular 2 I am trying to pass url args to http get request in angular 2 but getting an error in the console:

InstantiationError {_wrapperMessage: "DI Exception",
  _originalException:    TypeError: options.search.clone is not a function
      at BaseRequestOptions.RequestOptions.merge....

here's the code
Service
  var url = '/company/' + companyUnqName + '/logs' ;
  app.AuditLogsHttpService = ng.core.Injectable().Class({
      constructor: [ng.http.Http,  function(http){
        this.http = http
      }],

      getLogs: function(){
        var params = new URLSearchParams();
        params.set('uniquepage', 1);
        return this.http.get(url, {search: params})
              .map(function (res) {
                  return res;
              });
      }
});

Component
app.AuditLogs =
  ng.core.Component({
    selector: 'audit-logs',
    providers: [ng.http.HTTP_PROVIDERS, httpService],
    templateUrl: '/public/webapp/ng2/audit_logs/audit-logs.html'
  })
  .Class({
    constructor:[ng.http.Http, httpService, function(http, service) {
      this.result = {};
      this.http = http;
      service.getLogs().subscribe(function(result){
        this.result = JSON.parse(result._body);
        this.logs = this.result.body.logs;
      }.bind(this));
    }],
});

A: I would use the following:
getLogs: function(){
     var params = new ng.http.URLSearchParams(); // <--------
  params.set('uniquepage', 1);
  return this.http.get(url, {search: params})
          .map(function (res) {
            return res;
          });
}

The URLSearchParams object is defined under "ng.http.".


text:
Q: Python subprocess Popen returns with non zero error code but no error I am trying to execute an executable binary that produces an error. My code for the execution of binary using Popen:
p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
output, error = p.communicate()
return_code = p.returncode
if error:
   raise SomeLocallyDefinedError

This is supposed to raise error when the script execution results in an error. The cmd in this particular case is the path to the concerned executable binary.
Now when I execute this very binary on my terminal ./binary_file it gives me an error msg
"Floating point exception: 8".
But when the script is executed by Popen , there is no error as well as output. But the returncode is -8. I believe that a non zero return code implies an error and if so why was the message not captured by Popen.communicate()?
In case you guys are wondering what was the executable binary file. The binary file was generated by a compiling a c file that results in run time error. Here is the content of c file
# include<stdio.h>
int main(){
   int a = 18;
   int b = 0;
   int c = a/b;
   printf("%d", c);
}

A: The output is generated by the shell, while catching an SIGFPE signal. You have to catch this signal in your program by yourself and handle it as you wish.

A: This is not just an ordinary runtime error, it is a process crash raised by kernel (via a signal).
If you are running on UNIX//Linux/OS X you should get a core dump (ulimit -c unlimited in the shell). Kernel does not write to a process's stderr - it can't because the process has crashed.
This is not an issue with Python.


text:
Q: Default Configuration is Static. I have to create a web service supporting multiple clients Here is my situation. I need to create a web service for our clients to use to have their clients sign documents. Each of our clients will have their own username and password, etc. with DocuSign. We are just an integration partner creating a backend integration service for them to send out signature requests. Signers won't be logging in to DocuSign to sign.
I've gotten a test working and sending a document. However, any subsequent calls fail on the second line below with an error that the key already exists. Obviously, I have to be able to change the username/password per request since we're supporting multiple client users generating signing requests. How do I get around the fact that Configuration.Default is static and causing this problem?
string authHeader = "{\"Username\":\"" + usr + "\", \"Password\":\"" + pwd + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);

UPDATE:
So, I did end up switching to OAuth Code Grant authentication (see code sample below). However, this static configuration is still an issue. Each request could quite possibly have a different OAuth token associated with it. I've generated a class that I instantiate on each request that creates new ApiClient inside it. However, the default configuration is still there with the default header from the last request. This is an obvious problem. All the recipes and documentation use this configuration.default method. It seems someone must have run into this before and there must be a workaround to get the configuration set without this issue. Particularly in a service environment this could cause all kinds of problems if I did something gnarly like remove/re-readd/update that default header if it's shared among instances. I'm just not seeing the way around this.
CustomClass lib = new Lib();
//Inside lib this is called before creating envelopes, etc.
ApiClient dsClient = new ApiClient(userInfo.Docusign_Rooturl); // userInfo.Docusign_BaseUrl);
DocuSign.eSign.Client.Configuration.Default.ApiClient = dsClient;
//This is the problem bit
    DocuSign.eSign.Client.Configuration.Default.AddDefaultHeader("Authorization",<oauth_token>);
return dsClient;

UPDATE 2:
I believe I worked around this successfully. When initializing the ApiClient, rather than using the Default configuration object I use the following code:
 ApiClient dsClient = new ApiClient(<rootUrl>);
        DocuSign.eSign.Client.Configuration config = new DocuSign.eSign.Client.Configuration(dsClient);
        config.AddDefaultHeader("Authorization", <oAuthToken>);
        dsClient.Configuration = config;
 EnvelopesApi api = new EnvelopesApi(dsClient.Configuration)

I hope that helps someone else who runs into the same thing.

A: For authenticating users through your App you should be using the oAuth authorization code grant.
You can learn more about it here
The X-DocuSign-Authentication header is for backend service integrations where there is no involvement of an end user.

You can  also use Send On Behalf Of (SOBO) Authentication

Originally designed to send envelopes on behalf of other users in an account, Send On Behalf Of (SOBO) is an authentication method that allows a user (the authenticating user) to send envelopes and to perform almost any task in the name of another user (the operating user) in the same account.

You can specify the sendOnBehalfOf value in your header
 <DocuSignCredentials>
     <Username>nat.irving@example.com</Username>
      <Password>S3cre+p455w0Rd</Password>
       <IntegratorKey>230546a7-9c55-40ad-8fbf-af205d5494ad</IntegratorKey>
     <SendOnBehalfOf>ruggiero.gardener@example.com</SendOnBehalfOf>
   </DocuSignCredentials>


text:
Q: Selenium Java and Maven generate test jars without running the tests I'm using Azure DevOps for CI/CD and for CI portion, I want to package the entire project and the CD portion will execute the tests from the jars
I can't seem to generate the executables though. I am using PageObject model so my layout for my maven project is as such
---src/main/java
-------PageObject
---src/test/java
------>tests here
My goal in Azure DevOps is to make sure the code compiles and package up the tests and drop them into an artifact. The release will then run the tests from this artifact. I don't want to drop the entire repo into the artifact, rather just the binaries (so whatever is in the ~/target/ folder.
It seems that when I try to compile, there are not any jars that are created.
I do not want the CI portion to execute the tests; simiply package up the artifact is my goal here.


text:
Q: SQL a cumulative distinct count I have a SQL table that lists individual events and I am trying to aggregate to get a group of events as follows.
id |Name | Date|
0  |A    |2018-05-08
1  |A    |2018-05-09
2  |B    |2018-05-11
3  |B    |2018-05-12
4  |A    |2018-05-17
5  |A    |2018-05-17
6  |A    |2018-05-18
7  |C    |2018-05-25
8  |C    |2018-05-26
9  |B    |2018-05-27

Becomes:
Name|Group
|A  |1
|B  |2
|A  |3
|C  |4
|B  |5

This I believe is some form of a Count(), then OVER BY, which have always tripped me up. I do not know what I would even count over because there is little grouping these Names together. So far, I have the following:
select
    Name
    ,Count(Name)
from table
Group BY
    Name

A: This is a gaps and island problem, where you want to group together "adjacent" rows.
One approach relies on the difference between row numbers to indentify the groups. If id is continously increasing by 1, consider:
select
    name,
    row_number() over(partition by name, id - rn order by min(date)) grp
from (
    select
        t.*,
        row_number() over(partition by name order by date) rn
    from mytable t
) t
group by name, id - rn
order by grp

Otherwise, we can generate the id with row_number():
select
    name,
    row_number() over(partition by name, rn1 - rn2 order by min(date)) grp
from (
    select
        t.*,
        row_number() over(order by date) rn1,
        row_number() over(partition by name order by date) rn2
    from mytable t
) t
group by name, rn1 - rn2
order by grp

A: There is no reason to think of this as a gap-and-islands problem.  I mean, it is, but there is a simpler solution.
In this case, use lag() and row_number():
select name, row_number() over (order by date, id) as grp
from (select t.*,
             lag(name) over (order by date, id) as prev_name
      from t
     ) t
where prev_name is null or prev_name <> name;


text:
Q: How the web server and application server work in rails app A rails application has its own server but my question is how this web server talk or connect with the route file rails applications.

A: Well that's a very big question, but in a nutshell...
There's a component of the rails application suite called Rack. It processes incoming requests and outgoing responses. Rack itself organizes a number of "middleware" apps, each of which processes one aspect of the request/response.
The routes file defines the behaviour of ActionDispatch by defining how urls map to "rack endpoints". So if you type rails routes into the rails console, you'll see how each url maps to the controllers and their methods ("rack endpoints") in your app.


text:
Q: How can I check if a sql query is deterministic? What I mean by deterministic is that the query will always return exactly the same result set.  Is there a way to do this?

A: Queries aren't typically considered to be deterministic as the underlying tables can change between invocations.  Determinism typically only comes into play when talking about UDFs.

A: The only way I know of to produce deterministic data in a database is to create a snapshot of the necessary data at the appropriate point in time. Usually, data is transformed and loaded into a data warehouse, along with a timestamp for the rows being archived, for later retrieval. Auditing and other kinds of reporting queries may be run against the data warehouse, and the results are "deterministic" for any given time period, but not across time periods.
Information housed in a data warehouse may also be precomputed into a multi-dimensional cube for faster processing, if necessary. To maintain proper form, data warehouse tables should only ever be inserted into, and new batches of data should always be associated with a unique timestamp. It is usually best to store data in some form of star or snowflake schema, which facilitates generation of a cube if necessary.


text:
Q: Why sshxcute library returns error intermittently when tries to run Result class? I developed a Java application can connect to an IP address, run several scripts and return results, in Linux environment. I used sshxcute library for this task, it works perfectly But intermittently stuck when the sshxcute command try to return result, the only way to wraparound is force the sshxcute to close ssh manually and lost the result.
What is wrong with my code?
I guess sshexcute has problem to run Result class.
This is one of the methods used:
private void sshcopyimage(SSHExec ssh) {
    try {

        // Create a ExecCommand, the reference class must be
        // CustomTask

        CustomTask ct3 = new ExecCommand("cd /screenShots",
                "ls -tr | tail -1");

        Result res3 = ssh.exec(ct3);
        //The application stuck in this line intermittently.
        filename = res3.sysout;

        // Check result and print out messages.
        if (res3.isSuccess) {
            System.out.println("Return code: " + res3.rc);
            System.out.println("sysout: " + res3.sysout);
            output.setText("file name gotten.");
        } else {
            System.out.println("Return code: " + res3.rc);
            System.out.println("error message: " + res3.error_msg);
            output.setText("Error in getting the file name .");
        }
    } catch (TaskExecFailException e5) {
        MyMessage.infoBox(e5.getMessage(), "Error");
        output.setText("Error.");
        System.out.println(e5.getMessage());
        e5.printStackTrace();
    } catch (Exception e6) {
        MyMessage.infoBox(e6.getMessage(), "Error");
        output.setText("Error.");
        System.out.println(e6.getMessage());
        e6.printStackTrace();
    } finally {

        //MyMessage.infoBox("Picture created.", "Message");
        output.setText("Picture created.");
        bashcommand();
    }
}

more similar methods used in this app and all of them stuck in the same line intermittently 1/30.

A: Finally I found my answer.
I replaced excute library by JSCH and works perfectly.
It was good for me to find my answer by myself :)


text:
Q: Compare two MySQL databases, on command-line, with a free tool I would like to generate diff-like SQL files to compare the DATA and the STRUCTURE of two MySQL databases.
These resulting files would be executed as SQL queries, on command-line.
There is various old threads related on SO, and on various forums, but they deal with non-free tool with user interface (not command-line tools).
Also, the database should not be synced directly, but only by executing the resulting diff SQL script.

A: Check out the open-source Percona Toolkit ---specifically, the pt-table-sync utility.  It uses checksums on indexes and other strategies to diff tables fast.  Its primary purpose is syncing replicas, but with a little extra work, it's a great diff tool.  See my full answer about it here.
EDIT: I forgot to mention that comparison of the structure is a different beast.  I do this with a stored procedure that you can call from the command line, but it may not be what you're looking for.
Here's a snippet from a shell-script wrapper that I wrote for showing schema diffs:
mysql ${MYSQL_CNF_OPTION} -u ${DB_USER} \
-e "USE sys; CALL compareDBs('${DBDIFF_LOCAL_DB1}','${DBDIFF_LOCAL_DB2}');"

It calls the compareDBs stored procedure, which I got from the Artful Software query archive page.

A: The following will have a go at showing you the differences (the first part of your question) but the output won't really be useable as patch files.
To compare two tables:
 mysql -u whatever -e "describe table" database1 > file1.txt
 mysql -u whatever -e "describe table" database2 > file2.txt
 diff file1.txt file2.txt

To compare data:
 mysql -u whatever -e "select * from table" database1 > file1.txt
 mysql -u whatever -e "select * from table" database2 > file2.txt
 diff file1.txt file2.txt

To compare databases:
 mysqldump --extended-insert=FALSE -u whatever database1 > file1.txt
 mysqldump --extended-insert=FALSE -u whatever database2 > file2.txt
 diff file1.txt file2.txt

A: Tools for schema compare are more common. There are some perl packages for this which can easily be run from command line. I also found one for data diff (which is quite a complex problem!), but it's kind of old and I am not sure how good it is.
Schema compare:
http://adamspiers.org/computing/mysqldiff/
Data Compare:
http://rossbeyer.net/software/mysql_coldiff/


text:
Q: Remove high linespacing in asciidoctor stem block I am a newbie with asciidoctor trying to use it for education stuff.
I have a stem block with linespaces and those linespaces are so huge, that it negativly affect the readability.
Input
[stem]
++++
=> ggT(120, 7) =   1 * 120 (mod 7)\
=> ggT(120, 7) = -17 *   7 (mod 120)\
               = 103 *   7 (mod 120)\
++++

Output

So my Question:
Is it possible to reduce those red highlighted white spaces?
So that these matches the line heigth of the 'normal' text?
Thanks for help!
e.g: Good pages for learning Asciidoctor Syntanx are welcome

A: You didn't include the markup around the stem block, so it's hard to say for sure,
I suspect that each stem block is being treated as a paragraph, resulting in the extra whitespace.
Try adding a plus sign (+), by itself, on the line immediately before and/or after the stem block, to attach it to the "current" paragraph:
+
[stem]
++++
=> ggT(120, 7) =   1 * 120 (mod 7)\
=> ggT(120, 7) = -17 *   7 (mod 120)\
               = 103 *   7 (mod 120)\
++++
+

Assuming that I'm correct, you may have to experiment to find the combination that works for your document.


text:
Q: Controller didn't get more arguments laravel I'm trying to send two arguments and one request to controller with post request. This is the code where I send the arguments:
<form class="form-horizontal" name="form1"  method="post" action="{{ route('shipment_view', $uniqueid, $category_name) }}" role="form" enctype="multipart/form-data">

And this is the controller where I'm sending the arguments:
    public function storeShipment(Request $request, $number, $category_name){

           $category = Category::where('category_name', $category_name)->first();
           $user = Auth::user();

           $item = new Item([

           'id' => $user->id,
           'category_id' => $category->id,
           'unq' => $number,
           'fullname' => $request->input('name'),
           ]);

           $item->save();
   }

But when I open the view it gives me error
ErrorException in NewShipmentController.php line 53:
Missing argument 3 for App\Http\Controllers\NewShipmentController::storeShipment()

Update:
My route function:
Route::post('/ship/preview/{number}',[
   'uses' => 'Controllerr@storeShipment',
    'as' => 'shipment_view'
]);

Any ideas?

A: You can get the all the parameters through request it self But before this how you are defining the route
public function storeShipment(Request $request){

    $number = $request->number;
    $category_name = $request->number
}

A: replace your route function with the below one
 Route::post('/ship/preview/{number}/{category_name}',[
   'uses' => 'Controllerr@storeShipment',
    'as' => 'shipment_view'
]);

Hope this solves your problem.


text:
Q: Uncaught ReferenceError: jQuery is not defined other error So I go the error Uncaught ReferenceError: jQuery is not defined. I looked around for a solution to this error. It seems like all of the answers to this question were something like 'jQuery needs to be the first script'. The thing is that my jQuery is my first script. My code looks like this
<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8" />
    <title>Inventory </title>
    <style>
    //my styles
    </style>
</head>
<body>
    <script src="jquery.json-2.4.min.js" type="text/javascript"></script>
    //my html
    <script>
              function updateInv() {

            var i=0;
            var fail = 0;
            for(i=0; i < itemttl; i++)
            {

                var hill = 500000 + i;
                var available = document.getElementById(hill).innerHTML;

                if (available < 0)
                {
                  fail = 1;
                }
            }

            if (fail==0)
            {
                alert('start');
                var TableData;

                TableData = $.toJSON(storeTblValues());
                alert('here');
        $.ajax({
            type: "POST",
            url: "processJSONarray.php",
            data: "pTableData=" + TableData,
            success: function(msg){
                // return value stored in msg variable
            }
        });
                alert('Inventory was Updated');
            }

            else
            {
                alert('Not enough inventory available');
            }

      }

      function storeTblValues()
      {
        alert('1');
        var TableData = new Array();
        var i=0;
        var eq = 200000 + i;
        var skuId = 600000 + i;
        for(i=0; i < itemttl; i++)
        {
            eq = 200000 + i;
            skuId = 600000 + i;
            TableData[i]={
                "sku" : document.getElementById(skuId).innerHTML
                , "inv" : document.getElementById(eq).innerHTML
            }

        }
        //TableData.shift();
        return TableData;
      }
    </script>
</body>
</html>

Note: I have also put the  right after  and right before the first . All of them had the same error. So do i still have it in the wrong spot or is ther a different error?

A:
<script src="jquery.json-2.4.min.js" type="text/javascript"></script>

This is not loading jQuery successfully. It is possible that it is giving you a 404 or other error, but the filename suggests that it points to the JSON plugin for jQuery and not to jQuery itself.
You can get jQuery from the jQuery website.

A: Try using this in your script tag instead. Or alternatively Nuget Jquery and include it much like you are doing so now.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>


text:
Q: android.view.InflateException with dynamic setText from Custom view I have a custom view "BallHoldView" which is run from an activity "BallHoldActivity" by adding said view to the BallHoldActivity layout resource within merge tags. Also within the same layout xml is a TextView (scoreText). I want to set scoreText's text dynamically from the BallHoldView.
When my program tries to run scoreText.setText("new text here"); I get a view.InflateException. Commenting out this one line of code removes the errors.
Through online research I have identified the following:

*

*my BallHoldView needs a constructor with Attributes passed to it. (Check)

*my scoreText needs to be instantiated with reference to the activity, not the view: ((Activity)getContext()).findViewById(R.id.scoreText); (Check)

*It seems the majority of issues with this exception is that something is not declared properly in the xml file. I think the problem is that I'm missing something in the xml file, but I don't know what, and I can't find a solution online.

Can anyone see what I'm missing, or what I've done wrong?
Main errors seem to be:
android.view.InflateException: Binary XML file line #12: Error inflating class
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException

xml line #12 (& #13):
<oaa.tms.zoneball.ballHold.BallHoldView
android:id="@+id/ballHold"

Null Pointer is at BallHoldView.java:37 which is:
scoreText.setText("New Score"); // java line 37.

Here's BallHoldView:
public class BallHoldView extends View
{
private ShapeDrawable circle10, circle50, circleEYE;
private TextView scoreText;
private int viewWidth, viewHeight;
private float circCentreX, circCentreY, circ10Radius, circ50Radius, circEyeRadius;

public BallHoldView(Context context)
{
    super(context);
}

public BallHoldView(Context context, AttributeSet attrs)
{ super(context, attrs);
 Log.e("BallHoldView", "CONSTRUCTOR ENTERED");
 circle10 = new ShapeDrawable(new OvalShape());
    circle10.getPaint().setColor(0xffff9900);
 circle50 = new ShapeDrawable(new OvalShape());
    circle50.getPaint().setColor(0xffb80000);
 circleEYE = new ShapeDrawable(new OvalShape());
    circleEYE.getPaint().setColor(0xff000000);
 scoreText = (TextView)((Activity)getContext()).findViewById(R.id.scoreText);
            Log.e("BallHoldView", "scoreText created");
    scoreText.setText("New Score");
            Log.e("BallHoldView", "scoreText changed");
}

public void onDraw(Canvas c)
{
    super.onDraw(c);
    // Draw some circles here
}

protected void onSizeChanged(int w, int h, int oldW, int oldH)
{
    // change circle parameters here
}
}

Here's the xml:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/shape_rect_black_border"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="oaa.tms.zoneball.BallHoldActivity" >

<oaa.tms.zoneball.ballHold.BallHoldView
android:id="@+id/ballHold"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<TextView
android:id="@+id/scoreText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|left"
android:background="@drawable/shape_rect_textbg"
android:textSize="22sp"
android:text="@string/score" />

<TextView
android:id="@+id/timeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:background="@drawable/shape_rect_textbg"
android:textSize="22sp"
android:text="@string/time" />

</merge>

Here's the log cat (errors):
10-05 17:44:04.326: E/BallHoldView(3474): CONSTRUCTOR ENTERED
10-05 17:44:04.326: E/BallHoldView(3474): scoreText created
10-05 17:44:04.336: E/AndroidRuntime(3474): FATAL EXCEPTION: main
10-05 17:44:04.336: E/AndroidRuntime(3474): java.lang.RuntimeException: Unable to start activity ComponentInfo{oaa.tms.zoneball/oaa.tms.zoneball.BallHoldActivity}: android.view.InflateException: Binary XML file line #12: Error inflating class oaa.tms.zoneball.ballHold.BallHoldView
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2249)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.ActivityThread.access$700(ActivityThread.java:154)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.os.Looper.loop(Looper.java:137)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.ActivityThread.main(ActivityThread.java:5306)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at java.lang.reflect.Method.invokeNative(Native Method)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at java.lang.reflect.Method.invoke(Method.java:511)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at dalvik.system.NativeStart.main(Native Method)
10-05 17:44:04.336: E/AndroidRuntime(3474): Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class oaa.tms.zoneball.ballHold.BallHoldView
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.createView(LayoutInflater.java:619)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:693)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:752)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.inflate(LayoutInflater.java:460)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:342)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.Activity.setContentView(Activity.java:1928)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:217)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:110)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:77)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at oaa.tms.zoneball.BallHoldActivity.onCreate(BallHoldActivity.java:17)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.Activity.performCreate(Activity.java:5255)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)
10-05 17:44:04.336: E/AndroidRuntime(3474):     ... 11 more
10-05 17:44:04.336: E/AndroidRuntime(3474): Caused by: java.lang.reflect.InvocationTargetException
10-05 17:44:04.336: E/AndroidRuntime(3474):     at java.lang.reflect.Constructor.constructNative(Native Method)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
10-05 17:44:04.336: E/AndroidRuntime(3474):     at android.view.LayoutInflater.createView(LayoutInflater.java:593)
10-05 17:44:04.336: E/AndroidRuntime(3474):     ... 25 more
10-05 17:44:04.336: E/AndroidRuntime(3474): Caused by: java.lang.NullPointerException
10-05 17:44:04.336: E/AndroidRuntime(3474):     at oaa.tms.zoneball.ballHold.BallHoldView.<init>(BallHoldView.java:37)
10-05 17:44:04.336: E/AndroidRuntime(3474):     ... 28 more

EDIT:
Using the following code I have confirmed scoreText is null:
scoreText = (TextView)((Activity)getContext()).findViewById(R.id.scoreText);
            Log.e("BallHoldView", "scoreText created");
    if(scoreText != null)
    {
        scoreText.setText("New Score");
            Log.e("BallHoldView", "scoreText changed");
    }
    else
        Log.e("BallHoldView", "scoreText was null");

Why is it null?

A: The problem is that your code at line # 37
scoreText.setText("New Score");

scoreText is null.
scoreText = (TextView)((Activity)getContext()).findViewById(R.id.scoreText);

The above line is not able to find the scoreText. This might be because when the custom view layout is inflated, it will call its constructor, and in there you are trying to refer scoreText which has not been inflated yet, as it comes after ballHold in your android xml.
The solution might be to put the ballHold custom view after your scoreText in android xml. Or otherwise the proper way would be to pass the scoreText TextView from your java activity code to the BallHoldView CustomView class in its constructor and then use it. In that case, in your activity code you will definitely be able to find view by id.


text:
Q: Owl Carousel 1st item border none Use owl carousel plugin then apply those.
state-single div has a border. I want the 1st item state-single border none.
HTML:

Edit: Normal div it works but with owl-carousel plugin it not works.

A: This works for me :)
.owl-item:not(.active) + .owl-item.active .state-single{
    border: none;
}


text:
Q: Limit of ratio of sequences Let $\{ a_n\}$, $\{ b_n\}$ be two sequences where $b_n$ is increasing such that $ \lim_{n \rightarrow \infty}b_n = \infty$. Also that $$\lim_{n \rightarrow \infty} \frac{a_{n+1}-a_n}{b_{n+1}-b_n} = s$$
Show that $\lim_{n \rightarrow \infty}\frac{a_n}{b_n} = s$. Further show that if $b_n >0$ then  we have $$\lim_{n \rightarrow \infty} \frac{a_1+a_2+ . . . . . +a_n}{b_1+b_2+ . . . . . +b_n} = s.$$
I proceeded
$$ \lim_{n \rightarrow \infty} \{(a_{n+1}-a_n) - s(b_{n+1}-b_n)\} = 0$$
Then dividing this by $b_n$ gives me $$ \lim_{n \rightarrow \infty}\{s - \frac{a_n}{b_n}\} +  \lim_{n \rightarrow \infty}\{ \frac{a_{n+1}}{b_n} - s\frac{b_{n+1}}{b_n} \} = 0$$ Proceeding in a similar fashion with $$\lim_{n \rightarrow \infty} \frac{a_{n}-a_{n-1}}{b_{n}-b_{n-1}} = s$$ I got
$$\lim_{n \rightarrow \infty} \frac{a_{n+1}-a_{n-1}}{b_{n+1}-b_{n-1}} = s$$

A: This is the Stolz-Cesaro Theorem and you can google it.
Highlights of the proof: for any arbitrary $\;\epsilon>0\;$ :
There exists $\;N\in\Bbb N\;$ s.t. for $\;n>N\;$ :
$$s-\epsilon<\frac{a_{n+1}-a_n}{b_{n+1}-b_n}<s+\epsilon$$
Multiply through by $\;b_{n+1}-b_n\;$ and sum up from $\;i=N\;$ to $\;i= k>N\;$ :
$$(s-\epsilon)\sum_{i=N}^k(b_{n+1}-b_n)<\sum_{i=N}^k(a_{n+1}-a_n)<(s+\epsilon)\sum_{i=1}^k(b_{n+1}-b_n)$$
Observe we have here telescopic series...Then, divide by $\;b_{k+1}\;$:
$$(l-\epsilon)\left(1-\frac{b_N}{b_{{k+1}}}\right)+\frac{a_{N}}{b
_{{k+1}}}\le\frac{a_{k+1}}{b_{k+1}}\le(l+\epsilon)\left(1-\frac{b_N}{
b_{k+1}}\right)+\frac{a_N}{b_{{k+1}}}$$
End now the argument.


text:
Q: How to Add a Floating Action Button to Bottom Navigation Bar in IOS (Xamarin)? How to add a floating action button to bottom navigation bar in IOS (Xamarin)?
Example of screen layout

In order to add navigation bar, using freshmvvm provided function "FreshTabbedNavigationContainer".
However, I have no idea where should I add a floating action button on top of bottom navigation bar with the following code. Please feel free to comment.
using FreshMvvm;
.....
public App()
        {
            InitializeComponent();

            //MainPage = new MainPage();

            if (Device.RuntimePlatform == Device.iOS)
            {
                var tabs = new FreshTabbedNavigationContainer("MyTabs");

                tabs.AddTab<MainPageModel>("Home", "");
                tabs.AddTab<MainPageModel>("Saved", "");
                tabs.AddTab<MainPageModel>("Zoom", "");
                tabs.AddTab<MainPageModel>("Notifications", "");
                tabs.AddTab<MainPageModel>("Profile", "");

                // Set the selected tab to the middle one.
                tabs.SwitchSelectedRootPageModel<MainPageModel>();

                MainPage = tabs;
            }

        }

BasePage (Customized base class of contentPage)
public class BasePage : ContentPage
    {
        public BasePage()
        {
            NavigationPage.SetHasNavigationBar(this, false);
        }
    }


text:
Q: C# Build a List of Tasks from different injected services and execute them one by one So I want to build a List<Task<bool>> from different injected services in .NET Core 3.1. This is my code:
var tasks = new List<Task<bool>>()
{
    subscriptionService.ValidatePurchases(),
    serviceTwo.Task(),
    serviceThree.TaskTwo()
};

tasks.ForEach(task =>
{
    var fieldInfo = typeof(Task).GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic);
    Delegate action = fieldInfo.GetValue(task) as Delegate;
    string methodName = action?.Method.Name ?? "null";

    try
    {
        task.Start();
        task.Wait();

        if (!task.Result)
        {
            Log.Warning($"Scheduled task: ({methodName}) returned false in TaskRunner.");
        }
    }
    catch (Exception ex)
    {
        Log.Error(ex, $"Scheduled task: ({methodName}) threw an unhandled exception in TaskRunner.");
    }
});

Problem is that the tasks are instantly executed. How can I maintain a list that doesn't execute until I would call the Start method on the task?

A: Thanks to trashr0x I found a solution.
var tasks = new List<Func<Task<bool>>>()
{
    () => subscriptionService.ValidatePurchases(),
    () => serviceTwo.Task()
};

tasks.ForEach(async taskMethod =>
{
    try
    {
        var task = taskMethod();

        var result = await task;

        if (result) { // do something }
    }
    catch (Exception ex)
    {
        // log something
    }
});


text:
Q: Android app crashes with setText in second Activity my app should  show me in the second Activity a string that I generate with an editText in the first Activity after I press the button.
package com.example.josue.sw22;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button Siguiente;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText NUMERO = (EditText)findViewById(R.id.etTelefono);
        Siguiente=(Button)findViewById(R.id.bSiguiente);

        Siguiente.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intento = new Intent(MainActivity.this, LucesAlarma.class);
                intento.putExtra("numero",NUMERO.getText().toString());
                startActivity(intento);
            }
        });

    }

}

This is the second Activity:
 package com.example.josue.sw22;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LucesAlarma extends AppCompatActivity {

    public TextView numactual;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_luces_alarma);

        numactual = (TextView)findViewById(R.id.etTelefono);

        String numeropos;
        numeropos = getIntent().getExtras().getString("numero");
        numactual.setText(numeropos);

    }

}

After I use the button in the first activity, the app crashes, everything is OK in the getIntent part because when I don't use the setText line the app runs well.. PLease help!!!!!
Here are the layots:
First Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.josue.sw20.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Inserte el numero del modulo"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_marginTop="35dp" />

    <EditText
        android:id="@+id/etTelefono"
        android:layout_width="172dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="33dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Siguiente"
        android:id="@+id/bSiguiente"
        android:layout_below="@+id/etTelefono"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp" />

</RelativeLayout>

Second Activity layout (I dont use the buttons yet):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.josue.sw22.LucesAlarma"
    tools:showIn="@layout/activity_luces_alarma">

    <Button
        android:layout_width="120dp"
        android:layout_height="76dp"
        android:text="Prender Alarma"
        android:id="@+id/button2"
        android:layout_marginTop="49dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/button4"
        android:layout_alignEnd="@+id/button4" />

    <Button
        android:layout_width="120dp"
        android:layout_height="76dp"
        android:text="Apagar Alarma"
        android:id="@+id/button3"
        android:layout_alignTop="@+id/button2"
        android:layout_toRightOf="@+id/button2"
        android:layout_toEndOf="@+id/button2" />

    <Button
        android:layout_width="120dp"
        android:layout_height="76dp"
        android:text="New Button"
        android:id="@+id/button4"
        android:layout_below="@+id/button2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="120dp"
        android:layout_height="76dp"
        android:text="New Button"
        android:id="@+id/button5"
        android:layout_alignTop="@+id/button4"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignStart="@+id/button3" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="............"
        android:id="@+id/textView2"
        android:layout_alignBottom="@+id/button3"
        android:layout_toRightOf="@+id/button3"
        android:layout_toEndOf="@+id/button3"
        android:layout_marginLeft="26dp"
        android:layout_marginStart="26dp"
        android:layout_marginBottom="28dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="............"
        android:id="@+id/textView3"
        android:layout_alignBaseline="@+id/button5"
        android:layout_alignBottom="@+id/button5"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignStart="@+id/textView2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sensores"
        android:id="@+id/button6"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Numero Actual"
        android:id="@+id/textView8"
        android:layout_below="@+id/button6"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="77dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/tvNUMERO"
        android:layout_alignTop="@+id/textView8"
        android:layout_toLeftOf="@+id/textView3"
        android:layout_toStartOf="@+id/textView3" />

</RelativeLayout>

My App Manifest(I have a third activity, I am not using it yet):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.josue.sw22">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".LucesAlarma"
            android:label="@string/title_activity_luces_alarma"
            android:theme="@style/AppTheme.NoActionBar" />
        <intent-filter>
            <action android:name="com.example.josue.sw22" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <activity
            android:name=".Sensores"
            android:label="@string/title_activity_sensores"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="com.example.josue.sw22" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The exeption:
03-07 11:51:39.445 1412-1412/com.example.josue.sw22 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.example.josue.sw22, PID: 1412
                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.josue.sw22/com.example.josue.sw22.LucesAlarma}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                      at com.example.josue.sw22.LucesAlarma.onCreate(LucesAlarma.java:41)
                                                                      at android.app.Activity.performCreate(Activity.java:6237)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:148)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Thank you very much!!

A: Problem is here-
 numactual = (TextView)findViewById(R.id.etTelefono);

etTelefono is the ID of Edittext, which you are referencing as Textview.

A: just make this change in your manifest file:
 <activity
        android:name=".LucesAlarma"
        android:label="@string/title_activity_luces_alarma"
        android:theme="@style/AppTheme.NoActionBar" >
    <intent-filter>
        <action android:name="com.example.josue.sw22" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter></activity>//close your actvity here

hope this will help you

A: you miss this Intent intent = getIntent() in your second activity
public class LucesAlarma extends AppCompatActivity {

public TextView numactual;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_luces_alarma);

    numactual = (TextView)findViewById(R.id.etTelefono);

   Intent intent = getIntent();
   String numeropos =intent.getStringExtra("numero");
   numactual.setText(numeropos);
  }
 }

A: numactual = (TextView)findViewById(R.id.etTelefono);

In this line in your second Activity you are casting your EditText to a TextView. etTelefono is defined as a EditText in your first activity layout, did you want to use tvNUMERO or one of the other TextViews in your second xml instead?
You have set your second xml as Content view in your second Activity, thus you can only use the things you defined in your second xml.


text:
Q: Issue with gtfs_functions gtfs.cut_gtfs python Trying to use the gtfs_functions package with python, I am struggling with the cut_gtfs function. More specifically, this function returns the following error:
TypeError: object of type 'GeometryCollection' has no len().
Thank you for your help!

routes, stops, stop_times, trips, shapes = gtfs.import_gtfs("C:/Users/charl/OneDrive/Bureau/car_dependency/Data/tisseo_gtfs_v2.zip")

cutoffs = [0, 6, 9, 15, 19, 22, 24]
stop_freq = gtfs.stops_freq(stop_times, stops, cutoffs=cutoffs)
line_freq = gtfs.lines_freq(stop_times, trips, shapes, routes, cutoffs=cutoffs)
segments_gdf = gtfs.cut_gtfs(stop_times, stops, shapes)

Full error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[79], line 1
----> 1 segments_gdf = gtfs.cut_gtfs(stop_times, stops, shapes)

File c:\Users\charl\anaconda3\envs\inequality2\Lib\site-packages\gtfs_functions\gtfs_funtions.py:343, in cut_gtfs(stop_times, stops, shapes)
    340         loops_direction_id.append(direction_id)
    341         loops_shape_id.append(shape_id)
--> 343 segments = [cut_shapes_(shape_trans_lines[i], shape_closest_points[i])  for i in range(0, len(shape_trans_lines))]
    345 # Remove None values
    346 segments = [i for i in segments if i]

File c:\Users\charl\anaconda3\envs\inequality2\Lib\site-packages\gtfs_functions\gtfs_funtions.py:343, in (.0)
    340         loops_direction_id.append(direction_id)
    341         loops_shape_id.append(shape_id)
--> 343 segments = [cut_shapes_(shape_trans_lines[i], shape_closest_points[i])  for i in range(0, len(shape_trans_lines))]
    345 # Remove None values
    346 segments = [i for i in segments if i]

File c:\Users\charl\anaconda3\envs\inequality2\Lib\site-packages\gtfs_functions\gtfs_funtions.py:330, in cut_gtfs..cut_shapes_(shape_trans_lines, shape_closest_points)
    327     cut_points = MultiPoint(cut_points[1:-1])
    328     result = split(line, cut_points)
--> 330 if len(result)==len(trans_lines_all)-1:
    331     d['segment'] = [s for s in result]
    333     return d

TypeError: object of type 'GeometryCollection' has no len()


text:
Q: Programatically create tables in Python Here is an example Data Frame
import pandas as pd
from prettytable import PrettyTable

df = pd.DataFrame()
df["name"] = ["Nick","Bob", "George", "Jason","Death"]
df["Restaurant Manager"] = ["Sam","Mason", "Sam", "Mason","Mason"]
df["Score"] = [1,5, 7, 2,10]
df['Percentile Rank'] = [0,50,80,20,100]
df["Restaurant Name"] = "Elise"

What I am trying to do is to recreate this table (see screenshot) that we have in excel since we are in the process of trying to automate our reporting system.

I managed to get something a bit similar to this but I am stuck... Here is the following code:
#Add headers
column_names = ["Rank","Employee Name", "Score", "Percentile"]#Add columns
tb1.add_column(column_names[0],[1,2])
tb1.add_column(column_names[1],["Nick","George"])
tb1.add_column(column_names[2],[1,7])
tb1.add_column(column_names[3],[0,80])
tb1.title = "Elise"
print(tb1)

Not only would I like to replicate the table fully as in the image shared above. But I would also like to create multiple similar tables for each restaurant name and place them side by side if possible.

A: Create it from a dictionary:
df = pd.DataFrame({
    "name": ["Nick","Bob", "George", "Jason","Death"],
    "Restaurant Manager": ["Sam","Mason", "Sam", "Mason","Mason"],
    "Score": [1,5, 7, 2,10],
    'Percentile Rank': [0,50,80,20,100],
    "Restaurant Name": ["Elise", "Elise", "Elise", "Elise", "Elise"]
})


text:
Q: WordPress image URLs have a blank space before /wp-content I have run into a WP site which is not loading almost all images. The developer tools console shows 100s of these errors.
Failed parsing 'srcset' attribute value since it has an unknown descriptor.
Dropped srcset candidate "https://domain.tld"

After looking at the source code of the page, I found that the image URLs have a space before /wp-content/
This is happening for all src and srcset URLs.
I have tried troubleshooting by deactivating all plugins, but it did not fix the problem.
How do I go about fixing this issue?

A: The issue is that siteurl and home setting have a space at the end. The setting can either be found in wp-config.php file or in the database. I had to run the following command to fix it (replace https://example.com with the name your domain)
UPDATE `wp_options` SET `option_value` = 'http://example.com' WHERE `wp_options`.`option_name` = 'siteurl';
UPDATE `wp_options` SET `option_value` = 'http://example.com' WHERE `wp_options`.`option_name` = 'home';

You might find the following lines in wp-config.php:
define('WP_HOME','https://example.com');
define('WP_SITEURL','https://example.com');

Make sure they don't have a space at the end


text:
Q: React - creating accordion with bootstrap doesnt expand/close on click Iam trying to create a accordion from the bootstrap website in React. Iam following this website https://getbootstrap.com/docs/4.1/components/collapse/#accordion-example
I copied their example code and it looks exactly just as the example on the website but the problem is when I click on the accordion nothing happends, it doesn't expand or close. Is there suppose to be a onClick function somewhere in the code that needs to be included?

A: you need to copy the JS as well as the css code from bootstrap lib.
i suggest to use code from my google search bellow, create a component and just adapt the css style to bootstrap
https://www.google.it/search?q=accordion+example+jsfiddle&oq=accordion+example+jsf&aqs=chrome.1.69i57j0l5.12453j0j1&sourceid=chrome&ie=UTF-8
actually is very easy to build it

A: Forgive me if I'm totally wrong here, as I am fairly new to web development- but I've used that accordion before and simply copying and pasting their code should do the trick, provided you have added the proper link tags from their "Getting Started" section in documentation set in your index.html (not just CSS but all of the JS links, too).
I hope this helps!!


text:
Q: Possible to name table from value from a field of another table Is it possible to name a table from a value from a column of a different table.
Example:
Select a from dbo.[(select x of dbo.food where x=Candy)]

Other Table: dbo.Food
  X      Y       Z
--------------------
Candy  Apples  Pears
--------------------

I am trying to append the value from another table as a new table dbo.candy

A: I think, you are looking for select into
SELECT * INTO dbo.candy
FROM dbo.food;
WHERE x = 'Candy';

A: You can use sp_executesql with output parameter, like this:
DECLARE @tableName NVARCHAR(MAX);
DECLARE @command NVARCHAR(MAX);
DECLARE @result NVARCHAR(MAX);

SET @tableName = select x from dbo.food where x = 'Candy';
SET @command = 'select @tempResult = a from dbo.' + @tableName;

exec sp_executesql @command , N'@tempResult NVARCHAR(MAX) out', @result out;

select @result as 'a';


text:
Q: c++: How can I read double scalar data from a vti grid using the vtk library? I am trying to read the double values from a grid in my vti file. However, the return value I get from GetScalarPointer generates a segmentation fault when I try to access any element inside of it, e.g. with scalarPtr[0]:
#include <vtkSmartPointer.h>
#include <vtkXMLImageDataReader.h>
#include <vtkImageData.h>

int main(){
  vtkSmartPointer<vtkXMLImageDataReader> reader =
      vtkSmartPointer<vtkXMLImageDataReader>::New();
  reader->SetFileName("my_file.vti");
  reader->Update();
  vtkSmartPointer<vtkImageData> imageData = vtkSmartPointer<vtkImageData>::Take(reader->GetOutput());
  double* scalarPtr = static_cast<double*>(imageData->GetScalarPointer());
  std::cout << scalarPtr[0] << std::endl; // segmentation fault
}

I know the type is double because imageData->GetDataType() returns 11, which corresponds to VTK_DOUBLE.
I also tried to see if it was due to the endianness of the values, but
double* scalarPtr = static_cast<double*>(imageData->GetScalarPointer());
const vtkIdType numScalars = imageData->GetNumberOfPoints();
const int scalarSize = sizeof(double);
vtkByteSwap::SwapVoidRange(scalarPtr, numScalars, scalarSize);

also results in a segmentation fault, probably because scalarPtr is not accessible.
These are the contents of my vtkImageData class:
vtkImageData (0x556e1ad5afd0)
  Debug: Off
  Modified Time: 307
  Reference Count: 1
  Registered Events: (none)
  Information: 0x556e1ad5b470
  Data Released: False
  Global Release Data: Off
  UpdateTime: 0
  Field Data:
    Debug: Off
    Modified Time: 307
    Reference Count: 1
    Registered Events: (none)
    Number Of Arrays: 1
    Array 0 name = comments
    Number Of Components: 1
    Number Of Tuples: 1
  Number Of Points: 2431
  Number Of Cells: 1920
  Cell Data:
    Debug: Off
    Modified Time: 302
    Reference Count: 1
    Registered Events:
      Registered Observers:
        vtkObserver (0x556e1ad5cb00)
          Event: 33
          EventName: ModifiedEvent
          Command: 0x556e1ad5c6a0
          Priority: 0
          Tag: 1
    Number Of Arrays: 1
    Array 0 name = material
    Number Of Components: 1
    Number Of Tuples: 1920
    Copy Tuple Flags: ( 1 1 1 1 1 0 1 1 1 1 1 )
    Interpolate Flags: ( 1 1 1 1 1 0 0 1 1 1 1 )
    Pass Through Flags: ( 1 1 1 1 1 1 1 1 1 1 1 )
    Scalars: (none)
    Vectors: (none)
    Normals: (none)
    TCoords: (none)
    Tensors: (none)
    GlobalIds: (none)
    PedigreeIds: (none)
    EdgeFlag: (none)
    Tangents: (none)
    RationalWeights: (none)
    HigherOrderDegrees: (none)
  Point Data:
    Debug: Off
    Modified Time: 304
    Reference Count: 1
    Registered Events:
      Registered Observers:
        vtkObserver (0x556e1ad5c8e0)
          Event: 33
          EventName: ModifiedEvent
          Command: 0x556e1ad5c6a0
          Priority: 0
          Tag: 1
    Number Of Arrays: 0
    Number Of Components: 0
    Number Of Tuples: 0
    Copy Tuple Flags: ( 1 1 1 1 1 0 1 1 1 1 1 )
    Interpolate Flags: ( 1 1 1 1 1 0 0 1 1 1 1 )
    Pass Through Flags: ( 1 1 1 1 1 1 1 1 1 1 1 )
    Scalars: (none)
    Vectors: (none)
    Normals: (none)
    TCoords: (none)
    Tensors: (none)
    GlobalIds: (none)
    PedigreeIds: (none)
    EdgeFlag: (none)
    Tangents: (none)
    RationalWeights: (none)
    HigherOrderDegrees: (none)
  Bounds:
    Xmin,Xmax: (0, 5e-06)
    Ymin,Ymax: (0, 8e-06)
    Zmin,Zmax: (0, 6e-06)
  Compute Time: 308
  Spacing: (5e-07, 5e-07, 5e-07)
  Origin: (0, 0, 0)
  Direction: (1, 0, 0, 0, 1, 0, 0, 0, 1)
  Dimensions: (11, 17, 13)
  Increments: (0, 0, 0)
  Extent: (0, 10, 0, 16, 0, 12)

What am I doing wrong in terms of how I am accessing the grid values?


text:
Q: If $f : D(0;1) \setminus \{ 0 \}$ holomorphic such that $f(1/n) = 0$ then either $f=0$ or $f$ has an essential singularity at $0$ I'm trying to solve this question:

Let $f$ be a holomorphic function on $D(0; 1)\setminus\{0\}$ with the property that $f(1/n) = 0$ for every positive integer $n$. Show that $f$ is either identically zero, or that $f$ has an
  essential singularity at $0$. Give an example of the latter.

I'm thinking I need to use the Laurent expansion of the function to show the singularity is essential, but I'm unsure of how to do that since I don't know the function. I'm confused about how to show it could be identically zero as well. Any help is appreciated, thank you!

A: If $f$ does not have an essential singularity at $0$ then it has either a pole or  a removable singularity. If it is a removable singularity then defining it to be $0$ at $0$ gives an analytic function in the open unit disk whose zeros have a limit point, so $f \equiv 0$. If it has  a pole then necessarily $|f(z)| \to \infty$ as $ z \to 0$ but this is false because $f(\frac 1 n)=0$ for all $n$. An example where $f$ has an essential singularity is $f(z)=\sin (\frac {\pi} z)$.

A: Abridged proof. If $f$ does not have an essential singularity at zero and is not the function zero, Laurent development at zero gives an analytic function $f_1$ on the disc and an integer $m \geq 0$ such that $f(z) = \dfrac{1}{z^m} f_1(z),$ with $f_1(0) \neq 0.$ $f_1$ being analytic, cannot have cluster values for its set of zeroes, violating the hypothesis. Q.E.D.


text:
Q: Cloning rows not cloning tr I'm trying to cloning table row. But i'm only able cloning what inside it without the tr tag. Please check my script

$(".tr_clone_add").on('click', function() {
  $('.tr_clone').last().clone({
    withDataAndEvents: true
  }).insertBefore('.tr_clone_add:first');
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      Hari

        <select id="dropdown" class="form-control" name="hari[]">
          <option>Senin</option>
          <option>Selasa</option>
          <option>Rabu</option>
          <option>Kamis</option>
          <option>Jumat</option>
        </select>

<input type="button" name="add" value="Tambah Baris" class="tr_clone_add">

How can i fix it? Sorry for my bad english.

A: Firstly note that clone() accepts a boolean value as the first parameter, not an object.
Secondly your issue is because you're appending the tr element before the button, not inside the table. Instead, try using appendTo('table tbody') like this:

$(".tr_clone_add").on('click', function() {
  $('.tr_clone').last().clone(true).appendTo('table tbody');
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

      Hari

        <select id="dropdown" class="form-control" name="hari[]">
          <option>Senin</option>
          <option>Selasa</option>
          <option>Rabu</option>
          <option>Kamis</option>
          <option>Jumat</option>
        </select>

<input type="button" name="add" value="Tambah Baris" class="tr_clone_add">


text:
Q: Mudar valor do input com javascript Tenho um campo para inserir notas e gostaria que se o valor inserido fosse maior que 10 ou menor que 0 o valor fosse apagado do input.
Tentei fazer com o código abaixo, mas sem sucesso.

function verifica(v){
  if (v > 10 || v < 0){
   v = '';
  }
}
<input type="number" onchange="verifica(this.value)">

A: Passe this como argumento do onchange e altere o método para trabalhar com o elemento e não apenas o valor.
Assim você pode alterar a propriedade value.

function verifica(el){
  if (el.value > 10 || el.value < 0){
    el.value = '';
  }
}
<input type="number" onchange="verifica(this)">


text:
Q: JSON to swift how to obtain the key value in a 2d array Here is my code and I'm banging my head against the wall for not being able to get the values from the JSON array correctly:
func loadPosts(posts:NSArray){
    for post in posts {
        var ter = (post["Territory"] as! String).toInt()
        var reg = (post["Region"] as! String).toInt()
        var stno = (post["Store"] as! String).toInt()
        var stname = post["StoreName"] as! String
        var goal = (post["Goal"] as! String).toInt()
        println(post)'
    }
}

*

*println(ter) displays the value "loadData.collection"

*println(post)  spits out all the nodes

What am I doing wrong here? Please help!!

Here is the JSON data out put
{
Goal = 0;
Region = 704;
Store = 10;
StoreName = "Mmn";
Territory = 1;

}

A: You will need to cast it to the relevant type by using as? or as! then you can access the value.
Post json data for a better answer.


text:
Q: Mathematical proof question Let $a$, $b$, $c$ be integers. Prove that if $a|b$ and $a|c$, then $a$ divides every linear combination of the form ax + by, where $x, y \in \mathbb{Z}$.
Any help would be appreciated.

A: $a|b $ means $\exists n \in \mathbb{Z}$ such that $b = na$. Similarly, $a|c $ means $\exists m \in \mathbb{Z}$ such that $c = ma$.
Thus $\forall (x,y) \in \mathbb{Z}^2$,
$$ bx + cy = a(nx + my).$$
Since $\mathbb{Z}$ is close for addition and multiplication, $nx + my \in \mathbb{Z}$, so
$$ a |bx + cy , \, \forall (x,y) \in \mathbb{Z}^2.$$


text:
Q: Cannot instantiate any F# type provider from FSharp.Data I'm attempting to recreate the simplest example possible for the CSV type provider:

*

*I create a Library project in Visual Studio 2015, by default this
targets F#4.0 and .NET 4.5.2.

*I add FSharp.Data 2.2.5 via NuGet.

Already, I have one error and one warning in my project:

The type provider 'ProviderImplementation.JsonProvider' reported an
  error: The type provider constructor has thrown an exception: API
  restriction: The assembly 'file:///c:\users\james
  foye\documents\visual studio
  2015\Projects\CsvExample\packages\FSharp.Data.2.2.5\lib\net40\FSharp.Data.dll'
  has already loaded from a different location. It cannot be loaded from
  a new location within the same appdomain. CsvExample  c:\users\james
  foye\documents\visual studio
  2015\Projects\CsvExample\CsvExample\Library1.fs   1

and

Referenced assembly 'c:\users\james foye\documents\visual studio
  2015\Projects\CsvExample\packages\FSharp.Data.2.2.5\lib\net40\FSharp.Data.dll'
  has assembly level attribute
  'Microsoft.FSharp.Core.CompilerServices.TypeProviderAssemblyAttribute'
  but no public type provider classes were
  found CsvExample  c:\users\james foye\documents\visual studio
  2015\Projects\CsvExample\CsvExample\Library1.fs   1

All attempts to instantiate the provider fail, for example:
open FSharp.Data;;
let yahoo = CsvProvider<"sample.csv">;;

C:\Data\Ebooks\F#\Deep Dives\Source\Chap6\YahooProvider\stdin(4,13):
  error FS0039: The value or constructor 'CsvProvider' is not defined

It doesn't matter what I do to play around with the path (provide full path, change working directory of FSI, etc.)

A: I was not able to get to the bottom of the compiler error, it almost seems like a bug somewhere with Visual Studio, NuGet, or some other part of the tool chain. But as mpeac suggested, simply restarting VS cleared it.
Once I did that I needed to change my code from declaring a let binding to defining a type. I had just mistakenly typed "let =" instead of "type =".


text:
Q: Setup webjob ServiceBusTriggers or queue names at runtime (without hard-coded attributes)? Is there any way to configure triggers without attributes? I cannot know the queue names ahead of time.
Let me explain my scenario here.. I have one service bus queue, and for various reasons (complicated duplicate-suppression business logic), the queue messages have to be processed one at a time, so I have ServiceBusConfiguration.OnMessageOptions.MaxConcurrentCalls set to 1. So processing a message holds up the whole queue until it is finished. Needless to say, this is suboptimal.
This 'one at a time' policy isn't so simple. The messages could be processed in parallel, they just have to be divided into groups (based on a field in message), say A and B. Group A can process its messages one at a time, and group B can process its own one at a time, etc. A and B are processed in parallel, all is good.
So I can create a queue for each group, A, B, C, ... etc. There are about 50 groups, so 50 queues.
I can create a queue for each, but how to make this work with the Azure Webjobs SDK? I don't want to copy-paste a method for each queue with a different ServiceBusTrigger for the SDK to discover, just to enforce one-at-a-time per queue/group, then update the code with another copy-paste whenever another group is needed. Fetching a list of queues at startup and tying to the function is preferable.
I have looked around and I don't see any way to do what I want. The ITypeLocator interface is pretty hard-set to look for attributes. I could probably abuse the INameResolver, but it seems like I'd still have to have a bunch of near-duplicate methods around. Could I somehow create what the SDK is looking for at startup/runtime?
(To be clear, I know how to use INameResolver to get queue name as at How to set Azure WebJob queue name at runtime? but though similar this isn't my problem. I want to setup triggers for multiple queues at startup for the same function to get the one-at-a-time per queue processing, without using the trigger attribute 50 times repeatedly. I figured I'd ask again since the SDK repo is fairly active and it's been a year..).
Or am I going about this all wrong? Being dumb? Missing something? Any advice on this dilemma would be welcome.

A: The Azure Webjob Host discovers and indexes the functions with the ServiceBusTrigger attribute when it starts. So there is no way to set up the queues to trigger at the runtime.
The simpler solution for you is to create a long time running job and implement it manually:
public class Program
{
    private static void Main()
    {
        var host = new JobHost();
        host.CallAsync(typeof(Program).GetMethod("Process"));
        host.RunAndBlock();
    }

    [NoAutomaticTriggerAttribute]
    public static async Task Process(TextWriter log, CancellationToken token)
    {
        var connectionString = "myconnectionstring";
        // You can also get the queue name from app settings or azure table ??
        var queueNames = new[] {"queueA", "queueA" };
        var messagingFactory = MessagingFactory.CreateFromConnectionString(connectionString);
        foreach (var queueName in queueNames)
        {
            var receiver = messagingFactory.CreateMessageReceiver(queueName);
            receiver.OnMessage(message =>
            {
                try
                {
                    // do something
                    ....

                    // Complete the message
                    message.Complete();
                }
                catch (Exception ex)
                {
                    // Log the error
                    log.WriteLine(ex.ToString());

                    // Abandon the message so that it can be retry.
                    message.Abandon();
                }
            }, new OnMessageOptions() { MaxConcurrentCalls = 1});
        }

        // await until the job stop or restart
        await Task.Delay(Timeout.InfiniteTimeSpan, token);
    }
}

Otherwise, if you don't want to deal with multiple queues, you can have a look at azure servicebus topic/subscription and create SqlFilter to send your message to the right subscription.
Another option could be to create your own trigger: The azure webjob SDK provides extensibility points to create your own trigger binding :

*

*Binding Extensions Overview
Good Luck !

A: Based on my understanding, your needs seems to be building a message batch system in parallel. The @Thomas solution is good, but I think Azure Batch service with Table storage may be better and could be instead of the complex solution of ServiceBus queue + WebJobs with a trigger.
Using Azure Batch with Table storage, you can control the task creation and execute the task in parallel and at scale, even monitor these tasks, please refer to the tutorial to know how to.


text:
Q: stored procedure input parameter i am creating a stored procedure in sql server 2008 such as this
-- the code
create procedure proce
@database varchar(50)
as
begin
select * from [@database].[dbo].[sometable]
end

the procedure is compiled
but when i execute the procedure using
-- here i execute it
execute proce 'somedatabase'

it throws an error
-- me gets error :(
Invalid object name '@database.dbo.sometable'

where am i going wrong???????

A: You cannot directly parameterized the tableName. The only way you can do that is to make a dynamic SQL Statement.
eg,
CREATE PROCEDURE proce @database VARCHAR(50)
AS
BEGIN
    DECLARE @SQLQuery AS NVARCHAR(500)
    SET @SQLQuery = 'SELECT * FROM [' + @database + '].[dbo].[sometable]'
    EXECUTE(@SQLQuery)
END
GO

*

*Building Dynamic SQL In a Stored Procedure

A: I don't believe variables are allowed in that context, use the following which I've just confirmed works with your procedure:
exec('select * from [' + @database + '].[dbo].[sometable]')

A: You can go with this:
DECLARE @string AS NVARCHAR(500)
SET @string = 'select * from [' + @database + '].[dbo].[sometable]'
EXEC (@string)

More more info refer: Dynamic SQL


text:
Q: python SocketServer stuck on waitpid() syscall I am using Python (2.7) SocketServer with ForkingMixIn. It worked well.
However sometimes on heavy usage (tons of rapidly connecting/disconnecting clients) the "server" stuck, consuming all the idle CPU (shown 100% CPU by top). If I use strace from CLI on the process it shows it does endless sequence of waitpid() syscall. According to command "ps" there are no child processes though at this point.
After this problem my server implementation goes unusable and only its restarting helps :( Clients can connect but no anwser, I guess just the "backlog" queue is used on OS side, but the python code never accepts the connection.
It can be easily reproduced eg with some privimitive HTTP implementation, and a browser (I used chrome) with CTRL-R (reload) hold down for something like 10 seconds. Of course the problem is triggered without this "brutal" try as well "on normal usage" just more rarely, and it was quite hard to even come with the idea what can be the problem. I wrote my own implementation of something like SocketServer with os.fork(), and socket functions, and it does not have this problem, but I am more happy with some "already ready", and "standard" solution.
The problem: it is not a nice thing, as my script implementing a server can be DoS'ed very easily in this way.
What I could notice: I installed a singal handler for SIGCHLD. It seems if I remove that, I can't reproduce the problem, however then I can see zombie processes (I guess since they are not wait()'ed). Even if I install signal handler with signal.SIG_IGN, I expereince this problem.
Can anybody help what can be the problem and how I can solve this? I'd like use singal handler anyway since it's also not so nice to leave many zombie processes, especially after a long run.
Thanks for any idea.

A: maybe related: What is the cost of many TIME_WAIT on the server side?
it is possible that you have all your max connections in a time_wait state.

*

*check sysctl net.core.somaxconn for maximum connections.

*check sysctl net.ipv4 for other configuration details (e.g. tw

*check ulimit -n for max open file descriptors (sockets included)

*you can try: sysctl net.ipv4.tcp_tw_reuse=1 to quickly reuse those sockets (don't keep it enabled unless you know what you're doing.)

*check for file handle leaks.

[not-so] stupid question: how is your SocketServer implementation different from the standard one + ForkingMixIn?
However, it is really easy to abuse a ForkingMixIn (fork bomb), you might want to use green threads, e.g. the eventlet library ( http://eventlet.net/doc/index.html )
this might be your problem.

*

*this: http://bugs.python.org/issue7978

*this: http://mail.python.org/pipermail/python-bugs-list/2010-April/095492.html

*this: http://twistedmatrix.com/trac/ticket/733
you will see that SIGCHLD handler is discouraged unless you take some extra measures (signal.siginterrupt(signal.SIGCHLD, False) in handler, or using a wake-up fd in select() call)


text:
Q: Отправка на сервер кода 200 не используя return Имеется вебсервер для приема POST, данный сервер часть огромного конвеера который выполняется 5+ минут взависимости от приходящего POST
Из-за этого FLASK возвращает 500 код, как это можно исправить?
КОД FLASK
@app.route("/gitlab-webhook", methods=['POST'])
def githubWebhook():
    def load_secret(TOKEN, key):
        try:
            # slack_message_pipe(step=f'I LOAD JSON')
            print(TOKEN, ' !!! ', key)
            if TOKEN == key:
                return 200
            else:
                return 404
        except Exception as e:
            slack_message_pipe(step=e)
    try:
        content = request.json
        data = request.headers
        print(type(data))
        key = data['X-Gitlab-Token']
        load_secret(TOKEN, key)
        commits_list = content['commits']
        json_dump_for_proj(data=commits_list)
    except Exception as e:
        slack_message_pipe(step=e)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8889)

ОШИБКА:
ERROR in app: Exception on /gitlab-webhook [POST]
Traceback (most recent call last):
File "python3.8/site-packages/flask/app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "python3.8/site-packages/flask/app.py", line 1516, in full_dispatch_request
return self.finalize_request(rv)
File "/python3.8/site-packages/flask/app.py", line 1535, in finalize_request
response = self.make_response(rv)
File "/python3.8/site-packages/flask/app.py", line 1698, in make_response
raise TypeError(
TypeError: The view function for 'githubWebhook' did not return a valid response. The function either returned None or ended without a return statement.
"POST /gitlab-webhook HTTP/1.1" 500 -

Прочитав ошибку, появилась мысль использовать make_response(), но я не нашел пока примеров или что-о из чтива на этот счет

A: Воплотил идею @insolor, но решил не мудрить
Вышло это
@app.route("/gitlab-webhook", methods=['POST'])
    def githubWebhook():
        my_resp = ''
        def load_secret(TOKEN, key):
            try:
                # slack_message_pipe(step=f'I LOAD JSON')
                print(TOKEN, ' !!! ', key)
                if TOKEN == key:
                    my_resp = 200
                    return my_resp
                else:
                    my_resp = 404
                    return my_resp
            except Exception as e:
                slack_message_pipe(step=e)
        try:
            content = request.json
            data = request.headers
            print(type(data))
            key = data['X-Gitlab-Token']
            load_secret(TOKEN, key)
            commits_list = content['commits']
            thread = Thread(target=json_dump_for_proj, args=(commits_list))
            thread.start()
            return my_resp
        except Exception as e:
            slack_message_pipe(step=e)

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=8889)


text:
Q: Html.Kendo().MaskedTextBox() with two length? I have this MaskedTextBox:
                    <div style="direction:ltr;padding-left:20px;">
                        @(Html.Kendo().MaskedTextBox()
                              .Name("nationalityCode")
                              .Mask("000000000000").HtmlAttributes(new { @class = "login-input user-pass", width = "300px", placeholder = "Enter you code" })
                              )

                    </div>

My problem is NationalityCode can be 8 or 12 length , If I use above code,then in Runtime enter a code with 8 length, it will pass null to controller .


text:
Q: Virtual environment libraries do not update in Jupyter notebook? So I have a virtual environment created with Anaconda, and I've also installed it into Jupyter notebook as this link describes:
python -m ipykernel install --user --name=<my_env_name>

However, whenever I install something new onto my_env_name, it doesn't work within the notebook. For example, I just did the following:
>>> pip install boto3
>>> import boto3

This works in the anaconda prompt.
However, if I try to do import boto3 in the notebook, I just get:

ModuleNotFoundError: No module named 'boto3'

Why isn't the libraries syncing up? I actually ran the ipykernel command again as well to see if that would fix it, but nope. If I run !pip install boto3 within the notebook, I just get a bunch of "requirement satisfied already". What could be the reason causing this issue?
Edit:
While checking the sys.executable I get:

C:\Users\MyUser\AppData\Local\Continuum\anaconda3\python.exe

But I probably should be getting this, correct?

C:\Users\MyUser\AppData\Local\Continuum\anaconda3\envs\my_env_name\python.exe

A: You may need to install kernel within the required environment using
python3 -m ipykernel install --user

and then install required libraries within this environment. Just make sure ipykernel is installed in the virtualenv

If above solution does not work then you can try steps given below
Step 1: check the correct executable path of the anaconda environment.
Go on command line, activate the conda environment then check the correct executable path for the environment.
conda activate {envronment name}

then on python console,
import sys
sys.executable

For instance on Linux it will be
/media/{username}/{path-to}/anaconda3/envs/{environment name}/bin/python

Step 2: correct the executable path for jupyter sessions
From command line, check the path where kernel.json of your conda environment is located using below command
jupyter kernelspec list

For instance on Linux it will be:
/home/{username}/.local/share/jupyter/kernels/{environment name}

Open the kernel.json located in that folder and replace the incorrect executable path, as shown below.
{
 "argv": [
  "REPLACE-THIS-WITH-THE-CORRECT-EXECUTABLE-PATH",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "heterodimers",
 "language": "python"
}


text:
Q: MATLAB - Limitation of Fibonacci Code I tried to write a code for Fibonacci series  using while loop. I  wrote the following code
after editing to 46
Original code upto 45
f=[1,1]; %Valid till 44 terms, for larger numbers this method can't be used
i=3;
while i<45
    fNew=f(i-1)+f(i-2);
    f=[f,fNew];
    i=i+1;

end

Upto 45 numbers, it works fine . Bu if I write 46 instead of 45 in the code above, I get random zeroes ( about 40 in number) followed by some random numbers. Why is it so ?

A: There is no problem with the calculation of the Fibonacci row. You only misinterpreted the graphical representation of it.
If you print a matrix, you should always check the multiplication factor at the beginning. Note that 1e+9 * 0.0000 != 0, but 1e+9 * 0.0000 < 1e+5 By default matlab will not print the result with full resolution. You can change this with the format command, for example:
format longg

As alternative, you can print the matrix with a specified format as suggested in the comments:
fprintf('%i\n',f)

Or you can ask one element from the vector:
f(1) % will return allways 1

Note that Matlab by default tries to use a common scale factor for all elements in a printed matrix, which may not be appropriate for all elements.


text:
Q: Webscraping with BeautifulSoup in Python tags I am currently trying to scrape some information from the following link:
http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2001.nsf/ee3e4953228bd84705256dcd008385e7/4ec9c3be3fc593e2052571c40071de75?OpenDocument
I would like to scrape some of the information in the table using BeautifulSoup in Python. Ideally I would like to scrape the "Groupo Parliamentario," "Titulo," "Sumilla," and "Autores" from the table as separate items.
So far I've developed the following code using BeautifulSoup:
from bs4 import BeautifulSoup
import requests
import pandas as pd

url = 'http://www2.congreso.gob.pe/Sicr/TraDocEstProc/CLProLey2001.nsf/ee3e4953228bd84705256dcd008385e7/4ec9c3be3fc593e2052571c40071de75?OpenDocument'

page = requests.get(url)

soup = BeautifulSoup(page.text, 'html.parser')

table = soup.find('table', {'bordercolor' : '#6583A0'})
contents = []
summary = []
authors = []
contents.append(table.findAll('font'))
authors.append(table.findAll('a'))

What I'm struggling with is that the code to scrape the authors only scrapes the first author in the list. Ideally I need to scrape all of the authors in the list. This seems odd to me because looking at the html code for the webpage, all authors in the list are indicated with '<a href = >' tags. I would think table.findAll('a')) would grab all of the authors in the list then.
Finally, I'm sort of just dumping the rest of the very messy html (title, summary, parliamentary group) all into one long string under contents. I'm not sure if I'm missing something, I'm sort of new to html and webscraping, but would there be a way to pull these items out and store them individually (ie: storing just the title in an object, just the summary in an object, etc). I'm having a tough time identifying unique tags to do this in the code for the web page. Or is this something I should just clean and parse after scraping?

A: to get the authors you can use:
soup.find('input', {'name': 'NomCongre'})['value']

output:
'Santa María Calderón  Luis,Alva Castro  Luis,Armas Vela  Carlos,Cabanillas Bustamante  Mercedes,Carrasco Távara  José,De la Mata Fernández  Judith,De La Puente Haya  Elvira,Del Castillo Gálvez  Jorge,Delgado Nuñez Del Arco  José,Gasco Bravo  Luis,Gonzales Posada  Eyzaguirre  Luis,León Flores  Rosa Marina,Noriega Toledo  Víctor,Pastor Valdivieso  Aurelio,Peralta Cruz  Jonhy,Zumaeta Flores  César'

to scrape Grupo Parlamentario
table.find_all('td', {'width': 446})[1].text

output:
'Célula Parlamentaria Aprista'

to scrape Título:
table.find_all('td', {'width': 446})[2].text

output:
'IGV/SELECTIVO:D.L.821/LEY INTERPRETATIVA '

to scrape Sumilla:
table.find_all('td', {'width': 446})[3].text

output:
'  Propone la aprobación de una Ley Interpretativa del Texto Original del Numeral 1 del Apéndice II del Decreto Legislativo N°821,modificatorio del Texto Vigente del Numeral 1 del Apéndice II del Texto Único Ordenado de la Ley del Impuesto General a las Ventas y Selectivo al Consumo,aprobado por Decreto Supremo N°054-99-EF. '


text:
Q: How should I return 404 from a JsonResult Controller? In ASP.NET MVC5 I have a controller with a JsonResult return type.
Depending on parameters I want to return a 404, as this is descriptive of the user requesting non-existent data.
I could throw new HttpException(404, "message") but this feels dirty given the return HttpNotFound() syntax. This doesn't work, of course, because HttpNotFoundResult does not inherit JsonResult
How should I cleanly return 404's from JsonResult controller methods?

A: All your actions should simply have ActionResult return values. This allows you to return any valid result type, whether that's a JsonResult or HttpNotFoundResult.
public ActionResult Foo()
{
    if (!foos.Any())
    {
        return new HttpNotFoundResult();
    }

    return Json(foos, JsonRequestBehavior.AllowGet);
}


text:
Q: Drupal 5.x site shows > 550 MB memory consumption of every page. How to speed up Drupal 5.x site I developed a site in Drupal 5.x and now its done and working fine, but its very slow. Working fast some time, but for imp modules it takes time.
When I see the performance logs, its consuming my memory for 150 MB per page MINIMUM. This is the minimum. Most of the pages its shows 550~700 MB consumption.
What I did till now.

*

*Javascript Aggregation Enabled.

*Page caching Enabled.

*Bandwidth Optimization Enabled.

*Slow query log checked under constant check.

My question, what/how exectaly the memory consumption is imp in this application. Drupal automatically takes all the relation between DB and code. Only some few modules are developed by me.
What the the tips/tricks can be used to improve my site speed.

A: 150MB will not be fixed with some aggregation, cache tuning and so on. That is only tweaking.
You (seem to) have a severe problem with one of your modules or a misconfiguration.
Here is what to do, if you are not known to cachegrind, xdebug and such:

*

*Disable all contributed modules. Problem gone?

*if yes, enable them module-by-module. Enabling module X will drop performance, this way you find out what module X is.

*If you don't see a sudden decrease in performance (or increase in memory usage) it can be due to a combination of modules. In that case, try out disabling and enabling groups of modules.

Remember, 60 modules on a single site is considered rather much. 100+ is considered a nightmare.
If that does not work, or if you prefer a more prefessional (then trial-error) method, try cachegrind. That will show per-file, per-routine memory profiling. You will need cachegrind, Xdebug and a program to visualise the cachegrind output, such as kcachegrind (KDE, reported to work on windows too). More here: http://xdebug.org/docs/profiler
But I am confident that you will find one module that is misbehaving, and that pinning down that module will get you to the solution.
A normal Drupal5 site should run just fine under 36M of memory.


text:
Q: Screen height - Android In an Android Application, I want to know the height and the width of the screen. I'm using the following code:
 Point size = new Point();
 display.getSize(size);
 screenWidth = size.x;
 screenHeight = size.y;

The problem is than when the soft navigation bar exists, the returned height = the actual height - navigation bar height.
I want to get the total value.
Note: I'm using Android SDK 13 (v 3.2).

A: Check this, it may help:
FrameLayout root = (FrameLayout) findViewById(R.id.root);
    root.post(new Runnable() {
        public void run() {
            Rect rect = new Rect();
            Window win = getWindow();  // Get the Window
            win.getDecorView().getWindowVisibleDisplayFrame(rect);
            // Get the height of Status Bar
            int statusBarHeight = rect.top;
            // Get the height occupied by the decoration contents
            int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
            // Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
            int titleBarHeight = contentViewTop - statusBarHeight;

            // By now we got the height of titleBar & statusBar , Now lets get the screen size
            int screenHeight = dm.heightPixels;

            // Now calculate the height that our layout can be set If you know that your application doesn't have statusBar added, then don't add here also.
            //Same applies to application bar also
            int layoutHeight = screenHeight - (titleBarHeight + statusBarHeight);

        }
    });

A: You can use
display.getRealSize(size); instead of display.getSize(size);
source:
http://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)

A: you can use DisplayMetrics. This class holds information about the screen such its size, density, font scaling. For instance
getResources().getDisplayMetrics().widthPixels

returns
The absolute width of the display in pixels.

to retrieve the height
getResources().getDisplayMetrics().heightPixels

A: In onCreate method of your class write down this code, and you will get the actual width and height of screen:
Display mDisplay = this.getWindowManager().getDefaultDisplay();
    final int width = mDisplay.getWidth();

    final int height = mDisplay.getHeight();

    System.out.println("width " + width + "  height " + height);