text:
Q: NullPointerException starting Firebase Auth UI activity from Kotlin activity I had a java android app with androidx navigation (supportbar + navigation drawer) and it was launching Firebase UI to get the user logged in. Then I've decided to migrate the Activity code to Kotlin using the AS converter and some manual work on the navigation setup.
Despite my efforts it still breaks with this stack
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gabrielcalero.familytree, PID: 20260
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabrielcalero.familytree/com.firebase.ui.auth.KickoffActivity}: java.lang.NullPointerException: Attempt to invoke super method 'void androidx.fragment.app.FragmentActivity.onPanelClosed(int, android.view.Menu)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2793)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6524)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
 Caused by: java.lang.NullPointerException: Attempt to invoke super method 'void androidx.fragment.app.FragmentActivity.onPanelClosed(int, android.view.Menu)' on a null object reference
    at androidx.appcompat.app.AppCompatActivity.onPanelClosed(AppCompatActivity.java:505)
    at androidx.lifecycle.LiveData.observe(LiveData.java:172)
    at com.firebase.ui.auth.KickoffActivity.onCreate(KickoffActivity.java:35)
    at android.app.Activity.performCreate(Activity.java:6910)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6524)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)

The weird thing is that following the stack the exception is onPanelClosed, which means super is null. How is this possible?
@Override
public void onPanelClosed(int featureId, Menu menu) {
    super.onPanelClosed(featureId, menu);
}

UPDATE: here is the activity code
package com.gabrielcalero.familytree.ui
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.firebase.ui.auth.AuthUI
import com.gabrielcalero.familytree.R
import com.gabrielcalero.familytree.ServiceLocator
import com.gabrielcalero.familytree.entity.Constants
import com.gabrielcalero.familytree.ui.picasso.CropCircleTransformation
import com.google.android.material.navigation.NavigationView
import com.google.firebase.auth.FirebaseAuth
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, FirebaseAuth.AuthStateListener {

private var mUserPicture: ImageView? = null
private var mUserNameTextView: TextView? = null
private var mAuth: FirebaseAuth? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setupNavigation()

    mUserPicture = navView.getHeaderView(0).findViewById(R.id.picture)
    mUserNameTextView = navView.getHeaderView(0).findViewById(R.id.display_name)

    mAuth = FirebaseAuth.getInstance().apply { addAuthStateListener { this } }

    launchSignInUI()
}

override fun onStart() {
    super.onStart()
    updateLoggedInUser()
}

private fun updateLoggedInUser() {
    val currentUser = mAuth!!.currentUser
    if (currentUser == null) {
        mUserPicture!!.setImageResource(R.drawable.anonymous)
        mUserNameTextView!!.text = getString(R.string.not_logged_in)
        navView.menu.findItem(R.id.signout).isVisible = false
        navView.menu.findItem(R.id.signin).isVisible = true
        navView.menu.findItem(R.id.personFragment).isEnabled = false
        navView.menu.findItem(R.id.peopleListFragment).isEnabled = false
    } else {
        // show signout
        mUserNameTextView!!.text = currentUser.displayName
        Picasso.with(this)
                .load(currentUser.photoUrl)
                .placeholder(R.drawable.anonymous)
                .error(R.drawable.anonymous)
                .transform(CropCircleTransformation())
                .resize(resources.getDimension(R.dimen.profile_picture_width).toInt(),
                        resources.getDimension(R.dimen.profile_picture_height).toInt())
                .into(mUserPicture)
        navView.menu.findItem(R.id.signout).isVisible = true
        navView.menu.findItem(R.id.signin).isVisible = false
        navView.menu.findItem(R.id.personFragment).isEnabled = true
        navView.menu.findItem(R.id.peopleListFragment).isEnabled = true
    }
}

private fun setupNavigation() {
    setSupportActionBar(toolbar)

    supportActionBar!!.setDisplayShowHomeEnabled(true)
    supportActionBar!!.setDisplayHomeAsUpEnabled(true)

    val navController : NavController = findNavController(R.id.nav_host_fragment)
    val appBarConfiguration = AppBarConfiguration(navController.graph, drawerLayout)
    toolbar.setupWithNavController(navController, appBarConfiguration)
    navView.setupWithNavController(navController)
    navView.setNavigationItemSelectedListener(this)
}

private fun launchSignInUI() {
    // Choose authentication providers
    val providers = Arrays.asList(
            AuthUI.IdpConfig.EmailBuilder().build(),
            AuthUI.IdpConfig.GoogleBuilder().build())

    // Create and launch sign-in intent
    startActivityForResult(
            AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .setLogo(R.drawable.logo)
                    .build(),
            Constants.REQUEST_CODE_SIGN_IN)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    //updateLoggedInUser()
}

override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
    val navController = findNavController(R.id.nav_host_fragment)
    when (menuItem.itemId) {
        R.id.signout -> signout()
        R.id.signin -> launchSignInUI()
        R.id.personFragment -> {
            navController.popBackStack(R.id.peopleListFragment, false)
            navController.navigate(R.id.personFragment)
            drawerLayout?.closeDrawers()
            return true
        }
        else -> {
            navController.popBackStack(R.id.peopleListFragment, false)
            drawerLayout?.closeDrawers()
            return true
        }
    }
    drawerLayout?.closeDrawers()
    return true
}

private fun signout() {
    val navController = findNavController(R.id.nav_host_fragment)

    AuthUI.getInstance()
            .signOut(this)
            .addOnCompleteListener {
                navView.menu.findItem(R.id.signout).isVisible = false
                navController.popBackStack(R.id.peopleListFragment, false)
            }

}

override fun onAuthStateChanged(firebaseAuth: FirebaseAuth) {
    ServiceLocator.getRepository(application).setCurrentUserId(firebaseAuth.uid)
    updateLoggedInUser()
}

}

A: The issue was in Java to Kotlin conversion. In this case I've fixed it by removing the unused dependency
implementation "androidx.core:core-ktx:+"

I guess when I finish converting all java classes I will have to replace all androidx dependencies by their -ktx counterpart


text:
Q: Variance matrix from polar to cartesian coordinates I am dealing with a time series in polar coordinates and I am applying the Kalman filter for predictions. The time series is related with the satellite orbite.
However my prediction and estimation for the variance are expressed in polar coordinates [r,theta].
I know how to convert my prediction in cartesian coordinates with the function
  f(r,theta) <- [r*cos(theta),r*sin(theta)].

But I do not know how to deal with the variance since it is not a linear operator.
I provide you my data in order if you can help me with the transformation:
     Radius                  Angle
[1,] "39805.9613778309" "1.46134492279737"
[2,] "39805.9613778309" "1.48689546833425"
[3,] "39805.9613778309" "1.51244601387112"
[4,] "39805.9613778309" "1.537996559408"
[5,] "39805.9613778309" "1.56354710494488"
[6,] "39805.9613778309" "1.58909765048176"

And the variance matrix for the first prediction is :
        radius    theta
[1,] 5132782 0.000000000
[2,]       0 0.001646994

I would like to know how to obtain this matrix in cartesian coordinates for the first prediction. thanks!

A: This had me perplexed as well. I think I found the answer: the formula provided above,
,
follows from the most general form of error propagation. The formula is correct, provided you're OK with making a few assumptions, in particular that you are OK with linearizing the transformation.
See https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Non-linear_combinations. This section has a subsection, 'Caveats and Warnings,' which I think is worth approaching with an open mind (so you don't end up biased :P ).

A: In developing tracking filters for radar systems, I've used the following technique:
1) Determine the polar to Cartesian rotation matrix as
  R = [cos(theta)  - sin(theta);
       sin(theta)    cos(theta)]

2) Perform the following matrix multiplication to obtain the covariance matrix in Cartesian coordinates, Pcart:
  Pcart = R*Ppol*R'

  where Ppol is the covariance matrix in polar coordinates
        R' is the transpose of R

A: The best way to accomplish this is to find the Jacobian of the function Fhat = Jacobian[f(r,theta)]. If the variance matrix in spherical is R(polar), then P(Cart) = Fhat*R*Fhat'. Using a Rotation matrix gives you the wrong answer, as it simply rotates the Cartesian covariance into another 'rotated' Cartesian system. See the Appendix 18.B in my book "Bayesian Estimation and Tracking: A Practical Guide" for a complete derivation of this formula and how to use it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: linking Qt Creator plugin editor / highlighter I'm working on a qt creator plugin that adds support for certain types of files by supplying customized editors, etc. Right now it registers a new IEditorFactory which produces editors that I based off of the TextEditor::BaseTextEditor and TextEditor::BaseTextEditorWidget.
Eventually I will be creating and using specialized highlighters and other things, but for now I want to utilize things from other qt creator plugins, and this is where I run into trouble.
In particular I want to use the TextEditor::Internal::Highlighter, which can load and utilize kate files. I'm already using other classes from the TextEditor plugin so I have
include($$QTCREATOR_SOURCES/src/plugins/texteditor/texteditor.pri)

added to my project file. Inside texteditor.pri everything seems good
include(texteditor_dependencies.pri)
LIBS *= -l$$qtLibraryName(TextEditor)

and, indeed, I'm able to compile my editor (which is dependent on things inside the texteditor plugin).
The only difference with the TextEditor::Internal::Highlighter -as far as I can tell- is that it's in a subfolder of the texteditor plugin. This should be fine, and the object files seem to all land in the same directory, but when I say
new TextEditor::Internal::Highlighter()

(just as is done in texteditor/plaintexteditor.cpp) I get a linker error
Undefined symbols for architecture x86_64:
  "TextEditor::Internal::Highlighter::Highlighter(QTextDocument*)", referenced from:
      MyPlugin::MyEditorWidget::MyEditorWidget(QWidget*)in myeditor.o
      MyPlugin::MyEditorWidget::MyEditorWidget(QWidget*)in myeditor.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

What am I doing wrong? Are there more dependencies I have to declare? Is there a command I can use to force a folder of object files to be in my path while compiling?
Thnaks!

A: The classes and methods in the "Internal" namespace tend to not be exported, so they are not available outside the plugin that provides them. Check the class definition: Does it have "SOMETHING_EXPORT" between the class keyword and the class name? If not, then you are out of luck.
By default as few symbols as possible are exported: That leaves us a chance to actually change things around without worrying about breaking code outside the plugin. It also reduces load times a bit. If you have a use-case for the symbol to be exported: Feel free to ask on the Qt Creator mailing list or -- better yet -- provide a patch to codereview.qt-project.org which moves the class out of the Internal namespace and exports the symbol.
A better place to get questions like this answered is the Qt Creator mailing list and the #qt-creator IRC channel on freenode network.


text:
Q: Who is the original in the movie The Prestige? In the movie The Prestige, Hugh Jackman plays a magician who, when he performs a trick, gets cloned and becomes two people. But who is who? Is the one appearing on the balcony in the audience the original one or the clone? It would be logical if the clone was destroyed but how do we know it's not the clone that ends up continuing the trick / show?

A: You're asking the wrong question. They're both the original Angier. The whole point of the machine is that it creates a perfectly exact copy of the object that it clones.
You could argue from a technical viewpoint that the actual particles of the guy who appears on the balcony have been created by the machine and thus don't have the history of being part of Robert Angiers body. But this is a flawed premise, since a particle's history has no bearing on it anyway. There is absolutely no way to tell one Angier apart from the other.
That is the entire point of the machine and a point the movie reinforces repeatedly, be that when Angier and Tesla first discover the workings of the machine by finding all the cloned hats:

Tesla: Don't forget your hat
Angier: Well, which one is mine?
Tesla: They're all your hats, Mr. Angier.

Or at the end when Angier reveals the obvious but dark truth of his trick to Borden:

It took courage to climb into that machine every night not knowing if I'd be the man in the box...or in the prestige.

The point being, that Angier was always both men. He obviously always was the one who survived all the previous shows, but he also is the one who will survive the next show and the one who will die in the tank in the next show.
(This notion can as well be extrapolated onto a more metaphorical level where Angier pretty much sacrificed his own personality by just making copies of his own self and killing himself with each show, in the same way as he sacrificed his very soul with those terrible deeds.)

A: Since we see that Tesla's device clones objects at a distance, it stands to reason that it's the original that is drowned and killed, while the clone lives.
However, I don't think it really matters, except for the one that is killed of course, since the "original" that is killed today is the clone that lived yesterday.
The movie makes an explicit choice in the age-old "who is the real me" cloning dilemma, opting for the "both the clone and the original are equivalent" choice.

A: It actually is the clone that survives, that's the deep dark secret behind Tesla's device.
In the original novel, the device actually kills its user. After creating the clone and depositing it somewhere else, it leaves the now-dead body of the original user in the machine.
In the movie, the original body is dropped, tied up, into the tank of water to drown, while the clone finishes the show.
This is meant to show the depths that Angier (Hugh Jackman's character) is willing to go to one-up his rival: he's literally willing to kill himself on stage.
Even more, he's willing to drown himself, in what amounts to a failed escape trick - the tied-up Angier never gets out of the tank alive. Recall that this is exactly how his wife Julia died (which Angier blamed on Borden, and started the entire rivalry between them). That was Angier's self-imposed fate -- to suffer through his wife's death every night just to one-up Borden, only for his newly-created clone (which has his memories, feelings, etc.) to walk around knowing he was going to do it all again the next night.

A: The first Angier who appears outside the cage does say "No, wait, I'm the…!" just before he's shot.  If you take him to be trying to say "I'm the original!", then either he's the original and teleported or he's the clone and can't tell the difference because his memories and sense of identity are identical.  So Angier says he doesn't know whether he'll be the drowned man or the prestige because he knows that even if he thinks he's survived and teleported he can never be sure that it's not a cloned memory/identity and the original thread of consciousness didn't end up in the tank.  The drowning Angier would have the inverse uncertainty. I think from the first time he uses the machine he loses track of his identity in a way the twins never do.
Though having said that, maybe a machine that clones AND teleports is less elegant and Occam's Razor-y than just a clone machine, so if we have to make the distinction (ignoring Tesla's saying they are all the same) then the original always dies. But according to Tesla's definition ("They are all your hat, Mr. Angier"), which I think is important, it is a clone AND teleport because the hat/cat/magician that pops up at a distance is just as authentic as the one in the machine.

A: I thought that it was not specified, hence he was willing to risk being drowned in order to win the battle with his opponent.
Doesn't Hugh Jackman say in the film that he never knows whether he will be the one that falls or the one that bows?

A: I have read some very insightfull answers here and even though this post is 9 months old, I would like to add my 2 cents to the argument and perhaps in doing so leave you with some food for thought.
I have not read the original novel, but it would have been more clear cut if the version in the box was killed instantaniously like Mr Edenfield suggests, but that in itself leaves a very large conuncdrum. Why get in the box in the first place???
Here me out. Angier goes to Tesla (after aquiring the information from Bordens stolen diary) Tesla shows him the machine he made for Borden, but also that the machine is flawed. It does nothing (apparently). Angier repeatedly returns to Tesla to test the machine, untill finally they test the cat. It is only after testing the cat that Angier finds out that the box made clones. He finds the second cat (alive) and the multitudes of tophats. So, that would indicate that the machine was working "ALL THE TIME".
Ok, here goes. If we follow the novels trail of logic, the moment they put the cat in the box, it should have left them with a dead cat. Unless the cat comes walking back into the studio alive and well "whilst" Tesla is holding the dead body of the original cat, it would take a hell of a lot of guts to get into the machine if you knew you would just be dead like the cat. Who wants a box of death? It is the pivotal moment where he finds the two cats and then the tophats that reveals the true nature of the machine.
The film version actually puts a more plausible spin on the whole concept. It also leaves us with the conundrum that each time the machine is used, it makes a perfect copy, body/conscience/soul. Why do i say this...Tesla now has 2 cats, but imediately doing different things, as if it is a copy, but with a new life different from the original. This would also indicate why the copy is not made in the box, but rather some distance away. This indicates same, but seperate...ie unique.
We also see Angier falling into the water box and imediately trying to fight his way out. He "knows" he just got screwed. That would also indicate, that it is always the original that gets killed (in the watertank), which means the question you rather should be asking is this. Who killed who first? Remember Angier tests the machine on himself for the first and has that short episode of stunned realisation what the implication is of having 2 of himself around. He or he kills the other one in a very "there can be only one" type of way. SO did the clone kill the original, or did the original kill the clone...it depends on who thought about it first and we actually do not know...i will have to go check to make sure they dont show us. All we know is that one gets in the machine and climbs out and the other manifests somewhere else. That would indicate that when he knows that if he climbs into the machine he will die, because he knows he is killing himself, but that the "exact" copy up till that very second, will continue with his live. Will the copy keep up the act, or will it choose another path? We never find out.
Here is the bigger question i would like you guys to ponder over. It contains a SPOILER for those who have not seen the film after 6 years, so stop reading now.
Ok, keep in mind the old japanese magician with bowl of fish between his legs. We get a clue to the plot behind the film in that. "He is always doing the act, it never stops", this means he is always carrying that bowl between his legs...for the show. You got that...we later find that this is exactly what Borden does, he always switched roles. That is why he writes, he sometimes knows that he killed her and other times that he knows he did not. Which leaves us with the realisation that there is 2 Bordens. I always asumed this was just Bordens twin brother and that they masqueraded the whole thing. Very elaborate. It would also indicate why he was sometimes longing for his family and sometimes for the mistress, why 2 different persons, but very dedicated to the act(fishbowl)... Then it struck me, Angier read about Tesla in Bordens diary, borden went to Tesla for a machine, a machine that always worked. Did borden use the machine on himself, leave the studio after thinking it failed and then found himself in the forest? The only difference is he didnt kill himself like Angier, but conceived of the idea for the act. I will also theorise that it is the new Borden who shunned his family for the mistress, why...he could never be with the family he so desperately wanted to be with.
So what do you think...is Borden a clone or a twin...difficult to hide a twin for all those years.

A: If we are going by the books the answer is simple. In the books Angier dies and a dead body is left under the machine. The clone is not the original and Angier died the first time he used it. In the  movies no one dies. Angier is cloned and the clone is teleported near by but out of site.
When they first test the machine on the hat, the hat is still under the machine meaning that the original stays right there. Hence the need for the trap door. The original always falls through the trap door and is the one to always die. The clone is on the balcony.
And no they are all not the the original. One of them is a duplication. They may have the same memories and personalities but one is a duplicate personality and has its own soul.


text:
Q: How to extract URI argument result from deeplink navigation My goal is to extract the URI that was passed to my navController to navigate to destination B
so from A I do this
navController.navigate("myApp://destination")

From B I want to get this "myApp://destination" uri, this is because extra logic needs to be done after going to B from A, for this, I don't want to use any arguments in the navGraph
So after debugging I see that I can access mData from arguments and see the uri

Is there a way I can retrieve this URI from Fragment B ?
Problem from the above scenario is that I don't have the type or key to extract that uri from the arguments object without explicitly sending it myself
For external deeplinks opening the app it is working with activity.intent.data but for this in-app navigation I don't find a way to get this URI
A workaround could be sending it as parameter string from navigate() method and then get that from fragment B , but I want to know if there is a better way of doing it without involving writing an argument tag inside the navigation graph and add more code for it.


text:
Q: Htaccess redirecting wrong page here is my htaccess code
# Enable rewrite engine
RewriteEngine On
RewriteBase /

RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)\.php$ view-product.php?catSeoUrl=$1&subCatSeoUrl=$1&productSeoUrl=$3 [QSA,L]
RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)\.php$ products.php?catSeoUrl=$1&subCatSeoUrl=$1 [QSA,L]
RewriteRule ^([a-zA-Z0-9-]+)\.php$ products.php?catSeoUrl=$1 [QSA,L]

the second & third rules are working fine. Please have a look here
http://domain.tdl/consumer-electronics/mobiles.php
http://domain.tdl/consumer-electronics.php
but the First Rule for view Product also redirecting to products.php, have a look.
http://domain.tdl/consumer-electronics/mobiles/product-6.php
its strange, can you please help me to resolve this?

A: As soon as the third rule is applied then automatically the third rule gets applied too, since its pattern matches the target of the first rule.
With the apache http server from version 2.4 onwards you can use the END flag instead of the L flag to prevent that:
RewriteEngine On
RewriteBase /

RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)\.php$ view-product.php?catSeoUrl=$1&subCatSeoUrl=$1&productSeoUrl=$3 [END]
RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)\.php$ products.php?catSeoUrl=$1&subCatSeoUrl=$1 [END]
RewriteRule ^([a-zA-Z0-9-]+)\.php$ products.php?catSeoUrl=$1 [END]

For older apache versions you need to add rewrite conditions:
RewriteEngine On
RewriteBase /

RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)\.php$ view-product.php?catSeoUrl=$1&subCatSeoUrl=$1&productSeoUrl=$3 [END]
RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)\.php$ products.php?catSeoUrl=$1&subCatSeoUrl=$1 [END]
RewriteCond %{REQUEST_URI} ^([^\]+)\.php$
RewriteRule ^([a-zA-Z0-9-]+)\.php$ products.php?catSeoUrl=$1 [END]

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only supported as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


text:
Q: Can WebOptimizer be used with Single-File Application I'm currently unable to use the WebOptimizer with a single-file web-app (asp.net Core 6). I've used WebOptimizer in the past, I've created single-file applications in the past... I just can't get them to work together. If I use the bundler like:
// Add the bundler...
builder.Services.AddWebOptimizer(pipeline =>
{
    pipeline.AddJavaScriptBundle("~/js/myBundle.js","js/views/js1.js", "js/views/js2.js", "js/main.js");
});

And the file provider is:
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new EmbeddedFileProvider(
        assembly: Assembly.GetExecutingAssembly(),
        baseNamespace: "MyApp.wwwroot"),
})

And in the csproj file I have:
<ItemGroup>
    <Content Update="wwwroot\**" ExcludeFromSingleFile="false">
        <CopyToOutputDirectory> Always </CopyToOutputDirectory>
    </Content>
    <EmbeddedResource Include="wwwroot\**\*" />
  </ItemGroup>

Each time a page tries to load the bundle I get a warning:
warn: WebOptimizer.AssetBuilder[1005]
File '/js/myBundle.js' not found. Passing on to next middleware.
All the other resources under wwwroot are found in the EmbeddedFileProvider route, just not the ones put in the pipeline by WebOptimizer. It seems like it's close...I just can't find the right route.

A: Be sure set the EnableCompressionInSingleFile property to true:
<PropertyGroup>
    //......
    <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
 </PropertyGroup>

Reference:
https://learn.microsoft.com/en-us/dotnet/core/deploying/single-file/overview?tabs=cli#compress-assemblies-in-single-file-apps


text:
Q: Apigility and oAuth for users I'm about to start working on application with rest API and I want to use apigility. There is one problem unfortunately with this idea. I cannot find reliable source of information how to allow for authentication by oAuth for regular users.
I need to provide access for angular app and native mobile one (possibly in future for third-party web apps). All resources that I have found are about granting access to api for specific client application, not for specific users that use this applications. I don't want to implement two different authentication methods, so if there is a way to resolve this issue with apigility it would be great.
Do you have any suggestions how to approach this? I know that I can generate client id and secret for all registered users but this seams a little crappy solution and I have database schema already in place for storing user info.

A: What you're likely looking for is the "password" grant type. In this scenario, you will have a way of registering users and their passwords, and then a "login" screen of sorts. This login screen will send the following information:

*

*username

*password

*client_id -- this will be the OAuth2 client ID (not the user ID!) for the application

*"grant_type": "password"

Note that you are NOT providing the client_secret in this scenario! In the case of a user credential scenario, the user's credentials are validated, and then the server verifies that the client_id supports this grant type.
If the user provides successful credentials, then the OAuth2 endpoint will return a token, a TTL, and a refresh_token (which, if you send it before the TTL expires, will give you a new set of tokens).
From here, you will then send the token in the Authorization header: "Authorization: Bearer ". Apigility will then pick this up on each request and validate the token.
The validation returns also the username as part of the identity. This means that you can query the ZF\Mvc\Identity to retrieve the user in order to perform user-specific ACL assertions later!
Poke me on the mailing list (http://bit.ly/apigility-users) if you need some more direction.


text:
Q: How do you convert mixed fractions to decimal? How do I convert "1 1/4" to 1.25?
I want to take user input and convert it to the logical numerical equivalent.  I say logical because 2 R and R 2 need to be 2(has to do with measuring chiropractic adjustments).  Everything worked until they needed to be able to use mixed fractions.
Is there a library for this?
The only number that does not work is "1 1/4" which is converted in error to "2.75".
    // Sample input
    var values = ["2.5", "1 1/4", "1/4", "2 R", "R 2"];

    function l(msg) {
        console.log(msg)
    }

    function toDecimal(x) {
        if (x.indexOf('/') != -1) {
            var parts = x.split(" ")
            var decParts = parts[1].split("/")
            return parseInt(parts[0], 10) + (parseInt(decParts[0], 10) / parseInt(decParts[1], 10))
        } else {
            return x
        }
    }

    function total_it_up(values){
        var total = 0,
            value = 0

        if(values === undefined)
            return 0

        $.each(values, function(index, value){
            value = value.replace(/[^0-9./]+/g, "")
            value = eval(value)
            l(value)
            total += parseFloat(value)
        })

        return total
    }

SOLUTION
    function toDecimal(x) {
        if (x.indexOf('/') != -1) {
            var parts = x.split(" ")
            var decParts;
            if (parts.length > 1) {
                decParts = parts[1].split("/");
            }
            else {
                decParts = parts[0].split("/");
                parts[0] = 0;
            }
            return parseInt(parts[0], 10) + (parseInt(decParts[0], 10) / parseInt(decParts[1], 10))
        } else {
            return x
        }
    }

    function total_it_up(values){
        var total = 0;

        if(values === undefined)
            return 0;

        $.each(values, function(index, value){
            total += parseFloat(toDecimal($.trim(value.replace(/[^0-9./ ]+/g, ""))));
        })

        return total;
    }

A: We don't see any call for toDecimal(), so I'm assuming the $.each loop is calling it in your original code. If that is the case, then 1 1/4 is coming up as 2.75 because the regular expression is stripping the space between 1 and 1/4, resulting in 11/4, which is 2.75. Allow spaces, but $.trim the result so that any leading or trailing spaces are removed. You also shouldn't have to use eval().

A: I accidently posted perl instead of JS before. Here is the correct one. Please do the cleaning.
Example
    <html>
  <body>
    <script language=javascript>

 var txt='4 1/2';

      var re1='(\\d+)'; // Integer Number 1
      var re2='.*?';    // Non-greedy match on filler
      var re3='(\\d+)'; // Integer Number 2
      var re4='.*?';    // Non-greedy match on filler
      var re5='(\\d+)'; // Integer Number 3

      var p = new RegExp(re1+re2+re3+re4+re5,["i"]);
      var m = p.exec(txt);
      if (m != null)
      {
          var int1=m[1];
          var int2=m[2];
          var int3=m[3];
          document.write("("+int1.replace(/</,"<")+")"+"("+int2.replace(/</,"<")+")"+"("+int3.replace(/</,"<")+")"+"\n");
      }
    </script>
  </body>
</html>

A: This is terrible.
function ConvertFraction(fraction)
{
     eval(fraction.replace('R','').trim().replace(' ', '+'))
}


text:
Q: AttributeError: 'set' object has no attribute 'items', upon trying to train an xgboost model in AWS Sagemaker Here's the code that comes before the error:
from sagemaker.estimator import Estimator
from sagemaker.debugger import rule_configs, Rule, DebuggerHookConfig, CollectionConfig

sess = sagemaker.Session()
region = boto3.Session().region_name

container = retrieve('xgboost', region, 'latest')

save_interval = '1'

xgb = Estimator(
    container,
    role=sagemaker.get_execution_role(),
    sagemaker_session = sess,

    input_mode = 'File',
    output_path = 's3://{}/{}/output'.format(bucket, prefix),

    instance_count = 1,
    instance_type='ml.m4.2xlarge',

    use_spot_instances=True,
    max_run=300,
    max_wait=600,

    debugger_hook_config=DebuggerHookConfig(
        s3_output_path='s3://{}/{}/debug'.format(bucket, prefix),
        collection_configs=[
            CollectionConfig(
                name='metrics',
                parameters={'save_interval: save_interval'}
            ),
            CollectionConfig(
                name='feature_importance',
                parameters={'save_interval':save_interval}
            )
        ],
    ),

    rules=[
        Rule.sagemaker(
            rule_configs.class_imbalance(),
            rule_parameters={'collection_names':'metrics'}
        ),
    ]
)
xgb.set_hyperparameters(
    objective='binary:logistic',
    evat_metric='auc',
    num_round=100,
    early_stopping_rounds=10
)
xgb.fit({'train': s3_input_train, 'validation': s3_input_validation})

And here's the error
AttributeError                            Traceback (most recent call last)
<ipython-input-14-ef76c474a8e7> in <module>
----> 1 xgb.fit({'train': s3_input_train, 'validation': s3_input_validation})

/opt/conda/lib/python3.7/site-packages/sagemaker/workflow/pipeline_context.py in wrapper(*args, **kwargs)
    270             return _StepArguments(retrieve_caller_name(self_instance), run_func, *args, **kwargs)
    271
--> 272         return run_func(*args, **kwargs)
    273
    274     return wrapper

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in fit(self, inputs, wait, logs, job_name, experiment_config)
   1125             :class:`~sagemaker.workflow.pipeline_context.PipelineSession`
   1126         """
-> 1127         self._prepare_for_training(job_name=job_name)
   1128
   1129         experiment_config = check_and_get_run_experiment_config(experiment_config)

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in _prepare_for_training(self, job_name)
    753
    754         self._prepare_rules()
--> 755         self._prepare_debugger_for_training()
    756         self._prepare_profiler_for_training()
    757

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in _prepare_debugger_for_training(self)
    892             self.debugger_hook_config.s3_output_path = self.output_path
    893         self.debugger_rule_configs = self._prepare_debugger_rules()
--> 894         self._prepare_collection_configs()
    895         self._validate_and_set_debugger_configs()
    896

/opt/conda/lib/python3.7/site-packages/sagemaker/estimator.py in _prepare_collection_configs(self)
    934         # Add the CollectionConfigs from DebuggerHookConfig to the set.
    935         if self.debugger_hook_config:
--> 936             self.collection_configs.update(self.debugger_hook_config.collection_configs or [])
    937
    938     def _prepare_profiler_for_training(self):

/opt/conda/lib/python3.7/site-packages/sagemaker/debugger/debugger.py in __hash__(self)
    897     def __hash__(self):
    898         """Hash method override."""
--> 899         return hash((self.name, tuple(sorted((self.parameters or {}).items()))))
    900
    901     def _to_request_dict(self):

AttributeError: 'set' object has no attribute 'items'
I have absolutely no idea what the issue is and I dont know how to go about finding out, you guys are my last hope, thanks.


text:
Q: Fire off event after job-chain has "finished" I have below Listener called ProcessDocumentFields. My listener class implements the ShouldQueue.
In this, I fire off two jobs by using the withChain method as below:
ParseFieldContent::withChain([
        new ParseFieldRules($event->document, $fields),
])->dispatch($event->document, $fields);

Now, I want to conditionally fire off an event, which ultimately trigger another job.
The thing is, both jobs (ParseFieldContent and ParseFieldRules) must have finished running.
#If below is true, fire off
if ($event->document->stream->settings()->get('field_routing')) {
   event(new DocumentDefaultRulesWasProcessed($event->documents));
}

The above event, will trigger the same two jobs, but I have to do some other checks first:
#EventServiceProvider.php
DocumentDefaultRulesWasProcessed::class => [
     ProcessDocumentRouteFields::class,
],

Inside my ProcessDocumentRouteFields, I have:
foreach ($event->routes as $route) {
        if ($this->assertIfRouteFieldsShouldBeHandled($route, $event->document)) {
            ParseFieldContent::withChain([
                new ParseFieldRules($event->document, $route->fields, false),
            ])->dispatch($event->document, $route->fields);
        }
}

As you can see in above, I run the two same jobs (ParseFieldContent and ParseFieldRules) - but only if a certain assertion is true.
My question is: how can I ensure, that the jobs placed in ProcessDocumentFields runs first, then when the `` event is being fired,  the jobs in ProcessDocumentRouteFields will run?

A: On first thought, you could set some sort of indicator, either by caching or DB, which is used to check if the ProcessDocumentFields jobs are processing/running.
Then, in your ProcessDocumentRouteFields, you check to see if the job is still processing/running.
The cache method would look something like:
if (cache('processing_job')) {
    return;
}

foreach ($event->routes as $route) {
        if ($this->assertIfRouteFieldsShouldBeHandled($route, $event->document)) {
            ParseFieldContent::withChain([
                new ParseFieldRules($event->document, $route->fields, false),
            ])->dispatch($event->document, $route->fields);
        }
}

Please note that when caching, it must be set to enough time to execute the jobs.
cache('processing_job', true, now()->addMinutes(20));

You can then remove the key/value pair after all is completed (place at the end of job script):
Cache::forget('processing_job');

After this, the next time the cache check is performed, the cache helper will return false and process the other jobs.
I hope this helps.


text:
Q: Difference between initramfs.cpio and rootfs.cpio What are the differnces between the two?
Can I just use initramfs.cpio or do I need to use both?
Actually my rootfs.cpio file is 7 Mb and initramfs.cpio is just 0.5mb, so I was thinking if I can use initramfs.cpio only or not

A: It all depends on what you are trying to accomplish.
Rootfs is a special instance of ramfs (or tmpfs, if that's enabled).
Most systems just mount another filesystem over rootfs and ignore it.  The
amount of space an empty instance of ramfs takes up is tiny.
Linux kernels contain a gzipped "cpio" format archive, which is
extracted into rootfs when the kernel boots up.  After extracting, the kernel
checks to see if rootfs contains a file "init", and if so it executes it as PID
1.  If found, this init process is responsible for bringing the system the
rest of the way up, including locating and mounting the real root device (if
any).  If rootfs does not contain an init program after the embedded cpio
archive is extracted into it, the kernel will fall through to the older code
to locate and mount a root partition, then exec some variant of /sbin/init
out of that.


text: Q: How to make a car go down a ramp at contest velocity even when the angle of the ramp is changed This is a high school project, I need to make a car go down a ramp at a contest velocity even when the angle of the ramp is changed, I was hoping if anyone could help me, figure out some way of doing this.


text:
Q: OnNmeaMessageListener is not working even when called using the addNmeaListener This is the Interface which I'm using to get the Nmea and the altitude but when the onNmeaMessageListener is being called it does not execute it. I'm calling it using gpsManager which is  LocationManager variable,
the code neither works nor shows up as an error.
OnNmeaMessageListener onNmeaMessageListener = (nmea, timestamp) -> {
    Log.d("TrackManager", " NMEA : " + nmea + " TimeStamp : " + timestamp);
    if (trackStarted && !trackPaused) {
        if (nmea.startsWith("$GPGGA") || nmea.startsWith("$GPRMC")) {
            Log.d("TrackManager", "NMEA:" + nmea);
            try {
                out.write(nmea.getBytes());
                if (continuesMode) {
                    dataOut.write(nmea.getBytes());
                    bufferedNMEALines++;
                    if (bufferedNMEALines >= 10) {
                        flushContinuesTrack();
                        //dataOut.reset();
                        bufferedNMEALines = 0;
                    }
                } else {
                    outCompressed.write(nmea.getBytes());
                }
                // Log.d("TrackManager","NMEA:" + nmea);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (nmea.startsWith("$GPGGA")) {
                String[] nmeaSplit = nmea.split(",");
                if (nmeaSplit.length > 10) {
                    if (nmeaSplit[9].length() > 0) {
                        try {
                            mslAltitude = Float.parseFloat(nmeaSplit[9]);
                        } catch (NumberFormatException ex) {
                            mslAltitude = 0;
                        }
                    } else {
                        mslAltitude = 0.0f;
                    }
                }
            }
        }
    }

    if (markStarted && hasFix() && nmea.startsWith("$GPRMC")) {
        markProgress++;

        trackListener.onMarkProgress(markProgress);
        if (markProgress >= markMax) {
            stopMark();
        }
    }
};

This is how I'm calling it
gpsManager.addNmeaListener(onNmeaMessageListener);

EDIT
Declaration:
private LocationManager gpsManager;

Initialized in onCreate like so:
gpsManager = (LocationManager)
getSystemService(LOCATION_SERVICE);

Also got Location updated:
gpsManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
GPS_UPDATE_TIME, 0, gpsListener);

A: NMEA strings come from live GPS receivers; they're not cached by the OS. LocationManager.PASSIVE_PROVIDER is not going to turn on the GPS, so that choice of provider is inappropriate for this use case. Try GPS_PROVIDER instead.


text:
Q: Event 'kernel.request' doesn't dispatch correctly I'm trying tu use LexikJWTAuthBundle with FOSRestBundle to securize my API routes.
It works well when I manually give the JWT in the header of my requests, but for my app I would like to add it automatically in each API requests' header via the 'kernel.request' SF event.
The problem is that my event subscriber seems to not be dispatch correctly, I suppose that LexikJWTAuthBundle detect before that I don't have any JWT in my request and return me 401 responses.
The event subscriber :
<?php

namespace MyApp\APIBundle\EventListener;

use MyApp\APIBundle\Controller\TokenAPIController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RequestAPIListener implements EventSubscriberInterface
{
    /**
     * @var string Token API
     */
    private $apiToken;

    public function __construct(string $apiToken = null)
    {
        $this->apiToken = $apiToken;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        // dump('hi'); <---- This is execute when uncomment
        // die;
        return [
            KernelEvents::REQUEST => [
                'onRequest'
            ]
        ];
    }

    public function onRequest(GetResponseEvent $event)
    {
        dump($event, $this->apiToken); <---- This is not execute
        die;

        $request->headers->set('Authorization', "Bearer $token");
    }
}

The event subscriber definition :
services:
    myapp.api_bundle.event_listener.request_api:
        class: MyApp\APIBundle\EventListener\RequestAPIListener
        arguments: ['@=service("service_container").get("session").get("api_token")']
        tags:
            - { name: kernel.event_subscriber }

How can I solve this ? Or maybe if you know another way to add automatically the token ?

A: The problem was just the priority of my custom listener.
The Firewall listener was triggered before mine, so I set a priority higher for mine :
public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => [
                ['onRequest', 10]
            ]
        ];
    }


text:
Q: Powershell: Look for a folder name using a variable that will have a different value and length every time I have found answers all around this, but not quite what I am looking for. I'm not a programmer, so adjusting very complicated scripts has proven difficult.
Periodically we are provided a .zip file.  The filename (before the .zip extension) will be different most of the time. It could be letters or numbers, and vary in length.
I already have a PowerShell script that unzips the contents of the file into a folder named after the file (because the contents originally were in a folder with that name), using Windows' native unzip technology.  It then distributes the folder where it needs to go, then moves the folder to an "already deployed" folder, and then cleans up by deleting the .zip.  That all works great.
The problem is, sometimes the destination already contains a folder with the same name, so we want that backed up first.  I need PowerShell to see check or not there is a folder with that name, then copy it to a "rollback" folder.
I currently have a script that does all of this, but it uses an array (that I found) that assumes the filename always will contain 9 characters. I would like my script to just look at the foldername that was already created from the unzip process, rather than the filename.  Or, for the existing array to lop off the last four characters (.zip) instead of always utilizing the first nine.  Make sense?
Here is what I have right now:
# Following code sets variables

$filelocation = dir d:\admin\Type\files\*.zip
foreach ($file in $filelocation){
$filename = $file.name.ToString()
$shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace("d:\admin\Type\files\$filename")
$destination = $shell_app.namespace("d:\admin\Type\files\")

#Following line unzips the file

$destination.Copyhere($zip_file.items())
}

# Following chunk of code (that I found) converts the .zip filename to a string variable we can use in our Test-Path to see whether the folder already exists.
# NOTE: Right now it uses only the first 9 characters, but I would like it to only use the basename of the above zip file
# Or we could have it look at the name of the folder that results from the unzip (which always will match the basename of the .zip file)

$Directory = "d:\admin\Type\files";
$AllFiles = Get-ChildItem $Directory | where {$_.extension -eq ".zip"};
$FileNames = New-Object System.Collections.ArrayList;
foreach($File in $AllFiles)
{
    $FileNames.Add($File.Name.SubString(0,9));
}

# The above code loses me a bit, because it was written for someone whose filename will always be nine characters, and can handle multiple files.
# Ours rarely will be more than one file, and will vary in length.

# Following code says "if the folder exists in the website structure, back it up to the group.backups folder"

if(Test-Path -path "D:\acronym\CurrentVersion\website.acronym\Type\Brands\$Name")
{
Copy-Item D:\acronym\CurrentVersion\website.acronym\Type\Brands\$Name D:\group.backups\Type\Brands\ -force -recurse
}

# Following line removes the original .zip file from the files folder

Remove-Item d:\admin\Type\files\*.zip -force

# Following chunk of code copies the folder and its contents to the web server folder structure

Copy-Item d:\admin\Type\files\$Name D:\acronym\CurrentVersion\website.acronym\Type\Brands\ -force

# Following lines copy the folder and its contents to the completed folder
# and then removes the folder and its contents from the files folder (for some reason Move-Item was only moving the files)
# The files folder alway should be completely empty after this script finishes

Copy-Item d:\admin\Type\files\* D:\admin\Type\completed\ -force -recurse

Remove-Item d:\admin\Type\files\* -force -recurse

A: I can't give you a specific answer (not enough details provided), but Powershell has some very good built-in Help.
If you run these commands and read the help provided you should at least have enough information to get you started.
 Get-Help Test-Path -Full
 Get-Help Move-Item -Full


text:
Q: Como hacer una Consulta SQL que haga que todo los meses sean de 30 días Estoy tratando de realizar una consulta SQL, que haga el conteo de dos campos de fechas, la cuestión es que me están pidiendo que todos los meses se cuenten como si tuvieran todos 30 días.
He estado utilizando datediff para hacer el conteo de días, pero tengo el problema con eso de que todos los meses sean de 30 días, también he intentado agregar IF a la consulta pero no he podido realizar una consulta que funcione correctamente.

En la imagen muestro los dos campos de fechas, el campo cirrus es el conteo que debe haber en fechas y el campo DIAS es la consulta que he realizado y me arroja ese resultado
Este es el código que tengo hasta ahora
SELECT desde,hasta,cirrus, IF(datediff(hasta,desde)=30,30,IF(MONTH(desde)=2 AND day(hasta)>= 28,datediff(hasta,desde) +3 ,IF(MONTH(hasta) = 3 AND MONTH(desde) = 2 AND YEAR(desde) = 2020, datediff(hasta,desde)+2,IF(MONTH(hasta) = 3 AND MONTH(desde) = 2,datediff(hasta,desde)+3 ,IF(MONTH(desde)=1 AND MONTH(hasta)= 2,datediff(hasta,desde)+2, IF(MONTH(desde)=1 AND MONTH(hasta)= 3 AND YEAR(desde) = 2020 ,datediff(hasta,desde),IF(MONTH(desde)=12 AND MONTH(hasta)=2,datediff(hasta,desde)-1,IF(MONTH(hasta)=12 AND day(hasta)=31,datediff(hasta,desde),IF(MONTH(desde)=11 AND MONTH(hasta)=1,datediff(hasta,desde),IF(MONTH(desde)=1 AND MONTH(hasta)=3 AND DAY(hasta)<=27,datediff(hasta,desde)+1,datediff(hasta,desde)+1 )))))))))) AS DIAS FROM tmp

Estoy probando utilizar el CASE de la primer respuesta pero aun no logro que funcionen todas las fechas este es el código que voy
SELECT *,
 IF(month(desde) = month(hasta) AND diasmesuno = 30 AND diasmesdos = 30,
 diasmesdos,
    IF(month(desde) < month(hasta) AND year(desde) = year(hasta) AND (day(desde) - day(hasta) = 1),
       diasmesuno + day(hasta) + 1,
       IF(month(desde) < month(hasta) AND year(desde) = year(hasta) AND (day(hasta) - day(desde) = 1),
       diasmesuno + day(hasta) + 1,

          IF(month(desde) > month(hasta) AND year(hasta) = 2021 AND (day(hasta) - day(desde) = 1) and (month(desde) = 12),
       (diasmesuno + day(hasta) + 1) + ((month(hasta)-1) * 30) ,

               IF(month(desde) > month(hasta) AND year(hasta) = 2021 AND (day(desde) - day(hasta) = 1) AND (month(desde) = 12),
       (diasmesuno + day(hasta) + 1)  + ( ( month(hasta) - 1 ) * 30) ,

    IF(month(desde) = month(hasta) AND diasmesuno = 30  AND diasmesdos < 30 ,
    diasmesdos,
    IF(month(desde) = month(hasta),
    (diasmesdos - day(desde) + 1),
    IF(month(hasta) > month(desde) AND diasmesuno = 30 AND diasmesdos = 30,
       (((month(hasta) - month(desde)) = 2) * 30) + diasmesuno + diasmesdos,
           IF(month(hasta) > month(desde),
              (((month(hasta) - month(desde)) = 2) * 30) + diasmesuno + diasmesdos,
                IF(year(hasta) = 2021 AND (month(desde) < 12) AND (year(desde) = 2020)  AND diasmesdos = 30                   AND diasmesuno = 30,
                    ((12 - (month(desde))) * 30) + (month(hasta) * 30) + diasmesuno,

      IF((year(hasta) = 2021) AND (year(desde) = 2020) AND (month(hasta) < 30) AND (month(desde) = 12),
        diasmesuno + day(hasta) + (( month(hasta)-1) * 30),

      IF((year(hasta) = 2021) AND (year(desde) = 2020) AND (month(hasta) < 30),
                 diasmesuno + day(hasta) + (( month(hasta)-1) * 30) + ((12 - month(desde)) * 30),

         IF(year(hasta) = 2021 AND (month(desde) < 12) AND (year(desde) = 2020)  AND diasmesdos = 30                   AND diasmesuno = 30,
                    ((12 - (month(desde))) * 30) + (month(hasta) * 30) + diasmesuno,

               IF(month(desde) < month(hasta) AND  year(hasta) = 2021 AND (day(desde) - day(hasta) = 1),
     ((12 - (month(desde))) * 30) + (month(hasta) * 30) + diasmesuno + 1,

       diasmesuno + diasmesdos)))))))))))))) as dias
FROM   (SELECT CASE
                 WHEN Day(desde) <
                      -- si es febrero el límite sería 28 o 29
                      -- si es otro mes entonces 30
                      ( CASE
                          WHEN Month(desde) = 2 THEN (SELECT
                          Day(Last_day(desde)))
                          ELSE 30
                        end ) THEN
               -- si es día 1 incrementar límite a 31 para incluir el mes completo
               CASE
                 WHEN Day(desde) = 1 THEN 31
                 ELSE 30
               end - Day(desde)
                 ELSE 30
               end diasMesUno,
               CASE
                 WHEN Day(hasta) <
                      -- si es febrero el límite sería 28 o 29
                      -- si es otro mes entonces 30
                      ( CASE
                          WHEN Month(hasta) = 2 THEN (SELECT
                          Day(Last_day(hasta)))
                          ELSE 30
                        end ) THEN Day(hasta)
                 ELSE 30
               end diasMesDos,
               CASE
                 WHEN ( Month(hasta) - Month(desde) ) - 1 > 0 THEN (
                 Month(hasta) - Month(desde) - 1 ) * 30
                 ELSE 0
               end AS diferenciaMeses,desde,hasta,cirrus
        FROM   tmp) AS fechas_30dias

El resultado esperado es el siguiente, en el campo cirrus sale los dias que la empresa necesita que sea el resultado, en el campo dias es el resultado de la consulta

A: La función DateDiff existe para el caso complejo del calendario real. Si todos los meses son de 30 días, la aritmética es bien sencilla y puedes hacerla tu mismo.
La lógica sería algo como:

*

*Si ambas fechas están en el mismo mes, retornar la diferencia de días

*Si no sumar:

*

*30 - el día de inicio (que son los días transcurridos el primer mes)

*más el día final (que son los días transcurridos del último mes). Tener en cuenta que si el día final es 31, se deben sumar solamente 30 días.

*más el número de meses intermedios multiplicados por 30

Con una estructura y datos como estos:
CREATE TABLE fechas
  (
     fecha1 DATE,
     fecha2 DATE
  );

INSERT INTO fechas VALUES ('2020-01-02', '2020-01-26');
INSERT INTO fechas VALUES ('2020-01-01', '2020-03-31');
INSERT INTO fechas VALUES ('2020-01-15', '2020-03-05');
INSERT INTO fechas VALUES ('2015-10-24', '2020-03-05');
INSERT INTO fechas VALUES ('2018-10-24', '2019-10-24');
INSERT INTO fechas VALUES ('2018-10-24', '2020-10-24');
INSERT INTO fechas VALUES ('2018-12-24', '2019-01-24');

Esta consulta:
select   *
       , case
           when Year(Fecha2) = Year(Fecha1) and Month(Fecha2) = Month(Fecha1) then Day(Fecha2) - Day(Fecha1)
           else
                30 - day(fecha1)
              + case
                  when day(fecha2) = 31 then 30
                  else day(fecha2)
                end
              /* cálculo de meses */
              + case
                  when Year(Fecha2) = Year(Fecha1) then Month(Fecha2) - Month(Fecha1) - 1
                  else   12 - Month(Fecha1)
                       + Month(Fecha2) - 1
                       + (Year(Fecha2) - Year(Fecha1) - 1) * 12
                end * 30
         end dias
  from fechas;

Devuelve los siguientes resultados
| fecha1     | fecha2     | dias |
| ---------- | ---------- | ---- |
| 2020-01-02 | 2020-01-26 | 24   |
| 2020-01-01 | 2020-03-31 | 89   |
| 2020-01-15 | 2020-03-05 | 50   |
| 2015-10-24 | 2020-03-05 | 1571 |
| 2018-10-24 | 2019-10-24 | 360  |
| 2018-10-24 | 2020-10-24 | 720  |
| 2018-12-24 | 2019-01-24 | 30   |

A: La consulta está dividida en dos partes, la primera es una consulta que calcula los días que faltan para llegar al día 30 en la fecha1 haciendo corrección para el mes de febrero, y calcula los días que van de la fecha2. También calcula los meses entre ambas fechas.
La segunda parte es una consulta superior que se encarga de sumar los días de la fecha1 más los días de la fecha2 y los días de los meses entre esas dos fechas. También evalúa el caso cuando ambas fechas están en el mismo mes.
CREATE TABLE fechas
  (
     fecha1 DATE,
     fecha2 DATE,
     dias   INT
  );

INSERT INTO fechas
VALUES     ('2020-01-02',
            '2020-01-26',
            0);

INSERT INTO fechas
VALUES     ('2020-01-01',
            '2020-03-31',
            0);

INSERT INTO fechas
VALUES     ('2020-01-15',
            '2020-03-05',
            0);

SELECT *,
       CASE
         WHEN diferenciameses = 0 THEN diasmesdos - ( 30 - diasmesuno )
         ELSE diasmesuno + diasmesdos
       end AS dias
FROM   (SELECT CASE
                 WHEN Day(fecha1) <
                      -- si es febrero el límite sería 28 o 29
                      -- si es otro mes entonces 30
                      ( CASE
                          WHEN Month(fecha1) = 2 THEN (SELECT
                          Day(Last_day(fecha1)))
                          ELSE 30
                        end ) THEN
               -- si es día 1 incrementar límite a 31 para incluir el mes completo
               CASE
                 WHEN Day(fecha1) = 1 THEN 31
                 ELSE 30
               end - Day(fecha1)
                 ELSE 30
               end diasMesUno,
               CASE
                 WHEN Day(fecha2) <
                      -- si es febrero el límite sería 28 o 29
                      -- si es otro mes entonces 30
                      ( CASE
                          WHEN Month(fecha2) = 2 THEN (SELECT
                          Day(Last_day(fecha2)))
                          ELSE 30
                        end ) THEN Day(fecha2)
                 ELSE 30
               end diasMesDos,
               CASE
                 WHEN ( Month(fecha2) - Month(fecha1) ) - 1 > 0 THEN (
                 Month(fecha2) - Month(fecha1) - 1 ) * 30
                 ELSE 0
               end AS diferenciaMeses
        FROM   fechas) AS fechas_30dias

A: Si todos los meses son de 30 días únicamente habría que preocuparse por los meses que no, que exceptuando febrero tienen 31 y por lo tanto se les compensa restando un día, y a febrero se le compensa sumado dos, o uno cuando es bisiesto. Entonces, creando una vista (en memoria) de esas fechas y su respectivo número de días de compensación, para después contar cuántos días de compensación existen en cada intervalo de fechas.
SELECT f.desde
     , f.hasta
     , datediff(f.hasta,f.desde) dias
     , ( SELECT ifnull(sum(compensaciones.compensacion),0)
           FROM ( SELECT cast( concat_ws('-',a.anio, md.mes, md.dia) as date) fecha
                       , md.compensacion
                    FROM ( SELECT year(desde) anio FROM fechas
                           UNION
                           SELECT year(hasta) FROM fechas
                           GROUP BY 1
                         ) a
                      JOIN ( SELECT 01 mes, 31 dia, -1 compensacion UNION
                             SELECT 02, 28, +2 UNION
                             SELECT 02, 29, -1 UNION
                             SELECT 03, 31, -1 UNION
                             SELECT 05, 31, -1 UNION
                             SELECT 07, 31, -1 UNION
                             SELECT 08, 31, -1 UNION
                             SELECT 10, 31, -1 UNION
                             SELECT 12, 31, -1
                           ) md
                ) compensaciones
           WHERE compensaciones.fecha between f.desde and f.hasta
       ) comp
     , ( SELECT dias+comp+1 ) cirrus
  FROM fechas f;

A: Primeramente comentarte que en tu programa, en el intervalo de fechas desde 2021-01-15 hasta 2021-03-05, cirrus devuelve 50 días y creo que deberían ser 51 (16 días de enero + 30 días de febrero + 5 días de marzo).
Te dejo mi código en sql para oracle por si te ayuda.
Saludos!
select (años - dias_ini - dias_fin + 1) total_dias

  from

   (select (extract (year from hasta) - extract (year from desde) + 1) * 12 * 30 años,

           (extract (month from desde) - 1) * 30
            +
           case
              when (extract (day from desde) = 31) or
                   (extract (month from desde) = 2 and extract (day from desde) > 27)
              then 30
              else extract (day from desde)
           end dias_ini,

           (12 - (extract (month from hasta)) + 1) * 30
            -
           case
              when (extract (day from hasta) = 31) or
                   (extract (month from hasta) = 2 and extract (day from hasta) > 27)
              then 30
              else extract (day from hasta)
           end dias_fin

  from tabla_fechas

   )

tabla_fechas es una tabla con 2 campos, desde y hasta, de tipo DATE que contienen las fechas.


text:
Q: Always listen to window screen changes How do I make the code always respond to the changes in screen size?
I remember there is one globalEventHandler can do this but I'm not sure which one...
For example, the div#test-02 will always automatically adjust its width to 1/3 of the div#test-01. The problem is that as we use the developer tool (f12) to resize the window, the width of div#test-01 is keep changing but the code won't respond to it anymore...Unless we reload the page...

const test01 = document.querySelector('#test-01');
const test02 = document.querySelector('#test-02');
const data = test01.getBoundingClientRect().width;

test02.style.width = `${data / 3}px`;
#test-01 {
  width: 100vw;
  height: 50vh;
  background-color: grey;
  display: flex;
  justify-content: center;
  align-items: center;
}

#test-02 {
  height: 100%;
  background-color: orange;
}

A: To listen for window screen changes, you can use
window.addEventListener("resize", callback)

This will listen for resize events on the window, and execute the callback function if such an event occurs. So you could put the code which resizes your elements relative to each other into the callback, so that it is executed on every window resize. (The callback will not be run on page load, so you would have to run your code outside of the event handler once too.)
The following code should work in your case:
const test01 = document.querySelector('#test-01');
const test02 = document.querySelector('#test-02');

function onResize() {
  const data = test01.getBoundingClientRect().width;
  test02.style.width = `${data / 3}px`;
}

window.addEventListener("resize", onResize, {passive: true})
onResize()


text:
Q: album art with cursor and base adapter not showing in list or toast album art with cursor and base adapter not showing in list or toast
i am trying to display the album art and album details in a listview however neither does it display in toast or in listview
here is the code
mainactivity
public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //retrieveAudioFiles();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("NewApi")
    public void retrieveAudioFiles(){
        SongsList songsList = new SongsList();

        //Uri sd = Audio.Media.INTERNAL_CONTENT_URI ;
        //Uri sd = Audio.Media.EXTERNAL_CONTENT_URI;
        Uri sd = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
        String[] cols = {Audio.Media.TITLE,Audio.Media.ARTIST,Audio.Media.ALBUM};
        String where = Audio.Media.IS_MUSIC;
        Cursor audioCursor = getContentResolver().query(sd,cols,where,null,null);

        while (audioCursor.moveToNext()){
            int posColTitle = audioCursor.getColumnIndex(Audio.Media.TITLE);
            int posColArtist = audioCursor.getColumnIndex(Audio.Media.ARTIST);
            int posColAlbum = audioCursor.getColumnIndex(Audio.Media.ALBUM);

            String songTitle = audioCursor.getString(posColTitle);
            String songArtist = audioCursor.getString(posColArtist);
            String songAlbum = audioCursor.getString(posColAlbum);
            int posColId = audioCursor.getColumnIndex(Audio.Media._ID);
            long songId = audioCursor.getLong(posColId);
            Uri songUri = ContentUris.withAppendedId(Audio.Media.EXTERNAL_CONTENT_URI,songId);
            String[] dataColumn = {Audio.Media.DATA};
            Cursor coverCursor = getContentResolver().query(songUri, dataColumn, null, null, null);
            coverCursor.moveToFirst();
            int dataIndex = coverCursor.getColumnIndex(Audio.Media.DATA);
            String filePath = coverCursor.getString(dataIndex);
            coverCursor.close();
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(filePath);
            byte[] coverBytes = retriever.getEmbeddedPicture();
            Bitmap songCover;
            Toast.makeText(getApplicationContext(),audioCursor.getString(audioCursor
                    .getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM)),
                   Toast.LENGTH_LONG).show();

            if (coverBytes!=null) //se l'array di byte non è vuoto, crea una bitmap
                songCover = BitmapFactory.decodeByteArray(coverBytes, 0, coverBytes.length);
            else
                songCover=null;
            songsList.add(new Song(songTitle,songArtist,songAlbum));
            }
        audioCursor.close();
    }
    public class SongsAdapter extends BaseAdapter {

        private SongsList songsList;
        private LayoutInflater songInf;

        public SongsAdapter(Context c, SongsList theSongs){
            super();
            songsList=theSongs;
            songInf=LayoutInflater.from(c);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return songsList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return songsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            RowWrapper wrapper;
            if (convertView == null)
            {
                convertView = songInf.inflate(
                    R.layout.song_row, null);
                wrapper = new RowWrapper(convertView);
                convertView.setTag(wrapper);
            }
            else
            {
                wrapper = (RowWrapper) convertView.getTag();
            }
            Song song = (Song) getItem(position);
            wrapper.populate(song);

            return convertView;
        }

        private class RowWrapper
        {
            private TextView titleTextView;
            private TextView artistTextView;
            private TextView albumTextView;
            private ImageView coverImageView;

            public RowWrapper(View convertView)
            {
                titleTextView = (TextView) convertView.findViewById(R.id.textTitle);
                artistTextView = (TextView) convertView.findViewById(R.id.textArtist);
                albumTextView = (TextView) convertView.findViewById(R.id.textAlbum);
                coverImageView = (ImageView) convertView.findViewById(R.id.smallCover);
            }

            public void populate(Song song)
            {
                titleTextView.setText(song.title);
                artistTextView.setText(song.artist);
                albumTextView.setText(song.album);
               if (song.cover != null)
                coverImageView.setImageBitmap(song.cover);
            }
        }

    }
}

then in the song class
public class Song {

    public String title="";
    public String artist="";
    public String album="";
    public Bitmap cover=null;

    public Song(String t, String ar, String al){
        title=t;
        artist=ar;
        album=al;
        //cover=c;
    }

    public Song(){

    }

}

and songList class
public class SongsList extends ArrayList<Song> {

    public SongsList(){
        super();
    }

}

how ever nothing is displayed
here are the xml files
activty_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.stackalbumart.MainActivity" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" >

    </ListView>

</RelativeLayout>

and song_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical"
    android:onClick="songPicked" >

    <ImageView
        android:id="@+id/smallCover"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:contentDescription="coverDescription"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/labelTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="labelTitle" />

        <TextView
            android:id="@+id/textTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:text="textTitle" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/labelArtist"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:text="labelArtist" />

        <TextView
            android:id="@+id/textArtist"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:text="textArtist" />

        <TextView
            android:id="@+id/labelAlbum"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="labelAlbum" />

        <TextView
            android:id="@+id/textAlbum"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:text="textAlbum" />
    </LinearLayout>

</LinearLayout>

the app just opens and there is a blank white screen there is even no error
what really should be done

A: Since you are handle cursor, I would strongly suggest you to subclass CursorAdapter, which extends BaseAdapter and has the additional logic to handle the Cursor.
About your issue
in your retrieveAudioFiles(), after you close your cursor, you should instantiate the adapter and feed it to your ListView. E.g.
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(new SongsAdapter(this, songList));


text:
Q: Creating a new array from a subset of another one I need to create an array, correct_data, that is a subset of another one, all_data. This is all_data:
all_data = np.array([[[ 0, 11, 12, 13, 14],
                      [ 0, 21, 22, 23, 24],
                      [ 1, 31, 32, 33, 34],
                      [ 0, 41, 42, 43, 44]]])

The array correct_data will have all the the rows in all_data where the first item is a 1.
The way I was doing it is by creating a mask that identifies the rows starting with 1, such as:
correct_mask=all_data[:,0]==1
and then identifies the indexes of such rows (using "where").
Then I create a for loop that takes each row from the index and copy it onto correct_data (using vstack?).
Is this a practical way of doing it? If so, I need to create at fist correct_data as an empty array: can this be done?
Alternatively, I have tried to do it in a different way, i.e., delete the rows starting with a 0 from all_data
This is what I was trying:
for row in range(len(all_data)):
    this_row=all_data[row]
    if (this_row[0])==0:
        np.delete(all_data,row,0)

This does delete the rows, but then again how do I store the remaining rows in a new (or the same) array?
Many thanks for any help and clarification (I have a very basic knowledge of Python).

A: You can just filter it with an index condition:
>>> all_data[all_data[:,:,0]==1]
array([[ 1, 31, 32, 33, 34]])

A: To get all arrays starting with 1 you can use the following:
correct_data = all_data[all_data[:,:, 0] == 1]

It will reassign matching arrays to the desired variable.

A: correct_data = all_data[all_data[:, :, 0]==1]

The index here: all_data[:, :, 0]==1 returns a boolean array where the 0th element in 3rd dimension is 1. Just use this to index the original array. You will get array([[ 1, 31, 32, 33, 34]]) as the result.


text:
Q: When I remove error variable upload stops working Uploading photos on Amazon S3.
In this form, everything works and the photos appear in my basket
s3Client.upload(params, (err, data) => {
    if (err) {
        res.status(500).json({error:"Error -> " + err});
    }
});

But as soon as I bring it to this view, the files are no longer sent to Amazon S3.
s3Client.upload(params);

Help me understand why this is happening?

A: Seems the documentation is missing a critical part. Other methods have this note...

If a callback is not supplied, you must call AWS.Request.send() on the returned request object to initiate the request.

This caveat also applies to upload().
So if you're not going to supply a callback, you need
s3Client.upload(params).send()

A: I think "err" variable is part of its design wherein it catches the error in case there is a failure in processing the upload. If you are using a javascript framework, it has a documentation wherein you can see the purposes of each functions and what parameters it requires and how you should build a working prototype. Omitting some of the parameter will create an error if it does not match the method overloads in its component.


text:
Q: How do you display the contents of one cell to another in excel? I want to display the contents in column a in column b.

A: fx =(cell_reference)
when u do that in column a, drag it down for as many rows as needed.
fx =transpose(cell_array_reference)
choose the starting cell then ":" then the last row you want. This will auto list them swapping the row and column position.

A: Enter "=" then click the cell who's content you wand displayed. Hit enter.
Once it's working for the first cell, grab the little indicator in the corner of the cell and drag it down to do the same thing for the entire column.


text:
Q: open js popup by clicking a button i have index html page in my site, its the main page.
in the index html i have a button and by clicking it i want to open a popup form, i have the js file and css file of this popup included in the index html.
i just cant open this animated popup by clicking the input type button..
can anyone help me?
the clouds js:

        $(function ()
{
    // Register Smart skin.
    $.speedoPopup.registerSmartSkin('clouds', function (overlay, container)
    {
        // We don't want to brake anything if there is no overlay.
        if (!overlay)
        {
            return ;
        }

        if ($.speedoPopup.browser_ie && $.speedoPopup.browser_ie< 9)
        {
            return;
        }

        var clouds = '

';

        overlay.append(clouds);
    });
});

index html: below the head tag
<link type='text/css' href='clouds/clouds.css' rel='stylesheet' media='screen' />

and the button:

<input type='button' name='clouds' value='Clouds'/>

A: You have to invoke the dialog on click
Lets give you button an id

<input id="btnDialog" type='button' name='clouds' value='Clouds'/>

Now create a div that you want to show in dialog

   ...content here...

now you have to hook a click event on it
$('#btnDialog').click(function ()
{
    $(this).speedoPopup(
    {
        width:550,
        height:265,
        useFrame: TRUE,
        href: '#divContentToPopup'
    });
});


text:
Q: How to extract the informations of bounding box from TensorOutput TFLite Model in Android? Tensors Information (Input and Outputs)
I've procced the inputs and have the outputs without error.
I want to extract the information from the outputs in android, but I don't know how to do it.
Sample code
        var resized:Bitmap = Bitmap.createScaledBitmap(bitmap, 320,320,true)
        val model = ModelJerawatAutoml.newInstance(this)

        // Creates inputs for reference.
        val normalizedInputImageTensor = TensorImage.fromBitmap(bitmap)

        // Runs model inference and gets result.
        val outputs = model.process(normalizedInputImageTensor)
        val locations = outputs.locationsAsTensorBuffer
        val classes = outputs.classesAsTensorBuffer
        val scores = outputs.scoresAsTensorBuffer
        val numberOfDetections = outputs.numberOfDetectionsAsTensorBuffer

        textView1.setText((locations.floatArray[0] ).toString())
        textView2.setText((locations.floatArray[1]).toString())
        textView3.setText((locations.floatArray[2]).toString())
        textView4.setText((locations.floatArray[3]).toString())

Can you guys tell me how to create the bounding box in android?
and also I don't do real-time detection just only from the images


text:
Q: How to stop data grid adding additional row? I'm populating datagrid view like this.
var dataTable = new viewregisterdVotersOP().getTableRegVoters(lgdiv, elecid);
if (dataTable == null || dataTable.Rows.Count == 0)
{
    tempmsg1 = "Couldn't find data in the system";
    setErrorMSG(tempmsg1);
}
else
{
    dgvView.DataSource = new viewregisterdVotersOP().getTableRegVoters(lgdiv, elecid);
}

But it adds an extra empty row. How to stop that?

A:
But it adds an extra empty row. How to stop that?

That row is there to allow users to add new rows to grid, you can disable that either in code behind or at design view using DataGridView.AllowUserToAddRowsproperty
In code behind:
dgvView.AllowUserToAddRows = false;

Or set the property to false in design view.


text:
Q: Send multiple sensor value to python server I'm a new in python and IoT stuff. I want to send humidity and temperature value with DHT11 that attached to my ESP8266 to python server but, for a reason I want humid and temp are printed on different variable. e.g 2 variables. I read about splitting the string after received, but I still cannot figure it out.
#include <ESP8266WiFi.h>
#include <dht.h>

WiFiClient client;
dht DHT;

client.print("Temp: " + String(DHT.temperature, 0) + " °C");
client.print("Humid: " + String(DHT.humidity, 0) + "%");

Python (this is my expectation):
while True:
    try:
        humid, temp = conn.recv(2048).decode("utf-8")
        print(humid)
        print(temp)

    except Exception as e:
        print(e)
        break

Here's the output. The odd line is temp, and the even line is humid

If there are any better solution, please let me know. Sorry for my language, english is not my main language

A: try this code instead:
while True:
try:
    humid, temp = conn.recv(2048).decode("utf-8").split("\n")
    print(humid)
    print(temp)

except Exception as e:
    print(e)
    break


text:
Q: Heredar una función en Spark estoy aprendiendo a utilizar Spark y quiero poner a parte en una función la sección de acomoda campos para que desde esta clase solo mande a llamar dicha función
alguien tiene idea de como ?
de antemano gracias por su ayuda
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.hive.HiveContext

object tablaspark{
  def main(args: Array[String]) {

--lee tabla
 println("Prueba de Spark con Scala")
  val spark = SparkSession.builder().appName("tablaspark").enableHiveSupport().getOrCreate
  var query = "select cdelemen,dselemen as estatus_poliza from test_mrc.tablaorigen"

  val ktctget = spark.sql(query)

-- acomoda campos
          def get_schema(Dat: org.apache.spark.sql.DataFrame): String = {
            var fieldStr ="";
            Dat.schema.fields.foreach{f =>
                fieldStr += f.name + " " + f.dataType.simpleString + ",";
            }
            return fieldStr
        }

    var fieldStr = get_schema(ktctget)

--escribe tabla
    spark.sql("drop table if exists test_mrc.tabladestino")
    spark.sql("CREATE TABLE IF NOT EXISTS test_mrc.tabladestino(" + fieldStr.substring(0,fieldStr.length()-1)+") STORED AS PARQUET")
    ktctget.write.format("hive").mode("append").saveAsTable("test_mrc.tabladestino")
  }
}

A: Lo que tenes que hacer es crear un nuevo objeto y luego llamarlo utilizando el su nombre y el nombre del método al interior del mismo.
Ejemplo. Creo el Objeto GetSchema:
object GetSchema {
  // acomoda campos
  def get_schema(Dat: org.apache.spark.sql.DataFrame): String = {
    var fieldStr ="";
    Dat.schema.fields.foreach{f =>
      fieldStr += f.name + " " + f.dataType.simpleString + ",";
    }
    return fieldStr
  }
}

Luego los en el main para poder ver el resultado en los dos DataFrames:
object tablaspark{

  def main(args: Array[String]) {
    val df1 = Seq("12 https://jhafi.com xyza@gmail.com",
      "12 https://jhafi.com xyza@gmail.com",
      "12 https://jhafi.com xyza@gmail.com",
      "12 https://jhafi.com xyza@gmail.com").toDF("mycol")
    var fieldStr_df1 = GetSchema.get_schema(df1)
    println(fieldStr_df1)

    val df2 = Seq((0, "2016-07-02 12:01:40"),
      (1, "2016-07-02 12:21:23"),
      (1, "2016-07-02 13:22:56"),
      (1, "2016-07-02 13:27:07"),
      (0, "2016-07-02 13:30:12"),
      (0, "2016-07-02 13:40:34"),
      (1, "2016-07-02 13:57:07"),
      (1, "2016-07-02 14:08:07")).
      toDF("signal", "timestamp")
    var fieldStr_df2 = GetSchema.get_schema(df2)
    println(fieldStr_df2)
  }
}

Si lo creas en otro Paquete lo vas a tener que importar.


text:
Q: How to Suppress Data IF user click on print button for the first time I'm beginner with Crystal Reports.
Referring to the image below...

..., how can I suppress the data if the user prints for the first time?
Can I use printstate(OntheFirstTime)? If I can, how to use it?

A: Corrective Action:

*

*In Crystal Report, right-click and select Format Object.

*Search for "Suppress Embedded Field Blank Lines" checkbox and tick on it.

*Click Ok.

*Save the changes.

Thanks


text:
Q: What is the additional task that is being executed when using ExecutorService? I am learning Java Concurrency. So came across this example online for it. I have written the following code. The issue is, even though the tasks are done executing, it looks like there is something additional that is being executed. So how do I find out what is being executed?
package com.test.executors;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.logging.Logger;

class MyObject {
    private Integer number;
    private Integer result;

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public Integer getResult() {
        return result;
    }

    public void setResult(Integer result) {
        this.result = result;
    }
}

class FactorialCalculator implements Callable<MyObject> {

    private Integer number;

    public FactorialCalculator(Integer number) {
        this.number = number;
    }

    @Override
    public MyObject call() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " started...");
        MyObject object = new MyObject();
        object.setNumber(number);
        int result = 1;
        if (0 == number || 1 == number) {
            result = 1;
        } else {
            for (int i = 2; i <= number; i++) {
                result *= i;
                TimeUnit.SECONDS.sleep(1);
            }
        }
        object.setResult(result);
        System.out.println(Thread.currentThread().getName() + " done...");
        return object;
    }
}

public class ExecutorMain1 {

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(3);
        List<Future<MyObject>> results = new ArrayList<>();
        Random random = new Random();
        System.out.println("Starting Services...");
        for (int i = 0; i < 5; i++) {
            Integer number = random.nextInt(10);
            Future<MyObject> result = service.submit(new FactorialCalculator(number));
            results.add(result);
        }

        System.out.println("Done submitting tasks...");
        System.out.println("Will display results shortly...");

        for (Future<MyObject> future : results) {

            try {
                System.out.println("Number: " + future.get().getNumber() + "--> Result: " + future.get().getResult() + " Task Status: " + future.isDone());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Exiting main...");
    }
}

The output is -
Starting Services...
Done submitting tasks...
Will display results shortly...
pool-1-thread-2 started...
pool-1-thread-2 done...
pool-1-thread-2 started...
pool-1-thread-2 done...
pool-1-thread-2 started...
pool-1-thread-2 done...
pool-1-thread-1 started...
pool-1-thread-1 done...
Number: 6--> Result: 720 Task Status: true
Number: 5--> Result: 120 Task Status: true
pool-1-thread-3 started...
pool-1-thread-3 done...
Number: 4--> Result: 24 Task Status: true
Number: 0--> Result: 1 Task Status: true
Number: 1--> Result: 1 Task Status: true
Exiting main...

After Exiting main..., the program doesn't exit yet. It is blocking on something. The 5 tasks that are submitted are done as well. So what is being executed? How do I find that out?

A: JVM will not exit while there are non-daemon threads running.
And your ExecutorService creates non-daemon worker threads. So to allow JVM to terminate you need to shutdown executor service. By calling either shutdown() or shutdownNow() since all your tasks already finished.

A: You need call shutdown explictly to terminate the threads in the pool. After this, the jvm can shutdown.
service.shutdown();
System.out.println("Exiting main...");

A: One minor comment on your "found code:"  InterruptedException is almost solely useful as a request for a thread to exit.  Treating it as a normal exception is often a mistake.  This line of code:
} catch (InterruptedException e) {
    e.printStackTrace();
}

Is probably not useful, there's no reason to print a stack trace just because you've been requested to exit.
Also, when you catch an InterruptedException and you DO NOT THROW IT, you must reset the interrupted flag for your thread.
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}

This is because the other parts of the code must know that they are in an interrupted state and that they must exit as soon as possible.
C.f. Brian Goetz's Java Concurrency in Practice


text:
Q: Android view in Android studio says "nothing to show", can't run app anymore either I tried some things with vcs, git, not sure what I did. Suddenly my Android view says nothing to show:

However here's my Project view showing everything correctly:

I also can't run my app anymore, it prompts me with run configurations.

No idea what I did wrong.
Edit: I fixed it, luckily I backed up the project beforehand, simply replaced the whole folder of the project with the backed up folder.

A: When this happens, check your settings.gradle(Project Settings) file in Gradle Scripts, ensure that file has the following line;
include ":app"

A: I fixed it, luckily I backed up the project beforehand, simply replaced the whole folder of the project with the backed up folder.

A: Click on gradle tab in android studio.Now you can see your project name in opened window ; click on it and let to gradle build running. :)


text:
Q: Where is my iPhone backup kept? (Created prior iOS5 upgrade) I've just updated my wife's 3GS to iOS 5.1 from iOS 4. The restore seem to only restore the messages/photo roll and some other settings. I don't see most of the apps but the most important part is the contacts are missing. This is why I'm looking for the iPhone backup that iTunes creates before updating the software.
I currently have tried the following:

*

*Turn off iCloud

*Turn on then off iCloud

*Adding a Contact

*Restoring from the last backup file(without timestamp)

*Reset to Factory defaults and restoring

*Copying from Sim (Has some older contacts, not the recent ones)

*Using iBackupBot to browse the backups (only iOS5 backups seem to be there)

Here are some other valid points:
 1. The iPhone isn't regularly synced
 2. I created a backup before updating the OS I can't find it anywhere now
 3. There's no contacts on the Mac's Address Book.
 4. There is only Sim contacts in the iCloud sync
 5. iBackupBot shows me there are no other contacts other than the Sim ones that got synced to iCloud
 6. There are existing SMS-es without Contact Names
 7. I can try to correlate the SMSes with names but it will not give me the full contact list.
Since the Messages are restored, the contacts must be kept somewhere can anyone help me? I'm pretty sure I just need to find the backup that was created for the Update and somehow grab all the contacts maybe using ibackupbot.

A: If you are on WinXP -
C:\Documents and Settings/<user>\Application Data\Apple Computer\MobileSync\Backup

If you are on WinVista/Win7 -
C:\Users\<user>\AppData\Roaming\Apple Computer\MobileSync\Backup

If you are on MacOS -
~/Library/Application Support/MobileSync/Backup/

With the above path, if you still can not find the iPhone backup location, you may try an application called "iPhone Backup Unlocker", it will help you recover lost backup for your iPhone.

A: The backup location is here:
~/Library/Application Support/MobileSync/Backup/
That's the Library within your home directory.
In Lion it's hidden, so from Finder choose "Go To Folder" from the Go menu to get there.
Not sure you'll find what you're looking for though. If you had it backed up to iCloud I would log into iCloud (http://www.icloud.com) to see if the info is there.
Do you know if you were backing up to iCloud before as well, or backing up on the computer?

A: Exactly because I have found myself in situations like this, I keep a backup of my iPhone contacts on my PC via Windows Contacts. In the future you can copy iPhone contacts to your PC with third party apps or via iTunes sync.
The location of your iPhone backup files made by iTunes is as follows:
If you are on WinXP - C:\Documents and Settings\user\Application Data\Apple Computer\MobileSync\Backup
If you are on WinVista/Win7 - C:\Users\user\AppData\Roaming\Apple Computer\MobileSync\Backup
If you are on MacOS - ~/Library/Application Support/MobileSync/Backup/
If you are trying to access your iPhone backup files with a third-party application, there are lots such of apps I believe one of them was called iPhone Browser.


text:
Q: insuring CPU time after waking up - linux scheduler I'm running in a driver's context in linux kernel - this driver writes a value to a register - an operation which takes some time (~5 msec). I would like to sleep during that time in order to give away the CPU to other threads - but it is very important to me to have the CPU back immediatelly after I wake up (there's a short timeout which I must not exceed).
Same question goes for taking a mutex - say I'm blocking on a mutex (and triggering a re-schedule) - how can insure that I'll get the CPU back immediatelly when that mutex is released?
Is there a way to do this? what does it involve? (setting priority to the process? special scheduling mode? changing kernel config?)
EDIT:
I'll rephrase the question about the mutex since it's a bit more complicated:
I have a mutex which is used by important threads (important because of that timeout limit). I would like to take this mutex, knowing that if I will block on it and get reschduled, the lock will be be released quickly (because these threads will have a high priority), and immediatelly after that, my blocked thread will be able to run (and not some other, unrelated program).
This way I can save CPU time while not risking a timeout violation.
I currently use busy waiting in order to avoid rescheduling (my kernel is non preemptive) but I don't like this solution.
Any help will be appreciated!
thanks

A: You said you are observing delays while writing. I think in this situation you can use
schedule_timeout function. Device drivers use this technique while writing to register so that they dont lockup the system. Recently, I have come across a problem where writing to register is causing delays; I am planning to do schedule_timeout in my case too.
Setting priority, scheduling mode will not help here.


text:
Q: rails require local file I have rails project. And I want to add code to class MainParserPlugin ( path : app/controllers/admin/main_parser_plugin.rb") from class ParserPlagin (path :  "app/controllers/admin/parser_plugin.rb")
main_parser_plugin.rb:
 require 'parser_plugin'
 class Admin::MainParserPlugin < ApplicationController
    #Some code
 end

But it appear an error :
     cannot load such file -- parser_plugin
Can you tell me what path I must put, to work it well?

A: Within config/application.rb you'll need to add any subdirectories under app/models to the autoload_path by adding the following line:
config.autoload_paths += Dir["#{config.root}/app/models/**/"]