text:
Q: How to change text size of SPINNER (Android) I'm trying to decrease the font size of the spinner, and I created an XML file called spinner_item.
spinner_item.xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textColor="#800080" />

method to load the spinner:
private void loadCustomServiceSpinner(String workRequestType) {

    CustomServiceDBQueries csQueries = new CustomServiceDBQueries();
    customServices = csQueries.selectCustomService(workRequestType);

    String[] strCustomService = new String[customServices.size() + 1];
    strCustomService[0] = "";

    int i = 1;
    for (CustomService cs : customServices) {
        strCustomService[i] = cs.getCustomServiceName();
        i++;
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            R.layout.spinner_item, strCustomService);

    adapter.setDropDownViewResource(R.layout.spinner_drop_default);

    Spinner SpnCustomService = (Spinner) findViewById(R.id.SpnCustomService);
    SpnCustomService.setAdapter(adapter);
}

I do not see any changes, the source may be 20 or 50 SP SP that does not change anything. Can someone help me?


text:
Q: Expression Matching With MatchQ and HoldForm I am learning to work with MatchQ for pattern matching in expressions.  For instance:
MatchQ[x + y, Plus[_,__]]

returns True.
However,
MatchQ[1+1, Plus[_,__]]

returns False.
I believe the reason for this is that Mathematica has evaluated 1+1, and the structure of the expression has changed.
To check this:
FullForm[HoldForm[1+1]]

returns HoldForm[Plus[1,1]]
Ok.  Getting closer.
Where I am stuck is passing the unevaluated expression of 1+1 to MatchQ in functional format to test.
How would I structure MatchQ to evaluate the expression 1+1 as True?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set corner radius for all corners with image view rendered from UIGraphicsGetImageFromCurrentImageContext This is how it looks before:

and after I generate dragging view:

and this is how I generate the dragging view from cell:
private func setupDraggingViewForCell(cell: BWStudentWishlistBookCollectionViewCell) {

    UIGraphicsBeginImageContextWithOptions(cell.bounds.size, false, 0)
    cell.bookImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!)

    draggingView = UIImageView(image: UIGraphicsGetImageFromCurrentImageContext())
    draggingView?.clipsToBounds = true
    draggingView?.contentMode = .ScaleAspectFit
    draggingView?.layer.masksToBounds = true
    draggingView?.layer.cornerRadius = 10

    view.addSubview(draggingView!)

    UIGraphicsEndImageContext()
}

As you can see, only one corner is rounded. Why?

A: You can set the clipsToBounds to false, and probably it would solve the problem in your case. Otherwise it will show you the full frame of the cover, and you can decide afterwards what to do.
draggingView?.clipsToBounds = false

A: You Can Directly add this code into your custom cell otherwise as per your need.......
override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        imageView.layer.shadowColor = UIColor.blackColor().CGColor
        imageView.layer.shadowOpacity = 1
        imageView.layer.cornerRadius = 5
        imageView.layer.shadowOffset = CGSizeZero
        imageView.layer.shadowRadius = 2

 //If you added Aspect to Fill
        imageView.clipsToBounds = true
    }

I hope this will help you... (Y)

A: don't know but try to round image than imageView
func makeRoundedImage(image: UIImage, radius: Float) -> UIImage {
    var imageLayer: CALayer = CALayer.layer
    imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height)
    imageLayer.contents = (image.CGImage as! AnyObject)
    imageLayer.masksToBounds = true
    imageLayer.cornerRadius = 10
    UIGraphicsBeginImageContext(image.size)
    imageLayer.renderInContext(UIGraphicsGetCurrentContext())
    var roundedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return roundedImage
}

and then set image to you image view. and clear background color of dragableView
Hope it will help..!


text:
Q: Latitude and Longitude data in dataset while training the model I am using California housing data, which has latitude and longitude. Is it good practice to remove them (latitude & longitude)before I continue to train my model?

A: If you are just using raw lat/long information, then yes, you should remove them. That's because the values of lat/long are not meaningful in and of themselves, conditional on your model not having any "understanding" of what a change in lat/long means. For instance, what would a change in 1 degree in latitude mean in terms of a change in your target variable? If there is nothing related that way, then you introduce either noise or potentially spurious relationships.
Lat/long are more often useful as a way to calculate a feature that does have a meaningful impact on your response variable: distance between points, area withing boundries, or anything where you can say "the change in this feature that I calculate from spatial information correlates with a change in the response".
In short: either take it out, or use it to calculate a feature you do want to include.


text:
Q: How to create common folder for css and js files in Django? setting before any change.
STATIC_URL = '/static/'

here I want to create one static files folder rather than assigning them to each every app by creating there name as directory and then I have to assign. So I want one common folder for all JS and Css which can be reflected in each and every template rather than defining all of them at different places.

A: firstly make below changes in your settings.py file :
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(BASE_DIR, "allfiles"),
]

Remember that allfiles is also folder in your project root.
After that in your template load static files as given below:
inside template.py:
{% load static %}
<html><script src="{% static 'index.js' %}"></html>
<--this file is in your common file you can replace it with any JS or CSS-->


text:
Q: Cannot send events to objects owned by a different thread while runing a member method on another QThread I need to run a method in my MainWindow class, in a different thread as it is a length and time consuming process.
This is what I tried:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    initGui(ui);

    // Create background worker thread
    backgroundWorker = QThread::create([this] {
        backgroundMethod();
    });

    // Define when finished with work
    connect(backgroundWorker, &QThread::finished, [this] () {
        qDebug() << "Background method has finished";

        // Stop movie
        ui->lblLoading->movie()->stop();

        // go to next screen
        ui->tabbarMainWidget->tabBar()->setCurrentIndex(1);

        //show backup icon files
        if(filesToBackup.size() > 0) {
            qDebug() << "There are files to backup!";
            ui->lblInfoImage->show();
        }
    });

    // Start worker thread
    backgroundWorker->start();
}

backgroundMethod
void MainWindow::backgroundMethod() {
    for (int i = 0; i < 10; i++) {
        qDebug() << "Hello World";
    }
}

I am omitting alot of code as it is not necessary. The basic logic is as follows:

*

*Start new thread using QThread::create()

*Run the backgroundMethod() until completed while having the UI free for other work.

*When the backgroundMethod() has finished, the QThread should emit the finished() signal.

*I have a connection setup between the backgroundWorker thread's finished() and the lambda to run some more code.
The problem:

Background method has finished
QObject::killTimer: Timers cannot be stopped from another thread
ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 0x0x2801d950. Receiver 'lblInfoImage'
  (of type 'QLabel') was created in thread 0x0x2688c4b0", file
  kernel\qcoreapplication.cpp, line 578 04:11:28: The program has
  unexpectedly finished.

In short, I am accessing the lblInfoImage on the backgroundWorker thread. I understood that using the signal/slot mechanism should cater for this issue, where my use of it is correct.
I am not sure why this is happening, I need some help in understanding what I did to cause the problem and how I can fix it

A: The problem is simple: you execute UI code on a non-UI thread which is strictly forbidden in Qt (and in many other UI frameworks across different languages). That happens because you do the connection wrong:
connect(backgroundWorker, &QThread::finished, [this] () {
    ...
});

That connection means: whenever QThread emits a finished signal run this function. The thing is, it will run the function in the context of the emitted signal which is another thread not the thread backgroundWorker lives in. So you have to provide the UI thread context for receiving this signal:
connect(backgroundWorker, &QThread::finished, this, [this] () {
        ...
    });

Now the function provided will be executed in the context of the UI thread (this).


text:
Q: Pagination of data issue: java + oracle sql I have a requirement for pagination of data(items) retrieved from database.
The UI also contains search options and the amount of data, order also depends on search criteria.
Let's say a client send request for with some search criteria and gets 60 results. The client see the items from 1 to maxPageSize (25 by default). If 2nd page is requested - 26-50 items will be shown.
The problem is on current moment I can't get amount of max results and can't display number of maxPage.
I see 2 solutions for this problem:

*

*Query database second time with the same parameters but without
pagination and get count of the items.

*Retrieve all items from DB,
filter them on backend code by search criteria and send to client.

The questions are:
1) Which of the operations is less expensive in general?
2) What else can be done to solve this kind of task if there is better solution?
P.S. the backend code written on Java, queries send via JDBC to Oracle 11g DB.
---EDIT---
I've solved this problem this way:
WITH FINAL_RESULT AS
    (SELECT SORTED_ITEMS.*,
            ROWNUM RN
     FROM (sorted basic query with searches))

   SELECT FINAL_RESULT.*,
         (SELECT COUNT(*) FROM FINAL_RESULT) ITEMS_COUNT
    FROM FINAL_RESULT
    WHERE RN BETWEEN ? AND ?

A: Second solution would be quite expensive in case there is bulk amount of data in the Database.
However, the First solution is quite suitable with some tweeks in it. You don't need to Query database second time with the same parameters, instead the server should send the TOTAL_COUNT in each request and the value should be cached.
If the count hasn't changed, there would be no load to the Database because of caching.


text:
Q: Calling all comments for certain posts I am working with a Rails 2.3.9 application and in this case posts are workouts. I am trying to get all comments for the following workouts.
@workouts = Workout.today_only.all(:include => {:user => :memberships}, :conditions => ["workouts.public = '1' AND memberships.box_id = ?", @box.id], :order => "workouts.created_at DESC")

My associations are correct:
Workout has_many :comments
Comment belongs_to :workout

How would I get at list of comments on those specifc workouts ordered by created_at DESC?
Note: today_only is a named_scope and I can post the code if it is relevant.

A: In your Workout model, add:
has_many :comments, :order => 'created_at DESC'

then you can do:
Workout.today_only.all(:include => [:comments, {:user => :memberships}], ...


text:
Q: When MySQL tells me "Access Denied", why does it think my username is ''? I've just installed MySQL on OS X Lion through Homebrew, and followed the post-install instructions.  Now I need to make a database:
$ mysql -u peeja
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 5.5.25a Source distribution

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE DATABASE `new_db` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`;
ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'new_db'

What's up with user ''@'localhost'?  Why not user 'peeja'@'localhost'?  And why doesn't this Just Work™ for the installing user?  Isn't that how Homebrew is supposed to set it up?
Or have I done something wrong?

A: There is no user peeja without a password so it logs you as anonymous. If that user exists then log as:
mysql -u peeja -p mypassword

or
mysql -u peeja -p

A: You connected as anonymous user - ''@'localhost'. This user is created on your server.
And you do not have created user 'peeja'@'localhost'. By default MySQL connect uses anonymous account.
So, connect as root and create user -
CREATE USER 'peeja'@'localhost';

Then grant privileges you need and reconnect as 'peeja'@'localhost'.


text:
Q: Cannot connect to brltty at :0 I just installed updates on 16.04 and got stuck with the login loop issue, but that is now resolved. I'm still not able to get the rest of Unity to work, though. I have a Compaq CQ60 with an NVIDIA GeForce 8200M GPU. I want to use the dual monitor capability, which nouveau doesn't support, so I have the NVIDIA 340.101 driver installed (it's the latest that supports my GPU). I pulled this from the NVIDIA web site. I was able to get ccsm to come up and enable unity, but I still don't get the launcher or the task bar at the top of the display. I have the nouveau driver blacklisted.
Any suggestions for getting the rest of unity to work is appreciated.
The only two lines in .xsession-errors are
openConnection: connect: No such file or directory
cannot connect to brltty at :0

I don't see any errors in /var/log/Xorg.0.log.

A: *

*ALT-F1

*logon as user

*sudo bash

*rm .Xauthority

*ALT-F7 back on Xwindows, then login again.


text:
Q: How to display from category 17 only one post? I have some code that I was trying to display only one post from the category 17. But I can't it. Anybody have any idea? my code is below. I have tried it but show all post of category 17. I want to show only one post from cat 17.
              <?php
                if(have_posts()):?>
              <?php while(have_posts()):?>
               <?php the_post();?>
                <?php
                $post = $wp_query->post;
                if ( in_category( '17' ) ) {
                ?>
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">

<?php the_title(); ?>

                    <?php
                    // Post Image.

                    if ( has_post_thumbnail() ) {

                    the_post_thumbnail();
                    }
                    else {
                    echo '';
                    }
                    ?>

BMW 7 Series or simillar

                        4

                        3

                        5

                        Auto

                    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" class="viewmore left">View More

                <?php } ?>
                <?php endwhile;?>
              <?php endif;?>

A: Add break; in the loop after you've shown your first found post, that would be before you close the inner if statement.


text:
Q: DMZ (Portforwarding) in OpenVPN I am running an self-hosted openvpn server with few clients. I want to expose 1 client to the external network, how can I do that? I see similar option in paid admin panel, but I'm using the free version which offers only a command line interface (CLI). If the complete exposure of a client is not possible, then I want to forward the ports without manually changing iptables each and every time.
Current structure is something like that:
+------------+
|            |
|  Client 1  +--------------------+
|            |                    |                +----------------------+
+------------+                    v                |                      |
                               Internet <---------->   Self-Hosted        |
+------------+                    ^                |   OpenVPN Server     |
|            |                    |                |   Community Edition  |
|  Client 2  +--------------------+                |                      |
|            |                                     +----------------------+
+------------+

Now I want to expose the client 2 to the public network (internet) through the VPN server. I can do that manually exposing ports using IP tables. But if a new port need a new rule in IP table, which I have to put manually. I am not very proficient with IP tables or openvpn administration, also exposing port manually is not effective enough (though may good for security perspective).
I want to expose the client 2 through the vpn server for once and all. How can I achieve that goal?


text:
Q: Conditionally include provided scope dependencies with sbt and the universal plugin I have a project that is a scala & scalatra API.  I have two distributables that I build with sbt-native-packager -

*

*RPM & DEB install for on-premise installations

*heroku install for cloud installations

I'm currently using provided scope dependencies for items I need to manually manage with the RPM/DEB approach - database libraries that I cannot bundle and distribute due to license restrictions.
"mysql" % "mysql-connector-java" % "5.1.30" % "provided",
"com.microsoft" % "sqlserver.jdbc" % "4.1" % "provided",
..etc..

This has been working great.  I use the universal plugin and the dist task, somewhat massaged, and then hook up some package build scripts.
Now I'm building the heroku install, and I don't know how to add back in those provided dependencies.  I'm using the universal plugin and running the stage task.  However, provided dependencies are being filtered out and I'd like to actually have them included when running stage, because I don't have the license restriction anymore in heroku.
Options that I think I have...

*

*Add a mapping to add back in provided scope dependencies during the stage task, but not during the dist task

*Drop provided scope entirely and manually exclude those dependencies from the packaging process during dist
I have some mappings already like this,
//add webapp dir to zip
mappings in Universal ++= directory("src/main/webapp")

//add db dir to zip, but move it into /lib/db instead of /db
mappings in Universal ++= (directory("src/main/resources/db").map{t =>
    (t._1, "lib/"+t._2)
  }
)

So I feel like I could probably figure out how to add/exclude if I really tried, but I'm having problems finding any documentation for this stuff.  The examples here don't really help much, or I don't understand enough.
Thanks in advance!

A: This is an interesting question. Some time ago we added the possibility to add arbitrary artifacts from the build classpath. ( See scaladocs too )
Option 1 could look like this. Note, that this doesn't work as I expect, as some mappings are not exactly picked up by native-packager:
// `show universal::stage:mappings` works properly
mappings in (Universal, stage) ++= {
  // calculate provided dependencies.
  val compileDep = (managedClasspath in Compile).value.toSet
  val runtimeDep = (managedClasspath in Runtime).value.toSet
  val provided = compileDep -- runtimeDep

  // create mappings
  fromClasspath(provided.toSeq, "jar", artifact => true)
}

I suggest a variation of option 1 by providing a build environment and decided, which mappings to add.
mappings in Universal ++= {
  // a build environment
  val env = buildEnv.value

  // calculate provided dependencies.
  val compileDep = (managedClasspath in Compile).value.toSet
  val runtimeDep = (managedClasspath in Runtime).value.toSet
  val provided = compileDep -- runtimeDep

  // create mappings, depending on build environment
  fromClasspath(provided.toSeq, "jar", _ => env == BuildEnv.Stage)
}

// add the dependencies to the start script as well
scriptClasspath ++= { /* similar code as above */}

What I would like to have done
I hoped to be able to to something like this
libraryDependencies += "com.google.guava" % "guava" % "19.0" % "provided"

mappings in (Universal, stage) ++= fromClasspath(
   (managedClasspath in Compile).value,
   "jar",
    artifact => artifact.scope == "provided"
)

Which wasn't possible, as the sbt Artifact has no way to access the ivy-scope (or I haven't found it).
Then I tried to do this
libraryDependencies += "com.google.guava" % "guava" % "19.0" % "provided" extra("heroku" -> "true")

mappings in (Universal, stage) ++= fromClasspath(
   (managedClasspath in Compile).value,
   "jar",
    artifact => artifact.extra.find(_ == "heroku")
      .map(_.toBoolean)
      .getOrElse(false)
)

which didn't worked either, as it seems that SBT doesn't pass the extra attributes from the ModuleID to the Artifact model. This left me with the solution described above.


text:
Q: Lookig for a better/stronger sentence Could anybody let me know a stronger/improved sentence for the one shown below:
One of my interest is in applying machine learning to real world problems

A: One thing that interests me is exploring how machine learning can be applied to real world problems.

A: You could phrase it in a way such as this:
I am interested in the way in which machine learning can be applied to real world problems.

A: One way to strengthen a sentence is to remove unnecessary words. The message comes through more clearly if the sentence is short and to the point. Another way is to make the subject more active.
Thus, you could write, "I am interested in applying machine learning to real world problems."


text:
Q: How does caching in Spring Boot work when data is updated in the database? I have to use an old Oracle database to fetch the data through one of my GET calls with my Spring Boot controller. Now the catch is this -

*

*This is a new API, and an old legacy service updates the records in the DB. This new API's task is to only fetch the data from the DB. So no other methods to update or create data is in this new API.

*Also, there is no direct access to the DB if I want to implement or make changes anything there that will help my cause.
Given these above conditions, is there a way I can use any of the Spring supported cache providers such as Redis, to automatically update the cache or evict the cache once the data has changed on the DB?
I know I can use @CachePut or @CacheEvict to control my cache. But this is applicable only when I have methods that update or save something to the DB.  So is there any workaround so I can implement caching in this scenario?
Edit 1: Adding code
This is my controller
@Cacheable(value = "users", key = "#userId")
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public User getUserDetails(@PathVariable String userId) {
  // some other code to parse userId to Long
  user = userRepository.findOne(usrId);
  // other code
  return user;
}

A: Use REDIS Pub-Sub and listen to update or db event from another app via Redis PubSub Messaging and update or evict your cache in your local system
Refer : https://www.baeldung.com/spring-data-redis-pub-sub


text:
Q: How to add description lines to the header of a .txt output in R I'm trying to create a .csv or .txt file from a data.frame object that also contains some lines describing more detail about the variables.
Here's my first attempt:
Head <- "
#variables:
#sal - Salinity [PSU]
#temp - Temperature [degrees Celsius]
"

n <- 10
df <- data.frame(sal=runif(n, 30, 37), temp=runif(n, 15, 17))
df

sink("data.txt")
Head
df
sink()

which results in this:
[1] "\n#variables [units]:\n#sal - Salinity [PSU]\n#temp - Temperature [degrees Celcius]\n"
        sal     temp
1  32.11494 15.35176
2  30.57537 16.80972
3  32.90651 15.95174
4  30.62192 15.73436
5  31.43069 15.45873
6  34.38173 15.69713
7  31.27954 15.01126
8  32.77093 16.22493
9  35.99510 15.10123
10 35.52409 15.49084

but, I would really like it to look like this:
#variables [units]:
#sal - Salinity [PSU]
#temp - Temperature [degrees Celcius]

        sal     temp
1  32.11494 15.35176
2  30.57537 16.80972
3  32.90651 15.95174
4  30.62192 15.73436
5  31.43069 15.45873
6  34.38173 15.69713
7  31.27954 15.01126
8  32.77093 16.22493
9  35.99510 15.10123
10 35.52409 15.49084

A: Use cat instead of letting R call the object's print method.
sink("data.txt")
cat(Head)
df
sink()


text:
Q: How are values such as monthly cost stored in a data warehouse Would a value such as monthly cost from source data be represented as a fact?
If yes, how would a date dimension table be designed around that fact?


text:
Q: BeagleBoard: setting ALSA master volume I'm trying to set the master volume with alsa on a BeagleBoard (with Ubuntu installed) but when is executed the following code the result is always: "Mixer simple element not found"
elem = snd_mixer_find_selem(handle_mix, sid);
if(elem==NULL)
{
printf("Mixer simple element not found\n");
}

I've runned the same code on a computer (samsung NC10) and the result is correct and I can set the master volume. Could you give me some advice?

A: Mixer elements are hardware dependent, and even on the same hardware, mixer element IDs can change in different driver versions.
Run amixer scontrols to see which mixer controls are actually available.


text:
Q: Procedure for finding the right MOSFET, diode and resistor to make a solenoid valve open/close? I need a right MOSFET to make a 8 valves open/close about 15 times per second! It needs to switch very fast. Anything that can slows the speed of the valves is not desirable.
From what I see the valve is operating at approximately 12VDC, 0.55A.
I want to be able to control these valves with Arduino Uno or Mega and even possibly with Duo in the future. (with 5v output signal)
The valves are Airtec 2P025-08
I did my best to choose the right MOSFET. I don't care about the price and I'd rather to choose extra bucks to be on the safe side and make the circuit last longer.
So far I have chosen this MOSFET:  Fairchild Semiconductor FQP50N06L It is a power MOSFET but to me it is nothing wrong with it to make me go for logic MOSFET.
My questions:

*

*Why should one choose a logic MOSFET for such an application? The gate voltage seems fine with me. And some of the websites list this model as logic/power MOSFET!

*What is the exact procedure for choosing the right MOSFET?

*Is my Arduino capable of providing enough current to control 8 of these MOSFET to make the valves open/close? I mean is it able to provide enough ampere at digital outs? vales has an external 12v battery themselves.

*I don't know how to choose the right flyback diode? Does it have to be able to handle several times of the normal voltage and current passing through the circuit? Is IN5401 (100v, 3 A) enough? or Should I choose one with higher Ampere rating?

*What resistor should I choose for the digital to ground pin of Arduino? I have seen 10K for such applications but I don't know how they choose this number for it!

*Is Schottky diode more proper for this application!? If yes how can I choose the right one?

*And the most important question. Is making the diode series with a resistor going to affect the speed of the circuit? I read somewhere that it can affect it in negative way when opening and closing at very fast speed is important. Or am I wrong?. But wasn't able to find any explanations. Speed is crucial for me. If a resistor can help me, What should be the value of the resistor for my application?

*And do you think that the chosen MOSFET is going to do the job for me?
Thank you very much :-)

A: There are several problems with your project which I won't address because there's one fatal flaw which is going to shut you down, and that's the operating speed of the solenoid, which is specified as 50 milliseconds.
The data sheet's a little sketchy, but if it takes 50ms to open the valve and another 50ms to close it, that's 100ms, which means that it'll take one second just to open and close a valve 10 times, not the 15 times per second you're looking for, and that's not even taking account of how long you want the valve to stay open and let whatever your medium is, flow.
To worsen the picture, any flyback diode you use will slow down the solenoid's return to its normally closed position, so at this point your chance of success looks slim. Sorry. :-(


text:
Q: If $f$ is differentiable everywhere, then choose the correct option/options: If $f$ is differentiable everywhere, then choose the correct option/options:
($A$) $|f|$ is differentiable everywhere.
($B$) $|f|^2$ is differentiable everywhere.
($C$) $f|f|$ is not differentiable at some point.
($D$) None of these
I see that first option is wrong as $f(x)=x$ is differentiable but $f(x)=|x|$ is not.
Second looks correct as $|f|^2=f^2$ but not so sure about third.

A: Hint:
You may prove that if $g$ is differentiable everywhere then $g^2$ too. Now observe that
$$f(x)|f(x)|=\frac12\left[(f(x)+|f(x)|)^2-2(f(x))^2\right]$$


text:
Q: DB2 equivalency for Teradata clustered tables In Teradata the definition of a clustered table is very simple and exists in a single syntax (correct me if I'm wrong).
CREATE TABLE table_name (charcol1 varchar(10), idcol integer)
primary index (idcol);

I am reading that there are a whole number of "clustered" table types in DB2 with respect to creating a share-nothing physical data layout for the object.
Defined primary index in TD will spread the table data across all nodes/virtual cpus available to the TD server.
What is the closest method (and syntax) to achieve the same within DB2?

A: I would recommend to start with this overview of data partitioning (concepts) for Db2.

The following three clauses demonstrate the levels of data organization that can be used together in any combination:

*

*DISTRIBUTE BY to spread data evenly across database partitions (to enable intraquery parallelism and to balance the load across each database partition) (database partitioning)

*PARTITION BY to group rows with similar values of a single dimension in the same data partition (table partitioning)

*ORGANIZE BY to group rows with similar values on multiple dimensions in the same table extent (multidimensional clustering) or to group rows according to the time of the insert operation (insert time clustering table).

All three clauses can be used within the same CREATE TABLE statement. Its usage depends on the data and the envisioned queries.
The database partitioning (DISTRIBUTE BY) is the shared-nothing you asked for. Distribute the data across partitions based on the YEAR.
 CREATE TABLE SALES
     (CUSTOMER   VARCHAR(80),
      REGION     CHAR(5),
      YEAR       INTEGER)
   DISTRIBUTE BY HASH (YEAR)

A: Tables are created in tablespaces, tablespaces are created in database partition groups (or sets of nodes, which you can create as you want) in Db2 for LUW.
You may use the following query to understand which tablespaces reside in which database partition groups.
SELECT
--  T.TBSPACEID, T.TBSPACETYPE
  CASE T.DATATYPE
  WHEN 'A' THEN 'REGULAR'
  WHEN 'L' THEN 'LARGE'
  WHEN 'T' THEN 'SYSTEMP'
  WHEN 'U' THEN 'USRTEMP'
  END DATATYPE
, T.DBPGNAME
--, T.PAGESIZE
, T.TBSPACE
--, B.BPNAME
--, G.MIN_NODENUM, G.MAX_NODENUM, G.NODE_COUNT
, G.NODES_LIST
FROM SYSCAT.TABLESPACES T
JOIN SYSCAT.BUFFERPOOLS B ON B.BUFFERPOOLID=T.BUFFERPOOLID
LEFT JOIN (
SELECT
  DBPGNAME
, COUNT(*) NODE_COUNT
, MIN(DBPARTITIONNUM) MIN_NODENUM
, MAX(DBPARTITIONNUM) MAX_NODENUM
, LISTAGG(DBPARTITIONNUM, ',') WITHIN GROUP (ORDER BY DBPARTITIONNUM) NODES_LIST
FROM SYSCAT.DBPARTITIONGROUPDEF
GROUP BY DBPGNAME
) G ON G.DBPGNAME=T.DBPGNAME
ORDER BY T.TBSPACEID;

Let's say you get the following result:
DATATYPE  DBPGNAME        TBSPACE    NODES_LIST
--------  --------------- ---------- ----------
...
LARGE     IBMDEFAULTGROUP USERSPACE1 0,1,2,3
...

This means that if you run the following statement, then the table is created in a tablespace USERSPACE1 which resides on database partitions (nodes) 0-3, and table data is distributed between these nodes based on a hash value computed on values of YEAR column.
CREATE TABLE SALES
(
  CUSTOMER   VARCHAR(80)
, REGION     CHAR(5)
, YEAR       INTEGER
)
IN USERSPACE1
DISTRIBUTE BY HASH (YEAR);

It's always advisable to specify a tablespase explicitly, unless the rules of choosing such a tablespace which Db2 uses in case of absence of such a specification are applicable for your particular statement.

A: Is this for a OLAP system or OLTP?
Shared nothing with DB2 is rarely used for OLTP. There are colocation considerations, and importantly the cost of a commit is a good deal higher (2 phase commit).
If this is an OLAP system then are you considering column-organised tables? You may not need to partition.


text:
Q: Android app signing into Firebase using email and password error I'm trying to use a firebase email/password login inside my app.whenever I click on the sign-in button, the app would crash with a very unclear reason on the log. The log is as follows :
Error Log

2019-08-05 15:41:25.067 8157-8157/com.jesda.spiknix E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.jesda.spiknix, PID: 8157
  kotlin.KotlinNullPointerException
      at com.jesda.spiknix.Activities.SignUpActivity$clicks$1.onClick(SignUpActivity.kt:117)
      at android.view.View.performClick(View.java:6597)
      at android.view.View.performClickInternal(View.java:6574)
      at android.view.View.access$3100(View.java:778)
      at android.view.View$PerformClick.run(View.java:25885)
      at android.os.Handler.handleCallback(Handler.java:873)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:193)
      at android.app.ActivityThread.main(ActivityThread.java:6669)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I've tried initializing each layout element (shouldn't be required in Kotlin version 1.3.31) but doesn't solve the problem. I've tried cleaning, rebuilding and restarting an Android Studio (even PC).
Here is the SignUpActivity.kt where I tried implementing the sign-in
  class SignUpActivity : AppCompatActivity() {
    private var mAuth: FirebaseAuth? = null
    lateinit var gso: GoogleSignInOptions
    lateinit var callbackManager: CallbackManager
    lateinit var mGoogleSignInClient: GoogleSignInClient

    lateinit var login_BTN: Button

    var RC_SIGN_IN = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.sign_up_layout)
        // FacebookSdk.sdkInitialize(this)
        mAuth = FirebaseAuth.getInstance()
        try {
            val info = packageManager.getPackageInfo(
                "com.jesda.spiknix",
                PackageManager.GET_SIGNATURES
            )
            for (signature in info.signatures) {
                val md = MessageDigest.getInstance("SHA")
                md.update(signature.toByteArray())
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
            }
        } catch (e: PackageManager.NameNotFoundException) {
        } catch (e: NoSuchAlgorithmException) {
        }

        FacebookSdk.sdkInitialize(applicationContext)
        //AppEventsLogger.activateApp(this@SignUpActivity)

        gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso)

        callbackManager = CallbackManager.Factory.create()
        login_BTN = findViewById(R.id.loginBTN)

        clicks()
    }

    override fun onStart() {
        super.onStart()
        val currentUser = mAuth?.currentUser
        if (currentUser != null) {
            updateUI()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    fun clicks() {
        login_BTN.setOnClickListener {
            Toast.makeText(this, "Something here", Toast.LENGTH_SHORT).show()

            mAuth!!.signInWithEmailAndPassword(emailET.text.toString(), pwET.text.toString())
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d("TAG", "signInWithEmail:success")
                        val user = mAuth!!.currentUser
                        updateUI()
                    } else {
                        // If sign-in fails, display a message to the user.
                        Log.w("TAG", "signInWithEmail:failure", task.exception)
                        Toast.makeText(
                            this@SignUpActivity, "Authentication failed.",
                            Toast.LENGTH_SHORT
                        ).show()
                        //    updateUI(null)
                    }
                    // ...
                }
        }
        RegisterBTN.setOnClickListener {
            mAuth!!.createUserWithEmailAndPassword(emailET.text.toString(), pwET.text.toString())
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d("TAG", "createUserWithEmail:success")
                        val user = mAuth!!.currentUser
                        updateUI()
                    } else {
                        // If sign-in fails, display a message to the user.
                        Log.w("TAG", "createUserWithEmail:failure", task.exception)
                        Toast.makeText(
                            this@SignUpActivity, "Authentication failed.",
                            Toast.LENGTH_SHORT
                        ).show()
                        // updateUI(null)
                    }

                }

        }
        gplusBTN.setOnClickListener {

            val signInIntent = mGoogleSignInClient.signInIntent
            startActivityForResult(signInIntent, RC_SIGN_IN)

        }

    }

    fun updateUI() {
        var user_id = mAuth?.currentUser?.uid
        FirebaseMessaging.getInstance().subscribeToTopic(user_id)
        startActivity(Intent(this@SignUpActivity, MainActivity::class.java))
        finish()
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        callbackManager.onActivityResult(requestCode, resultCode, data)
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            println("Error code 1 $task")
            try {
                // Google Sign In was successful, authenticate with Firebase
                //  val account = task.getResult(ApiException::class.java)
                val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
                println("Error code 2 $result")
                if (result.isSuccess) {
                    val account = result.signInAccount
                    Toast.makeText(applicationContext, "Signed in Using Google $account", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(applicationContext, "Sign in Using Google Failed $task", Toast.LENGTH_SHORT).show()
                }
                //  val task2 = GoogleSignIn.getSignedInAccountFromIntent(data)
                //  handleSignInResult(result)
                //  firebaseAuthWithGoogle(account!!)
            } catch (e: ApiException) {
                // Google Sign In failed, update UI appropriately
                Log.w("TAG", "Google sign in failed", e)
            }
        }
    }

 }

The error says null pointer exception yet the layouts are all present and the error points inside the "onClickListener " of the button which I click(for login button, an error would point to signInWithEmailAndPassword line).
XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
              android:orientation="vertical"
              tools:context="jesda.com.spiknik.Activities.SignUpActivity">

    <LinearLayout
            android:id="@+id/login_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical">

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="visible">

            <EditText
                    android:id="@+id/emailET"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="email"/>

            <EditText
                    android:id="@+id/pwET"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Password"/>

            <Button
                    android:id="@+id/loginBTN"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Log In"/>

            <Button
                    android:id="@+id/RegisterBTN"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Register"/>

        </LinearLayout>

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="or"/>

        <com.google.android.gms.common.SignInButton
                android:id="@+id/gplusBTN"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

        </com.google.android.gms.common.SignInButton>

       <!-- <com.facebook.login.widget.LoginButton
                android:layout_width="wrap_content"
                android:id="@+id/FBlogin_button"
                android:layout_height="wrap_content"/>
-->
    </LinearLayout>

    <LinearLayout
            android:id="@+id/registerLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        <EditText
                android:id="@+id/nameET_reg"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"/>

        <EditText
                android:id="@+id/emailET_reg"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="email"/>

        <EditText
                android:id="@+id/pwET_reg"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"/>

        <EditText
                android:id="@+id/pwET_re2g"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"/>

        <Button
                android:id="@+id/RegisterBTN_reg"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Register"/>

    </LinearLayout>

</LinearLayout>


text:
Q: Communication between spring boot dockerized apps I new using spring boot and docker and I faced a problem running the docker containers.
On debug mode, there is no problem on applications boot, but when I run them as a container, there is something wrong.
For example, I have my server config with all the yml files, also eureka properties.
The config server boot perfectly, but not the eureka server, it must look for it`s configuration to the config server becouse of these:
uri: ${vcap.services.config-service.credentials.uri:http://127.0.0.1:8888}

In the eureka`s log I can found:

Could not locate PropertySource: I/O error on GET request for
  "http://127.0.0.1:8888/server-eureka/default":Connection refused;
  nested exception is java.net.ConnectException: Connection refused

So I see that eureka cant connect to the config server for a reason I cant understund.
Maybe I miss something in my docker file.

A: If you are not using docker linked containers you'll have to use only the public ip addresses. Docker will assign every running container an own ip address which is per default not accessible. Only when you start to expose ports there will be an entry to iptables that is linking the hosts public ip address and given port to the internal used port and (dynamically assigned) ip address of the docker container. This is also why 127.0.0.1 does not work cause it would look into the containers local context but tgere the service is not running.


text:
Q: Trouble mapping custom Odata function I am trying to execute a custom function on an Odata webservice (in this case it is the Proof()). I am attempting to figure out what URL I need to use in order to execute this controllers Proof() method from a client. This is obviously incorrectly mapped cause I do not see the method executed when running in debug mode and making a client call (_http://localhost:53610/Receipt/AccountsReceivableWebService.Proof()).
What URL should I be using to execute this method from the client? Better yet, how can I properly map this path from the WebApiConfig? Critique is most welcome! Thanks in advance.
The webservice controller is as follows:
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Routing;
using AccountsReceivableWebService.Models;

namespace AccountsReceivableWebService.Controllers
{
  public class ReceiptController : ODataController
{
ReceiptContext db = new ReceiptContext() { Receipt = new Receipt() { ReceiptLines = new List<ReceiptLine>() } };

private bool ReceiptExitsts(string key)
{
  return true;
}

public IHttpActionResult Get()
{

  return Ok(db.Receipt);
}

public IHttpActionResult Post(Receipt receipt)
{
  if (!ModelState.IsValid) return BadRequest(ModelState);
  if (!receipt.Insert()) BadRequest("Poorly formed receipt.");
  db.Receipt = receipt;
  return Created(db.Receipt);
}

/// <summary>
/// Checks that this receipt is a valid receipt
/// </summary>
/// <returns></returns>

[HttpGet]
public IHttpActionResult Proof()
{
  return Ok();
}

  }
}

The WebApiConfig.cs is where I am attempting to map the function I am wanting to execute. The code for this is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using AccountsReceivableWebService.Models;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

namespace AccountsReceivableWebService
{
 public static class WebApiConfig
 {
  public static void Register(HttpConfiguration config)
  {
  // Web API configuration and services

  // Web API routes
  ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
  builder.EntitySet<Receipt>("Receipts");

  builder.Namespace = "AccountsReceivableWebService";
  builder.EntityType<Receipt>().Collection.Function("Proof").Returns<string>();

  config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: null,
    model: builder.GetEdmModel());

  }
 }
}

EDIT: The error I receive is 404.0 - Not Found, which leads me to believe it is a mapping issue.
Metadata:
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
  <edmx:DataServices>
    <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="AccountsReceivableWebService.Models">
      <EntityType Name="Receipt">
        <Key>
          <PropertyRef Name="ReceiptId"/>
        </Key>
        <Property Name="ReceiptId" Type="Edm.String" Nullable="false"/>
        <Property Name="comments" Type="Edm.String"/>
        <Property Name="remitter" Type="Edm.String"/>
        <Property Name="ReceiptLineId" Type="Edm.String"/>
        <NavigationProperty Name="ReceiptLines" Type="Collection(AccountsReceivableWebService.Models.ReceiptLine)"/>
      </EntityType>
      <EntityType Name="ReceiptLine">
        <Key>
          <PropertyRef Name="ReceiptLineId"/>
        </Key>
        <Property Name="ReceiptLineId" Type="Edm.String" Nullable="false"/>
        <Property Name="Comments" Type="Edm.String"/>
        <Property Name="FiscalYear" Type="Edm.String"/>
        <Property Name="CostCenter" Type="Edm.String"/>
        <Property Name="object" Type="Edm.String"/>
        <Property Name="Amount" Type="Edm.String"/>
        <Property Name="Function" Type="Edm.String"/>
      </EntityType>
    </Schema>
    <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="AccountsReceivableWebService">
      <Function Name="Proof" IsBound="true">
        <Parameter Name="bindingParameter" Type="Collection(AccountsReceivableWebService.Models.Receipt)"/>
        <ReturnType Type="Edm.String" Unicode="false"/>
      </Function>
      <EntityContainer Name="Container">
        <EntitySet Name="Receipts" EntityType="AccountsReceivableWebService.Models.Receipt"/>
      </EntityContainer>
    </Schema>
  </edmx:DataServices>
</edmx:Edmx>

A: This is how I use a bounded to collection function in one of my project
In WebApi.config
var function = customerBuilder.EntityType<MyType>().Collection.Function("MyFunction");
function.Returns<MyReturnType>();
function.Parameter<string>("myStringParameterName");

In my MyTypeController : ODataController
[HttpGet]
public IHttpActionResult MyFunction(string myStringParameterName)
{
    //DBContextStuff
    return Ok(new MyReturnType())
}

This I consume data in MVC Controller
var myData = MyODataClient.MyType.MyFunction(myStringParameterName).GetValue();

Hope it helps.


text:
Q: Logistic regression: recoding ordinal independent variables into dichotomous variables — yes or no? What is the reasoning behind recoding ordinal independent variables in a binary logistic regression?
Example: imagine a researcher is intrested in the effects of some political attitudes on turnout {0;1}. He or she would draw on survey data and the key independent variable of interest would by a typical Likert-scale variable like this one ('internal efficacy'):
Normal people like me cannot make a difference in politics.
1 - Strongly agree
2 - Somewhat agree
3 - Neither agree nor disagree
4 - Somewhat disagree
5 - Strongly disagree

Suppose, the researcher would then recode survey responses into a dichotomous independent variable by combining 1 & 2 into 1 and assigning 0 to everything else. This would of course reduce information (i.e., somewhat agree is treated the same as strongly agree), but would simplify the interpretation in the sense that a respondent can be thought of either having high internal efficacy, or not.
Here are two examples of analyses of voter turnout that actually recode independent variables that way or at least following similar lines of thinking; one of which is an article by myself.
Habersack, F., Heinisch, R., Jansesberger, V., & Mühlböck, A. (2021). Perceived Deprivation and Voter Turnout in Austria: Do Views on Social Inequality Moderate the Deprivation—Abstention Nexus?. Political Studies, Link.
Mahlangu, T., & Schulz-Herzenberg, C. (2022). The Influence of Political Efficacy on Voter Turnout in South Africa. Politikon, 1-17, Link.
I wonder if there is any other reasoning behind transforming independent variables in logistic regression like this, meaning other than just simplifying the interpretation of survey responses.
EDIT (1):
I'm aware of @Tom's question from 2013 (What is the benefit of breaking up a continuous predictor variable?), but in contrast to his post, I'm exclusively interested in binary logistic models and the practice of dichotomizing ordinal variables (because it seems to be related to logistic regression models and the nature of the outcome variable).
EDIT (2):
I have edited my initial question to clarify that I am interested only in the dichotomization of independent variables in logistic regression, I am not interested in dependent variables and the approriate choice of logistic regression (binary, ordinal...).


text:
Q: how to pack python packages and sub-packages as single package in python3 I'm trying to create a python package with below structure. when i'm trying to create the package testproject it is creating successfully and uploading successfully to https://test.pypi.org/legacy/
testproject/
    testproject/
        Core/
            __init__.py
            BaseModel.py
        lib/
            __init__.py
            RunModel.py
        __init__.py
        RunWorkflow.py
    LICENSE
    README.md
    setup.py

When i attempt to download it to my new environment it is downloading the correct version to my environment and when i run conda list i can see the installed package with correct version.
The actual problem is when i tried to run help('modules') command, it returns all the sub-packages [Core and lib] too. when i see other packages such as os, numpy, scikit-learn. it is not showing its sub-packages in help('modules').
how can i avoid this situation, am i doing anything wrong here ?
Please find my setup.py below.
import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name='Test-Project-pypi',
    version='0.0.1',
    author="Manikandan Jeyabal",
    author_email="ManikandanJeyabal029@gmail.com",
    description="My longdestription",
    long_description=long_description,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    install_requires=[
        "numpy <=1.17.4", "pandas", "scikit-learn >= 0.21.3, <= 0.22"
    ],
    python_requires='>=3.7'
 )

A: This issue got resolved by adding the below code in Main init.py under 'testproject'
from . import Core
from . import lib


text:
Q: Public traffic routed over an Amazon AWS VPN dies. Want it to egress from our corporate network We're migrating to a new jump host, migrating from a machine in-house.  We also have 100+ customers that we will still need to communicate with via SSH.  Their firewalls currently allow our primary office in via SSH, but not our AWS host.  It takes time to migrate 100+ customers' firewalls, so until that is finished, we want to route all traffic for these IPs over a VPN that's already established so the traffic exits from our office and not the Internet Gateway (IGW) on Amazon.
I'm missing a few details in my education with regard to routing, so if someone could explain this to me, that would be great...
The VPC has this routing table:
0.0.0.0/0 -> igw
172.31.254.0/24 -> local
172.27.0.0/16 -> vgw
8.8.4.4 -> vgw

8.8.4.4 is Google's secondary DNS server that's open to all and has ICMP enabled, perfect for testing.
traceroutes show no hops.  The connection seems to die after going nowhere.  I'm obviously missing something, but I do not know what.  How can I complete this setup so all traffic shoved to the Virtual Gateway (vgw) goes over the VPN?

full gallery here, individual images below

traceroute
pings
cgw
route table details
route table entries
route table subnet associations
route table propagation
vgw details Not much useful here.
vpc details
vpn details
vpn status Only 1 tunnel is configured.
vpn static routes  This is where the route table pulled the 172.27.224.0/24 address from.

A: Unless you want to create a route for every customer, change your default route to send all traffic over the VPN and remove the IGW. Then you corporate router can manage the traffic.
Your route table will then look like this:
0.0.0.0/0 -> vgw
172.31.254.0/24 -> local

The second route CIDR above looks weird - it looks like a subnet instead of a VPC network. You want this to be your VPC CIDR.
Once you have verified this this is working correctly for all traffic, then you can add a VPC endpoint to your VPC if you need to access AWS resources such as updates, S3 storage, etc.

A: The above setup is correct.  The issue has been determined to be a poor firewall on the corporate side that, when replaced, functioned just fine as a VPN endpoint.  For the record, I strongly recommend AGAINST WatchGuard brand firewalls.  Been screwing with them for years now and they seem to be inferior in most aspects and generally buggy.


text:
Q: Fastest way to diagonalize a matrix with a parameter I want to diagonalize this matrix $B$ with a parameter $k$:
$$\begin{pmatrix}
5+k & -4-2k & 4+2k & -9-4k \\
2+2k & 1 & 2 & -4-2k \\
7 & -5-2k & 8+2k & -15-3k \\
4 & -4-2k & 4+2k & -8-3k
\end{pmatrix}$$
for all values of $k$. I calculated the characteristic polynomial and found that the spectrum of $B$ is $\{1+k,-k,2,3\}$.
I am perfectly capable of diagonalizing $B$ for every value of $k$, but the struggle is time: there are a lot of matrices that have to be row reduced in order to find a dimension or a basis.
For instance, if $k \in \{1,2,-2,-2\}$, you'll have to rowreduce the eigenspace of resp. eigenvalues $2, 3, 2, 3$ to check multiplicities. I found that $B$ is diagonalizable if $k \in \mathbb{R} \setminus  \{1\}$.
Then, I'll have to row reduce the four eigenspaces again for a $k \in \mathbb{R} \setminus \{2,-2,-3\}$ in order to find a basis for them to write the equation $\Lambda = P^{-1} \cdot B \cdot P$. After that, I have to find a basis of the odd eigen space for $k = 2, k=-2,k=-3$ (with the odd eigenspace, I mean the eigenspaces of resp. eigenvalues $2,3,2$, which have a multiplicity $> 1$), in order to find the $P$ matrices and thus the eigenvectors.
In total, there are 12 row reductions to be done, including matrices with parameters which is an extra struggle. Is there a faster way to achieve the same result with less work?


text:
Q: find t so that U + W = $\mathbb R^4$ I have the following vectors
$$ u_1 = (1, t, 2t, 0)^T,
u_2 = (t, t, t, t)^T,
v_1 = (t - 2, -t, -3t, t)^T,
v_2 = (2, t, 2t, 0)^T
$$
and
$$ U = span\{u_1, u_2\} , V = span\{v_1, v_2\} $$
And I am to find a $t$ so that $U + V = \mathbb R^4$
To be honest I'm not entirely sure where to start. I have tried to understand the definition of $U + V$ but what I'm unsure of is if I have to add every vector in $U$ with every vector in $V$ so that
\begin{align*}U + V &= span\{u_1 + v_1, u_1 + v_2, u_2 + v_1, u_2 + v_2\} \\
         &=span\{(t-1, 0, -t, t)^T, (3, 2t, 4t, 0)^T, (2t-2, 0, -2t, 2t)^T, (t+2, 2t, 3t, t)^T\}
\end{align*} and then put that into a matrix and more or less solve for t, or if I have perhaps completely misunderstood what $U + V$ actually means.

A: We define the direct sum of two vector spaces, $U,V$, denoted $U+V$ or $U\oplus V$ to be be the set $W$ such that $W=\{w=u+v:u\in U,v\in V\}$. In words, this set is what you get when you take each element of $U$ and add it to each element of $V$.
It is a fact about direct sums that if $G_U$ generates $U$ and $G_V$ generates $V$ then $G_{U+V}=G_U\cup G_V$ generates $U+V$. Therefore you're interested in finding the values of $t$ such that $span\{u_1,u_2,v_1,v_2\}=\mathbb R^4$


text:
Q: "RNRangeSlider" was not found in the UIManager I'm a little new to react-native and am trying to implement a basic range slider in my app. I'm using the range slider from @jesster2k10/react-native-range-slider (https://github.com/jesster2k10/react-native-range-slider) and followed the example exactly. i.e. I installed with
npm install --save @jesster2k10/react-native-range-slider

and
cd ios && pod install

I'm using a bare workflow and I'm starting with implementing it in ios only for now.
The error I'm getting is: Invariant Violation: requireNativeComponent: "RNRangeSlider" was not found in the UIManager.
I've tried linking it with react-native link  but that doesn't work either.
Any ideas what's wrong?


text:
Q: how to select rows with no null values (in any column) in SQL? I have a table called table1
It has 100 columns: {col1, col2, ...,col100}
I understand how to SELECT rows not containing null values in a specific column for instance col1:
SELECT *
FROM table1
WHERE col1 IS NOT NULL

How do I SELECT all rows that do not contain null values in any column

Attempt
SELECT *
FROM table1
WHERE * IS NOT NULL

but this returns an error in MySQL (which I am using)

A: You need to explicitly list each column.  I would recommend:
select t.*
from t
where col1 is not null and col2 is not null and . . .

Some people might prefer a more concise (but slower) method such as:
where concat(col1, col2, col3, . . . ) is not null

This is not actually a simple way to express this, although you can construct the query using metadata table or a spreadsheet.

A: While I would recommend writing out each column name and refactoring your table as suggested, here's an option using dynamic sql:
SET @sql = NULL;
SELECT CONCAT('SELECT * FROM table1 WHERE ',
              GROUP_CONCAT(c.COLUMN_NAME SEPARATOR ' IS NOT NULL AND '),
              ' IS NOT NULL') INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE c.TABLE_NAME = 'table1'
ORDER BY c.ORDINAL_POSITION;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

*

*DB Fiddle Demo

A: To return rows with no nulls in any columns: (in PostgresSQL)
SELECT *
FROM tablename
WHERE tablename.* IS NOT NULL

A: Get the length of each column and multiply them. If the result is not null then all columns are non null values. Try following sample code. Since I am not using multiple AND clause, it is a better approach.
CREATE TABLE #Temp (OdSal INT,NewSal INT,EmpName CHAR(20),IsCurrentEmp BIT)

INSERT INTO #Temp VALUES
(100,150,'Vikas',1),        -- No null records
(NULL,NULL,NULL,NULL),      -- all records are null
(NULL,NULL,'Nayanthara',1), -- more than 1 column is null
(NULL,150,'Priyamani',1)    -- only one column is null

--Will return only one row
SELECT * FROM #Temp
WHERE LEN(OdSal) * LEN(NewSal) * LEN(EmpName) * LEN(IsCurrentEmp) IS NOT NULL


text:
Q: MySQL deadlock - cannot restart normally? MySQL version 5.5.13-1
A snippet from the SHOW ENGINE INNODB STATUS\G:
LATEST DETECTED DEADLOCK
------------------------
111218 10:22:34
*** (1) TRANSACTION:
TRANSACTION 1318D95B, ACTIVE 0 sec starting index read
mysql tables in use 6, locked 6
LOCK WAIT 53 lock struct(s), heap size 14776, 77 row lock(s)
MySQL thread id 60933, query id 124472414 192.168.6.31 thanhnt Copying to tmp table
INSERT INTO usertmp(userid,npayvalue,balance)
    SELECT B.`userid`, SUM(C.`moneyv`) a,(B.`balance` + B.`promotions`+ B.`promotions1`+ B.`overdraft`) b
    FROM `ox_campaigns` A
    INNER JOIN `v3_cam_date` C ON C.`campaignid` = A.`campaignid`
    INNER JOIN `selfserving_users_balances` B ON B.`userid` = A.`uid`
    INNER JOIN `selfserving_users` F ON F.`user_id` = B.`userid`
    INNER JOIN `selfserving_users_group_balances` E ON E.`groupid` = F.`groupid` AND E.`ispostpaid` = 0
    WHERE A.`revenue_type` = 6 AND C.`dt` BETWEEN A.`activate` AND A.`expire` AND C.`dt` >=  (SELECT DATE_ADD( A.ssv_payment_date_lastest, INTERVAL 1 DAY)  FROM `000_sys_params_v3` A)
    AND C.`viewcharge` >0
    GROUP BY B.`userid`
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 222397 page no 2576 n bits 304 index `GEN_CLUST_INDEX` of table `reportingdb`.`v3_cam_date` /* Partition `p3` */ trx id 1318D95B lock mode S locks rec but not gap waiting
Record lock, heap no 170 PHYSICAL RECORD: n_fields 15; compact format; info bits 0
 0: len 6; hex 0000a61821ff; asc     ! ;;
 1: len 6; hex 00000b168ac0; asc       ;;
 2: len 7; hex 5200035d760432; asc R  ]v 2;;
 3: len 3; hex 8f661d; asc  f ;;
 4: len 3; hex 0000ac; asc    ;;
 5: len 4; hex 000cc08c; asc     ;;
 6: len 3; hex 0000ac; asc    ;;
 7: len 3; hex 000000; asc    ;;
 8: len 4; hex 000852a6; asc   R ;;
 9: len 3; hex 0519d2; asc    ;;
 10: len 3; hex 00009b; asc    ;;
 11: len 3; hex 8fb747; asc   G;;
 12: len 3; hex 800000; asc    ;;
 13: len 4; hex 00000000; asc     ;;
 14: len 4; hex 00249eda; asc  $  ;;

    ...

*** (2) TRANSACTION:
TRANSACTION 1318D958, ACTIVE 1 sec inserting, thread declared inside InnoDB 123
mysql tables in use 3, locked 3
4808 lock struct(s), heap size 555448, 1122860 row lock(s), undo log entries 7058
MySQL thread id 130380, query id 124472416 192.168.6.31 thanhnt
LOAD DATA INFILE '/data10/select_into.outfile/v3_cam_date.out' INTO TABLE v3_cam_date FIELDS TERMINATED BY  ','
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 222397 page no 2576 n bits 304 index `GEN_CLUST_INDEX` of table `reportingdb`.`v3_cam_date` /* Partition `p3` */ trx id 1318D958 lock_mode X
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 222397 page no 6296 n bits 1000 index `ix_campaignid_dt` of table `reportingdb`.`v3_cam_date` /* Partit
ion `p3` */ trx id 1318D958 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 213 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
 0: len 3; hex 8f63a5; asc  c ;;
 1: len 3; hex 8fb73b; asc   ;;;
 2: len 6; hex 0000a617374f; asc     7O;;

*** WE ROLL BACK TRANSACTION (1)

Sometime, it combines with a huge of "Waiting for global read lock" in the SHOW FULL PROCESSLIST\G and my database is locked completely. Cannot restart with the init script, so I must do a kill -9 <PID> (it causes a lot of crashed tables).
InnoDB Lock Monitor was enabled follow this guide. information_schema.innodb_locks is empty and belows is the innodb_trx table:
*************************** 1. row ***************************
                    trx_id: 135937A0
                 trx_state: RUNNING
               trx_started: 2011-12-19 11:16:04
     trx_requested_lock_id: NULL
          trx_wait_started: NULL
                trx_weight: 43929
       trx_mysql_thread_id: 257731
                 trx_query: INSERT INTO `__tZoneTempTable` (zoneid, rc, v, dt)
    (SELECT a.`zoneid`, sum(a.`realclick`) as rc, sum(a.`totalview`) as v , a.`dt` FROM `v3_zone_date` a INNER JOIN `ox_zones` b ON a.`zoneid` = b.`zoneid` where b.`is_smallbiz` = 3 AND b.`deleted` = 0 AND a.`zoneid` > 0 AND a.`dt` =  NAME_CONST('_date',_latin1'2011-12-17' COLLATE 'latin1_swedish_ci') GROUP BY a.`zoneid`)
       trx_operation_state: fetching rows
         trx_tables_in_use: 10
         trx_tables_locked: 9
          trx_lock_structs: 43929
     trx_lock_memory_bytes: 6093240
           trx_rows_locked: 15961781
         trx_rows_modified: 0
   trx_concurrency_tickets: 359
       trx_isolation_level: REPEATABLE READ
         trx_unique_checks: 1
    trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
 trx_adaptive_hash_latched: 0
 trx_adaptive_hash_timeout: 10000
*************************** 2. row ***************************
                    trx_id: 13590BD9
                 trx_state: RUNNING
               trx_started: 2011-12-19 11:15:23
     trx_requested_lock_id: NULL
          trx_wait_started: NULL
                trx_weight: 43929
       trx_mysql_thread_id: 257456
                 trx_query: INSERT INTO `__tZoneTempTable` (zoneid, rc, v, dt)
    (SELECT a.`zoneid`, sum(a.`realclick`) as rc, sum(a.`totalview`) as v , a.`dt` FROM `v3_zone_date` a INNER JOIN `ox_zones` b ON a.`zoneid` = b.`zoneid` where b.`is_smallbiz` = 3 AND b.`deleted` = 0 AND a.`zoneid` > 0 AND a.`dt` =  NAME_CONST('_date',_latin1'2011-12-17' COLLATE 'latin1_swedish_ci') GROUP BY a.`zoneid`)
       trx_operation_state: fetching rows
         trx_tables_in_use: 10
         trx_tables_locked: 9
          trx_lock_structs: 43929
     trx_lock_memory_bytes: 6093240
           trx_rows_locked: 15961781
         trx_rows_modified: 0
   trx_concurrency_tickets: 359
       trx_isolation_level: REPEATABLE READ
         trx_unique_checks: 1
    trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
 trx_adaptive_hash_latched: 0
 trx_adaptive_hash_timeout: 10000
*************************** 3. row ***************************
                    trx_id: 1358EA92
                 trx_state: RUNNING
               trx_started: 2011-12-19 11:14:57
     trx_requested_lock_id: NULL
          trx_wait_started: NULL
                trx_weight: 0
       trx_mysql_thread_id: 257363
                 trx_query: NULL
       trx_operation_state: NULL
         trx_tables_in_use: 0
         trx_tables_locked: 0
          trx_lock_structs: 0
     trx_lock_memory_bytes: 376
           trx_rows_locked: 0
         trx_rows_modified: 0
   trx_concurrency_tickets: 0
       trx_isolation_level: REPEATABLE READ
         trx_unique_checks: 1
    trx_foreign_key_checks: 1
trx_last_foreign_key_error: NULL
 trx_adaptive_hash_latched: 0
 trx_adaptive_hash_timeout: 10000

As @Chris suggested, I would like to provide the SHOW CREATE TABLE outputs:
mysql> show create table v3_cam_date\G
*************************** 1. row ***************************
       Table: v3_cam_date
Create Table: CREATE TABLE `v3_cam_date` (
  `campaignid` mediumint(9) NOT NULL DEFAULT '0',
  `totalclick` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `totalview` int(11) unsigned NOT NULL DEFAULT '0',
  `realclick` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `clickcharge` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `viewcharge` int(11) unsigned NOT NULL DEFAULT '0',
  `uv` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `uc` mediumint(9) unsigned NOT NULL DEFAULT '0',
  `dt` date NOT NULL DEFAULT '0000-00-00',
  `ctr` decimal(5,3) NOT NULL DEFAULT '0.000' COMMENT '=-1: meaning not available(N/A)',
  `moneyc` int(11) unsigned NOT NULL DEFAULT '0',
  `moneyv` int(11) unsigned NOT NULL DEFAULT '0',
  KEY `ix_campaignid_dt` (`campaignid`,`dt`),
  KEY `ix_dt` (`dt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
/*!50100 PARTITION BY RANGE (TO_DAYS(dt))
(PARTITION p0 VALUES LESS THAN (0) ENGINE = InnoDB,
 PARTITION p01 VALUES LESS THAN (734502) ENGINE = InnoDB,
 PARTITION p2 VALUES LESS THAN (734683) ENGINE = InnoDB,
 PARTITION p3 VALUES LESS THAN MAXVALUE ENGINE = InnoDB) */

This deadlock situation happens frequently. I want to find out what causes this to avoid in the future.

A: This particular deadlock is being caused by attempting to read from your v3_cam_date table for inserting rows into your usertmp table while another thread is updating the v3_cam_date table. Indicated by this statement:
LOAD DATA INFILE '/data10/select_into.outfile/v3_cam_date.out' INTO TABLE v3_cam_date FIELDS TERMINATED BY  ','

This documentation page has some useful steps in dealing with deadlocks, but perhaps the most useful tip in your situation might be to use the READ COMMITTED transaction isolation level when doing your insert into usrtmp table.
This basically means that what you are selecting is only the committed values, not any changes that are happening from your LOAD DATA INFILE statement if it hasn't finished committing.
If that is acceptable to you, something like this might work*:
-- SET SESSION TO READ COMMITTED --
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;

-- ISSUE THE INSERT...SELECT --
INSERT INTO usertmp(userid,npayvalue,balance)
SELECT B.`userid`, SUM(C.`moneyv`) a,(B.`balance` + B.`promotions`+ B.`promotions1`+ B.`overdraft`) b
FROM `ox_campaigns` A
INNER JOIN `v3_cam_date` C ON C.`campaignid` = A.`campaignid`
INNER JOIN `selfserving_users_balances` B ON B.`userid` = A.`uid`
INNER JOIN `selfserving_users` F ON F.`user_id` = B.`userid`
INNER JOIN `selfserving_users_group_balances` E ON E.`groupid` = F.`groupid` AND E.`ispostpaid` = 0
WHERE A.`revenue_type` = 6 AND C.`dt` BETWEEN A.`activate` AND A.`expire` AND C.`dt` >=  (SELECT DATE_ADD( A.ssv_payment_date_lastest, INTERVAL 1 DAY)  FROM `000_sys_params_v3` A)
AND C.`viewcharge` >0
GROUP BY B.`userid`

-- SET BACK TO 'DEFAULT' --
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;

* Note, I haven't personally tried the above to ensure READ COMMITTED will stop the deadlock.
But how long does it take to load this file? You might add a table lock around the LOAD DATA INFILE, but of course that will make the INSERT wait for the file to load all the time.

A: DEADLOCK EXPLANATION
If the underlying tables use the InnoDB Storage Engine, row locks (even on the same row) can never block reads, but deadlocks are still possible during writes. With AUTOCOMMIT=0 set in /etc/my.cnf, each DML statement (INSERT,UPDATE, and DELETE) will be executed as a single line transaction. Individual row locks are issued. Thus, 50 DB Connections can go after 50 different rows and nothing tragic happens.
Where can deadlocks come in?
Since the PRIMARY KEY of InnoDB tables is contained within the Clustered Index (internally known as the gen_clust_index), the row data is tightly coupled with the index entries. Any index made against columns not part of the PRIMARY KEY are cataloged with tow basic items, the column value and the gen_clust_index key. At times, update indexes columns in InnoDB may cause what I jokingly call index constipation. That's occurs when two or more locks are generated on index entries stored close to one another. This is possible in a heavily trafficked website.
I once helped a Developer see why this can happen in the DBA StackExchange. That developer made code changes afterwards. Here were those posts:

*

*Will these two queries result in a deadlock if executed in sequence?

*Trouble deciphering a deadlock in an innodb status log

*Reasons for occasionally slow queries?
YOUR QUESTION
In the snippet you provided, you have this:
/* Partition p3 */ trx id 1318D95B lock mode S locks rec but not gap waiting
This message show a Shared Row Locked (lock mode S) in this Partition. Somewhere in the SHOW ENGINE INNODB STATUS\G, you should also have seen another Row Lock tagged as Exclusive (lock mode X).


text:
Q: Оптимизировать python задачу на двумерные массивы Помогите ускорить решение, пожалуйста!
Условие: в первой строке вводится число N, далее в N строках вводится по 2 числа a и b. Их нужно считать, если b не равен 0, то список [a, b] добавляется в массив. Соответственно, если в течение ввода b не равен 0, то получаем двумерный массив array[N][2]. Задача в том, чтобы отсортировать наш массив array сначала по убыванию второго элемента, потом по возрастанию первого элемента. Затем выводим текущее количество вложенных списков (необязательно N, т.к. по ходу ввода b  могло быть равно 0). И, наконец, выводим отсортированный массив.
n = int(input())
all = []
for i in range(n):
    a, b = map(int, input().split())
    if b != 0:
        all.append([a, b])
all.sort(key=lambda x: (x[0], -x[1]))
print(len(all))
for i in all:
    print(*i)

Проблема в том, что решение не проходит по времени. Есть ли какой-то способ ускорить код?


text:
Q: how to get Monday as first day in jquery datepicker if you run the code snippet, you'll see that Monday is day number 7, how can I get Monday as the first day of the week
example:
Monday 05/01/2017 the week No. 1
Tuesday 05/02/2017 the week No. 2

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Date: <input type="text" id="date">

Day: <input type="text" id="day">

week: <input type="text" id="week">

work: <input type="text" id="work">

A: You were missing firstDay: 1 param.

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Date: <input type="text" id="date">

Day: <input type="text" id="day">

week: <input type="text" id="week">

work: <input type="text" id="work">

A: my answer is month to 0
var weekStart = new Date(2017, 0, 27);

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Date: <input type="text" id="date">

Day: <input type="text" id="day">

week: <input type="text" id="week">

work: <input type="text" id="work">


text:
Q: Flutter - How to pause qr scan reading I'm developing a qr scan app. And using qr_code_scanner 0.5.2.
When i scan a qr code, my app jump to another page with the scanned code, but the app still scanning the qr codes and new pages appears until you d not focus on any qr code.
How can i scan codes one by one and pause scanning while on the another page and resume scanning when the new page is closed?
Thanks
code:
  void _onQRViewCreated(QRViewController controller) {
setState(() {
  this.controller = controller;
});
controller.scannedDataStream.listen((scanData) {
  setState(() {
    controller.pauseCamera();
    Navigator.push(context,
      MaterialPageRoute(builder: (context) {
        return ReadData(data: scanData.code);
      }),
    );
    controller.resumeCamera();
  });
});

}
edit:
solution code:
  void _onQRViewCreated(QRViewController controller) {
  this.controller = controller;

controller.scannedDataStream.listen((scanData) async {

  controller.pauseCamera();
  await Navigator.push(
    context,
    MaterialPageRoute(builder: (context) {
      return ReadData(data: scanData.code);
    }),
  );

  controller.resumeCamera();
});

}

A: qr_code_scanner controller got a method called  pauseCamera use that to pause camera whenever a valid barcode is detected.
edit: if pauseCamera is not working then you can add boolean variable and switch it to true whenever you get valid QR code. And, navigate to new page only if this variable is false.
I've updated the code, Please take a look.
...
bool gotValidQR = false; //toggle this value when you got a new qr code
...
controller.scannedDataStream.listen((scanData)async {
    if(gotValidQR) {
      return;
    }
    gotValidQR = true;
    dynamic pop = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) {
        return ScannedData(data: scanData.code);
      }),
    );
    gotValidQR  = false;
});
...


text:
Q: When I opened the Software centre, I could not see any application. I am getting an error when I try to reinstall it I could not see applications when I opened Software Center. When I tried to reinstall I got an error message:
E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 8394 (apt-get)
N: Be aware that removing the lock file is not a solution and may break your system.
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?

Please help me resolve the above issue.

A: Explore with ps -fp8394. If process 8394 exists, you (or unattended-updates) are updating the packaging system elsewhere.
If process 8394 does not exist, the lock file may be left over from an update interrupted by a sudden reboot. If so, it should be deleted, BUT your packaging system may be in an inconsistent state.
Do
sudo apt update
sudo apt upgrade

and Read the Error Messages.
An alternative explanation for ps -fp8394 being empty may be that process 8394 has finished, and deleted the lock file.


text:
Q: Always a Collision I created a tilemap and a player (Which is just a squiggle right now). I put the tilemap and the player on the screen, but the player is in the upper left corner, and is always stuck in the tile.  I can't figure out how to:

*

*Get it out of the corner and

*stop the collision from happening because it's a non-blocked block.

A few things you need to know before the code:
The tilesheet is the sheet with the different tiles on it and it goes

[non-blocked, nonblocked]
  [blocked, blocked]

Here's the collision part of my object superclass (I know it looks like a lot but after the beginning you can get the drift):
public void calculateCorners(double x, double y) {

        int leftTile = (int)(x - cwidth / 2) / tileSize;
        int rightTile = (int)(x + cwidth / 2 - 1) / tileSize;
        int topTile = (int)(y - cheight / 2) / tileSize;
        int bottomTile = (int)(y + cheight / 2) / tileSize;

        int tl = tileMap.getType(topTile, leftTile);
        int tr = tileMap.getType(topTile, rightTile);
        int bl = tileMap.getType(bottomTile, leftTile);
        int br = tileMap.getType(bottomTile, rightTile);

        topLeft = tl == Tile.BLOCKED;
        topRight = tr == Tile.BLOCKED;
        bottomLeft = bl == Tile.BLOCKED;
        bottomRight = br == Tile.BLOCKED;

    }
public void checkTileMapCollision() {
    currCol = (int) x / tileSize;
    currRow = (int) y / tileSize;
    x += velX;
    y += velY;
    calculateCorners(x, ydest);

    if (velY < 0) {
        if (topLeft || topRight) {
            velY = 0;
            y = currRow * tileSize + cheight / 2;
            System.out.println("Collision");
        } else {
            y += velY;
        }
    }

    if (velY > 0) {
        if (bottomLeft || bottomRight) {
            velY = 0;
            falling = false;
            y = (currRow + 1) * tileSize - cheight / 2;
            System.out.println("Collision");
        } else {
            y += velY;
        }
    }

    calculateCorners(xdest, y);

    if (velX < 0) {
        if (topLeft || bottomLeft) {
            velX = 0;
            System.out.println("Collision");
            x = currCol * tileSize + cwidth / 2;
        } else {
            x += velX;
        }
    }

    if (velX > 0) {
        if (topRight || bottomRight) {
            velX = 0;
            System.out.println("Collision");
            x = (currCol + 1) * tileSize - cwidth / 2;
            System.out.println("Collision");
        } else {
            x += velX;
        }
    }
}

And here's the most important stuff in my Player class:
public void update() {
    System.out.println("update");
    getNextPosition();
    checkTileMapCollision();
    setPosition((int) xtemp, (int) ytemp);
}

public void setLeft(boolean b) {
    left = b;
}

public void setRight(boolean b) {
    right = b;
}

public void getNextPosition() {
    if (left) {
        velX = -2;
        System.out.println("Left");
    } else if (right) {
        velX = 2;
        System.out.println("Right");
    }
}

public void draw(Graphics2D g) {
    x += velX;
    y += velY;
    g.drawImage(spriteSheet, (int) x, (int) y, null);
}

public void setPosition(int x, int y) {
    this.x = x;
    this.y = y;
}

public void setVel(int velX, int velY) {
    this.velX = velX;
    this.velY = velY;
}

If you need anything else, just tell me and I'll give it to you.


text:
Q: User input validation to only include alphabetical characters I'd like to have the user type in only alphabetical characters in my autocompletetextview and not be allowed to insert blank characters, or numbers, or symbols.
Currently, the Toast message pops up correctly when I dont put in alphabetical characters, but it is also popping up when the correct input(matching key value in firebase database) is put in.
I think I am having problem doing this because my if statement is currently in a for loop that reiterates every key value in my firebase database(which i have to do for my function to work). Is there any workaround for the user input validation to still work in this situation?
public void onClick(View v) {
    for (final DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        source = textView.getText().toString();

        if (source.equals(childSnapshot.getKey())) {
            GlideApp.with(Translate.this).load(childSnapshot.getValue(String.class)).placeholder(R.drawable.ic_launcher_background).into(imageView);
        } else if(!source.equals(!source.equals("[0-9]+")) {
            Toast.makeText(Translate.this, "No number", Toast.LENGTH_SHORT).show();
        } else if(source.equals("[a-zA-Z_]+")) {
            Toast.makeText(Translate.this, "Invalid text", Toast.LENGTH_SHORT).show();
        }
    }
}

A: You could create a function for the regex which will test the validity of the input and return true or false like below:
private boolean isValidInput(String someText) {
    Pattern p = Pattern.compile("^([a-zA-Z]+)$");
    Matcher matcher = p.matcher(someText);
    if(matcher.find())
        return true;
    return false;
}

And then use it like this:
public void onClick(View v) {
    source = textView.getText().toString().trim();

    if( !isValidInput(source) ) {
        Toast.makeText(Translate.this, "Invalid input. Please use alpabetical characters.", Toast.LENGTH_SHORT).show();
        return;
    }

    for (final DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
        if (source.equals(childSnapshot.getKey()) ) {
           GlideApp.with(Translate.this).load(childSnapshot.getValue(String.class)).placeholder(R.drawable.ic_launcher_background).into(imageView);
        }
    }
}

A: use

.getText().toString().trim();

, this is the thing I found while entering email addresses on websites,
If You have space in the end, their validation doesn't seem to works


text:
Q: Backend access rights for news records Is it possible to store all records of the news extension (ext:news) on the same storage page, but show only records, which are created by the loggedin backend user?
So the current backend user can just see and edit his own records? Admins should see all records of course.

A: No, this is not possible, since backend user permissions on record level are not implemented in TYPO3.
So you either have to separate the news records of the users in separate sysfolders or you could try to use hooks (e.g. $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.db_list_extra.inc']['getTable']) or XClass to customize TYPO3 backend to your needs. I do not recommend the latter, since the TYPO3 backend permission system is complex and you would need to make sure to restrict record access in several parts of TYPO3 (e.g. recordlist, element browser, related news field, ...)

A: There are two ways to archive that:

*

*If the backend user is not too much. You can just create a page(type
is folder) named with the backend user name. And in the backend user
module you can set the permission(Not for the group user but for the
single backend user only).

*if the backend user is too much. and You just wanna set permissions for the group and all backend users are sharing the same rules. You can refer to Hook:https://docs.typo3.org/p/georgringer/news/main/en-us/Tutorials/ExtendNews/Hooks/Index.html so that the basic logic is like this:
2.1 get current logged-in user group.
2.2 if the group is Reporter, we can use the hook for the listing page:
$constraints[] = $query->equals('cruser_id', $be_id);

Edit(3/3/2022):
Hi Chris, Yes you are right.
Today, I have got a chance to dig into the news extension. I think we can still make it by the hook

*

*in your ext_localconf.php

$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Recordlist\RecordList\DatabaseRecordList::class]['modifyQuery'][$_EXTKEY]
 = \T3docs\SitePackage\Hooks\DatabaseRecordListHook::class;

(Please make sure the namespace is correct)

*within the file : T3docs\SitePackage\Hooks\DatabaseRecordListHook.Create a function named modifyQuery:

public function modifyQuery($parameters,
                             $table,
                             $pageId,
                             $additionalConstraints,
                             $fields,
                             $queryBuilder)
 {
     if ($table === 'tx_news_domain_model_news') {
         $tsconfig = $GLOBALS['BE_USER']->getTSConfig();
         if (!empty($tsconfig['options.']['be_users'])) {
             $be_users = $tsconfig['options.']['be_users'];
             $queryBuilder->andWhere('cruser_id IN (' . $be_users . ')');
         }
     }
     return $queryBuilder;
 }

*in the user Options tab set Tsconfg : options.be_users = 3,100
(3,100 is the be_user id. And the 2 two backend users's news will show up)

thus, it works for me.


text:
Q: From CTE to mySQL stored procedure code This is a query using sql CTE's to create a transitive closure of a table containing relations
between users.(edges of a graph).
How can this be done in mySQL?

WITH RECURSIVE transitive_closure(a, b, distance, path_string) AS
( SELECT a, b, 1 AS distance,
         a || '.' || b || '.' AS path_string
  FROM edges
 WHERE a = 1 -- source

  UNION ALL

  SELECT tc.a, e.b, tc.distance + 1,
         tc.path_string || e.b || '.' AS path_string
  FROM edges AS e
  JOIN transitive_closure AS tc ON e.a = tc.b
 WHERE tc.path_string NOT LIKE '%' || e.b || '.%'
)
  SELECT * FROM transitive_closure
  ORDER BY a, b, distance;

or at least find all simple paths between two nodes without creating a transitive closure for all nodes.
code taken from: http://techportal.inviqa.com/2009/09/07/graphs-in-the-database-sql-meets-social-networks/


text:
Q: Postgres query running very slow SELECT st.id
FROM
       station st, strike s
WHERE s.srikedatetime > (current_timestamp - interval '20 seconds')  and srikedatetime < current_timestamp
    AND ST_Distance_Sphere(st.Geometry, s.strikepoint)/1000 <= st.radius

The idea is when a strike hits, it could be in boundary of multiple stations based on station monitoring radius. I need to select all stations affected by any strikes in the last 20 seconds. In 20 seconds I can have thousands of strikes and when executing this query every  20 seconds, the CPU goes high and the query takes minutes to complete. When CPU is not high, it runs in milliseconds.
Query Plan:
"Nested Loop  (cost=0.42..505110.20 rows=21 width=7)"
"  Join Filter: ((_st_distance(geography(a.Geometry), geography(s.strikepoint), 0::double precision, false) / 1000::double precision) <= (a.radius)::double precision)"
"  ->  Index Only Scan using dup_strike_constraint on strike s  (cost=0.42..8.45 rows=1 width=36)"
"        Index Cond: ((srikedatetime > (now() - '00:00:20'::interval)) AND (srikedatetime < now()))"
"  ->  Seq Scan on station  st  (cost=0.00..505084.86 rows=62 width=549)"

I have tried inner join, something like this
Inner JOIN strike s ON ST_Distance(a.Geometry, s.strikepoint) < 1

and also tried ST_DWithin in where clause and grouping still slow.
ST_DWithin(s.strikepoint,a.Geometry, a.radius)

Any thoughts, please? I have indexes on strike and station tables.
The data types for st.strikepoint and a.geomerty columns is geometry.
 The coordinate system is 4326.
Thank You!

A: You could create a Lazy Materialized View to stock just the data you need. It's a lot faster if you just query one table instead of joining 'station' and 'strike' tables.
Obviously, your lazy table should be indexed properly, especialy if you don't plan to 'clean' the data periodicaly.
Other option could be using a TEMP table to handle the data, if it's not necessary to store it historically and you handle the data in one session. TEMP tables are just visible to one session and 'die' when the session ends. You can create them and destroy them at any point, but in this case you should pay attention to the memory usage.
Hope it helps.

A: Once your stations are changed rearely you can create field of type Geometry, reflecting the Polygon, representing the registration area of the station. i.e. using default value ST_Buffer(Geometry, radius/1000).  And make a check of hit using ST_Contains(st.the_polygon, s.strikepoint) .
If this doesn't speedup you can than introduce additional indexing on Station polygon.

A: I would try to reduce the usage of the possible costly function ST_Distance_Sphere by reducing the possible matches. Instead of using the exact spherical Distance for each possible match, you first check a cube around the station, and only the matches inside the cube are checked via ST_Distance_Sphere().
SELECT st.id
FROM
       station st, strike s
WHERE s.srikedatetime > (current_timestamp - interval '20 seconds')  and srikedatetime < current_timestamp
    AND ST_Distance_Sphere(st.Geometry, s.strikepoint)/1000 <= st.radius
    and s.strikepoint.x between st.Geometry.x - st.radius*1000 and st.Geometry.x + st.radius*1000
    and s.strikepoint.y between st.Geometry.y - st.radius*1000 and st.Geometry.y + st.radius*1000
    and s.strikepoint.z between st.Geometry.z - st.radius*1000 and st.Geometry.z + st.radius*1000

In a next step, you could store st.Geometry.x - st.radius*1000 as st.range_x_negative , in order to prevent calculations during the join.


text:
Q: Check a string for values that shouldn't belong I have a string that could contain any of these values set @string = "a, b, c"
I thought I could do this using AMPscript
if IndexOf(@string,'a') > 0 or IndexOf(@string,'b') > 0 or IndexOf(@string,'c') > 0 then

   /* do nothing */

else

  RaiseError('Unknown value submitted',true)

endif

The idea being if my string contains, say, "a, b, c, x", or anything other than a or b or c there would be an error and skip that record.
But it's not working and I have no idea why. Anyone have ideas?

A: You could use the regexmatch function:
Code
%%[

set @pattern = "[^(a|b|c|,|\s)]+"
set @str = "a, b, c, x"
set @result = RegExMatch(@str, @pattern, 0)
output(concat("<br>result: ", @result))

]%%

Output
result: x

In your example:
%%[

set @pattern = "[^(a|b|c|,|\s)]+"
set @str = "a, b, c, x"
set @result = RegExMatch(@str, @pattern, 0)

if empty(@result) then

   /* do nothing */

else

  RaiseError('Unknown value submitted',true)

endif

]%%

I used this to test the pattern.


text:
Q: android sqlite database delete query this is working delete but there is problem in data fetching after deleting the data and also problem comes data saving after deleting data
database class
     public void delete_byID(long id1)
     {
         Log.d("unicorn","in DELETE");
         db.delete(DATASAVE, _id+"-1="+id1, null);
      }

in activity i want to delete from profile activity and return to second activity
   delete.setOnClickListener(new OnClickListener()
       {
        public void onClick(View v)
        {
            Intent i = new Intent(ProfileActivity.this,SecondActivity.class);
            startActivity(i);
            d1.delete_byID(id4);

    }
});

A: put d1.delete_byID(id4) as first line in onClick(View v) method


text:
Q: PHP output buffering not flushing I have an ob_start(); in my header.php and ob_end_flush(); include("cron.php"); in my footer.
Now the cron.php takes a few seconds to load so it takes time for the page to render.
How come it isn't rendering considering I have flushed the output? I know browsers mess with this and in the past their have been techniques but I have tried them (eg. adding flush(); or a UTF-8 header) but none of them have worked.
Is there a solution that works or is there another way for me to accomplish this?
How does WordPress include it's cron file?
header.php:
<?php
    ob_start();
    require_once("config.php");
?>

Then there's the page code.
footer.php:
<?php ob_flush(); flush(); ob_end_flush(); require("cron.php"); ?>