text:
Q: How to configure multiple DB in Zend1.12 and Doctrine2 To get Entity Manager, Im using
$doctrine = Zend_Registry::get('doctrine');
$em = $doctrine->getEntityManager();

In application/Bootstrap.php
public function _initAutoloaderNamespaces()
    {

    require_once APPLICATION_PATH . '/../library/Doctrine/Common/ClassLoader.php';
    $autoloader = Zend_Loader_Autoloader::getInstance();
    $fmmAutoloader = new \Doctrine\Common\ClassLoader('Bisna');
    $autoloader->pushAutoloader(array($fmmAutoloader, 'loadClass'), 'Bisna');
    $classloader = new \Doctrine\Common\ClassLoader('Models', APPLICATION_PATH);
    $classloader->register();
    }

        /**
     * Set up sessions to be saved to the database.
     * Begin or resume a session.
     */
    protected function _initSaveSession()
    {

        if (strpos(APPLICATION_ENV, 'setup') !== false)
            return;
        $this->bootstrap('doctrine');
        // We can use the same connection settings for Zend_Db_Adapter too!
        // So less configuration, more flexibility.
        $doctrine = $this->getResource('doctrine');
        $entityManager = $doctrine->getEntityManager();

        //Register Blob Type
        Doctrine\DBAL\Types\Type::addType('blob', 'Doctrine\DBAL\Types\BlobType');
        $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('BLOB', 'blob');

        $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('ENUM', 'string');

        $dbParameters = $entityManager->getConnection()->getParams();

        // Hack
        // Doctrine uses 'user' instead of 'username' for connection params
        $dbParameters['username'] = $dbParameters['user'];

        $db = Zend_Db::factory('PDO_MYSQL', $dbParameters);
        Zend_Db_Table::setDefaultAdapter($db);

        $config = array(
                'name' => 'sessions',
                'primary' => 'id',
                'modifiedColumn' => 'modified',
                'dataColumn' => 'data',
                'lifetimeColumn' => 'lifetime',
                'db' => $db
        );

        //Tell Zend_Session to use your Save Handler
        $savehandler = new Zend_Session_SaveHandler_DbTable($config);
        $savehandler->setLifetime(3600)->setOverrideLifetime(true);
        Zend_Session::setSaveHandler($savehandler);
        Zend_Session::start();
    }

    protected function _initDoctrine2()
    {

        $this->bootstrap('doctrine');

    }

In application/config/application.ini
;------------------------------------------------------------------------------

; Doctrine Cache Configuration

; ------------------------------------------------------------------------------

; Points to default cache instance to be used. Optional is only one cache is defined
resources.doctrine.cache.defaultCacheInstance = default

; Cache Instance configuration for "default" cache

;resources.doctrine.cache.instances.default.adapterClass = "Doctrine\Common\Cache\MemcacheCache"
resources.doctrine.cache.instances.default.adapterClass = "Doctrine\Common\Cache\ArrayCache"
resources.doctrine.cache.instances.default.namespace    = "Models"

resources.doctrine.cache.instances.default.options.servers.0.host           = localhost
resources.doctrine.cache.instances.default.options.servers.0.port           = 11211
resources.doctrine.cache.instances.default.options.servers.0.persistent     = true
resources.doctrine.cache.instances.default.options.servers.0.retryInterval  = 15

; ------------------------------------------------------------------------------

; Doctrine DBAL Configuration

; ------------------------------------------------------------------------------

; Points to default connection to be used. Optional if only one connection is defined
resources.doctrine.dbal.defaultConnection = default

; DBAL Connection configuration for "default" connection
resources.doctrine.dbal.connections.default.id                  = default
resources.doctrine.dbal.connections.default.eventManagerClass   = "Doctrine\Common\EventManager"
resources.doctrine.dbal.connections.default.configurationClass  = "Doctrine\DBAL\Configuration"
;resources.doctrine.dbal.connections.default.sqlLoggerClass     = "Doctrine\DBAL\Logging\EchoSQLLogger"

; Database configuration
;resources.doctrine.dbal.connections.default.parameters.wrapperClass = ""
resources.doctrine.dbal.connections.default.parameters.driver   = "pdo_mysql"
resources.doctrine.dbal.connections.default.parameters.dbname   = "database_test"
resources.doctrine.dbal.connections.default.parameters.host     = "localhost"
resources.doctrine.dbal.connections.default.parameters.port     = 3306
resources.doctrine.dbal.connections.default.parameters.user     = "root"
resources.doctrine.dbal.connections.default.parameters.password = "Tdatabase_password"

;resources.doctrine.dbal.connections.default.parameters.driverOptions.ATTR_USE_BUFFERED_QUERIES = true
doctrine.data_fixtures_path = APPLICATION_PATH "/configs/data/fixtures"

; ------------------------------------------------------------------------------

; Doctrine ORM Configuration

; ------------------------------------------------------------------------------

; Points to default EntityManager to be used. Optional if only one EntityManager is defined
resources.doctrine.orm.defaultEntityManager = default
; EntityManager configuration for "default" manager
resources.doctrine.orm.entityManagers.default.connection                               = default
resources.doctrine.orm.entityManagers.default.proxy.autoGenerateClasses                = true
resources.doctrine.orm.entityManagers.default.proxy.namespace                          = "Models\Proxy"
resources.doctrine.orm.entityManagers.default.proxy.dir                                = APPLICATION_PATH "/Models/Proxy"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.adapterClass           = "Doctrine\ORM\Mapping\Driver\AnnotationDriver"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.mappingNamespace       = "Models"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.mappingDirs[]          = APPLICATION_PATH "/Models"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.annotationReaderClass  = "Doctrine\Common\Annotations\AnnotationReader"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.annotationReaderCache  = default

How to add multiple database connection other than default and how to use that in Entity and select that particular entity manager


text:
Q: Is there an NPM location where I can download Gulp 4 or a pre-release of Gulp 4? I'm using a package.son where I list all the Gulp NPM modules. In that file I have "gulp": "3.8.11",
I would like to use Gulp4 and I read here some different ways to access it:
   http://stackoverflow.com/questions/33429727/how-do-i-install-gulp-4

But is it possible to also do this with a package.json? When I try to look at versions of "gulp" the auto part of Visual Studio doesn't prompt me for anything more than a 3.9 version.
Also is there a way that I could have some tasks use Gulp3 and others uses Gulp4?

A: Duplicate, but regardless:
npm install gulpjs/gulp#4.0 --save-dev

That adds this to the package.json:
"gulp": "gulpjs/gulp#4.0"

A: Here is the only solution that I could get to work:
"gulp-4.0.build": "4.0.0-build.a271520",

Note that the version details on the right were added automatically by Visual Studio.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a type safe version of the @ operator? Or a compiler warning that can be switched on? The following code does not generate a compiler warning in D6. Can I make it warn me about pointing ps at an integer when I have told it that ps points to a string?
procedure Test;
var
  i: integer;
  s, m: string;
  ps: ^string;
begin
  s := 'Test message';
  ps := @s;
  m := ps^;
  MessageDlg(m, mtInformation, [mbOK], 0);  // This displays 'Test message'.
  ps := @i;  // I would like a warning here.
  m := ps^;
  MessageDlg(m, mtInformation, [mbOK], 0);  // This might display garbage.
end;

A: Use Type-checked pointers ({$T+} directive)

A: There's an option in Project settings -> Compiler settings exactly for this.


text:
Q: Voltage stabilizing circuit I have the following case:

*

*I need a stable power for esp32 at 3.3V (around 300mA) for at least
10 seconds

Power source is:

*

*not DC, it is irregular

*source provides bursts of around 1.0V each second, 42W

*it can get more intensive: up to 16V with more frequent intervals (up to 1400W)

I assume I need some capacitors and diodes, but I don't know how to hook it up.

A: You need some capacitance, as energy storage, a harvester to charge it, and a converter to use it. And some low power control circuitry to manage the whole thing.
Your ESP32 uses about 1 watt when running. If it runs for 10 seconds, that's 10 Joules. Let's choose to use a buck converter to get between the energy store and 3.3v, so your minimum capacitor is allowed to be 4v or so, let's say 5v to give a bit of margin. Allow the capacitor to supply up to 10v, a 2:1 voltage swing uses 75% of the energy stored, a reasonable figure. So you want a capacitor that will store 13.3J at 10v. A buck converter isn't 100% efficient, so we inflate this by another 10/15% to allow for losses, to get 15J.
\$E=0.5CV^2\$ so C = 300mF (300,000uF), which is big, but not too big for a supercap. You could use a smaller value if you chose to charge to a higher voltage.
Now you need a harvester circuit, to use your 1v to 16v inputs to charge this capacitor. This is where you need a lot more information about your power source and its power capabilities. Texas Instruments do a lot of power harvesting converters, so read their application notes.
You may need some low power (read CMOS) amplifiers or references to monitor the store, to trigger the ESP32 wake-up, or to see if it's OK for it to wake up when it asks whether it can.
Notes on the energy store. You will find some fairly cheap supercaps designed for memory backup, which may not be able to deliver the 1 watt needed for your ESP32, check the power output of any you buy. You may be better off with a LiPo. Choose one large enough that swinging 15J barely changes its state of charge. This would give it very long life, NASA have found that charging their cells to a max of 3.92v allows 8year+ life in satellites in a 90 minute light/dark orbit.


text:
Q: Trying to verify signature of Wasabi-1.1.12.3.deb package but it won´t find the file (THE FILE IS THERE) Ey there,
So, i have been trying for hours to install wasabi in Ubuntu without success. Having downloaded the
files and following the guide i get to the point of not being able to verify the freaking signature.
I write the following command (taken from the installation guide i'm following at http://wasabiwallet.io):
gpg --verify Wasabi-1.1.12.3.deb

and the terminal tells me there is no such file (but the files is there... i'm sure
The text i get back is:

gpg: can´t open 'Wasabi-1.1.12.3.deb.asc: No such file or directory
gpg: verify signatures failed: No such file or directory

And so...  I'm lost. I googled but did not find anything helpful. I just spend a couple days to install the VPN (a couple weeks ago) and remember my ex flatmate who was a computer wizard and still was to be seen losing his hair with Ubuntu once in a while... and i wonder why i even try to use it XD.
I hope someone here can help me.
TO BE CLEAR:
-Followed the Guide's steps

*

*.deb file downloaded

*.deb.asc file downloaded in same folder

*PGP.txt imported

I give gpg --verify Wasabi-1.1.12.3.deb.asc
(yes, i checked, File name is correct)
I receive:

gpg: can´t open 'Wasabi-1.1.12.3.deb.asc: No such file or directory
gpg: verify signatures failed: No such file or directory

A: Silly question, but you did read step 2 at least twice, right?

There is the .deb file and, under the green button, a blue "Signature" link that points to the .asc file. Both will need to be located in the same directory.
-rw-rw-r-- 1 jason jason 69997812 12月  7 23:22 Wasabi-1.1.12.3.deb
-rw-rw-r-- 1 jason jason      499 12月  7 23:23 Wasabi-1.1.12.3.deb.asc

Now you can then perform Step 3 and verify the .deb:
$ gpg --verify Wasabi-1.1.12.3.deb.asc

gpg: assuming signed data in 'Wasabi-1.1.12.3.deb'
gpg: Signature made 2020年12月07日 23時22分15秒 JST
gpg:                using RSA key 6FB3872B5D42292F59920797856348328949861E
gpg: Can't check signature: No public key

So long as the RSA key matches what is listed on the website, you can move on to the next step.


text:
Q: Chrome extension to change DOM with a button in extension popup i am completely new to chrome extension development.
I am trying to change the DOM (append data to active webpage) when clicked on a button in the extension popup. How is this possible.
the manifest file
{
  "manifest_version": 2,

  "name": "test 2",
  "description": "test ext 2",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*","https://*/*"],
      "js": ["jquery.min.js", "main.js"]
    }
  ],
  "permissions": [
   "activeTab"
   ]
}

suppose if the popup.html file is
<!doctype html>

    <title>test extension 2</title>

    button

and when i click on #button, i want to execute some jquery code in main.js file which will append some data to the active webpage.
Thank you.

A: *

*Use Programmatic injection. You could register event listener in popup.js and call chrome.tabs.executeScript to inject some js code/file to current active tab. This requires host permissions.
popup.js
document.getElementById('button').addEventListener('click', function() {
    chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
        // WAY 1
        chrome.tabs.executeScript(activeTabs[0].id, { code: 'YOUR CODE HERE' });
    });
});

*Use Message Passing. You could call chrome.tabs.sendMessage in popup.js and listen to that via chrome.runtime.onMessage in content.js.
popup.js
// WAY 2 (Replace WAY1 with following line)
chrome.tabs.sendMessage(activeTabs[0].id, { action: 'executeCode' });

content.js
chrome.runtime.onMessage.addListener(function(request) {
    if(request.action === 'executeCode') {
        // YOUR CODE HERE
    }
});

*Use Storage. You could call chrome.storage.local.set in popup.js and listen to storage change in content.js via chrome.storage.onChanged.
popup.js
// WAY 3 (Replace WAY1 with following line)
chrome.storage.local.set({ action: 'executeCode' });

content.js
chrome.storage.onChanged.addListener(function(changes) {
    var action = changes['action'];
    if(action.newValue === 'executeCode') {
        // YOUR CODE HERE
    }
});


text:
Q: jQuery - selecting inside click method Consider the following :-
$("#id").click(function(){
// how do i access $("#id") here: say i want to add a class to #id? without $("#id")
});

A: You can use the this context to access the item selected.
$("#id").click(function() {
  $(this).addClass("blah");
});

Alternatively, each event handler is also passed an event and you can derive the information from that:
$("#id").click(function(evt) {
  $(evt.target).addClass("blah");
});

See the jQuery Event object.
I generally favour the approach using this however.

A: $(this).addClass("class");

A: Read the JQuery documentation and you will find that you should use $(this).


text:
Q: Reverse Proxy Behavior in a K8s Cluster for SSH Calls I am building an application over a managed K8s cluster. I can create deployments & co with NodePort. Services are then accessible via these ports.
Managing all the exposed services and their ports is becoming a challenge and for the HTTP traffic, I was thinking of exposing a single nginx proxy that would proxy https://someservice.someurl:someport to  https://someservice:someport and have someurl DNS mapped to my front-end Ubuntu IP as depicted below.

For the web traffic, I reckon that it should work as expected. However, I have some deployments that are accessible via ssh;  git daemon for example. With these demons I am currently doing commands like this git clone ssh://git@someipsofthecluster:someport/git-server/repos/somerepos and I'd like to use the same DNS name as for http traffic (i.e. git clone ssh://git@someservice.someurl:someport/git-server/repos/somerepo)
I know about iptables where I can redirect traffic incoming from one port to another IP/port but I don't know how I would go about redirecting to a given machine/port with regards to the subdomain used.

A: You'll probably have to re-think how to do this as TCP load balancing or proxying based on DNS name is not really possible. More on this here. Keep in mind that HTTP is a Layer 7 protocol so the proxy can use the 'Host' header to direct requests.
Filtering based on hostname is also not possible with iptables. More on that here.
You can, however, use a Layer 4 proxy, meaning a TCP proxy but this will be based on listening on a specific TCP port. Nginx can do it or you can also use something else like Haproxy.


text:
Q: jquery name selector not working in ie6 var brands = document.getElementsByName("brand");
for(var brand in brands){
    $("input[name='brand']").eq(brand).click(function(){
                        alert("hello22");
                        loadDataFN(1);
                });
}

This code is not executing in ie6,
Any help would be appreciated.

A: The problem is likely that you are trying to use a for-in construct to iterate over a numeric array. This often won't give expected results. Use an incremental for loop instead:
var brands = document.getElementsByName("brand");

// Use an incremental for loop to iterate an array
for(var i=0; i<brands.length; i++){
    $("input[name='brand']").eq(brands[i]).click(function(){
                        alert("hello22");
                        loadDataFN(1);
                });
}

However,
after seeing the first part of your code, the loop appears unnecessary. You should only need the following, since you are assigning the same function to all brand inputs.
// These will return the same list of elements (as long as you don't have non-input elements named brand)
// though the jQuery version will return them as jQuery objects
// rather than plain DOM nodes
var brands = document.getElementsByName("brand");
$("input[name='brand']");

Therefore, the getElementsByName() and loop are not necessary.
$("input[name='brand']").click(function() {
       alert("hello22");
       loadDataFN(1);
});

for-in loops are used for iterating over the properties of an object, not over the elements of an array.

A: Why don't you write the code without jQuery if this doesn't work?
Something like this:
function getInputByName(name) {
    var i, j = document.getElementsByTagName('input').length;

    for(i=0;i<j;++i) { // You can also use getAttribute, but maybe it won't work in IE6
        if(document.getElementsByTagName('input')[i].name === name) {
            return document.getElementsByTagName('input')[i];
        }
    }

    return null;
}

I don't know jQuery, but maybe you can do something like this:
$(getInputByName('brand')).eq(brand).click(function(){
                    alert("hello22");
                    loadDataFN(1);
            });


text:
Q: JSX rendered by nuxt dev server works, while the prod version doesn't work I have a nuxt app with a component that uses JSX.  It works locally using npm run dev, but the dist build I get after running npm run build fails to properly render.
Here' the component's code:
<script>
import draggable from 'vuedraggable'
export default {
  data () {
    return {
      columns: [
        { width: 2 },
        { width: 3 },
        { width: 4 }
      ]
    }
  },
  components: {
    draggable
  },
  render (h) {
    const buildColumn = (column, index) => {
      const result = (
        <v-col md={ column.width } cols="auto">
          <v-card>
            <v-row>
              <v-col>
                <v-icon class="handle">mdi-drag</v-icon>
              </v-col>
              <v-col>
                { index }
              </v-col>
            </v-row>
          </v-card>
        </v-col>
      )
      return result
    }
    return (
      <v-container>
        <draggable handle=".handle" onEnd={ () => this.$emit('update-order', this.columns) } list={this.columns} tag="v-row" options={{ animation: 500 }}>
          { this.columns.map((column, index) => buildColumn(column, index)) }
        </draggable>
      </v-container>
    )
  }
}
</script>

When running npm run dev, it renders the following:

After building:

Can anyone help me figure out what could be causing this?  I'm including a base repo that demonstrates the problem
https://gitlab.com/qualisign/test_jsx
One more possible clue:
the first image is the non-working html one sees on the production server when inspecting the icons that fail to load:

this second image is how the working html looks when one inspects the same elements on the dev server:

I don't know if this helps, but I thought it might be relevant.

A: Update: after looking the code shared by OP, this seems to be a BUG #382 and is mentioned on the project repository as well.
There seems to be an issue with vuetify-loaded and to get around this issue, disabling treeShake option in the configuration like:
nuxt.config.js
{
...
    vuetify: {
        ...,
        treeShake: false
    }
...
}

Original answer:
Looks like material icon library is not configured property due to which icons are not rendered. Check if following are configured properly as mentioned in the guide:

*

*Check if material-design-icons-iconfont is installed

npm install material-design-icons-iconfont -D

*Check if css file is imported are on entry point of your app (index.js/app.js)

import 'material-design-icons-iconfont/dist/material-design-icons.css' // Ensure you are using css-loader
import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

export default new Vuetify({
  icons: {
    iconfont: 'md',
  },
})

If you are using CDN link for the library check if it is correct.
<link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet">.
If this still doesn't work, check for all console and network errors, it's possible you have misconfigured style/font url somewhere in your app.


text:
Q: Can i combine many jar files in one jar file I have multiple JAR files, which I have to add to classpath in Eclipse.
Is it possible to combine 30 files in one file and include that file?

A: You can, but I don't think it would necessarily be a good idea to do so. Three possible reasons, and no doubt there are more:

*

*It makes it harder to see where any one constituent file comes from.

*It makes it harder to replace just one library

*If there are files which are contained in multiple jar files, which should "win"? For example, all the jar files will have their own manifest... you may be able to merge them all, but not necessarily... and for other files there may well simply not be a sensible way of merging them.

My vote is to keep the jar files separate.

A: Your may want to have a look at jarjar.
If you use an ant task you can also go for zipgroupfileset:
<zip destfile="jarlibrary.jar">
    <zipgroupfileset dir="lib" includes="*.jar"/>
</zip>

A: There are a number of existing tools for this:

*

*Uberjar

*Megajar

*Onejar

A: This question seems probable duplicate. Please try to find answer from similar article in this forum
Clean way to combine multiple jars

A: The jarjar project is what you need.

A: There is another thread here that explains how to package jars for releases, including using Ant, jarjar and eclipse plugins.

A: First, you can. JAR is just a ZIP file. You can extract all stuff into one directory, then create zip file (even manually using WinZip or similar tool), call the result *.jar (if you wish) and add it into the classpath.
The only problem that will probably happen is if several jar files contain resources with the same name (and path). for example, manfest.mf, or other descriptors. In most cases it will not cause any problem but sometimes if application code uses these resources you can have trouble.
There are some automatic tools that do this. Take a look on JarJar.
BUT the more important question: why do you want to do this? If you do not use maven put all library jars to one directory named lib under your project. Then add all these jars to your classpath in eclipse using 2-3 clicks. That's it.
if you are using maven, include all your direct dependences into your pom.xml, compile the project, then say mvn eclipse:eclipse. This will create .classspath and .project for you. Now just use it.

A: Jar files are just ZIP files, so you can try to unzip all jars, put all files together and then ZIP them again.


text:
Q: Why would I ever want to revert a migration? In Rails, migrations have a down method by default for reverting a migration. In what scenario would I ever want to revert a migration, though?
Some thoughts:
Whether in development or production, I always have a snapshot of my database to go back to, before I even run the migrations. Especially for migrations which perform data conversion, I find in most cases that reverting a snapshot is even faster than reverting a migration. (So I would never do it in a rush!)
If a migration were to fail, it would either:

*

*fail with an exception on a non-transactional database, and thus leave the database broken, or

*fail with an exception and roll back the transaction, and thus there would be no need to revert otherwise.

If the changes made are in production (or late in development), and later turn out to be a mistake, I would fix my mistake in a new migration. I would not revert the old one. In development, I'd simply delete the migration.
I also find that the down method introduces extra code in which I repeat myself, and thus may introduce new bugs. This is against the DRY principle.
So I'm curious about the pros, because I can't think of any.

A: In development, it is easy and fast to incrementally "improve" migrations by using the down method automatically. Eg

*

*Create a migration and migrate to it

*Realize you need to make a change

*Migrate to the ver prior to your new migration by using db:migrate with a version

*Improve/fix your migration

*Rerun the migration task

Your method of taking snapshots works fine. But rails includes the same effect auto-magically using the "down" migration techniques. Works with all db's, tastes great
Added:
For production, I agree that a down migration shouldn't be needed. But sometimes mistakes happen and you need to roll back. The down migration path gives you a first, and quick opportunity to fix things in an emergency situation during an upgrade that goes wrong.
-- it is much faster to try a down migration in an emergency than to restore the db using a checkpoint.

A: The "down" migration used for DB Rollbacks is in place so that every action has an equal and opposite action.  It takes the onus off of the developer to maintain database snapshots, and allows them to use code to achieve the same ends.  As Larry K said,
they're good for situations like so:

*

*Add a database column called 'resubmitted', it's a boolean.

*Product owner says they can resubmit multiple times, so change that column needs to be an int

Now, if you're 10 or 15 migrations deep, it's easier to just write a new one instead of losing all the dev data in the new tables/columns by doing a rollback.  However, if you've just written that migration, it's cleaner and less cluttered to roll back, change the migration, and re-run it.
The other extremely useful feature of rollbacks is this:

*

*Developer 1 has his own Dev DB.  He writes a migration and runs it.

*Developer 1 commits his migration to source control

*Developer 2 has her own Dev DB.  She writes a migration and runs it.

*Developer 2 updates from source control

*Developer 2 tries to run migrations but can't, as her local DB says "the latest migration has already been run", since her migration (the latest one), has technically already been run.  Now she needs to rollback, then do a db:migrate to get all migrations in her local DB.

A: The idea of running a down migration in production horrifies me. Back when the preferred way to rollback all migrations was rake db:migrate VERSION=0 I would do this all the time in development. However, then I got paranoid that because it was committed to muscle memory I would accidentally type this on a production server when I meant to simply migrate.
Because of this paranoia, I add the following to all of my down methods.
  def self.down
    if Rails.env.production?
      raise ActiveRecord::IrreversibleMigration
    else
      drop_table :foo_bars
    end
  end

This way, it still works in development, but I can't accidentally nuke my production database from orbit while half-asleep at 2:00 AM.

A: When a migration hasn't had the expected result, it is better to roll back and rewrite it than to keep the failed migration in the code.


text:
Q: Material style navigation drawer, statusbar color gets too dark I am trying to follow the Material Design guidelines to make an app with an actionbar(toolbar) and a navigation drawer, so that it would look like in Google Apps. The solution I have found is to set "android:windowTranslucentStatus" to true in my theme , as well as keeping "android:fitsSystemWindows" as false , compensating for it with extra padding on my toolbar.
The problem is though, that the final color of the statusbar is too dark. Even if I set the toolbar to the same material color as the G-mail app for example, the statusbar color is darker in my app than in the G-Mail app.
Could somebody please point me in the right direction here? I've heard a lot about some custom ScrimLayout hack , but I would like to stick to Android APIs if possible.

A: I don't know for which api level you're trying this, but for api>=21 try this:
In your values-v21/styles.xml do the following:
   <style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">

    <item name="android:colorPrimary">@color/toolbarcolor</item>
    <item name="android:colorPrimaryDark">@color/navdrawercolor</item>

   </style>

sources: Youtube - AndroidDeveloper / from Holo to Material
Edit:
for setting the status bar color in api >=21 you could use:
<item name="android:statusBarColor">@android:color/transparent</item>

and set the fullscreen mode in your onCreate in your activity:
            getWindow().getDecorView().setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

A: Put this in your styles.xml (v21) inside your AppTheme style
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>


text:
Q: HTTP request doesn't hit WEB API 2 controller I'm trying to secure a web API 2 with MSAL.
My authentication client side works and I get a valid token (verified with jwt.io).
I have a Web API 2 configured as such :
The WebAPI Config :
public static void Register(HttpConfiguration config)
{
   config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
   config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    config.EnableCors();
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
        );
}

My Startup.Auth.cs looks like this:
        public void ConfigureAuth(IAppBuilder app)
    {
        string clientId = "the_client_id";

        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidAudience = clientId,
            ValidateIssuer = false
        };
        Debug.WriteLine("Client ID = " + tokenValidationParameters.ValidAudience);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tokenValidationParameters, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"))
        });
    }

And a simple controller :
[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class BundlesController : ApiController
{
    private APIContext db = new APIContext();

    // GET: api/Bundles
    public IQueryable<Bundles> GetBundles()
    {
        Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier);
        db.Configuration.ProxyCreationEnabled = false;
        return db.Bundles.Include(x => x.Products.Select(y => y.Defects));
    }

Before adding the [Authorize] attributes, the API worked like a charm and returned correctly the data.
If I set a breakpoint in the GET function from the controller, it won't get hit and I'll get a 401 : Authorization has been denied for this request.
I'm fairly sure I registered my app correctly in apps.dev.microsoft.com.
I don't understand at what point my API is blocking the calls.
Any suggestion is greatly appreciated !
Thank you !

A: I just tested your code both on my local and Azure Web App. All worked fine. The API could be reached after adding [Authorize] attributes.

My authentication client side works and I get a valid token (verified with jwt.io).

Token will expired depends on the exp property of JWT. By default, it will expired in 60 min. Try to re-generate the token and use it to access your Web API.

A: Hi can you please try adding supports credentials: true to your cors?.
So your EnableCors attribute would look something like this
 EnableCors [origin:*,headers:*,methods:*,supportsCredentials:true]

Hope this helps.
Thanks,
Bhadhri

A: So, sorry for the disturbance !
My issue was that I was calling from the App the token method that way:
App.IdentityClientApp.AcquireTokenAsync(new String[] { premissionScopes });

When I should have done
App.IdentityClientApp.AcquireTokenAsync(new String[] { Constants.ApplicationID });

So yeah, you're supposed to get the first token with the application ID and then give the scopes to the silent token acquiring method once you have the token.


text:
Q: how to implement mapbox.js offline caching I'm creating a phonegap mobile app that have a map in it.
I'm using mapbox.js
i know that it allows offline capability but i couldn't figure out how to do it
i searched on how to but i could not find the documentation
this is my code so far

A: I don't know who told you or where you read that it's possible while using mapbox-js (some kind of reference would be nice) but it isn't and that's why you can't find it. However, it is possible using the iOS or Android SDK's:
https://www.mapbox.com/help/ios-offline/
https://www.mapbox.com/help/android-offline/


text:
Q: Sort MySQL query with JOIN I'm getting an error when I try to order my column on phpmyadmin result.
This is the error:

My query is:
SELECT Cliente.Codigo, Cliente.Nome, Contato.Nome, Grupo.Nome FROM Cliente JOIN Grupo ON ( Grupo.codigo = Cliente.Codigo_Grupo ) JOIN Contato ON ( Contato.Codigo_Cliente = Cliente.Codigo ) GROUP BY Cliente.Codigo ASC

The ORDER BY was added automatically, when I click on title of column.
Does anyone know how to solve this problem?

A: I suspect this to be wrongly-gerated SQL: Try
SELECT Cliente.Codigo AS Codigo, Cliente.Nome, Contato.Nome AS Contato, Grupo.Nome AS Grupo
FROM Cliente
JOIN Grupo ON ( Grupo.codigo = Cliente.Codigo_Grupo )
JOIN Contato ON ( Contato.Codigo_Cliente = Cliente.Codigo )
GROUP BY Cliente.Codigo
ORDER BY `Grupo` ASC
LIMIT 0,30

After discussion in the comments, it turns out, that an underlying bug in a framework is the culprit:
- Without alias on Grupo.Nome it will choke on the Nome part
- With alias on Grupo.Name it will choke on the alias
There is a really, really dirty way around this - but please be aware, that it is a workaround (at best), not a solution
Do this once:
CREATE VIEW GrupoWorkaround SELECT Grupo.*,Grupo.Nome AS Grupo FROM Grupo

This will create a parallel view.
No change your Query to
SELECT Cliente.Codigo AS Codigo, Cliente.Nome, Contato.Nome AS Contato, GrupoWorkaround.Grupo
FROM Cliente
JOIN GrupoWorkaround ON ( GrupoWorkaround.codigo = Cliente.Codigo_Grupo )
JOIN Contato ON ( Contato.Codigo_Cliente = Cliente.Codigo )
GROUP BY Cliente.Codigo
ORDER BY `Grupo` ASC
LIMIT 0,30

in fact replaceing Grupo with GrupoWorkaround and thus obliverating the need for an alias.


text:
Q: Is there a keyboard shortcut for the Close Search button in File Explorer on Windows 10? Has anyone found a keyboard shortcut for the Close Search button in File Explorer on Windows 10?

A: Use ALT+J,X from the File Explorer window.

A: Try: Alt + Left-Arrow
The Alt+J,X doesn't work on my Windows 11 machine.
PS: Alt + Right-Arrow takes you back to the search.
So, you can page through history by using Alt + Left/right-arrow keys.


text:
Q: Can I activate a function in a different javascript file than the one I'm trying to activate it from? I've got two javascript files, screenfunction.js and map.js
In screenfunctions.js there's a function that I want to be able to start another function called "go" which is in map.js, is this possible?
This is what's written in the function in screenfunctions.js. The console obviously tells me that "go" is not defined.
if (doAnimation == 0){
   go(function(){});
}

A: Yes, as long as the required function has already been included beforehand.
There are two ways to do this.
ECMAScript modules
Read more about ES modules on the MDN.
Use this if you are writing a server-side application with Node.js (in which case ignore index.html), or writing a client-side application for modern browsers. All major browsers have supported ES modules since ~2018, but IE does not support them (check Can I use here).
<!-- index.html -->
<html>
  <head>
    <!-- ... -->
    <script type="module" src="./screenfunctions.js"></script>
    <script type="module" src="./map.js"></script>
  </head>
  <!-- ... -->
</html>

// screenfunctions.js
export function go() {
  console.log('Called go()');
  // ...
}

// map.js
import { go } from './screenfunctions.js';

go();

Legacy global declaration
Use this if you are writing a client-side application which must work in older browsers. This approach is worse because the function is declared in the global scope. This could interfere with other code which is also included. This approach is also more prone to breaking because the dependency of the second script upon the first is not obvious at first glance.
<!-- index.html -->
<html>
  <head>
    <!-- ... -->
    <script src="./screenfunctions.js"></script>
    <script src="./map.js"></script>
  </head>
  <!-- ... -->
</html>

// screenfunctions.js
function go() {
  console.log('Called go()');
  // ...
}

// map.js
// `go()` already exists, because `./screenfunctions.js` was included earlier in the markup.
go();

A: Yes! You'll want to export the function you want to use. See this doc for more information and examples.


text:
Q: Surface area of ellipsoid given by rotating $\frac{x^2}{2}+y^2=1$ around the x-axis Calculate the surface area of the ellipsoid that is given by rotating
$\frac{x^2}{2}+y^2=1$ around the x-axis.
My idea is that if $f(x)=\sqrt{1-\frac{x^2}{2}}$ rotates around the x-axis we will end up with the same figure. The formula for calculating the surface area is:
$ 2\pi \int_{-\sqrt{2}}^{\sqrt{2}} f(x)\sqrt{1+f'(x)^2}dx $ and with $f'(x)^2 = \frac{x^2}{4-2x^2}$ the integral becomes $$ \int \sqrt{1-\frac{x^2}{2}}\sqrt{1+\frac{x^2}{4-2x^2}} \space dx$$ Now how do I integrate this?

A: Looks like one of those times you'll just have to tangle with the algebra monster. $$\begin{align} \sqrt{1-\frac{x^2}{2}}\sqrt{1+\frac{x^2}{4-2x^2}} = \sqrt{\frac{2-x^2}{2}}\sqrt{\frac{4-x^2}{4-2x^2}} \\ = \sqrt{\frac{2-x^2}{2}}\sqrt{\frac{4-x^2}{2(2-x^2)}} \\ = \frac{1}{2} \sqrt{\frac{(2-x^2)(4-x^2)}{2-x^2}}\end{align} \\ = \frac{1}{2}\sqrt{4-x^2} $$ Can you take it from here?


text:
Q: How to mock private or protected class variable in Microsoft moles? I have the following example code as a class variable.
protected static readonly string _url = "SomeURL";

I want to access that _url variable through either stub type or moled type. As I test, public static class variables can be accessed through the stub type. But not the private or protected static class variables. So any idea regarding accessing the private or protected class variables from moles ? It will be very helpful.
Thank you !

A: You can create a stub that derives from the class containing the protected static variable. Use the stub in your test rather than the class you're actually trying to test:
public class MyActualClass
{
  protected static readonly string _url = "SomeURL";
  //... other code
}

public class MyActualClassStub : MyActualClasss
{
  public string GetUrlValue()
  {
    return _url;
  }
}

Something like that. Note that you can't change the value of a readonly member or property though.
Edit: I just realised you asked specifically about how to do this with Moles. I've not used Moles so I can't provide any advice in that direction. However, the approach described above is useful in many situations when you need to "get at" protected members, properties, or methods in a test scenario.


text:
Q: /usr/bin/ld: cannot find -lpthreads I'm compiling NVIDIA Caffe tool on a Fedora 22 and I having problems to find lpthread library:
Determining if the pthread_create exist failed with the following output:
Change Dir: /home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/gmake" "cmTC_d410e/fast"
/usr/bin/gmake -f CMakeFiles/cmTC_d410e.dir/build.make CMakeFiles/cmTC_d410e.dir/build
gmake[1]: Entering directory '/home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp'
Building C object CMakeFiles/cmTC_d410e.dir/CheckSymbolExists.c.o
/usr/bin/cc    -o CMakeFiles/cmTC_d410e.dir/CheckSymbolExists.c.o   -c /home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp/CheckSymbolExists.c
Linking C executable cmTC_d410e
/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_d410e.dir/link.txt --verbose=1
/usr/bin/cc       CMakeFiles/cmTC_d410e.dir/CheckSymbolExists.c.o  -o cmTC_d410e -rdynamic
CMakeFiles/cmTC_d410e.dir/CheckSymbolExists.c.o: En la función `main':
CheckSymbolExists.c:(.text+0x16): referencia a `pthread_create' sin definir
collect2: error: ld devolvió el estado de salida 1
CMakeFiles/cmTC_d410e.dir/build.make:97: recipe for target 'cmTC_d410e' failed
gmake[1]: Leaving directory '/home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp'
Makefile:126: recipe for target 'cmTC_d410e/fast' failed
gmake[1]: *** [cmTC_d410e] Error 1
gmake: *** [cmTC_d410e/fast] Error 2

File /home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp/CheckSymbolExists.c:
/* */
#include <pthread.h>

int main(int argc, char** argv)
{
  (void)argv;
#ifndef pthread_create
  return ((int*)(&pthread_create))[argc];
#else
  (void)argc;
  return 0;
#endif
}

Determining if the function pthread_create exists in the pthreads failed with the following output:
Change Dir: /home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/gmake" "cmTC_e693b/fast"
/usr/bin/gmake -f CMakeFiles/cmTC_e693b.dir/build.make CMakeFiles/cmTC_e693b.dir/build
gmake[1]: Entering directory '/home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp'
Building C object CMakeFiles/cmTC_e693b.dir/CheckFunctionExists.c.o
/usr/bin/cc   -DCHECK_FUNCTION_EXISTS=pthread_create   -o CMakeFiles/cmTC_e693b.dir/CheckFunctionExists.c.o   -c /usr/share/cmake/Modules/CheckFunctionExists.c
Linking C executable cmTC_e693b
/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_e693b.dir/link.txt --verbose=1
/usr/bin/cc   -DCHECK_FUNCTION_EXISTS=pthread_create    CMakeFiles/cmTC_e693b.dir/CheckFunctionExists.c.o  -o cmTC_e693b -rdynamic -lpthreads
/usr/bin/ld: cannot find -lpthreads
collect2: error: ld outputs 1
CMakeFiles/cmTC_e693b.dir/build.make:97: recipe for target 'cmTC_e693b' failed
gmake[1]: Leaving directory '/home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp'
Makefile:126: recipe for target 'cmTC_e693b/fast' failed
gmake[1]: *** [cmTC_e693b] Error 1
gmake: *** [cmTC_e693b/fast] Error 2

It seems that it doesn't find pthreads lib (/usr/bin/ld: cannot find -lpthreads), but running command find / name "*pthread*" it outputs this:
/usr/lib64/libpthread.so
/usr/lib64/libpthread.a
/usr/lib64/libpthread_nonshared.a
/usr/lib64/libpthread-2.21.so
/usr/lib64/libpthread.so.0

But there is something strange with this, becaue CMakeOutut.log has this:
Determining if the function pthread_create exists in the pthread passed with the following output:
Change Dir: /home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp

Run Build Command:"/usr/bin/gmake" "cmTC_705ba/fast"
/usr/bin/gmake -f CMakeFiles/cmTC_705ba.dir/build.make CMakeFiles/cmTC_705ba.dir/build
gmake[1]: Entering directory '/home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp'
Building C object CMakeFiles/cmTC_705ba.dir/CheckFunctionExists.c.o
/usr/bin/cc   -DCHECK_FUNCTION_EXISTS=pthread_create   -o CMakeFiles/cmTC_705ba.dir/CheckFunctionExists.c.o   -c /usr/share/cmake/Modules/CheckFunctionExists.c
Linking C executable cmTC_705ba
/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_705ba.dir/link.txt --verbose=1
/usr/bin/cc   -DCHECK_FUNCTION_EXISTS=pthread_create    CMakeFiles/cmTC_705ba.dir/CheckFunctionExists.c.o  -o cmTC_705ba -rdynamic -lpthread
gmake[1]: Leaving directory '/home/user1/Sources/caffe/build/CMakeFiles/CMakeTmp'

It has this line using lpthread:
/usr/bin/cc   -DCHECK_FUNCTION_EXISTS=pthread_create    CMakeFiles/cmTC_705ba.dir/CheckFunctionExists.c.o  -o cmTC_705ba -rdynamic -lpthread

And this is CMakeList.txt:
cmake_minimum_required(VERSION 2.8.7)

# ---[ Caffe project
project(Caffe C CXX)

# ---[ Caffe version
set(CAFFE_TARGET_VERSION "0.14.5")
set(CAFFE_TARGET_SOVERSION "0.14")
add_definitions(-DCAFFE_VERSION=${CAFFE_TARGET_VERSION})

# ---[ Using cmake scripts and modules
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/Modules)

include(ExternalProject)

include(cmake/Utils.cmake)
include(cmake/Targets.cmake)
include(cmake/Misc.cmake)
include(cmake/Summary.cmake)
include(cmake/ConfigGen.cmake)

# ---[ Options
caffe_option(CPU_ONLY  "Build Caffe without CUDA support" OFF) # TODO: rename to USE_CUDA
caffe_option(USE_CUDNN "Build Caffe with cuDNN library support" ON IF NOT CPU_ONLY)
caffe_option(BUILD_SHARED_LIBS "Build shared libraries" ON)
caffe_option(BUILD_python "Build Python wrapper" ON)
set(python_version "2" CACHE STRING "Specify which Python version to use")
caffe_option(BUILD_matlab "Build Matlab wrapper" OFF IF UNIX OR APPLE)
caffe_option(BUILD_docs   "Build documentation" ON IF UNIX OR APPLE)
caffe_option(BUILD_python_layer "Build the Caffe Python layer" ON)
caffe_option(USE_OPENCV "Build with OpenCV support" ON)
caffe_option(USE_LEVELDB "Build with levelDB" ON)
caffe_option(USE_LMDB "Build with lmdb" ON)
caffe_option(ALLOW_LMDB_NOLOCK "Allow MDB_NOLOCK when reading LMDB files (only if necessary)" OFF)

# ---[ Dependencies
include(cmake/Dependencies.cmake)

# ---[ Flags
if(UNIX OR APPLE)
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wall")
endif()

if(USE_libstdcpp)
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libstdc++")
  message("-- Warning: forcing libstdc++ (controlled by USE_libstdcpp option in cmake)")
endif()

add_definitions(-DGTEST_USE_OWN_TR1_TUPLE)

# ---[ Warnings
caffe_warnings_disable(CMAKE_CXX_FLAGS -Wno-sign-compare -Wno-uninitialized)

# ---[ Config generation
configure_file(cmake/Templates/caffe_config.h.in "${PROJECT_BINARY_DIR}/caffe_config.h")

# ---[ Includes
set(Caffe_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/include)
set(THIRDPARTY_DIR ${PROJECT_SOURCE_DIR}/3rdparty)
include_directories(${Caffe_INCLUDE_DIR} ${PROJECT_BINARY_DIR} ${THIRDPARTY_DIR})
include_directories(BEFORE src) # This is needed for gtest.

# ---[ Subdirectories
add_subdirectory(src/gtest)
add_subdirectory(src/caffe)
add_subdirectory(tools)
add_subdirectory(examples)
add_subdirectory(python)
add_subdirectory(matlab)
add_subdirectory(docs)

# ---[ Linter target
add_custom_target(lint COMMAND ${CMAKE_COMMAND} -P ${PROJECT_SOURCE_DIR}/cmake/lint.cmake)

# ---[ pytest target
add_custom_target(pytest COMMAND python${python_version} -m unittest discover -s caffe/test WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/python )
add_dependencies(pytest pycaffe)

# ---[ Configuration summary
caffe_print_configuration_summary()

# ---[ Export configs generation
caffe_generate_export_configs()

What do I have to install? Does libphreads exist or I have to use libphread?

A: You have a typo. You should use -lpthread instead of -lpthreads.
Alternatively you can just use -pthread, that also works.

A: I have this error when I follow the caffe doc on a new Ubuntu, and after some Google with caffe collect2: error: ld returned 1 exit status, I find I was lack of some packages, not typo:
sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libboost-all-dev libhdf5-serial-dev libgflags-dev libgoogle-glog-dev liblmdb-dev protobuf-compiler libatlas-base-dev
sudo apt-get install python-dev python-pip gfortran

For more detailed info, ref here.

A: The problem is caused by googletest, and just set the following line of CMakeList.txt of googletest:
option(gtest_disable_pthreads "Disable uses of pthreads in gtest." ON)

by the flags on.
The reason is:
We must check for the threads library under a number of different
names; the ordering is very important because some systems
(e.g. DEC) have both -lpthread and -lpthreads, where one of the
libraries is broken (non-POSIX).


text:
Q: android.support.v7.widget.Toolbar element is not declared Hi I'm new to android dev and start using Xamarin last week, I'm trying to build an app to test and learn how to use material design using Android Support Library v7 AppCompat.
I encounter a problem saying that the element is not declared even though I already added the component. I'm using Xamarin Visual studio.
First problem
Then I separate the toolbar but this happens
Kindly enlighten me about whats causing this.


text:
Q: How to generate csr file by X.509 certificate I wanna know how to generate csr file by using X.509 certificate standard.
What the different between X500Name and X509Name? I wanna add subject data with :
Common Name, Organization, Organization Unit, Locality, Country, State and Email.
Please explain how to generate csr file and give me some link.
Where do i add email in this X500Name?
X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
Please explain me!!!
Thanks.

A: X.500 is more general standard about organization of objects. X500Name is a name of such object in some structural repository/system.
X.509 is a substandard related to security objects, certificates, algorithms. See more >>

What the different between X500Name and X509Name?

X509Name could (incorrectly) be a name of certificate property - it should reather be e.g. "X500Name of some X509 cetificate attribute"


text:
Q: How to display customized fancybox when user presses F5 key or clicks browser's back / close button? I need to display a fancybox using onbeforeunload event or any other possiblities, and instead of native confirm box, i need to display my customized fancybox.
Here's my current code..
window.onbeforeunload = function(e) {
     $.fancybox({
          content : 'test'
     });
     return false; // if this line commented, browser won't wait for confirmation
}

Please provide working answers. Thanks..

A: Do you need something like this?
function unload(){
  $.fancybox('<div>Your custom element<div>');
}

$(document).ready(function() {
   window.onbeforeunload=function() {
    unload();
   };
});

Demo


text:
Q: AngularUI router issue "TypeError: Cannot read property 'name' of undefined" I have a set of DIV's that contain A's and use AngularUI to load Angular templates within a ui-view DIV. I'm implementing a set of tabs that switch between the view templates based on which one a user clicks. I have several of these within the application and all work as designed. However, on one of my pages I keep getting a "TypeError: Cannot read property 'name' of undefined" that blows up in the angular-ui-router isMatch() call in the $StateRefActiveDirective($state, $stateParams, $interpolate) function on the line 'return $state.includes(state.name) && matchesParams();' because state is not defined. I've stepped through the calls to this code and it processes all of the ui-srefs in my markup successfully. Then after those are processed it gags.
The only real difference between other pages with these tabs on them is that I have the other pages with no other markup on them except the tabs and their ui-views. On this one I have 2 bootstrap columns, a col-md-5 and col-md-7. The col-md-5 contains a table of objects. When the user clicks on one of the rows the col-md-7 is shown, the $state is changed to one of its tabs and the data for the object is loaded for the tab by its controller.
On the other pages the tabs are always displayed and clicking them takes you to different ui-views the same as the my problem child. One real difference between them is a directive I wrote to 'disable' the links based on a Boolean. The uiSrefIf directive is at the bottom of the JavaScript listing. The idea is that when the File tab is shown the other tabs are visible but disabled.
Here is the JavaScript and markup:

angular.module('meritApp.screens.importUsers', [
    'ui.router', 'ngSanitize', 'ui.select', 'ui.bootstrap', 'meritApp.global.services.profile',
    'meritApp.global.services.common', 'angularFileUpload', 'meritApp.global.services.managedFiles'
  ])
  .config(function($stateProvider) {

    $stateProvider
      .state('importUsers', {
        url: "/admin/importUsers",
        templateUrl: "app/screens/admin/importUsers/importUsers.html?v=" + APP_VERSION
      });

    $stateProvider
      .state('importUsers.file', {
        url: "/file",
        templateUrl: "app/screens/admin/importUsers/file.html?v=" + APP_VERSION
      });

    $stateProvider
      .state('importUsers.inserted', {
        url: "/inserted",
        templateUrl: "app/screens/admin/importUsers/inserted.html?v=" + APP_VERSION
      });

    $stateProvider
      .state('importUsers.insertError', {
        url: "/insertError",
        templateUrl: "app/screens/admin/importUsers/insertError.html?v=" + APP_VERSION
      });

    $stateProvider
      .state('importUsers.skipped', {
        url: "/skipped",
        templateUrl: "app/screens/admin/importUsers/skipped.html?v=" + APP_VERSION
      });

    $stateProvider
      .state('importUsers.updated', {
        url: "/updated",
        templateUrl: "app/screens/admin/importUsers/updated.html?v=" + APP_VERSION
      });

  })
  .controller('importUsersController', [
    '$scope', '$state', '$log', '$rootScope', '$filter', 'appConfig', '$http', 'roleSvc',
    function($scope, $state, $log, $rootScope, $filter, appConfig, $http, roleSvc) {

      $rootScope.$broadcast("SET_BREADCRUMB", []);

      $scope.itemsPerPage = 10;
      $scope.currentPage = 1;

      $rootScope.importing = false;

      $rootScope.roleChanged = function(user, role) {
        // todo - set the user's role
      };

      $scope.newImport = function() {
        $rootScope.importing = true;
        $rootScope.savedLocation = $rootScope.selectedLocation;
        $rootScope.selectedLocation = null;
      };

      $rootScope.defaultRole = {
        name: "Associate"
      };
      roleSvc.listAllActive(0, 40).then(
        function(response) {
          $rootScope.roles = $filter('orderBy')(response.data.results, "name");
          angular.forEach($rootScope.roles, function(role) {
            if (role.name == "Associate") {
              $rootScope.defaultRole = role;
            }
          });
        },
        function(err) {
          console.log("roleSvc.listAllActive Error: " + err.status + " " + err.statusText);
        });

      var init = function() {
        $scope.loading = true;
        $scope.locations = [];

        var skip = ($scope.currentPage - 1) * $scope.itemsPerPage;
        var userImportQueryPath = "queries/Merit.Components.UserImport.Queries/UserImportQueries";

        $http.get(appConfig.urlRoot + userImportQueryPath + "/GetImportSummaries/results").then(
          function(response) {
            $scope.totalItems = response.data.results.length;
            angular.forEach(response.data.results, function(location) {
              if (skip-- <= 0 && $scope.locations.length < $scope.itemsPerPage) {
                $scope.locations.push(location);
              }
            });

            $scope.loading = false;
          }, function(err) {
            alert("GetImportList Error: " + err.status + " - " + err.statusText);
          });

        $http.get(appConfig.urlRoot + userImportQueryPath + "/GetAuditRecords/results").then(
          function(response) {
            $rootScope.importData = [];
            angular.forEach(response.data.results, function(record) {
              record["isInvited"] = false;
              record["selectedRole"] = $rootScope.defaultRole;
              record.errorText = JSON.parse(record.errorText);
              $rootScope.importData.push(record);
            });

            $scope.users = _.sortBy($rootScope.importData, 'employeeId');
          }, function(err) {
            alert("GetImportList Error: " + err.status + " - " + err.statusText);
          });
      };

      init();

      $scope.refresh = function() {
        init();
      };

      $scope.viewImports = function(location) {
        $rootScope.selectedLocation = location;
        $state.go('importUsers.inserted', {}, {
          reload: true
        });
      };

      $rootScope.closeView = function() {
        $rootScope.importing = false;

        if ($rootScope.savedLocation) {
          $rootScope.selectedLocation = $rootScope.savedLocation;
          $rootScope.savedLocation = null;
        } else {
          $rootScope.selectedLocation = null;
        }
      };

      $scope.inviteUsers = function() {
        angular.forEach($scope.users, function(userArray) {
          if (userArray) {
            angular.forEach(userArray, function(user) {
              if (user.isInvited) {
                // todo - send email to invited user
                console.log("Sending email to " + user.name);
                user.isInvited = false;
              }
            });
          }
        });
      };
    }
  ])
  .controller('iuInsertedController', [
    '$scope', '$state', '$log', '$rootScope',
    function($scope, $state, $log, $rootScope) {

      $rootScope.$broadcast("SET_BREADCRUMB", []);

      $scope.itemsPerPage = 10;
      $scope.selectedTab = "Inserted";
      $scope.currentPage = 1;
      $scope.inviteCount = 0;

      var init = function() {
        $scope.users = [];
        $scope.totalItems = 0;

        if (!$rootScope.selectedLocation) return;

        var skip = ($scope.currentPage - 1) * $scope.itemsPerPage;

        angular.forEach($rootScope.importData, function(user) {
          if (user.isInserted && !user.hasErrors && user.locationCode == $rootScope.selectedLocation.code && user.timestampUtc == $rootScope.selectedLocation.timeStampUtc) {
            if (skip-- <= 0 && $scope.users.length < $scope.itemsPerPage)
              $scope.users.push(user);

            $scope.totalItems++;
          }
        });
      };

      init();

      $scope.refresh = function() {
        init();
      };

      $scope.invite = function(user) {
        $scope.inviteCount = (user.isInvited ? $scope.inviteCount + 1 : $scope.inviteCount - 1);
      };

      $scope.inviteUsers = function() {
        alert("todo - send email to invited users");

        angular.forEach($scope.users, function(user) {
          if (user.isInvited) {
            // todo - send email to invited user
            console.log("Sending email to " + user.name);
            user.isInvited = false;
          }
        });
      };
    }
  ])
  .controller('iuInsertErrorController', [
    '$scope', '$state', '$log', '$rootScope',
    function($scope, $state, $log, $rootScope) {

      $rootScope.$broadcast("SET_BREADCRUMB", []);

      $scope.itemsPerPage = 10;
      $scope.currentPage = 1;
      $scope.selectedTab = "Inserted with Errors";

      var importData = $rootScope.importData;

      var init = function() {
        $scope.users = [];
        $scope.totalItems = 0;

        if (!$rootScope.selectedLocation) return;

        var skip = ($scope.currentPage - 1) * $scope.itemsPerPage;

        angular.forEach(importData, function(user) {
          if (user.isInserted && user.hasErrors && user.locationCode == $rootScope.selectedLocation.code && user.timestampUtc == $rootScope.selectedLocation.timeStampUtc) {
            if (skip-- <= 0 && $scope.users.length < $scope.itemsPerPage)
              $scope.users.push(user);

            $scope.totalItems++;
          }
        });
      };

      init();

      $scope.refresh = function() {
        init();
      };

      $scope.inviteUsers = function() {
        angular.forEach($scope.users, function(userArray) {
          if (userArray) {
            angular.forEach(userArray, function(user) {
              if (user.isInvited) {
                // todo - send email to invited user
                console.log("Sending email to " + user.name);
                user.isInvited = false;
              }
            });
          }
        });
      };
    }
  ])
  .controller('iuUpdatedController', [
    '$scope', '$state', '$log', '$rootScope',
    function($scope, $state, $log, $rootScope) {

      $rootScope.$broadcast("SET_BREADCRUMB", []);

      $scope.itemsPerPage = 10;
      $scope.currentPage = 1;
      $scope.selectedTab = "Updated";

      var init = function() {
        $scope.users = [];
        $scope.totalItems = 0;

        if (!$rootScope.selectedLocation) return;

        var skip = ($scope.currentPage - 1) * $scope.itemsPerPage;

        angular.forEach($rootScope.importData, function(user) {
          if (user.isUpdated && user.locationCode == $rootScope.selectedLocation.code && user.timestampUtc == $rootScope.selectedLocation.timeStampUtc) {
            if (skip-- <= 0 && $scope.users.length < $scope.itemsPerPage)
              $scope.users.push(user);

            $scope.totalItems++;
          }
        });
      };

      init();

      $scope.refresh = function() {
        init();
      };

      $scope.inviteUsers = function() {
        angular.forEach($scope.users, function(userArray) {
          if (userArray) {
            angular.forEach(userArray, function(user) {
              if (user.isInvited) {
                // todo - send email to invited user
                console.log("Sending email to " + user.name);
                user.isInvited = false;
              }
            });
          }
        });
      };
    }
  ])
  .controller('iuSkippedController', [
    '$scope', '$state', '$log', '$rootScope',
    function($scope, $state, $log, $rootScope) {

      $rootScope.$broadcast("SET_BREADCRUMB", []);

      $scope.itemsPerPage = 10;
      $scope.currentPage = 1;
      $scope.selectedTab = "Skipped";

      var init = function() {
        $scope.users = [];
        $scope.totalItems = 0;

        if (!$rootScope.selectedLocation) return;

        var skip = ($scope.currentPage - 1) * $scope.itemsPerPage;

        angular.forEach($rootScope.importData, function(user) {
          if (user.wasSkipped && user.locationCode == $rootScope.selectedLocation.code && user.timestampUtc == $rootScope.selectedLocation.timeStampUtc) {
            if (skip-- <= 0 && $scope.users.length < $scope.itemsPerPage)
              $scope.users.push(user);

            $scope.totalItems++;
          }
        });
      };

      init();

      $scope.refresh = function() {
        init();
      };

      $scope.inviteUsers = function() {
        angular.forEach($scope.users, function(userArray) {
          if (userArray) {
            angular.forEach(userArray, function(user) {
              if (user.isInvited) {
                // todo - send email to invited user
                console.log("Sending email to " + user.name);
                user.isInvited = false;
              }
            });
          }
        });
      };
    }
  ])
  .controller('iuFileController', [
    '$scope', '$state', '$log', '$rootScope', 'managedFileSvc', 'commandSvc', 'appConfig', '$http', 'modalMsgSvc',
    function($scope, $state, $log, $rootScope, managedFileSvc, commandSvc, appConfig, $http, modalMsgSvc) {

      $rootScope.$broadcast("SET_BREADCRUMB", []);

      $scope.locations = mockExtraLocations;
      $scope.importLocation = undefined;
      $scope.importFile = undefined;
      $scope.buttonText = "Browse...";
      var locationsQueryPath = "queries/Merit.Components.Locations.Queries/LocationQueries";

      $http.get(appConfig.urlRoot + locationsQueryPath + "/FindAllActive/results?skip=" + 0 + "&pageSize=" + 20).then(
        function(response) {
          $scope.locations = response.data.results;
        }, function(err) {
          console.log("LocationQueries.FindAllActive Error: " + err.status + " - " + err.statusText);
        });

      $scope.doImport = function() {
        managedFileSvc.uploadFile($scope.importFile, function(evt) {
          console.log(evt);
          $scope.uploadProgress = evt;
        }, function(response) {
          console.log('upload response :: File ID: ', response[0].QueryReferences[0].QueryParameter);

          var command = {
            ImportFileId: response[0].QueryReferences[0].QueryParameter,
            LocationCode: $scope.importLocation.code,
            LocationName: $scope.importLocation.name
          };

          modalMsgSvc.showLoading("Importing...");

          commandSvc.publish('Merit.Components.User.Commands', 'ImportHumanicUsers', command)
            .then(function(record) {
              modalMsgSvc.hideLoading();
              console.log("ImportHumanicUsers Published: " + record.status);
              $scope.importFile = undefined;
              $rootScope.closeView();
              $state.go("importUsers", {}, {
                reload: true
              });
            }, function(err) {
              modalMsgSvc.hideLoading();
              if (err.errors)
                console.log("ImportHumanicUsers ERROR: " + err.errors[0]);
              else if (err.errorHeadline)
                console.log("ImportHumanicUsers ERROR: " + err.errorHeadline);
              else
                console.log("ImportHumanicUsers ERROR: unknown");
              // TODO?
            });
        });
      };

      $scope.fileSelected = function(files) {
        // even though ng-multiple is false, we still get an array
        if (files != null) {
          $scope.importFile = files[0];
        }
      };

      $scope.cancelImport = function() {
        $scope.importFile = undefined;
        $rootScope.closeView();

        if ($rootScope.selectedLocation)
          $state.go("importUsers.inserted");
      };
    }
  ])
  .directive('uiSrefIf', function($compile) {
    return {
      scope: {
        val: '@uiSrefVal',
        if : '=uiSrefIf'
      },
      link: function($scope, $element, $attrs) {
        $element.removeAttr('ui-sref-if');
        $compile($element)($scope);

        $scope.$watch('if', function(bool) {
          if (bool) {
            $element.attr('ui-sref', $scope.val);
          } else {
            $element.removeAttr('ui-sref');
            $element.removeAttr('href');
          }
          $compile($element)($scope);
        });
      }
    };
  });

Import Users

              New

Past Imports

                Location
                Update / New / Skip
                Imported

 0" ng-click="viewImports(location)">
                {{location.name}} - {{location.city}}, {{location.state}}
                {{location.updated}} / {{location.inserted}} / {{location.skipped}}
                {{location.timeStampUtc | date:'MM/dd/yyyy'}}

 0)">
                No Imports Found.

            <pagination total-items="totalItems" items-per-page="itemsPerPage" ng-model="currentPage" max-size="5" ng-show="totalItems > itemsPerPage || true" direction-links="false" boundary-links="false" rotate="false" ng-change="refresh()" class="pagination-sm pull-right"></pagination>

            NewView Import

                File

                Inserted

                Inserted with Errors

                Updated

                Skipped

Because we use so many service calls I haven't tried to get this working in Plunker. It's not a show stopper since the page behaves as expected. It is an annoyance that I'd like to understand and eliminate. Also, my QA folks can then stop complaining to me about it :)
Thanks, Mike


text:
Q: How to convert string type to shapely object I used to have a Pandas data frame with geometry column (I guess you call it as GeoPandas data frame) where all the instances were multiline string with shapely.geometry data type.
When I saved it as a csv (with pandas.to_csv function) I guess python converts them into string type, because when I try to reload it (with pandas.read_csv function), read data frame has a string type data under geometry column.
How can I convert string type MultilineString rows under geometry column into shapely.geometry object.
active.geometry[0]

Gives:
'MULTILINESTRING ((4.6902978485015 50.8812913672182, 4.69041863376864 50.8813473567576,
4.69048964428198 50.8814069648068, 4.69054925191282 50.8814797434961, 4.69058047643031 50.8815178675679, 4.69103203247511 50.8820691915014, 4.69112606776955 50.8821748368663, 4.69118560934351 50.8822527991125, 4.69122586159577 50.8823195293716, 4.69133401466373 50.8824824286198, 4.69153580362294 50.8827908199779, 4.69155260179444 50.8828164920095))'

BUT,
this:
active.geometry[0][0]

Gives
'M'

instead of a shapely object of the first line string that the multiline string objects is composed of.
I also tried shapely.wkt function but it outputs only the first lineString, instead all the lineStrings that multiline string has

A: You need to convert your pandas DataFrame to a geopandas GeoDataFrame to access the geometry column as shapely object. This post describes how to achieve it.
one solution:
from shapely import wkt
df = pd.read_csv('myFile.csv')
df['geometry'] = df['geometry'].apply(wkt.loads)
gdf = gpd.GeoDataFrame(df, crs='epsg:4326')

A: In addition to the answer of CodeBard:
When Pandas read a csv file, the columns are strings or numbers, never  shapely geometries. A Pandas DataFrame with a geometry column (string) is not a GeoPandas GeoDataFrame (geometry column, shapely geometry)
import pandas as pd
df = pd.read_csv("lat_long.csv")
df
          lat       lon           geometry
0  41.389474  2.156421  POINT (2.15642 41.38947)
1  41.383093  2.181116  POINT (2.18112 41.38309)
df.geometry[0]
'POINT (2.156421 41.389474)'
df.dtypes
lat         float64
lon         float64
geometry    object # not a shapely geometry, in Pandas, an object is a string and it performs strings operations
dtype: object

With the the solution of CodeBard
df['geometry'] = df['geometry'].apply(wkt.loads)
df.geometry[0]
<shapely.geometry.point.Point object at 0x1207ab828>
df.geometry[0].wkt
'POINT (2.156421 41.389474)'
# but
df.dtypes
lat         float64
lon         float64
geometry    object #

Even if the rows of the column are shapely geometries, this is still not a shapely geometry field
This is why GeoPandas was created (add a geopspatial component to Pandas). With a GeoDataFrame,
gdf = gpd.GeoDataFrame(df)
gdf.geometry[0]
<shapely.geometry.point.Point object at 0x1207ab828>
gdf.dtypes
lat          float64
lon          float64
geometry     geometry #  shapely geometry field here

But when you print or export the GeoDataFrame to a csv file (text file), the geometry field must be a string, the wkt representation of the shapely geometry (= geometry.wkt, POINT (2.15642 41.38947)), and not the shapely geometry (Point(2.15642,41.38947))
 from shapely.geometry import Point
 pt = Point(2.15642,41.38947)
 pt
 <shapely.geometry.point.Point object at 0x10e12ab00>
 pt.wkt
 'POINT (2.15642 41.38947)'
 print(pt)
 POINT (2.15642 41.38947)

gdf
          lat       lon           geometry
0  41.389474  2.156421  POINT (2.15642 41.38947)
1  41.383093  2.181116  POINT (2.18112 41.38309)


text:
Q: iPhone app freezes briefly during fetch for content updates. Can this be fixed? I have an iPhone app that displays blog articles. You can drill into one article and look at it's entire story. At the bottom of the story are comments from other users.
The app fetches latest comments from the server every 15 seconds. If there are more comments returned, the app prepends them to the top of the list. This is all working pretty well.
The problem is that, whenever the app does the fetch (every 15 seconds), the app sort of "freezes" for about 1 second, sometimes 2 seconds. If you are scrolling through the comments, this delay becomes pretty noticeable because the scrolling stops in place while the update processes.
This iPhone app is being developed by a third-party dev team who is remote. I have asked the dev team to stop the "freeze" from happening, but they insist that it's normal functionality when updating a table in the iPhone.
I am not an iPhone developer and have no knowledge or experience of working in that environment, so I am not able to really argue against this. But, I have to imagine that there is some way to do a background fetch and update of the table without causing lag to the user experience.
Does anyone have any thoughts around this? Are there techniques that the devs could be employing to create a smooth experience during the update process?

A: They are fetching comments in synchronous mode in which UI will hang until it downloads completely. Tell them to download content in asynchronous mode so that it will fetch comments in background and UI scrolling will be smooth then.
Example Codes:
[connection startAsynchronous];

https://gist.github.com/fspeirs/106457

http://allseeing-i.com/ASIHTTPRequest/How-to-use

Let me know if you find any difficulty.


text:
Q: Table Creation in Stata: Creating Multiple Row Variable Headers I am using esttab to create tables in Stata and rendering them in LaTeX and want to split an mgroups variable header so that it is stretched across two rows (i.e. basically creating two mgroups). This is so I can create a table that looks like this: link.
Since I haven't been able to figure out how to do this, I have for now combined the two 'subject type' and 'teacher gender' heading row, in the above table, into a single row using the following command:
esttab Classics_M_M Classics_F_M Classics_M_F Classics_F_F Science_M_M Science_F_M Science_M_F Science_F_F EScience_M_M EScience_F_M EScience_M_F EScience_F_F using "$dir/Graphs_Tables/tableA17.tex", p stats(N fixed1 fixed2 fixed3 fixed4 fixed5 fixed6 fixed7 fixed8, fmt(%9.0gc) labels("\vspace{0.7em} Observations \vspace{0.7em}" "Teacher Characteristics" "Previous Year Test Scores" "Grade FE" "Year FE" "Track FE" "Subject FE" "Class FE" "Student FE")) mlabels(Male Female Male Female Male Female Male Female Male Female Male Female, begin(Student Gender)) varlabels(tv "Teacher VA") mgroups("Classics Male" "Classics Female" "Science Male" "Science Female" "Exact Science Male" "Exact Science Female", pattern(1 0 1 0 1 0 1 0 1 0 1 0) begin(Subject and Teacher Gender) prefix(\multicolumn{@span}{c}{) suffix(}) span erepeat(\cmidrule(lr){@span})) f nomtitles booktabs drop(experience lag_mod _cons) nolines posthead(\midrule) replace

I have tried things like using two mgroups() commands and including "\par" in the titles to split them on two rows but no luck! I am hoping someone on here has an idea!

A: This is really a Latex question wrapped in a Stata question.
The Latex question: How to get the contents of a cell to wrap.
Variations of this are discussed often on tex.stackexchange, here are a couple.

*

*https://tex.stackexchange.com/questions/54069/table-with-text-wrapping

*

*Uses \newcommand.

*https://tex.stackexchange.com/questions/40561/table-with-multiple-lines-in-some-cells

*

*Just nests a table within a table.

The Stata question: Is there an easy way to do this from the esttab command? #2 above provides a relatively easy way to do this.
"Simply" replace: mgroups("Classics Male")
with mgroups("\begin{tabular}{@{}c@{}}Classics \\ Male\end{tabular}")
This is just an answer to #2 above dropped into your esttab statement, so that answer is certainly recommended reading.


text:
Q: TikZ drawing over plot I would like to draw the red line over the plotted points. What am I doing wrong?
Here is the code:
    \begin{figure}[!ht]
    \centering\
    \begin{tikzpicture}
    \begin{axis}[
  ymin=0, ymax=4.75,
  xmin=0, xmax=14.5,
  grid,
  xtick={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14},
  ytick={0,0.5,1,1.5,2,2.5,3,3.5,4,4.5},
 xlabel={Velocidad [rad/s]},
ylabel={Tensión DC [V]},
width=\textwidth,
height=0.7\textwidth,
]
\addplot[only marks,mark size = 0.4pt,
  mark options={teal}] table[x=vel_dec, y=v_DC_dec,col sep=semicolon]{k_E_DCPM.csv};
\draw[red, ultra thick, domain=0.2997:12.5188] plot (\x,{0.321210875886567*\x});

    \end{axis}
    \end{tikzpicture}
    \caption{Tensión generada en terminales en función de la velocidad del rotor de la máquina DCPM}
\label{fig:k_E_DCPM}
\end{figure}

Here is the output I get:

Thanks in advance.

A: You can use clip mode=individual like this:
\documentclass[tikz, border=1cm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin=0, xmax=14.5,
ymin=0, ymax=4.75,
grid,
xtick distance=1, ytick distance=0.5,
xlabel={Velocidad [rad/s]},
ylabel={Tensión DC [V]},
clip mode=individual,
]
\addplot[teal, only marks]{0.33*x};
\draw[red, ultra thick, domain=0.2997:12.5188, samples=2] plot (\x,{0.321210875886567*\x});
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Mouse & Touchpad Separate Settings Missing Ubuntu 16.04: The settings menu used to have separate settings for external mouse and touchpad, now it only contains one set of settings for both. The settings for pointer speed actually do not change any behavior of the mouse - the mouse motion doesn't change regardless the change in the speed setting.
This is what my settings look like after mouse & touchpad settings broke:

It looks like this might have been an issue before...  mouse and touchpad settings missing
...but I am running 16.04, not 14.04. There is no touchpad-indicator program by default, and when adding the repository listed in one of the answers, it didn't help anything.
This may also be related to ELAN touchpad suddenly stopped working, worked the day before, but I do not have nearly as many problems as that person is having:
The touchpad works, it is at an okay speed, I can scroll with two-fingers, but these are all settings I set before Settings broke like this. I can no longer change the speed, disable two-finger scrolling, or anything like that. No mouse settings, except for double-click speed and primary button work.
Again, this is what it is supposed to look like (something close to it). This is what it did look like, but now it looks like the one above.

I know an issue like this is a known bug: https://bugs.launchpad.net/ubuntu/+source/gnome-control-center/+bug/1132063, but this recently happened. That bug has been an issue for a while it seems, and my machine (originally 14.04) has been through updates and new releases, and it only recently broke after an update. As well, I have a basic "Mouse: Pointer Speed" setting in mine that isn't present in the bug report screenshots.
Any way to fix this?
Edit 1:
Output of xinput:
⎡ Virtual core pointer                       id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ Logitech M570                             id=10   [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=13   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ Sleep Button                              id=9    [slave  keyboard (3)]
    ↳ BisonCam, NB Pro                          id=11   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=12   [slave  keyboard (3)]

Edit 2:
Output of xinput list-props 13:
Device 'SynPS/2 Synaptics TouchPad':
    Device Enabled (151):   1
    Coordinate Transformation Matrix (153): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Tapping Enabled (301): 0
    libinput Tapping Enabled Default (302): 0
    libinput Tapping Drag Enabled (303):    1
    libinput Tapping Drag Enabled Default (304):    1
    libinput Tapping Drag Lock Enabled (305):   0
    libinput Tapping Drag Lock Enabled Default (306):   0
    libinput Accel Speed (284): 0.000000
    libinput Accel Speed Default (285): 0.000000
    libinput Natural Scrolling Enabled (289):   0
    libinput Natural Scrolling Enabled Default (290):   0
    libinput Send Events Modes Available (268): 1, 1
    libinput Send Events Mode Enabled (269):    0, 0
    libinput Send Events Mode Enabled Default (270):    0, 0
    libinput Left Handed Enabled (291): 0
    libinput Left Handed Enabled Default (292): 0
    libinput Scroll Methods Available (293):    1, 1, 0
    libinput Scroll Method Enabled (294):   1, 0, 0
    libinput Scroll Method Enabled Default (295):   1, 0, 0
    libinput Disable While Typing Enabled (307):    1
    libinput Disable While Typing Enabled Default (308):    1
    Device Node (271):  "/dev/input/event6"
    Device Product ID (272):    2, 7
    libinput Drag Lock Buttons (300):
    libinput Horizonal Scroll Enabled (273):    1

Edit 3:
Output of xinput list-props 13 after removing xserver-xorg-input-libinput:
Device 'SynPS/2 Synaptics TouchPad':
    Device Enabled (151):   1
    Coordinate Transformation Matrix (153): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    Device Accel Profile (279): 1
    Device Accel Constant Deceleration (280):   2.500000
    Device Accel Adaptive Deceleration (281):   1.000000
    Device Accel Velocity Scaling (282):    12.500000
    Synaptics Edges (303):  1768, 5410, 1645, 4563
    Synaptics Finger (304): 25, 30, 0
    Synaptics Tap Time (305):   180
    Synaptics Tap Move (306):   238
    Synaptics Tap Durations (307):  180, 100, 100
    Synaptics ClickPad (308):   0
    Synaptics Middle Button Timeout (309):  75
    Synaptics Two-Finger Pressure (310):    282
    Synaptics Two-Finger Width (311):   7
    Synaptics Scrolling Distance (312): 108, 108
    Synaptics Edge Scrolling (313): 0, 0, 0
    Synaptics Two-Finger Scrolling (314):   1, 1
    Synaptics Move Speed (315): 1.000000, 1.750000, 0.036866, 0.000000
    Synaptics Off (316):    2
    Synaptics Locked Drags (317):   0
    Synaptics Locked Drags Timeout (318):   5000
    Synaptics Tap Action (319): 0, 0, 0, 0, 0, 0, 0
    Synaptics Click Action (320):   1, 1, 0
    Synaptics Circular Scrolling (321): 0
    Synaptics Circular Scrolling Distance (322):    0.100000
    Synaptics Circular Scrolling Trigger (323): 0
    Synaptics Circular Pad (324):   0
    Synaptics Palm Detection (325): 0
    Synaptics Palm Dimensions (326):    10, 200
    Synaptics Coasting Speed (327): 20.000000, 50.000000
    Synaptics Pressure Motion (328):    30, 160
    Synaptics Pressure Motion Factor (329): 1.000000, 1.000000
    Synaptics Resolution Detect (330):  1
    Synaptics Grab Event Device (331):  0
    Synaptics Gestures (332):   1
    Synaptics Capabilities (333):   1, 0, 1, 1, 1, 1, 1
    Synaptics Pad Resolution (334): 65, 44
    Synaptics Area (335):   0, 0, 0, 0
    Synaptics Noise Cancellation (336): 8, 8
    Device Product ID (268):    2, 7
    Device Node (269):  "/dev/input/event6"

Settings menu after removing xserver-xorg-input-libinput:

So now all settings are working except for the touchpad speed.

A:
WARNING: Following these instructions blindly may damage your system and require you to do an install from scratch.  **Read the entirety of the answer and pay attention to all statements and caveats before attempting any commands or actions recommended in this answer.

You have installed libinput. It is used instead of xorg-synaptics to manage the touchpad.
Unfortunately current Ubuntu with Unity DE does not have libinput settings GUI by default. unity-control-center can control only of xorg-synapics.
Another option is to uninstall xserver-xorg-input-libinput package and use xserver-xorg-input-synaptics that is installed by default instead.

A: On my Lenovo Thinkpad L380 Yoga, I was having a similar issue on Pop!_OS 19.04 when I installed Unity. I had to install the xserver-xorg-input-synaptics package, and then the settings showed up.

A: DO NOT UNINSTALL xserver-xorg-input-libinput
Especially when You are on notebook, dont have wired connection (LAN cable) and don't have any other computer.
Your keyboard and mouse will stop working.
You will not be able to login to Your PC, You will not be able to launch terminal.
All You can do, is to download xserver-xorg-input-libinput and xserver-xorg-input-all on some other machine, put them on USB drive and install them manually from recovery mode.


text:
Q: How do I ask for user input and based on that input ask for following input I'm attempting to write a code that asks if a person completed a physical activity and if the user enters yes then  want to ask what the activity was but if they answer no then the program just prints that they didn't complete an activity. Here's what I've got so far
while True:
    largemuscle=input('Did they complete a large muscle activity for 1 hour today? y or n:')
    if largemuscle not in ('y','n'):
        print('not and appropriate choice please enter y or n')
        continue
    else:
        break
if largemuscle=='y':
    activity=input('What activity did they do for large muscle?:')
    largemuscle='He completed his large muscle today. For large muscle he'

elif largemuscle=='n':

    largemuscle='He did not complete a large muscle activity today'

print(largemuscle,activity)

The problem I'm running into is if the user enters 'n', then there is a traceback stating that activiy is not defined. If I add activity under the elif then I would need to have it be blank. also I want this printed off with other inputs in a paragraph and dont want there to be whitespace if the user enters n for the activity.

A: Your code is fine. The only thing you have to do is to initialize the activity variable and assign it to an empty string above your while loop:
activity=''


text:
Q: Best Language for real time analytics website I'm developing an app that is essentially going to pull data from a ton of different sources (twitter, facebook, github, basecamp, stackoverflow, etc.) and aggregate it all into a useful interface.  Everything is going to need to be real-time.
I'm thinking that the majority of the app will avoid database usage - so the data I pull isn't going to be stored, it'll just be repulled and formatted everytime a user needs it.  Obviously there is going to be a lot of AJAX involved and a lot of grabbing data from different APIs.
I'm most skilled in PHP, but I often times find it to be clunky, especially with this sort of thing.  What language or framework would be the cleanest for pulling this kind of data so often, and quickly parsing it for the user?  I know my way around Node.js and Ruby, but am very open to learning a new language/framework if need be.

A: all popular web languages are fine, but, i'd vote for node.js for the following reasons:

*

*you know it.

*easy for async networking to 3rd party services such as stackoverflow

*your system won't be so snappy and node.js can handle many simultaneous clients.

php you know too and has curl that can do multi get to solve 2. but that won't help you with 3. ruby is in the same boat as php.


text:
Q: Why does my scan tool still report a security issue? Our application uses HP Fortify to scan for security vulnerabilities.  One vulnerability that it's found is the Unreleased Resource: Database vulnerability.
The abstract suggests this as a solution:
public void execCxnSql(Connection conn) {

Statement stmt;

try {

stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(CXN_SQL);

...

}

finally {

if (stmt != null) {

safeClose(stmt);

}

}

}

public static void safeClose(Statement stmt) {

if (stmt != null) {

try {

stmt.close();

} catch (SQLException e) {

log(e);

}

}

}

Which I have implemented to some success on the following type of database connection closure:
if(conn != null){

try{

    conn.rollback();

    conn.Close(); // Report indicates an issue here

}catch SQLException{}

By transforming it into this:
if(conn != null){

try{

    conn.rollback();

}catch SQLException{}

finally{

safeClose(conn);  //Issue no longer reported

}

public static void safeClose(Connection stmt) {

if (stmt != null) {

try {

stmt.close();

} catch (SQLException e) {

log(e);

}

}

}

(Note: "Connection" is an SQL database connection)
However, attempting the same fix on this type of database closure:
if(conn != null){

try{

    conn.commit ();

    conn.Close(); // report indicates an issue here

}catch SQLException{}

Does not remove the issue from our security scan.
if(conn != null){

try{

    conn.commit();

}catch SQLException{}

finally{

safeClose(conn); // Issue not resolved

}

(Note our app is Java 1.4, so we cannot use "try-with-resourses")
The actual scan doesn't go into detail as to why the two are different – so assuming all other things about the application's use of the connection are the same (and they are as far as I can tell), what reason would it have for reporting a security issue in one case, and not the other?

A: if(conn != null){

try{

    conn.commit ();

    conn.Close(); // report indicates an issue here

}catch SQLException{}

So conn.close() will not be executed if conn.commit() throws SQLException, or for that matter any other exception.
As you guessed, move it to finally should resolve the issue if it resolves it in the other case.
Further, since Connection is AutoCloseable consider using try-with-resources


text:
Q: Sliding Header/NavBar I have a header but I am stuck at 2 things.

*

*How do I get it all positioned properly? What I want is it to be positioned as a header with a navbar at the bottom of it, then in that navbar I want a div that I can make slide around and I want x amount of tabs.

*How would I make the div slide left/right using JavaScript/JQuery? Sorry if it doesn't make sense.

My code is:

        //buttons/text here

I have tried using positioning (absolute/relative) but when I make the navBar relative it doesn't stay at the bottom but if I make both it and the slider absolute, the slider doesn't stay in the navBar. Is there any other way to accomplish it?

A: I am not able to understand how to make it work. However, here it goes.
The css for header would be:
.header {
display: block; // for that overall div..
}

Then you are having a top header, that would be more like a top header under which you want the nav bar. Ok for that you said you want it to be as header. Then just write it the way it is! And it will be used as a header, I mean just add some margins and paddings so that it has some distance from other objects.
#topHeader {
margin: 5px; // overall 5px pixel for all sides.
padding: 2px; // 2 pixel padding..
}

The nav bar, was the one with may buttons and texts that you will be using as hyperlinks to other pages. Right? So try using something like this:

First text

Second text

Third text

Now, show them all in a line. Because you wanted them in line, the list items will be shown in a line instead of being shown under each other as default. The x tabs will be the amount of the li used in the list, and it will show all the buttons or what ever you were trying to show. To do that the CSS is:
li {
display: inline;
}

To remove the bullet style, use this:
ul {
list-style: none;
}

This way the navbar will be shown in a line as other websites show.
Second question:
The sliders slide with the help of mouse, not jQuery (Just kidding). You can use scroll bars buddy, jQuery is used to scroll or slide, but that hides once slided. You will be able to see it but when it will scroll back it will hide, and go out of the page untill you slide it back again. You can just stick to the scroll bars to scroll or slide.
That's all!
jQuery slider:
From jQuery API if you check the slide() you will find out, that any event on any element would cause a slide (that will slide the element up and down) in some element.
Here would be an example:
$(document).ready(function () {
  $("#slider").click(function () {
    $(".navBar").slideToggle(1000); // the time consumed is 1 sec = 1000 milliseconds.
  }
});

You can see, that a click on the element with id="slider" would slide the element with class="navBar" and the slide will consume the time of 1 second.
Advice or Suggestion:
I would like to advise you to first learn the basics about the codes that you will use. They are easily searchable via Google, Bing or any other search engine. Because if you will post questions that you know nothing about would cause downvotes for you. That's ridiculous I know. So please when you are going to use jquery and know nothing about it, please try to go to Google and write this search item jquery if nothing found then append tutorial to the search query and find it. Best tutorial would be found on the site of the developer. Like you can learn jQuery on jquery.com and JSON at json.org.


text:
Q: How can I align such equation?
This is my code, but I'm failing to achieve the same result as in the picture.
\begin{eqnarray*}
\Delta&=\frac{2M}{2n+1}(1+\frac{1}{3}\cdot\frac{1}{(2n+1)^2}+\frac{1}{5}\cdot\frac{1}{(2n+1)^4}+...)&< \\
&<\frac{2M}{3(2n+1)^3}(1+\frac{1}{(2n+1)^2}+\frac{1}{(2n+1)^4}+...)&=\frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)}< \frac{2M}{24n^3}
\end{eqnarray*}

A: From question is not clear, how you like to have aligned your equation, so, I made two version. The first use array environment and align equation in two places (quite unusual), the second use align  and equation are aligned only in one plaece.
\documentclass{article}
    \usepackage{mathtools}

\usepackage[active,tightpage]{preview}% just for shoving only an equation
    \setlength\PreviewBorder{1em}

    \begin{document}
    \begin{preview}
\setlength\arraycolsep{2pt}
\[
    \begin{array}{rll}
\Delta  & = \frac{2M}{2n+1}\left(1+\frac{1}{3}\cdot\frac{1}{(2n+1)^2}
                            +\frac{1}{5}\cdot\frac{1}{(2n+1)^4}+\dotsm\right)
            & < \\[1ex]
        & < \frac{2M}{3(2n+1)^3}\Bigl(1+\frac{1}{(2n+1)^2}
                            +\frac{1}{(2n+1)^4}+\dotsm\Bigr)
            & = \frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)} < \frac{2M}{24n^3}
\end{array}
\]

\begin{align*}
\Delta  & = \frac{2M}{2n+1}\left(1+\frac{1}{3}\cdot\frac{1}{(2n+1)^2}
                            +\frac{1}{5}\cdot\frac{1}{(2n+1)^4}+\dotsm\right) \\
        & < \frac{2M}{3(2n+1)^3}\biggl(1+\frac{1}{(2n+1)^2}
                            +\frac{1}{(2n+1)^4}+\dotsm\biggr)
            = \frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)} < \frac{2M}{24n^3}
    \end{align*}

    \end{document}

I also change your elipsis with ones which are provided by amsmath (in ma MWE called by mathools)
Edit: As you can see, the fractions are not the same in both cases. In array environment are not in displaystyle mode. To have them equal as they are in align environment, than you need to replace \frac{...}{...} with \dfrac{...}{...}.
Now you can select a solution, which you more like.
Edit: Barbara Beeton noted me, that I would consider the size parenthesis too. So I correct my MWE so, that the first line of cases use \left( and \right) parenthesis, the second one \Bigl( and \Bigr) (the first case) and \biggl( and \biggr) respectively. By this I try to give comparison between automatic "stretchable" and "fixed" size of parenthesis. Many people prefer to use fixed size.

A: You can reproduce the picture, but I don't advise to:
\documentclass{article}
\usepackage{amsmath}
\usepackage{newtxtext,newtxmath}

\makeatletter
\newcommand{\Spread}[2]{%
  \ifmeasuring@
    #2%
  \else
    \makebox[\ifcase\expandafter #1\maxcolumn@widths\fi][s]{$\displaystyle#2$}%
  \fi
}
\makeatother

\begin{document}
\begin{alignat*}{2}
\Delta
&= \frac{2M}{2n+1}
   \biggl(1+\frac{1}{3}\cdot\frac{1}{(2n+1)^2}
           +\frac{1}{5}\cdot\frac{1}{(2n+1)^4}+\dotsb
   \biggr)
   &&< \\
&\Spread{2}{
   {<{}}\frac{2M}{3(2n+1)^3}
     \biggl(1+\frac{1}{(2n+1)^2}
             +\frac{1}{(2n+1)^4}+\dotsb
     \biggr)
    }
    &&= \frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)} < \frac{2M}{24n^3}
\end{alignat*}

\end{document}

The above code uses a number of nasty tricks I'm not going to explain. I'd rather explain why you shouldn't use that format:

*

*there's no need to repeat the < sign at the end of the first line;

*the entire construction is unbalanced.

I'd much prefer three lines:
\documentclass{article}
\usepackage{amsmath}
\usepackage{newtxtext,newtxmath}

\begin{document}
\begin{align*}
\Delta
&= \frac{2M}{2n+1}
   \biggl(1+\frac{1}{3}\cdot\frac{1}{(2n+1)^2}
           +\frac{1}{5}\cdot\frac{1}{(2n+1)^4}+\dotsb
   \biggr) \\
&< \frac{2M}{3(2n+1)^3}
   \biggl(1+\frac{1}{(2n+1)^2}
           +\frac{1}{(2n+1)^4}+\dotsb
   \biggr) \\
&= \frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)} < \frac{2M}{24n^3}
\end{align*}

\end{document}

A: To closely mimic the image, you can still do this (observe the font and italic symbol \mathit{\Delta}, etc):
\documentclass{article}
\usepackage{mathtools}
\usepackage{newtxtext,newtxmath}
\begin{document}

\setlength\arraycolsep{2pt}
\begin{eqnarray*}
\mathit{\Delta} &= \dfrac{2M}{2n+1}\left (\dfrac{1}{3}\cdot\dfrac{1}{(2n+1)^2}+\dfrac{1}{5}\cdot\dfrac{1}{(2n+1)^4}+\dotsc \right ) &< \\
&< \dfrac{2M}{3(2n+1)^3}\left (1+\dfrac{1}{(2n+1)^2}+\dfrac{1}{(2n+1)^4}+\dotsc \right ) &= \frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)} < \frac{2M}{24n^3}
\end{eqnarray*}

\end{document}

But, if you needed something more professional, you would go with mtpro2, for example. Your example, then, could be written in a better way like this (similar to egreg's proposition):
\documentclass{article}
\usepackage{amsmath}
\usepackage[lite]{mtpro2}
\begin{document}

\begin{align*}
\Delta
&= \frac{2M}{2n+1}
   \Bigl(\frac{1}{3}\cdot\frac{1}{(2n+1)^2}
           +\frac{1}{5}\cdot\frac{1}{(2n+1)^4}+\dotsb
   \Bigr) \\
&< \frac{2M}{3(2n+1)^3}
   \Bigl(1+\frac{1}{(2n+1)^2}
           +\frac{1}{(2n+1)^4}+\dotsb
   \Bigr) \\
&= \frac{2M}{3\cdot(2n+1)\cdot 2n \cdot (2n+2)} < \frac{2M}{24n^3}
\end{align*}

\end{document}