text:
Q: XSLT: Using parent node's namespace I would like to avoid producing a repeated namespace in my XSLT output.
(I am using XSLT to massage some XML so that Microsoft's DataContractSerializer sees fit to actually process it properly. One of the things that the DCS doesn't seem to like is defining the same namespace multiple times.)
I am taking all of the "Characteristics" elements from under the XXX element and grouping them together in a new array element like so:
<xsl:stylesheet version="1.0"
              xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              xmlns:feature="some namespace">
<xsl:template match="feature:XXX">
  <xsl:copy>
    <feature:Characteristics>
      <xsl:apply-templates select="feature:Characteristics"/>
     </feature:Characteristics>
    <xsl:copy-of select="*[not(self::feature:Characteristics)]" />
  </xsl:copy>
</xsl:template>
<xsl:template match="feature:Characteristics">
  <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <xsl:value-of select="." />
  </arrays:unsignedShort>
</xsl:template>
</xsl:stylesheet>

The "feature" namespace is defined at the top of the XSLT file. However the value "feature" is not going to be found in the source XML, it will be some arbitrary prefix (usually "h"). The problem is that if I use this XSLT then the namespace is assigned to 2 prefixes in the output XML: the original namespace from the input XML (usually "h") and "feature" generated by the XSLT. (While valid XML, this confuses poor Microsoft.)
So I would like to completely avoid defining the "feature" namespace in the output XML by instead referring to the current element's namespace instead. I tried variants on this but I don't know how to set the namespace value of the xsl:element correctly in order to get the current context node's namespace prefix...
<xsl:stylesheet version="1.0"
              xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              xmlns:feature="some namespace">
  <xsl:template match="feature:XXX">
   <xsl:copy>
    <xsl:element name="Characteristics" namespace="{???}">
      <xsl:apply-templates select="feature:Characteristics"/>
    </xsl:element>
    <xsl:copy-of select="*[not(self::feature:Characteristics)]" />
  </xsl:copy>
</xsl:template>
  <xsl:template match="feature:Characteristics">
  <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <xsl:value-of select="." />
  </arrays:unsignedShort>
</xsl:template>
</xsl:stylesheet>

Sample input:
<h:XXX xmlns:h="http://stackoverflow.com">
 <h:Characteristics>7</h:Characteristics>
 <h:Characteristics>11</h:Characteristics>
 <h:Characteristics>12</h:Characteristics>
 <h:ProductName>blah</h:ProductName>
 <h:Vendor>blah</h:Vendor>
 <h:Version></h:Version>
</h:XXX>

Repeat namespaces (bad):
<h:XXX xmlns:h="http://stackoverflow.com">
 <feature:Characteristic xmlns:feature="http://stackoverflow.com">
      <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">7</arrays:unsignedShort>
      <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">11</arrays:unsignedShort>
      <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">12</arrays:unsignedShort>
 </feature:Characteristic>
 <h:ProductName>blah</h:ProductName>
 <h:Vendor>blah</h:Vendor>
 <h:Version></h:Version>
</h:XXX>

Desired output:
<h:XXX xmlns:h="http://stackoverflow.com">
 <h:Characteristic>
      <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">7</arrays:unsignedShort>
      <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">11</arrays:unsignedShort>
      <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">12</arrays:unsignedShort>
 </h:Characteristic>
 <h:ProductName>blah</h:ProductName>
 <h:Vendor>blah</h:Vendor>
 <h:Version></h:Version>
</h:XXX>

This XSLT almost works, but it involves hardcoding the "h" value, and I would like to support an arbitrary value instead:
<?xml version ="1.0" encoding="iso-8859-1"?>
  <xsl:stylesheet version="1.0"
              xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              xmlns:feature="some ns"
              xmlns:h="some ns"
              exclude-result-prefixes="h">

<xsl:template match="feature:XXX">
  <xsl:copy>
    <h:Characteristic>
      <xsl:apply-templates select="feature:Characteristics"/>
    </h:Characteristic>
    <xsl:copy-of select="*[not(self::feature:Characteristics)]" />
  </xsl:copy>
</xsl:template>

<xsl:template match="feature:Characteristics">
  <arrays:unsignedShort xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <xsl:value-of select="." />
  </arrays:unsignedShort>
 </xsl:template>

 </xsl:stylesheet>

A: I just removed that feature namespace; if I understood correctly, it'll contain same URI  than h, right?
<xsl:stylesheet version="1.0"
              xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              xmlns:h="http://stackoverflow.com">
  <xsl:output method="xml" indent="yes" />
  <xsl:template match="h:XXX" >
    <xsl:copy>
      <h:Characteristics>
        <xsl:apply-templates select="h:Characteristics"/>
      </h:Characteristics>
      <xsl:copy-of select="*[not(self::h:Characteristics)]" />
    </xsl:copy>
  </xsl:template>
  <xsl:template match="h:Characteristics">
    <arrays:unsignedShort
        xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
      <xsl:value-of select="." />
    </arrays:unsignedShort>
  </xsl:template>
</xsl:stylesheet>

A: This seems to work for me, I am sure there must be an easier way but I cannot think at this moment. All this does it use the name() function to get the prefixed name of the root name, substring-before() to get the prefix then rebuild the values and emit them as unescaped text.
<xsl:stylesheet version="1.0"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          xmlns:feature="http://stackoverflow.com"
      exclude-result-prefixes="feature" >
<xsl:template match="feature:XXX">
  <xsl:variable name="p" select="substring-before(name(), ':')"/>
  <xsl:copy>
   <xsl:value-of select="concat('<', $p,':Characteristic', '>')" disable-output-escaping="yes"/>
   <xsl:apply-templates select="feature:Characteristics"/>
   <xsl:value-of select="concat('</', $p,':Characteristic', '>')" disable-output-escaping="yes"/>
   <xsl:copy-of select="*[not(self::feature:Characteristics)]" />
 </xsl:copy>
</xsl:template>
  <xsl:template match="feature:Characteristics">
   <arrays:unsignedShort
       xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
     <xsl:value-of select="." />
   </arrays:unsignedShort>
 </xsl:template>
</xsl:stylesheet>

A: If you want consistent namespace prefixes then you will need to generate new elements, rather than copy-of.  Set your namespace prefix to whatever you want it to be (feature, h, etc) in the XSLT.
The following XSLT:
<xsl:stylesheet version="1.0"
              xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
              xmlns:feature="http://stackoverflow.com"
              xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <xsl:output method="xml" indent="yes" />

  <xsl:template match="feature:XXX">
   <xsl:element name="feature:XXX">
    <feature:Characteristic>
      <xsl:apply-templates select="feature:Characteristics"/>
    </feature:Characteristic>
    <xsl:apply-templates select="*[not(self::feature:Characteristics)]" />
  </xsl:element>
  </xsl:template>

  <xsl:template match="feature:Characteristics">
    <xsl:element name="arrays:unsignedShort">
        <xsl:value-of select="." />
    </xsl:element>
  </xsl:template>

  <xsl:template match="*">
     <xsl:element name="feature:{local-name()}" >
        <xsl:value-of select="." />
     </xsl:element>
  </xsl:template>

</xsl:stylesheet>

Generates the following output:
<?xml version="1.0" encoding="UTF-16"?>
<feature:XXX xmlns:feature="http://stackoverflow.com">
 <feature:Characteristic xmlns:arrays="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <arrays:unsignedShort>7</arrays:unsignedShort>
  <arrays:unsignedShort>11</arrays:unsignedShort>
  <arrays:unsignedShort>12</arrays:unsignedShort>
 </feature:Characteristic>
 <feature:ProductName>blah</feature:ProductName>
 <feature:Vendor>blah</feature:Vendor>
 <feature:Version></feature:Version>
</feature:XXX>


text:
Q: Running a macro via task scheduler in Windows server 2012 We have created a macro to run in MS access (Office 365) on windows server 2012 so that it runs script that creates and sends emails via MS outlook. We can run the macro from inside MS Access but we cannot get windows task scheduler to automatically schedule this process. What we are doing is creating invoices for our customers automatically using MS Access. The macro works perfectly if we execute it within the open file. It creates all the emails with an invoice attached as a PDF which is then sent via outlook to our customers. This is all done with one click of the macro. But we cannot get this process to schedule via windows task scheduler. Can anyone help?

A: I am answering my own question as the comments don't allow enough info to be posted.
We have finally managed to do this using the suggestion in one of the above comments to use Outlook reminders rather than task scheduler.
This solution involves setting up a task and scheduled reminder in OUTLOOK.
The recurrent schedule for the reminder in Outlook acts as a replacement for Task Scheduler.
We categorised the reminder to aid the exact identification. (For task add new category and give it a name)
The VBA script in Outlook is triggered by identifying the reminder category and the MSAccess macro is initiated which sends the emails then closes the Access application. This is done on a set scheduled recurrent basis as set for this Outlook reminder task.
The only  issue we had was with the following line
    mydb.Application.Run "MacroName"
the resulting error was rectified by
mydb.DoCmd.RunMacro "MacroName"
We now have a method of scheduling which works.
It would seem that when an Access VBA script, which includes sending an email is  called from an OUTLOOK scheduled script it has no problem in completing the task, whereas, the exact same script actioned through Task Scheduler just does not complete.
Hope this helps others.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error al compilar proyecto en Angular Estoy usando Angular (versión 6) con TypeScript (versión 1.6) y cuando compilo el código obtengo estos errores:
Date: 2018-09-13T19:39:25.926Z
Hash: 0a25dba23a607e77d976
Time: 5711ms
chunk {main} main.js, main.js.map (main) 1.91 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 685 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.22 kB [entry] [rendered]
chunk {scripts} scripts.js, scripts.js.map (scripts) 142 kB  [rendered]
chunk {styles} styles.js, styles.js.map (styles) 148 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 326 kB [initial] [rendered]
i 「wdm」: Failed to compile.

ERROR in Cannot read property 'loadChildren' of undefined

Este es el codigo de mi appmodules.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { EmpleadoComponent } from './empleado/empleado.component';
import { appRouting } from './app.routing';
import { RouterModule,Routes } from '@angular/router';

const appRoutes: Routes = [
  { path: 'empleado', component: EmpleadoComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    EmpleadoComponent
  ],
  imports: [
    appRouting,
    CommonModule,
    RouterModule.forRoot(routes),
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  exports: [
  RouterModule
  ],

  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
Q: Indented text after title How can I achieve this

without specifying indent size? I found tips, how to indent all paragraph etc., but I think, thats not what I want. I need easy way, because I found it in many documents (title + description) and it looks like thats a some kind of \paragraph{}.

A: As suggested by @David Carlisle, it seems you're after a description environment, with the 'title' on a line of its own. You can obtain this very easily with enumitem:
\documentclass{book}
\usepackage{enumitem}
\setlength\parindent{1em}

\begin{document}

\begin{description}[style=nextline, listparindent=\parindent, parsep=0pt]
  \item[The First Item]This text describes the first item.
  \item[The Second Item]This text describes the second item.
        Contrary to the description of the first item, it is quite a bit longer.

        Additionally, it consists of multiple paragraphs, which causes problems
  with redefining the item command.
\end{description}

\end{document}


text:
Q: Woocommerce how do I add an "Add to cart" button in content-widget-product.php I am looking to add the "add to cart" button in the woo commerce content-widget-product that is called from the woocommerce widget..
Here is the code now
<?php global $product; ?>

<a href="<?php echo esc_url( get_permalink( $product->id ) ); ?>" title="<?php echo esc_attr( $product->get_title() ); ?>">
    <?php echo $product->get_image(); ?>
    <?php echo $product->get_title(); ?>

<?php if ( ! empty( $show_rating ) ) echo $product->get_rating_html(); ?>
<?php echo $product->get_price_html(); ?>

Any ideas what I would need to add to put the add to cart button in? Im looking EVERYWHERE and dying here

A: Here is how you can add  "add to cart" button with this code :
 global $product;
 $product_id = $product->id;
 echo do_shortcode('[add_to_cart id="'.$product_id.'"]');

A: Copy content-widget-product.php to your theme's /woocommerce folder as per WooCommerce's template override system.


text:
Q: Why does Ruby convert integer to octal-escaped string instead of hex-escaped one? I need:
"ff".hex.chr #=> "\xff"

but instead I get:
"ff".hex.chr #=> "\377"

Where is my mistake? What is missing? Environment is HBase 0.98.6 shell, which seems to be based on JRuby 1.6.8 console.

A: "\xff" and "\377" are different representations of the same data:

*

*"\xff" is hexdecimal, and is typical of newer Ruby versions.

*"\377" is octal, and is typical of older Ruby versions.

You can see how the same number produces different strings:
printf("%o",255) #=> "377"
printf("%x",255) #=> "ff"

The default representation is a typically due to your console settings and Ruby version.
In general, do not rely on String#inspect to produce a consistent  represenation, even on the same Ruby version. You can see this in action if you use some of the special characters:
"\007" #=> "\a"

The String#inspect method has altered the representation to neither octal nor hex.
If you're outputting to a system that requires a specific format, you can be explicit:
printf("\\x%x", 255) #=> \xff  # lower case
printf("\\x%X", 255) #=> \xFF  # upper case

You can also try the pack and unpack methods:
["ff"].pack("H*") #=> "\xFF"

If your string is always hex digits, and your desired output is just inserting "\x" in front of every two characters, then there's a fast solution:
print "a1b2c3".gsub(/../){"\\x#{$&}"}
#=> \xa1\xb2\xc3

A good quick introduction to Ruby string represenations and how to work with unprintable characters is in the Safari Books Ruby Cookbook

A: Lessons learned:

*

*Actually there was no any functional problem with octets. Just representation (thank to all comments and answers). Internally String content was the same.

*Yes, in Ruby 1.8 there was String#inspect with "%03o" format. And yes, HBase 0.98.6 uses this Ruby version for JRuby 1.6.8. This cannot be easily resolved in my case.

*Inspection has nothing to actual results so I have used Hbase Bytes class and prepared special printer for people who needs to see expected keys representation.

Here is the code which actually solves all my tasks including output that was wanted:
# Convert binary string to hex digits.
def bin_to_hex(s)
  s.each_byte.map { |b| b.to_s(16).rjust(2, '0') }.join
end

# Convers hex string to binary string.
def hex_to_bin(s)
  s.scan(/../).map { |x| x.hex.chr }.join
end

# HBase special 'convert and print' routine to get hex digits, process them and print.
def print_hex_to_bin(s)
  Kernel.print "\"" + Bytes.toStringBinary(s.scan(/../).map { |x| x.hex.chr }.join.to_java_bytes) + "\"\n"
end

Composed mostly based on http://anthonylewis.com/2011/02/09/to-hex-and-back-with-ruby/


text:
Q: Help needed on resolving a string into MDX expression The string is stored in a parameter.
Say, @FiscalPeriod = "[Date].[Fiscal Dates].[Fiscal Quarter]"
Now,
I need to use the parameter as
SELECT Measures.[Revenue] ON 0,
CLOSINGPERIOD("Parameter Here") ON 1
FROM [Sales]
STRTOMEBER function gives error because it is looking for a member at the leaf left such as
 [Date].[Fiscal Dates].[Fiscal Quarter].&[Q1 - 2009]
How can I resolve the string into the mdx expression to use it with closing period??

A: The following should work:
SELECT Measures.[Revenue] ON 0,
STRTOMEMBER("CLOSINGPERIOD(" + @FiscalPeriod + ")") ON 1
FROM [Sales]


text:
Q: How to save information in array for session to recall php So this is from a very bad PHP book. It assumes you already know how to do PHP and gives totally inapplicable examples for the questions it asks. I need to save the tasks to an array so when the page opens back up it shows the tasks you made previously. The web is almost devoid of any PHP examples beyond the extremely simple and extremely difficult.
<?php
$lifetime = 60 * 60 * 24 * 365 ;
session_set_cookie_params($lifetime, "/");
session_start();

if (empty($_SESSION['tasks'])) $_SESSION['tasks'] = array();

if (isset($_POST['tasklist'])) {
    $task_list = $_POST['tasklist'];
} else {
    $task_list = array();
}

$errors = array();

switch( $_POST['action'] ) {
    case 'add':
        $new_task = $_POST['newtask'];
        if (empty($new_task)) {
            $errors[] = 'The new task cannot be empty.';
        } else {
            $task_list[] = $new_task;
        }
        break;
    case 'delete':
             $task_index = $_POST['taskid'];
             unset($task_list[$task_index]);
            $task_list = array_values($task_list);
            break;
    }

task_list.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Task List Manager</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>

Task List Manager

    <?php if (count($errors) > 0) : ?>

Errors

        <?php foreach($errors as $error) : ?>

<?php echo $error; ?>

        <?php endforeach; ?>

    <?php endif; ?>

Tasks

    <?php if (count($task_list) == 0) : ?>

There are no tasks in the task list.

    <?php else: ?>

        <?php foreach($task_list as $id => $task) : ?>

<?php echo $id + 1 . '. ' . $task; ?>

        <?php endforeach; ?>

    <?php endif; ?>

Add Task

    <form action="." method="post" >
        <?php foreach($task_list as $task) : ?>
          <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/>
        <?php endforeach; ?>
        <input type="hidden" name="action" value="add"/>
        Task:
        <input type="text" name="newtask" id="newtask" />

        <input type="submit" value="Add Task"/>
    </form>

    <?php if (count($task_list) > 0) : ?>

Delete Task

    <form action="." method="post" >
        <?php foreach($task_list as $task) : ?>
          <input type="hidden" name="tasklist[]" value="<?php echo $task; ?>"/>
        <?php endforeach; ?>
        <input type="hidden" name="action" value="delete"/>
        Task:
        <select name="taskid">
            <?php foreach($task_list as $id => $task) : ?>
                <option value="<?php echo $id; ?>">
                    <?php echo $task; ?>
                </option>
            <?php endforeach; ?>
        </select>

        <input type="submit" value="Delete Task"/>
    </form>
    <?php endif; ?>

A: You are not storing new array in _SESSION after modify (switch with actions). Do it in this way:
$_SESSION['tasks'] = $task_list;

To view them:
foreach($_SESSION['tasks'] as $value) {
    //display task
}

Btw, this is terrible idea. You should use database. Some hostings blocks session_set_cookie_params and User will lost his data after clearing browser cache.
You should also call it like that:
session_set_cookie_params($time);

Second parameter is optional.
More datailed example
Core:
//session start etc
if(!isset($_SESSION['tasks'])) $_SESSION['tasks'] = array();
if(isset($_POST['action']) {
    switch($_POST['action']) {
        case 'add':
            if(isset($_POST['newtask']) && !empty($_POST['newtask']))
                $_SESSION['tasks'][] = $_POST['newtask'];
            break;
        case 'remove':
            if(isset($_POST['taskid']))
                unset($_SESSION['tasks'][$_POST['taskid']]);
            break;
    }
}

Display:
echo '<form method=post><input type=hidden name=action value=remove>';
foreach($_SESSION['tasks'] as $k => $v) {
    echo $v.'
Remove: <input type=submit name=taskid value='.$k.'>';
}
echo '</form>';

Add:
<form method=post>
<input type=hidden name=action value=add>
<input type=text name=newtask>
<input type=submit>
</form>


text:
Q: How to manually join two different table with different attribute name in Ruby on Rails controller I am currently making a website that runs on Ruby on Rails. I am facing some issues while I was trying to join two tables, Rates and Locations, that I have with two different attributes name.
Rates: id rater_id rateable_id (and a few more attributes in this table)
Locations: id title body user_id (and a few more attributes in this table)
Here is the query that I am trying to do in SQL.
SELECT *
FROM rates, locations
WHERE rates.rater_id = locations.user_id AND rates.rateable_id = locations.id

I have read the official active record documents that provided by rubyonrails.org. I have tried doing these, but it does not work. Here is the code that I am trying to implant in app\controllers\users_controller.rb
@join_rating = Rate.joins(:locations).where("rates.rateable_id = locations.id AND rates.rater_id = locations.id")
@all_rating = @all_rating.where(rater_id: @user)
@count_all_rating = @all_rating.count

@join_rating, is trying to join the attributes with different names.
@all_rating, is trying to filter which location to show using the user ID
@join_rating, is trying to calculate the total numbers of locations that are rated by the user
Assume that everything is setup correctly and the only error is in the query that I am trying to do, how should I rewrite the statement so that I am able to show the locations that the user has rated using @all_rating.
Thank you!

A: A few points:
When in ActiveRecord you're starting a statement with the Rate class, it means the result is going to be a collection of Rate objects. So if you're trying to show locations, you should start with a Location class.

@locations_user_rated = Location.joins('INNER JOIN rates ON
  rates.rateable_id = locations.id').where('rates.rater_id' => @user)

And if your ActiveRecord associations are well defined, you could simply do:

@locations_user_rated = Location.joins(:rates).where('rates.rater_id' => @user)

"Well defined" simply means you'll need to do something like the following. Note that I am not sure I understand your model relationships correctly. I assume below that every location has multiple rates, and that the reason your Rate model has the field called rateable_id instead of a location_id is because you want :rateable to be polymorphic. This means you probably also have a rateable_type field in rates table.
class Location < ActiveRecord::Base
  has_many :rates, as: :rateable
end

class Rate < ActiveRecord::Base
  belongs_to :rateable, polymorphic: true
end

If this polymorphism is not the case, things should actually be simpler, and I highly recommend that you follow Rails's conventions and simply name the relationship field location_id on your Rate model instead of rateable_id. Then you can do:
class Location < ActiveRecord::Base
  has_many :rates
end

class Rate < ActiveRecord::Base
  belongs_to :location
end

If still you are not convinced about the field name, you can customize things and do:
class Location < ActiveRecord::Base
  has_many :rates, foreign_key: :rateable_id
end

class Rate < ActiveRecord::Base
  belongs_to :location, foreign_key: :rateable_id
end

You can find more about how to customize associations here, and here.

A: I highly recommend taking advantage of ActiveRecord's has_many, belongs_to, and has_many through: functionality.
If you set up a model for each of these tables, with the correct relationships:
class User < ActiveRecord::Base
  has_many :ratings, foreign_key: :rater_id
  has_many :rated_locations, through: ratings, class_name: Location.name, source: :rater
end

class Rating < ActiveRecord::Base
  belongs_to :rater, class_name: User.name
  belongs_to :location
end

class Location < ActiveRecord::Base
  has_many :ratings
end

Then to access the locaitons that a user has rated, you just call
user.rated_locations


text:
Q: Successfully installed libtiff but while importing getting error I installed libtiff successfully in python 2.7 using "pip install libtiff". It successfully installed the libtiff-0.4.0 package.
But when I am importing the package using "import libtiff".I get an error which is:
     Traceback (most recent call last):
    File "D:/Python/p1.py", line 1, in <module>
     import libtiff
    File "D:\Python\lib\site-packages\libtiff\__init__.py", line 20, in <module>
      from .libtiff_ctypes import libtiff, TIFF, TIFF3D
        File "D:\Python\lib\site-packages\libtiff\libtiff_ctypes.py", line 41,         in <module>
    raise ImportError('Failed to find TIFF library. Make sure that libtiff is    installed and its location is listed in PATH|LD_LIBRARY_PATH|..')
ImportError: Failed to find TIFF library. Make sure that libtiff is installed and its location is listed in PATH|LD_LIBRARY_PATH|..

Kindly Clarify.

A: I got libtiff to work with the following steps:

*

*install Microsoft Visual C++ 9.0

*install GnuWin32 TIFF

*pip install libtiff
Then, in my script I just used the os library to add the necessary folder to my path:
import os
os.environ["PATH"] += os.pathsep + "C:\\Program Files\\GnuWin32\\bin"

(Of course you can edit your path variable manually as well.)

A: I encounter the same problem, but when I install the packge offline I worked well.
you should download libtiff at https://www.lfd.uci.edu/~gohlke/pythonlibs/ where you search
libtiff in the web, then you can obtain it.
last, you can pip install that in its path.


text:
Q: How to create n-level (multi-level, cascading) dependent dropdown (selects, options)? Purpose: To find the easiest and more flexible way creating cascading dropdown lists, using tools jquery(javascript), php, mysql;
If you have other easier/flexible options then please, share it.

A: HTML
<select class="step1 step" name="step1"></select>
<select class="step2 step" name="step2"></select>
<select class="step3 step" name="step3"></select>
<select class="step4 step" name="step4"></select>
<select class="step5 step" name="step5"></select>

For information purposes, usually on last dropdown is selected:
<textarea id="info" disabled=""></textarea>

JQUERY
$.get(url, function(data){
    var options = function(data, level, selected) {
        $.each(data, function(i, item) {
            var pid = $('.step'+(level-1)).val();

            if(pid == item.pid || item.pid == 0) {
                if(!$('.step').find('option[value='+item.id+']').length) {
                    $('.step'+level).append($('<option>', {
                        value: item.id,
                        text : item.name,
                        info: item.info,
                    }));
                }

                if(item.childs)
                    options(item.childs, level+1);
            }
        });

        var info = $('.step option:selected:last').attr('info');
        $('#info').val(info);
    }
    options(data, 1);

    $('.step').change(function() {
        var selected = $(this).val();
        $(this).nextAll('.step').empty();

        options(data, 1);
    });
});

JSON
{"1":{"id":"1","name":"Category-1","info":"","pid":"0","childs":{"3":{"id":"3","name":"Category-1-2","info":"","pid":"1","childs":{"19":{"id":"19","name":"Captiva","info":"Some text","pid":"3"}}}}}}

and so on ...
PHP
foreach ($info as $key => $value) {
    $info[$value->id] = $value;
    unset($info[0]);
}

foreach($info as $key => $val)
    $childs[$val->pid][$key] = $val;

foreach($info as $item)
    if (isset($childs[$item->id]))
        $item->childs = $childs[$item->id];

$total = count($info);
foreach($info as $key => $val){
    if($info[$key]->pid != 0)
        unset($info[$key]);
}

MYSQL
CREATE TABLE IF NOT EXISTS `dropdown_list` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `info` varchar(1000) NOT NULL,
  `pid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


text:
Q: Push inside forEach with query not working properly I'm working with mongodb stitch/realm and I'm trying to modify objects inside an array with a foreach and also pushing ids into a new array.
For each object that i'm modifying, I'm also doing a query first, after the document is found I start modifying the object and then pushing the id into another array so I can use both arrays later.
The code is something like this:
exports = function(orgLoc_id, data){
    var HttpStatus = require('http-status-codes');
    // Access DB
    const db_name = context.values.get("database").name;
    const db = context.services.get("mongodb-atlas").db(db_name);
    const orgLocPickupPointCollection = db.collection("organizations.pickup_points");
    const orgLocStreamsCollection = db.collection("organizations.streams");
    const streamsCollection = db.collection("streams");

    let stream_ids = [];

    data.forEach(function(stream) {

      return streamsCollection.findOne({_id: stream.stream_id}, {type: 1, sizes: 1}).then(res => { //if I comment this query it will push without any problem
        if(res) {
          let newId = new BSON.ObjectId();
          stream._id = newId;
          stream.location_id = orgLoc_id;
          stream.stream_type = res.type;
          stream.unit_price = res.sizes[0].unit_price_dropoff;
          stream._created = new Date();
          stream._modified = new Date();
          stream._active = true;

          stream_ids.push(newId);

        }
      })
    })
    console.log('stream ids: ' + stream_ids);

    //TODO

  };

But when I try to log 'stream_ids' it's empty and nothing is shown. Properties stream_type and unit_price are not assigned.
I've tried promises but I haven't had success

A: It's an asynchronous issue. You're populating the value of the array inside a callback. But because of the nature of the event loop, it's impossible that any of the callbacks will have been called by the time the console.log is executed.
You mentioned a solution involving promises, and that's probably the right tack. For example something like the following:
exports = function(orgLoc_id, data) {
  // ...
  let stream_ids = [];
  const promises = data.map(function(stream) {
    return streamsCollection.findOne({ _id: stream.stream_id }, { type: 1, sizes: 1 })
      .then(res => { //if I comment this query it will push without any problem
        if (res) {
          let newId = new BSON.ObjectId();
          // ...
          stream_ids.push(newId);
        }
      })
  })

  Promise.all(promises).then(function() {
    console.log('stream ids: ' + stream_ids);

    //TODO
    // any code that needs access to stream_ids should be in here...
  });
};

Note the change of forEach to map...that way you're getting an array of all the Promises (I'm assuming your findOne is returning a promise because of the .then).
Then you use a Promise.all to wait for all the promises to resolve, and then you should have your array.
Side note: A more elegant solution would involve returning newId inside your .then. In that case Promise.all will actually resolve with an array of the results of all the promises, which would be the values of newId.


text:
Q: datepicker and css style I have a problem with a date picker that I attached to my page
the style of the date picker is overridden by another style, and it makes the datepicker bad
the file which affect the datepicker style is
the css sheets
but when I put this .css online I got this result
the current view
any help!

A: problem is width in smoothness.css file
.ui-datepicker {
    display: none;
    padding: 0.2em 0.2em 0;
    width: 17em;//remove this line then it will work or change into auto
}

A: LESS might be a perfect solution. Convert the CSS to LESS by add a scope like this
#myId{
  .ui-datepicker {
          ... /* width:auto; (in example) */
  }
}

Now convert it back via LESS2CSS to
#myId .ui-datepicker{
   ...
}

Regards.

A: add !important;  to the end of any CSS styles that are clashing with the other style sheet but you want them to be the ones taking effect


text:
Q: Defining template function with std::is_invocable_v outside of class I have this class:
template <typename T>
class Value {
    private:
    bool fixed;
    union {
        T value;
        std::function<T()> get;
    };

    public:
    Value(const T& value);
    template <typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
    Value(F&& get);
    Value(const T* pointer);
    ~Value();
    operator T();
};

I initially wrote it all on a header file but am now transfering the code to a .cpp file. The problem is I don't know how to include the typename = std::enable_if_t<std::is_invocable_v<F>> part when defining Value(F&& get).
First, I tried:
template <typename T>
template <typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
Value<T>::Value(F&& get) : fixed(false), get(std::forward<F>(get)) {}

which produced the error:
error: a default template argument cannot be specified on the declaration of a member of a class template outside of its class

Then, after reading this answer, I tried:
template <typename F>
std::enable_if_t<std::is_invocable_v<F>>
Value<T>::Value(F&& get) : fixed(false), get(std::forward<F>(get)) {}

which results in:
error: return type may not be specified on a constructor

What should I do instead?

A:     template <typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
    Value(F&& get);

Here, std::enable_if_t<std::is_invocable_v<F>> is a default template argument (default value of the second template argument) and you have already specified it in the declaration inside the class. So, when you add an implementation outside the class, you should omit the default value:
template <typename T>
template <typename F, typename>
Value<T>::Value(F&& get) : fixed(false), get(std::forward<F>(get)) {}

This is indeed what the error says: a default template argument cannot be specified on the declaration of a member of a class template outside of its class


text:
Q: Keras loss consistently low but accuracy starts high then drops First off my assumptions might be wrong:

*

*Loss is how far from the correct answer each training example is (then divided by the number of examples -  kind of a mean loss).

*Accuracy is how many training examples are correct (if the highest output is taken as the correct answer then it doesn't matter if it's 0.7 which would give a loss of 0.3, it still outputs the correct answer). This is given as a percentage.

To my eye that means that accuracy will typically be closer to 100% than loss will be to 0.  This is not what I'm seeing:
10000/10000 [==============================] - 1067s - loss: 0.0408 - acc: 0.9577 - val_loss: 0.0029 - val_acc: 0.9995
Epoch 2/5
10000/10000 [==============================] - 991s - loss: 0.0021 - acc: 0.9997 - val_loss: 1.9070e-07 - val_acc: 1.0000
Epoch 3/5
10000/10000 [==============================] - 990s - loss: 0.0011 - acc: 0.4531 - val_loss: 1.1921e-07 - val_acc: 0.2440

That's on 3 epochs, the second attempt at getting this working. This is with the train_dategen having shuffle=True. I have results with shuffle=False (I initially thought this might be the issue), here:
10000/10000 [==============================] - 1168s - loss: 0.0079 - acc: 0.9975 - val_loss: 0.0031 - val_acc: 0.9995
Epoch 2/5
10000/10000 [==============================] - 1053s - loss: 0.0032 - acc: 0.9614 - val_loss: 1.1921e-07 - val_acc: 0.2439
Epoch 3/5
10000/10000 [==============================] - 1029s - loss: 1.1921e-07 - acc: 0.2443 - val_loss: 1.1921e-07 - val_acc: 0.2438
Epoch 4/5
10000/10000 [==============================] - 1017s - loss: 1.1921e-07 - acc: 0.2439 - val_loss: 1.1921e-07 - val_acc: 0.2438
Epoch 5/5
10000/10000 [==============================] - 1041s - loss: 1.1921e-07 - acc: 0.2445 - val_loss: 1.1921e-07 - val_acc: 0.2435

I use categorical_crossentropy for loss, since I have 3 classes. I have more data than needed (about 178,000 images, all classified into 1 of 3 classes).
Am I misunderstanding something, or has something gone wrong?
Here's my full code:
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (200, 200, 3), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 3, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('dataset/training_set',
                target_size = (200, 200),
                batch_size = 64,
                class_mode = 'categorical',
                shuffle=True)

test_set = test_datagen.flow_from_directory('dataset/test_set',
                target_size = (200, 200),
                batch_size = 62,
                class_mode = 'categorical',
                shuffle=True)

classifier.fit_generator(training_set,
                steps_per_epoch = 10000,
                epochs = 5,
                validation_data = test_set,
                validation_steps=1000)

classifier.save("CSGOHeads.h5")
# Part 3 - Making new predictions
import numpy as np
from keras.preprocessing import image
test_image = image.load_img('dataset/single_prediction/1.bmp', target_size = (200, 200))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
training_set.class_indices
if result[0][0] == 1:
    prediction = 'head'
else:
    prediction = 'not'

A: Since you are classifying images into one of 3 classes (i.e. which is called single-label multi-class classification: there are multiple classes but each image has only one label) you should use softmax as the activation function of last layer instead of using sigmoid:
classifier.add(Dense(units = 3, activation = 'softmax')) # don't use sigmoid here

If you want me to explain more, let me know and I will update my answer.

A: To complement @today's answer, if the last layer's activation is sigmoid, the loss should be binary_crossentropy. It's a recipe for multi-label classification problems. Otherwise, for one-label classification, use softmax plus categorical_crossentropy. Do not mix up sigmoid with categorical_crossentropy.


text:
Q: Firebase - How to extend FirebaseError? I am implementing a cloud function for signing up with unique username and password.
In order to throw exceptions, I was previously doing the following:
signUpValidation.js
if (!validateUsername(username)) {
  throw new functions.https.HttpsError(
    "invalid-argument",
    "Invalid username.",
    {
      status: "error",
      code: "auth/invalid-username",
      message: "Username must be between 3 and 30 characters, including numbers, letters, hyphens, periods, or underscores.",
    }
  );
}

signUp.function.js
try {
  await validateSignUpData(
     username,
     email,
     password,
     repeatPassword,
     name,
     birthday,
     clientIp
  );
} catch(err) {
    if (err instanceof functions.https.HttpsError) {
      throw err;
    }

    // An unknown error has occurred
    console.error(err);

    throw new functions.https.HttpsError(
      "unknown",
      "Unexpected error.",
      {
        status: "error",
        code: err.code ?? "unknown",
        message: err.message ?? "The registration request could not be processed. Please, try again later."
      }
    );
}

But, I don't really like this way of throwing the exceptions in the signUpValidation module... it makes more sense to me to throw "AuthErrors" instead of "HttpsErrors".
So, as it seems not possible to extend the default Firebase Errors, I have decided to create my own util/authErrors module:
class AuthError extends Error {
  constructor(code, message) {
    super(message);
    this.code = code;
    this.name = "AuthError";
  }
}

const authErrors = Object.freeze({
  usernameAlreadyExists(message = "The username is already in use by an existing account") {
    return new AuthError('auth/email-already-exists', message);
  }

   ... more errors
});

module.exports = authErrors;

as you can see, I have created my custom Error and some factory functions for every error type. Then, in my signUpValidation.js, I just do:
if (!(await isUsernameUnique(username))) {
  throw authErrors.usernameAlreadyExists();
}

Is it possible to extend a FirebaseError? If not, why?
Is it considered a bad practice to work this way in order to throw custom exceptions in Cloud Functions? I mean, should I just throw HttpsErrors?

A: Having Custom Error Type is useful if you are going to treat it differently.
For example if you have a try/catch block and want to have a different logic for your custom error.
but here you are passing error to client which has no idea of either Firebase HttpsError or your custom AuthError. because at the end your object will be serialized to JSON and at the other end there is no class to convert it back to HttpsError or AuthError.
Also at HTTP protocol level, authentication errors are defined by HTTP status codes (e.g. 401 ,403) so they are not inherently different object types.
What I'm saying is that I don't see any advantage in having a custom AuthError class on your server side when it can not be transformed as it is to your client to be treated differently.
For client the HTTP status code is the key to differentiate an Auth error from other type of errors.


text:
Q: Problems with size of logo in the nav I have problems with bootstrap website template. I wanted to change width of the logo but that isnt working and I tried to change some things like max-width and more but this was useless, dont know how to do right way. What I want is to have bigger logo image and centered. I will be so grateful if someone can fix that.
Website template: https://technext.github.io/newbiz/index.html


text:
Q: WP_Query order by multiple meta keys & fields How to order query by multiple meta keys and fields/custom fields?
This is my code:
$args = array
    (
        'post_type' => 'listing',
        'posts_per_page' => -1,
        'tax_query' => array
        (
            array
            (
                'taxonomy' => 'listing_category',
                'field' => 'slug',
                'terms' => urldecode($category)
            ),
            array
            (
                'taxonomy' => 'location',
                'field' => 'slug',
                'terms' => urldecode($location)
            )
        ),

        //*** THIS NOT WORK
        'meta_query'    => array
        (
            array(
                'key'     => 'listing_status',
                'orderby' => 'meta_value',
                'order' => ASC,
            ),
            array(
                'key'     => 'listing_total_rank',
                'orderby' => 'meta_value',
                'order' => DESC,
            ),
            array(
                'key'     => 'listing_free_date',
                'orderby' => 'meta_value',
                'order' => ASC,
            ),
            array(
                'key'     => 'title',
                'orderby' => 'meta_value',
                'order' => ASC,
            ),
        ),
        //***
    );

$listings = new WP_Query( $args );

The part of 'meta_query' does not working in the code.

A: You are using meta query without setting a value. The way you are doing it is using to query posts, not to order them.
Using Named Meta Queries
To order your posts by different meta datas, you can give your meta queries a name and then use that to set the ordering. Here is a simple example for you:
$args = array(
    'meta_query' => array(
        'relation' => 'AND',
        'query_one' => array(
            'key' => 'key_one',
            'value' => 'value_one', // Optional
        ),
        'query_two' => array(
            'key' => 'key_two',
            'compare' => 'EXISTS', // Optional
        ),
    ),
    'orderby' => array(
        'query_one' => 'ASC',
        'query_two' => 'DESC',
    ),
);

You can check this section of codex page for WP_Query() to familiarize yourself with sorting the posts.


text:
Q: Applying templates to elements in a variable/sequence When I use "apply-templates" and select a variable sequence, does the template act upon the context of the element in the sequence, or does it act upon the context of the element in the document?
In the below example, it seems to do either, or none, but I don't understand why.
<root>

<c></c>

</root>

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="root">

    <xsl:variable name="someElementA1" select="//a"/>
    <xsl:variable name="someElementA2">
        <xsl:copy-of select="//a"/>
    </xsl:variable>
    <xsl:for-each select="$someElementA1/a">
        <xsl:element name="test">
            <xsl:text>This is scenario 1: </xsl:text>
            <xsl:apply-templates select="."/>
        </xsl:element>
    </xsl:for-each>
    <xsl:for-each select="$someElementA2/a">
        <xsl:element name="test">
            <xsl:text>This is scenario 2: </xsl:text>
            <xsl:apply-templates select="."/>
        </xsl:element>
    </xsl:for-each>
    <xsl:element name="test">
        <xsl:text>This is scenario 3: </xsl:text>
        <xsl:apply-templates select="$someElementA1"/>
    </xsl:element>
    <xsl:element name="test">
        <xsl:text>This is scenario 4: </xsl:text>
        <xsl:apply-templates select="$someElementA2/a"/>
    </xsl:element>
</xsl:template>

<xsl:template match="a[parent::c]">
    <xsl:text>This element has a parent</xsl:text>
</xsl:template>
<xsl:template match="a[parent::root]">
    <xsl:text>This element is in the root element</xsl:text>
</xsl:template>
<xsl:template match="a">
    <xsl:text>This element is in the sequence</xsl:text>
</xsl:template>
</xsl:stylesheet>

OUTPUT:
<test>This is scenario 2: This element is in the sequence</test>
<test>This is scenario 2: This element is in the sequence</test>
<test>This is scenario 2: This element is in the sequence</test>
<test>This is scenario 3: This element is in the root elementThis element has a parentThis element is in the root element</test>
<test>This is scenario 4: This element is in the sequenceThis element is in the sequenceThis element is in the sequence</test>

A: The results you get are due to the following facts:

*

*A sequence of nodes contains the nodes as they are in their respective document -- not copies of the nodes.

*<xsl:copy-of> creates a copy of each node selected by the expression in the select attribute.

creates a new XML fragment (temporary tree) and this is the value of the variable $someElementA2
$someElementA1/a

does not select any node, because none of the elements in $someElementA1 have any children named a.
$someElementA2/a

selects all elements a that are children of the document node (/).


text:
Q: Hide certain fields in Django admin site for different user I have an admin site that I need to open up to more admins.
Currently my model looks like
class YouTube(models.Model):
    name =  models.CharField(max_length=100)
    credit_card_number = models.CharField(max_length=100)

Is there a way in the admin site frame work to make it so that only superusers can see the credit card number?  In the admin site framework, I can only see the ability to add, edit, delete.

A: Create method YouTube.get_cc_root_only, where you are to check if user is root, and use it in YouTubeAdmin class (list_display)
UPDATED:
class XyzAdmin(admin.ModelAdmin):
    def get_cc_root_only(self, obj):
        if self.username == "admin":
            return "CC"
        return "XXX"

    def changelist_view(self, request, extra_context = None):
        self.username = request.user.username
        return super(XyzAdmin,self).changelist_view(request, extra_context = extra_context)

    list_display = ("name", "get_cc_root_only")


text:
Q: Access 2010 - Query to produce a total count/sum of specific occurences in multiple Tables using Union All and Sum Iif I have a database with four tables: Table 1, 2, 3, & 4. Each table holds the following fields: ID (AutoNumber), Date (Date/Time), Name (Text), and Item (Text)
I created an SQL Query that uses Union All and a Sum Iif expression to retrieve the number of "Apples", "Oranges", and "Pears" that occur under the Item column for each individual. For example, when the Query runs, I want the query to provide me the date, the name of the individual, and the grand total of "Apples", "Oranges", and/or "Pears" for the date and individual. (12/15/2015 - Dee Wolf - 15 Apples, 10 Oranges, 20 Pears)
Problem: My query successfully counts all of the data from all 4 tables, however, it is not producing a total. It is, instead, giving my a 1-to-1 count for each table. For example: Table 1 will show that John has 1 apple and 1 orange, where Table 2 shows that John has 2 apples and 1 orange. When I run my query, it will show that John has 2 apples, 1 apple, 1 orange, and 1 orange (a result for each table), but I want it to just say John has 3 total apples.
I have written this code in another database and it seems to produce the results I want. But I'm not sure why I'm unable to reproduce the results. Am I overlooking something?
Here is the SQL:
SELECT Table1.Date, Table1.Name, Sum(IIf([Table1]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table1]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table1]![Item]="Pears",1,Null)) AS CountPears
FROM Table1
GROUP BY Table1.Date, Table1.Name
HAVING (((Table1.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table1.Name)))
UNION ALL
SELECT Table2.Date, Table2.Name, Sum(IIf([Table2]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table2]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table2]![Item]="Pears",1,Null)) AS CountPears
FROM Table2
GROUP BY Table2.Date, Table2.Name
HAVING (((Table2.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table2.Name)))
UNION ALL
SELECT Table3.Date, Table3.Name, Sum(IIf([Table3]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table3]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table3]![Item]="Pears",1,Null)) AS CountPears
FROM Table3
GROUP BY Table3.Date, Table3.Name
HAVING (((Table3.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table3.Name)))
UNION ALL
SELECT Table4.Date, Table4.Name, Sum(IIf([Table4]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table4]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table4]![Item]="Pears",1,Null)) AS CountPears
FROM Table4
GROUP BY Table4.Date, Table4.Name
HAVING (((Table4.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table4.Name)));

A: HAVING ((...) AND ((Table1.Name)))

still doesn't make much sense...
To get the totals, wrap your whole query into a Sum() / GROUP BY query:
SELECT [Date], [Name], Sum(CountApples) AS TotalApples, Sum(CountOranges) AS TotalOranges,
                       Sum(CountPears) AS TotalPears
FROM (
    -- your UNION query goes here
)
GROUP BY [Date], [Name]

(Shamelessly lifted from https://stackoverflow.com/a/32274957/3820271)


text:
Q: How can I use the actual datetime for a field in Odoo 11 I want some like datetime.now() or similar in Odoo 11 to get the actual date and time.
I tried the code I saw in another answers in stawoverflow, but doesn´t works for me. Can someone put an example for how to do it?
Examples that doesn´t works:
exit = fields.Datetime('Date current action', required=False, readonly=False, select=True, default=lambda self: fields.datetime.now())

exit = fields.Datetime(string="Date current action", default=lambda *a: datetime.now())

exit= fields.Date.context_today(self, timestamp=datetime.datetime.now())

A: from datetime import datetime

    exit = fields.Date(string='Date Current Action',default=datetime.now())

A: Use:
default=fields.Datetime.now

You can find an example at sale.py.
The following explanation is taken from Odoo 11 ORM API

class odoo.fields.Datetime(string=, **kwargs)
     ...
For default values fields.datetime.now() should be used instead.

Edit
You can also use time module to set default values
default=lambda *a: time.strftime('%Y-%m-%d')

A: try to use lambda For example in Odoo 8 to Odoo 14 :
exit = fields.Datetime(string="Date",  default=lambda *a: datetime.now())


text:
Q: jolt transform json nested array into array of jsons I want to transform my json into another json with jolt. I have the following JSON :
{
  "centre": [
    {
      "name": "A",
      "accesses": [
        {
          "name": "a",
          "totalInputs": 140,
          "totalOutputs": 77
        },
        {
          "name": "b",
          "totalInputs": 1374,
          "totalOutputs": 1068
        }
      ]
    },
    {
      "name": "B",
      "accesses": [
        {
          "name": "c",
          "totalInputs": 610,
          "totalOutputs": 511
        }
      ]
    }
  ]
}

and I want to extract information from diferent levels of the tree and form a list of jsons. This is my expected output:
[
  {
    "center": "A",
    "accesses": "a",
    "totalInputs": 140,
    "totalOutputs": 77
  },
  {
    "center": "A",
    "accesses": "b",
    "totalInputs": 1374,
    "totalOutputs": 1068
  },
  {
    "center": "B",
    "accesses": "c",
    "totalInputs": 610,
    "totalOutputs": 511
  }
]

A: You can separate the objects by center and accesses through use of &3 and &1 substitutions respectively while walking by the indices of the accesses array within a shift transformation such as
[
  {
    "operation": "shift",
    "spec": {
      "centre": {
        "*": {
          "accesses": {
            "*": {
              "@(2,name)": "&3[&1].&4", // go the tree up two levels and grab the "name"'s value while separating the objects by the indices of ***center*** and ***accesses*** arrays
              "n*": "&3[&1].&2", // filter "name" in this object by using "n*"(eg. a key starting with "n") since only name's key needs to be replaced, and go two levels up to grab the literal "accesses"
              "*": "&3[&1].&" // the rest of the attributes within the current object
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "" // get rid of the key names
      }
    }
  }
]

the demo on the site http://jolt-demo.appspot.com/ is


text:
Q: LHT00SU1 logic analyzer clock generator I was using a LHT00SU1 logic analyzer and according to this it should have the capability to produce a variable frequency signal (i assume through the CLK pin).
Using pulseview with fx2lafw firmware I didn't find any way to use that function, is it possible to use it?

A: From what I can see you can do what you want. However I do not have the time to read the manual for you but here is a link to it. https://www.usbee.com/axmanual.pdf I got this information from the link you provided.
The first five lines from your link:
The Noname LHT00SU1 is a USB-based, 8-channel logic analyzer with up to 24MHz sampling rate, with 1 additional analog channel (theoretically 2, but only one of them can be used at a time; 3MHz analog bandwidth).
It is a clone of the CWAV USBee AX-Pro.
In sigrok, we use the open-source fx2lafw firmware for this logic analyzer.
Note: fx2lafw currently doesn't support switching between the two possible analog channels, 1ACH will be used unconditionally.
See Noname LHT00SU1/Info for some more details (such as lsusb -v output) on the device.


text:
Q: JQuery: Send data through Ajax before openining modal I have a form with a single text box and a button, once the button is pressed the value entered in the textbox is then passed to my index method that runs a linq query. the results are then to be displayed on a modal.
I'm new to ajax but after looking at several other posts Ive come up with the below, my problem is that the ajax runs and the modal opens but the data has not been populated. Can anyone see where I'm going wrong?
Here is my code:
Form:
<form id="getDataForm" action="/Home/Index" method="get" role="form">
        Enter Code, IMEI or Phone Number:

            <input id="filtername" name="filtername" type="text" class="form-control" value="" placeholder="Please Enter Code" data-toggle="popover" data-original-title="Larger Tool tip."/>

        <input id="btnGetData" class="btn btn-success" value="GO" />
    </form>

Home/Index method:
[HttpGet]
    public ActionResult Index(string filtername)
    {
        var filterresults = from m in db.UserInfoes select m;
        filterresults = filterresults.Where(x => x.UserCode.ToString().Contains(filtername)).OrderBy(x => x.UserCode);

        MasterModel model = new MasterModel();
        model.UserInfo = filterresults;

        return CheckUserLogged(model);
    }

JQuery:
$("#btnGetData").click(function () {
    $.ajax({
        type: "GET",
        url: "/Home/Index",
        data: $('#getDataForm').serialize(),
        datatype: "html",
        success: function (data) {
            $('#basicModal2').modal('show');
            console.log("yaya");
        }
    });
});

Edit Added Modal:
@* Existing Request - Date Selection Modal *@

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

Summary

Results

<button type="submit" class="btn btn-success" id="toggle">Toggle</button>

                        Date
                        Diagnostic Mode

                    @if (Model != null)
                    {
                        foreach (var item in Model.UserInfo)
                        {

                                    <input type="checkbox" class="checks">

                                    @Html.DisplayFor(modelItem => item.CreationDateTime)

                                    @Html.DisplayFor(modelItem => item.AppModeId)

                        }
                    }

Usefull info:
I followed this which allowed me to see the value being called as it should:
Go to the web page which makes the AJAX call
In Chrome press F12
Go to the Network tab
Activate the AJAX call by submitting the form #reservSearch
In the Network tab look for a call to /Home/GetRates
Click it
Check the Preview and Response tabs to see the output from your server
Is it displaying the expected HTML data which your AJAX call is listening for?
http://stackoverflow.com/questions/21533285/why-the-ajax-script-is-not-running-on-iis-7-5-win-2008-r2-server/21617685#21617685

The output in my case:
Request:    GET /Home/Index?filtername=3it60nhrha HTTP/1.1 (filtername=3it60nhrha is expected)
Response    HTTP/1.1 200 OK


text:
Q: Bayesian approach to testing an unfair die Suppose you have a six-sided die that you suspect is not fair and toss it N times. What would be a Bayesian approach to estimating the probability of the six outcomes given that you suspect the die may be unfair?
I know that I have to come up with a prior density and a likelihood in order to define what the posterior would be.
I was thinking of using the multinomial as the likelihood, but I am not sure what to use for a prior since the die is suspected to be not fair.
Any help is appreciated... Thank you!

A: Based on the information you have provided, I would suggest the conjugate Dirichlet prior with the unit vector as the parameter with the multinomial likelihood. This doesn't account for the fact that you suspect the die to be unfair, but you have also not specified how you expect the die to be unfair. As you collect data, the estimated probabilities for each outcome will converge to their true probabilities which seems sufficient. If you would rather encode how you believe the die to be unfair, you can easily modify the vector parameter of the Dirichlet to put more (or less) weight on some outcomes.


text:
Q: Why is the search bar not pulling up the users from parse? I want to search for users in the parse database, but when I type the username into the search bar nothing is being added to the uitable. How do I get the searched user on the uitableview? I tried printing the users into the console after searched but I'm not getting any names.
@IBOutlet weak var searchbar: UISearchBar!
var searchActive : Bool = false
var data:[PFObject]!
var filtered:[PFObject]!

override func viewDidLoad() {
searchbar.delegate = self
    search()
}

func search(searchText: String? = nil){
    let query = PFQuery(className: "User")
    if(searchText != nil){
        query.whereKey("username", containsString: searchText)
    }
    query.findObjectsInBackgroundWithBlock { (results, error) -> Void in
        self.data = results as? [PFObject]
        self.table3.reloadData()
    }

}
func tableView(tableView: UITableView, numberOfRowsInTableView: Int) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(self.data != nil){
        println(self.data.count)
        return self.data.count
    }
    return 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
    let obj = self.data[indexPath.row]
    cell!.textLabel!.text = obj["text"] as? String
    return cell!
}

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    searchActive = false;
}

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    search(searchText: searchText)
}

A: Try this:
let query = PFQuery(className: "_User")
Or
let query = PFUser.query()
Check out this SO question
Parse.com querying User class (swift)


text:
Q: How to make marginratio from geometry package work also with LaTeX3? With LaTeX2e, the marginratio key provided by geometry package can be used safely:
\documentclass{book}
\usepackage{geometry}
\usepackage{calc}

\newlength{\mylayoutwidth}
\newlength{\mylayoutheight}

\setlength{\mylayoutwidth}{170mm}
\setlength{\mylayoutheight}{240mm}

\geometry{%
  layoutsize={\mylayoutwidth,\mylayoutheight}
  ,textwidth=\mylayoutwidth*3/4
  ,textheight=\mylayoutheight*3/4
  ,marginratio={4:6,5:7}
}

\begin{document}
Foo.
\end{document}

But the same kind of code expressed in the LaTeX3 way:
\documentclass{book}
\usepackage{expl3}
\usepackage{geometry}
\usepackage{calc}

\ExplSyntaxOn

\dim_const:Nn \c_my_layoutwidth_dim  { 170mm}
\dim_const:Nn \c_my_layoutheight_dim { 240mm}

\geometry{
  layoutsize={\c_my_layoutwidth_dim,\c_my_layoutheight_dim}
  ,textwidth=\c_my_layoutwidth_dim*3/4
  ,textheight=\c_my_layoutwidth_dim*3/4
  ,marginratio={4:6,5:7}
}

\ExplSyntaxOff

\begin{document}
Foo.
\end{document}

fails with the error:
Runaway argument?
4:6\relax \ifnum \@tempcntb >\z@ \else \Gm@warning {margin ratio a:b \ETC.
! File ended while scanning use of \Gm@sep@ratio.
<inserted text>
                \par
<*> test.tex^^M

?

I guess this comes from colon catcode in LaTeX3 but is it possible to make marginratio work also with LaTeX3?

A: The : has catcode 11 inside of \ExplSyntax....  You have to spawn a : of catcode 12 in the marginratio by replacing : with \char_generate:nn { `\: } { 12 }.  Alternatively, you can define a macro to expand to the colon of catcode 12.  The best solution though is to use the predefined constant \c_colon_str which is a colon of catcode 12.  There are more constants for the "special" symbols of TeX, such as percent, ampersand, or circumflex, all of catcode 12.  Part XII, section 6 of the LaTeX3 interfaces documentation has a list.
Edit:  As of Jean-François' answer I corrected the width/height confusion.
\documentclass{book}
\usepackage{expl3}
\usepackage{geometry}
\usepackage{calc}

\ExplSyntaxOn

\dim_const:Nn \c_my_layoutwidth_dim  { 170mm}
\dim_const:Nn \c_my_layoutheight_dim { 240mm}

\geometry{
  layoutsize={\c_my_layoutwidth_dim,\c_my_layoutheight_dim}
  ,textwidth=\c_my_layoutwidth_dim*3/4
  ,textheight=\c_my_layoutheight_dim*3/4
  ,marginratio={4 \c_colon_str 6, 5 \c_colon_str 7}
}

\ExplSyntaxOff

\begin{document}
Foo.
\end{document}

A: You can also simply prefix the colons with \string (but note the space...).
Notice that your OP had a typo in the LaTeX3 part, using width for the height... thus skip to the bottom of this answer for the fix and skip the confusing discussion in-between which I leave here a testimony of how to lose one's time.

SKIP THIS!
But something seems to be wrong (also with the code of @HenriMenke's answer: if I add package layout the use of \geometry with \ExplSyntaxOn/\ExplSyntaxOff generates 6 pages not 3 pages.
And the issue is there also with package layout not used, just check the log for the geometry parameters, particularly \topmargin and \textheight
I don't know the cause (*) but indeed the page parameters differ:

(*) perhaps this is caused by
\mylayoutwidth=\skip52
\mylayoutheight=\skip53

versus
\c_my_layoutwidth_dim=\dimen144
\c_my_layoutheight_dim=\dimen145

i.e. the use of \dimen rather than \skip (=LaTeX's length) ?. I don't know LaTeX3 hence do not know what one should do to use \skip's there and check is that is indeed the issue

(update: or rather not at all: evidently just replacing "dim" by "skip" is the syntax, but it does not change anything to the observed problem).
without LaTeX3 syntax:

with LaTeX3 syntax (either the one here with \string or the one from @HenriMenke's answer):

As one can see there are differences for \topmargin and \textheight.
\documentclass{book}
\usepackage{expl3}
\usepackage{geometry}
\usepackage{calc}
\usepackage{layout}

\ExplSyntaxOn

\dim_const:Nn \c_my_layoutwidth_dim  { 170mm}
\dim_const:Nn \c_my_layoutheight_dim { 240mm}

\geometry{
  layoutsize={\c_my_layoutwidth_dim,\c_my_layoutheight_dim}
  ,textwidth=\c_my_layoutwidth_dim*3/4
  ,textheight=\c_my_layoutwidth_dim*3/4
  ,marginratio={4\string :6,5\string :7}
}

\ExplSyntaxOff

\begin{document}
\layout % gives different results if \geometry used with l3 syntax or not ...

Foo.
\end{document}

Code with OP's typo fixed...
\documentclass{book}
\usepackage{expl3}
\usepackage{geometry}
\usepackage{calc}

\ExplSyntaxOn

\dim_const:Nn \c_my_layoutwidth_dim  { 170mm}
\dim_const:Nn \c_my_layoutheight_dim { 240mm}

\geometry{
  layoutsize={\c_my_layoutwidth_dim,\c_my_layoutheight_dim}
  ,textwidth=\c_my_layoutwidth_dim*3/4
  ,textheight=\c_my_layoutheight_dim*3/4
  ,marginratio={4\string :6,5\string :7}
}

\ExplSyntaxOff

\begin{document}
Foo.
\end{document}

No issues then.


text:
Q: PHP and MySQL help needed I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table  catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");

$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());

?>

<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select>

<input type="text" name="name" value="">

<input type="submit" value="submit"/>
</form>

add_products.php Code
<?php
include("db.php");

$cat = $_POST['catid'];

$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');

while($row = mysql_fetch_array($result)){
$catn = $row['catid'];

}

$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');

echo "Product Added";

?>

A: Some unrelated, but very important things:

*

*you should escape $cat before it goes into the query

*you should always escape strings that go out to HTML with htmlspecialchars

*you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?

A: You already have it in??
$cat = $_POST['catid'];

If you only want to insert IF they $cat exists, then:
<?php
include("db.php");

$cat = $_POST['catid'];

$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');

if($result)
{
    $name = mysql_real_escape_string($_POST['store']);
    $query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
    mysql_query($query) or die ('Error Updating');
    echo "Product Added";
}
?>

A: You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).

A: seem many mistakes here:
select name="cat"

and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";

when you need to compare ids  catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
  $catn = $row['catid'];

}

A: Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name  = mysql_real_escape_string($_POST['store']);

$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');

echo "Product Added";

Please also look into PDO for the best way to handle DB queries like this.

A: try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";

to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";

A: You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the  you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";

For more info refer to the w3school manual for , at this link.


text:
Q: Ubuntu Linux Library Path How do I determine the Ubuntu Linux Library Path? That is, how does the linker know where to got to grab the object files when linking my program?

A: The file paths can be set explicitly when linking using the -L parameter, as well as the environment variable LD_LIBRARY_PATH.
There are also some paths hard-coded into the linker, using the -L param.  You can see these with the command:
gcc -Xlinker -v

A: If it's not a standard path (/lib, /usr/lib), you can specify the location with the compiler flag. For g++, it's -L/some/path/lib. If you use autotools, you can just configure with LDFLAGS=-L/some/path/lib if you need a specific path. If configure has been properly designed for the project, it should have a --with-some-library=PATH option, where you can also specify a path for that library only.

A: When linking, you need to specify the -L flag to indicate where the library is located. At runtime, the dynamic linker uses the paths given in "/etc/ld.so.conf", "/etc/ld.so.conf.d/*" and the value of LD_LIBRARY_PATH.

A: "sudo ldconfig" updates the system's cache if you've just installed something new.

A: Look at /etc/ld.so.conf and the files in the /etc/ld.so.conf.d/ directory -- that's where it is set.


text:
Q: putty from a batch file and a script? I have a batch file that opens putty just fine.
c:\putty.exe root@192.168.12.34 -pw boyhowdy. But to make this work for me I need to understand how to include a script of a command so it will run under the putty tool. Like mount –o remount,rw / . Or is this something I can do with a tool called pscp. I am a nube to these tools and really could use some guideance. I have a bunck of these scripts and would really like to automate them. Thankyou

A: *

*If your goal is to execute shell commands remotely through putty, you should probably look at plink (putty without the gui, in other words an ssh client for windows) and then apply the standard here-doc techniques to plink.

*plink is part of the putty collection and is also downloadable from the same page as putty.

*If you want to execute a local script you would use

plink user@host -m local_script.sh

*For instance. Assuming you're running on some Windows box (fyi the putty suite also runs on Linux) and want to execute a batch of commands on some remote box you would create a shell script on your local machine (say mount.sh) and run it like this:

C:\> type mount.sh
whoami
hostname
/usr/sbin/mount -t iso9660 -o ro /dev/cdrom /mnt
/usr/sbin/mount | grep mnt
C:\> plink remoteuser@remotehost -pw secret -m mount.sh
remoteuser
remotehost
/dev/cdrom on /mnt type iso9660 (ro)

*Also, it's probably better to copy your public key over so that the password is not coded in some batch file.

*Finally, be aware that not all environment variable defined in an interactive shell process will be available in the remote shell process.  You might need to 'source' some profile script at the beginning of your script.


text:
Q: Does the order of include functions of jquery and jquery mobile matters? If I use this order:
<script src="jsv3/jquery-1.8.3.js"></script>
<script src="jsv3/jquery.mobile-1.2.0.min.js"></script>
<script src="jsv3/turn.min.js"></script>
<script src="jsv3/onload_mobile.js"></script>
<script src="jsv3/jquery-ui-1.9.2.custom.min.js"></script>
<script src="jsv3/jquery.viewport.min.js"></script>
<script src="jsv3/jquery.scraggable.js"></script>

Return Error:
Uncaught TypeError: Object 0 has no method 'match'
(Type error: c.match is not a function using FireBugs error report)
If I use this order
<script src="jsv3/jquery.mobile-1.2.0.min.js"></script>
<script src="jsv3/jquery-1.8.3.js"></script>
<script src="jsv3/turn.min.js"></script>
<script src="jsv3/onload_mobile.js"></script>
<script src="jsv3/jquery-ui-1.9.2.custom.min.js"></script>
<script src="jsv3/jquery.viewport.min.js"></script>
<script src="jsv3/jquery.scraggable.js"></script>

Uncaught TypeError: Cannot read property 'mobile' of undefined
(Type error: a is undefined using FireBugs error report)
According to official website , the order is the first one, however, the first one seems display nothing while the second one is function properly for my case. Is using second order is correct, also, why is this error occur? Is it due to I use desktop browser to view the page? Sorry for newible to mobile web development, thanks

A: The problem is due to conflict between jquery mobile and jquery ui

A: I had the same problem.
This is the order that I have now and works correctly
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
    <script language="javascript" src="js/scripts.js"></script>


text:
Q: How to cache a query in web api? Say I have a controller action like this:
//GET: api/Creditors
public IQueryable<Creditor> GetCreditors()
{
    return db.Creditors;
}

Is there an easy way in web api to cache the result as the data will not change very often?

A: I found an easy solution - CacheCow:
http://damienbod.wordpress.com/2014/05/18/exploring-web-api-2-caching/
If anyone has any better suggestions please let me know ;)


text:
Q: PowerApps DropDown Errors I have a SharePoint list full of listings that users can edit/add new line items to within the app. Everything was working with my PowerApp until today and one of my users showed me the following error when trying to submit a new form:
"There was a problem saving.  Your data source may be invalid"
From here, I checked the actual PowerApp and saw a single error on the SubmitForm() function with no further explanation as to why.  I refreshed the data set (SharePoint List) associated with it, and then the errors popped up onto each dropdown item:
"The Data source Supplied to the function is invalid"
I've searched all around and have been unable to find a solution to this.  They said that this was fixed in a recent update, but I am still seeing this issue (and never saw it in the prior months).  Any suggestions?

A: Have you tried to re-write the code that is returning the error to check what item in specific is creating the problem? Or you can create other application just to test if the same datasource returns the same error.
And how many rows have your sharepoint list? Powerapps has a limit of results he can return when using some Non-delegable functions (500 by default).


text:
Q: Rails Amazon s3, Paperclip missing required :bucket option I'm trying to use Paperclip and Amazon S3 in a rails application. And the weird part is that it worked before I stored my variables in the environment.yml
I get the error

ArgumentError - missing required :bucket option:

Here is my environment development:
  AWS_ACCESS_KEY_ID:  "myid"
  AWS_SECRET_ACCESS_KEY: secretkey
  AWS_BUCKET: elasticbeanstalk-us-west-1-299430007588.s3.amazonaws.com8

in the config/environments/development.rb
config.paperclip_defaults = {
   :storage => :s3
   :s3_credentials => {
    :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
   }
  }

then in the production
config.paperclip_defaults = {
   :storage => :s3
   :s3_credentials => {
    :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
   }
  }

In my Recipe model
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
      validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
      has_attached_file :download,
                        :storage => :s3,
                        :s3_credentials => Proc.new{|a| a.instance.s3_credentials }

      def s3_credentials
         {:bucket => ENV['AWS_BUCKET'], :access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']}
      end

The gemfile
gem "paperclip", "~> 4.3"
gem 'aws-sdk','< 2.0'

Any help will be great, I have seen people already asking and followed what people suggested to fixed but it did not work.
In the  config/application.rb
config.assets.version = '1.0'

     config.before_configuration do
        env_file = File.join(Rails.root, 'config', 'local_env.yml')
        YAML.load(File.open(env_file)).each do |key, value|
        ENV[key.to_s] = value
     end if File.exists?(env_file)
    end


text:
Q: tikzpicture in beamer titlepage Here is an ECM:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{decorations.text}
\title{TWO PROBLEMS
 {\begin{tikzpicture}
  \path [decorate,decoration={text along path, text={around the}}]
   (0,0) sin (1,1) cos (2,0);
  \end{tikzpicture}}}

\begin{document}
  \begin{frame} \titlepage \end{frame}
\end{document}

This code gives me what I want, expect that the compiler shouts at me:
Use of \begin doesn't match its definition.
\inserttitle ->TWO PROBLEMS {\begin {
                                     tikzpicture}

Can anyone tell me how to mend this glitch? Thanks in advance! O.

A: The title is not only used on the title page, but also in other places, such as the pdf meta data. Your hack to add the tikzpicture to the title page collides with this usage.
I suggest to insert the image via the \titlegraphic{} macro, this is normally printed at the bottom of the title page, but if you would like it below the title, you could redefine the titlepage as following:
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{decorations.text}
\title{TWO PROBLEMS}

\titlegraphic{  \begin{tikzpicture}
    \path [decorate,decoration={text along path, text={around the}}]
     (0,0) sin (1,1) cos (2,0);
    \end{tikzpicture}}

\makeatletter
\setbeamertemplate{title page}{
  \vbox{}
  \vfill
  \begingroup
    \centering
    \begin{beamercolorbox}[sep=8pt,center]{title}
      \usebeamerfont{title}\inserttitle\par%
      \ifx\insertsubtitle\@empty%
      \else%
        \vskip0.25em%
        {\usebeamerfont{subtitle}\usebeamercolor[fg]{subtitle}\insertsubtitle\par}%
      \fi%
    \end{beamercolorbox}%
    {\usebeamercolor[fg]{titlegraphic}\inserttitlegraphic\par}
    \vskip1em\par
    \begin{beamercolorbox}[sep=8pt,center]{author}
      \usebeamerfont{author}\insertauthor
    \end{beamercolorbox}
    \begin{beamercolorbox}[sep=8pt,center]{institute}
      \usebeamerfont{institute}\insertinstitute
    \end{beamercolorbox}
    \begin{beamercolorbox}[sep=8pt,center]{date}
      \usebeamerfont{date}\insertdate
    \end{beamercolorbox}\vskip0.5em
  \endgroup
  \vfill
}
\makeatother

\begin{document}
  \begin{frame}
        \titlepage
   \end{frame}
\end{document}

A simpler approach, thankfully pointed out by @marmot, could be to use \titlegraphic{} together with absolute positioning on the page. This could save you from redefining the titlepage (if there is enough room for the image).
\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{decorations.text}
\title{TWO PROBLEMS}

\titlegraphic{%
    \begin{tikzpicture}[overlay,remember picture]
        \path [decorate,decoration={text along path, text={around the}}, shift={(current page.center)}] (0,0) sin (1,1) cos (2,0);
    \end{tikzpicture}
}

\begin{document}
    \begin{frame}
        \titlepage
    \end{frame}
\end{document}


text:
Q: Dockerfile Alpine Mariadb latest with SphinxSE I have a Dockerfile for MariaDB 10.1.26 which I use in connection with SphixSE.
Defining Dockerfiles for versions 10.4.18 and 10.5.9 along the same lines is easy, but SphinxSE cannot be installed.
Specifically the command INSTALL SONAME 'ha_sphinx'; raises an enigmatic error.
What can I do to make it work with these versions, too?

A: For the time being it cannot be done.
https://git.alpinelinux.org/aports/tree/main/mariadb/APKBUILD#n162 shows that the package does not support SphinxSE.
https://github.com/MariaDB/mariadb-docker/pull/343 shows that MariaDB does not support Alpine.


text:
Q: Errors while building MVC 6 source code from https://github.com/aspnet/Mvc I'm trying to build MVC 6 source code from github.I've installed dnvm and pulled source code from repo as decriped in https://github.com/aspnet/Mvc/wiki/Building-MVC then i run build using cmd (as administrator). But I've errors when building like (there're 50 errors):
C:\Dev\Sandbox\ASP.NET5\mvc\src\Microsoft.AspNet.JsonPatch\project.json(0,0): error NU1002: The dependency System.Dynamic.Runtime 4.0.0 in project Microsoft.AspNet.JsonPatch does not support framework DNXCore,Version=v5.0.
C:\Dev\Sandbox\ASP.NET5\mvc\src\Microsoft.AspNet.JsonPatch\project.json(0,0): error NU1002: The dependency System.Globalization.Calendars 4.0.0 in project Microsoft.AspNet.JsonPatch does not support framework DNXCore,Version=v5.0.
C:\Dev\Sandbox\ASP.NET5\mvc\src\Microsoft.AspNet.JsonPatch\project.json(0,0): error NU1002: The dependency System.ObjectModel 4.0.10 in project Microsoft.AspNet.JsonPatch does not support framework DNXCore,Version=v5.0.

.... errors go on...
The build set deafult dnvm as  1.0.0-rc1-15838 clr x86 - does it matter?
When opening solution in VS 2015 Community I've got errors next to References - DNX 5.0 Core as on picture
Can anyone give me any clue?

A: Most likely, if you install dnvm/dnx you just have stable channel runtime (beta8) while the packages already want to compile against rc1 (unstable ATM).
Just download the unstable runtime
dnvm install -r coreclr -arch x64 latest -u


text:
Q: Create images dynamically in vba and add click function to them I am trying to dynamically add images to a form in a grid like fashion. The images are from a folder for now then, I'm trying to add a click function to each dynamically created images on the form to execute something but I'm stuck on that part.   I am successful in importing the images to a form and showing it in a grid like fashion with the code below I came up with.
Option Explicit

Private Sub Pic2_Click()
    'not working :(
    MsgBox "worked!!"
End Sub

Private Sub UserForm_Initialize()
    Dim img As Object
    Dim picSheet As Worksheet
     'Add Dynamic Image and assign it to object 'Img'

    Dim i, h, t As Integer
    ' Set picSheet = ThisWorkbook.Worksheets("Themes")

    ' Dim pictureList As Object
    ' Dim pics As Shapes
    ' Dim pic As Shape
    ' Set pics = ThisWorkbook.Worksheets("Themes").Shapes
    Dim picPath As String
    t = 10
    h = 10

    picPath = Dir(Environ("USERPROFILE") & "\Pictures\*pic*") 'getting pictures from picpath folder image names are ranged from "pic1.jpg" to "pic12.jpg"
    Do While Not Blank(picPath) ' blank determines if a string is empty (boolean value)
     i = i + 1
     If i > 1 Then h = h + 90
        Set img = Me.Controls.Add("Forms.image.1", picPath, True)
            If i Mod 4 = 1 And i > 1 Then 'new row after first 4 images to create grid
                t = t + 100
                h = 10
            End If
        With img
            .Picture = LoadPicture(Environ("USERPROFILE") & "\Pictures\" & picPath)
            .PictureSizeMode = fmPictureSizeModeStretch
            .Left = h
            .Top = t
            .name = Split(picPath, ".")(0)
            Debug.Print "name is: " & .name
        End With
        picPath = Dir
    Loop
End Sub

A: This is my entire solution and it worked for me. I changed a few things by using buttons instead that had the images embedded in them.
Option Explicit

Dim ColTB As Collection

Private Sub UserForm_Initialize()
    Dim picPath, path As String
    Dim i, h, t As Integer
    Dim button As Object
    Dim fso As New FileSystemObject
    t = 10
    h = 10
    Set ColTB = New Collection

    picPath = Dir(Environ("USERPROFILE") & "\OneDrive\Pictures\Themes\" & "*.jpg")
    Do While Not Blank(picPath)
    i = i + 1
    If i > 1 Then h = h + 120
    If i Mod 4 = 1 And i > 1 Then
        t = t + 100
        h = 10
    End If
    Set button = Me.Controls.Add("Forms.CommandButton.1", picPath, True)
    With button
        .Font.Bold = True
        .Left = h
        .Top = t
        .Picture = LoadPicture(Environ("USERPROFILE") & "\OneDrive\Pictures\Themes\" & picPath)
        .Height = 72
        .Width = 100
    End With
    ColTB.Add EventObj(button)
    picPath = Dir
    Loop
End Sub

Function EventObj(obj As MSForms.CommandButton) As Class1
    Dim o As New Class1
    Set o.buttonClickEvent = obj
    Set EventObj = o
End Function

Class1  module
Option Explicit
Public WithEvents buttonClickEvent As MSForms.CommandButton

Private Sub buttonClickEvent_Click()
    Dim name, imgpath, sheetName As String
    Dim answer
    Dim ac As Worksheet
    Set ac = ThisWorkbook.ActiveSheet
    name = buttonClickEvent.name

    answer = MsgBox("You want to apply the " & Split(name, ".")(0) & " theme now?", vbQuestion + vbYesNo + vbDefaultButton2, "Apply Theme")

    If answer = vbYes Then
        imgpath = Environ("USERPROFILE") & "\OneDrive\Pictures\Themes\" & name
        ac.SetBackgroundPicture Filename:=imgpath
    End If

End Sub


text:
Q: Batch File to read value of a specific property and use it as a variable I am writing a batch script to read the values of property which is passed as a argument to batch script during execution.
I have a Properties File (Input.properties) with below entries.
APP1_NAME=common1
APP1_PATH=path1\val\test
APP1_VERSION=1.0
APP2_NAME=common2
APP2_PATH=path2\val\test
APP2_VERSION=2.0
APP3_NAME=common3
APP3_PATH=path3\val\test
APP3_VERSION=3.0

I have a batch (Read.bat) script to which ${APP} an argument is passed with a value either of 3 APP1/APP2/APP3.  I am trying to read the value of a specific property based on the value passed and store it in a variable and use it for further. Let's say we pass APP1 to the Read.bat we should be able to read NAME, PATH and VERSION of APP1.
I tried below which works If i want to read a value by passing static property  but I am looking something works if a part of property name passed as variable value.
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,* delims== " %%i in (Input.properties) do (
echo %APP1_NAME%
)

The expected one is if we pass APP2 as an argument to Read.bat
We should be able to read the value of APP2_NAME and store it in variable and read value of APP2_PATH and store it another variable for further use.

A: You are not assigning a single variable in your code although you try to return one.
You could use the following code, which searches the file Input.properties for lines that begin with the string given as a command line argument followed by an underscore (_) and assigns all the respective matching variables:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

(
    for /F "tokens=1* delims==" %%I in ('findstr /IBC:"%~1_" "Input.properties"') do (
        set "%%I=%%J"
    )
) || (>&2 echo No items found! & exit /B 1)
set "%~1_"

endlocal
exit /B

Note that the variables are no longer available after the endlocal command, so if you need the variables after the above code ran you need to remove the setlocal and endlocal lines.

A: Slightly different answer, first checking the passed argument for validity and not using setlocal:
:: Q:\Test\2019\06\06\SO_56480912.cmd
@Echo off
Echo:%~1|findstr /ix "APP[1-3]" >Nul ||(Echo wrong arg %1 &Pause&exit /B 1)
for /f "delims=" %%A in ('findstr /I "^%~1_" input.properties') do set "%%A"
set %~1

> Q:\Test\2019\06\06\SO_56480912.cmd apP2
APP2_NAME=common2
APP2_PATH=path2\val\test
APP2_VERSION=2.0

> Q:\Test\2019\06\06\SO_56480912.cmd apP4
wrong arg apP4


text:
Q: Wordpress rest-api authentication from react app for non-logged in user I'm building a series of react apps which are injected to wordpress websites (survey like apps to gather guest/non-logged in users data).
The final step requires creating new post in wordpress with all the gathered data - I'm trying to use rest-api to accomplish this.
To use wordpress rest-api I at least need to authenticate with ANY user so I started with mentioned in documentation authentication methods like "application passwords" or JWT token generation (plugin) and trying to auth wordpress admin user created for this purpose only.
It turned out both methods requires using credentials on frontend react app to POST data to the wordpress rest-api. The problem is:

*

*I'm trying to hide authentication so its happening without user registration or any other action being taken on their part to save the form

*when using "application password" I need to put credentials on react app to make a POST request -  but its exposing credentials

*when using JWT Token approach - I can get token only if I send username and password from react app - but its then again exposing login details
Is there a way I could:

*

*exchange credentials between wordpress and react app in a form of encrypted data? (eg through cookies)

*or authenticate react app in other way?

*or create wordpress post from react app in a different way?

thank you

A: In case anyone is interested how this can be done:

*

*No auth, rest-api solution - using js ajax call to invoke php script and handle rest api call internally on server side, then getting response back to JS
pros:

*

*no auth step, we still utilize wordpress rest-api but internally on the server

*just by adding or removing add_action we can specify if the code can be triggered by logged in or non logged in users
*the below example is not using reactjs but jQuery.ajax but this can be easily replaced on frontend by anything react related (axios or similar)

functions.php / plugin php file:
function pp_reactapp_ajax( ){
    // wp_enqueue_script( 'script-checker', plugin_dir_url( __FILE__ ) . 'js/script-checker.js' );
    wp_enqueue_script( 'pp_reactpp', get_stylesheet_directory_uri() . '/js/pp_reactpp.js', ['jquery'] );
    wp_localize_script( 'pp_reactpp', 'pp_reactapp', array(
                    'ajaxurl' => admin_url( 'admin-ajax.php' ),
            )
    );
}
add_action( 'wp_enqueue_scripts', 'pp_reactapp_ajax' );
add_action( 'admin_enqueue_scripts', 'pp_reactapp_ajax' );

the code above is to get js file with ajax call and output ajaxurl to be used in that file (see below)
function pp_check_reactapp_ajax() {

    $request = new WP_REST_Request( 'POST', '/wp/v2/posts' );
    $request->set_header( 'content-type', 'application/json' );
    $request->set_body( '{
            "title": "'. $_POST['title'] .'"
        }');

    $response = rest_do_request( $request );

    $server = rest_get_server();
    $data = $server->response_to_data( $response, false );

    if($data['id']){
        echo '{"success": '. json_encode($data) .'}';
    } else {
        echo '{"error": "'. $data['message'] .'"}';
    }

    wp_die();

}
add_action( 'wp_ajax_nopriv_pp_check_reactapp_ajax', 'pp_check_reactapp_ajax' );
add_action( 'wp_ajax_pp_check_reactapp_ajax', 'pp_check_reactapp_ajax' );

this is php function which is executed by ajax call
ajax call on js file data.action is connecting it with php function name
example js ajax call:
jQuery.ajax({
  type: 'POST',
  url: pp_reactapp.ajaxurl,
  data: {
      action: 'pp_check_reactapp_ajax',
      title: 'new post works with ajax ALL WORKS 2',
  },
  beforeSend: function ( ) {
      jQuery( 'body' ).html( pp_reactapp.loading_message );
  },
  success: function ( data, textStatus, XMLHttpRequest ) {
    console.log(JSON.parse(data));

  },
  error: function ( XMLHttpRequest, textStatus, errorThrown ) {
      console.log( errorThrown );
  }
});

*auth solution

An idea: this is still not ideal but with similar to the above approach we can generate token by php call to rest-api (get token) for a user credentials responsible for authenticating react app, then output it with localize_script to frontend where reactapp can read it and attach to headers for request.
To move forward with securing the token - Instead of outputing with localize_script I would request token generation and sending to frontend just before data needs to be transmitted to rest-api (using ajax call to execute php from above example) and send it back with very short lifetime (eg 20s).
This way even if token is exposed without "proper authorization" - it still can be used but only for very limited time.