text:
Q: Menu scaling in browser While scaling down in browser menu has broken - flows on next line. What is wrong in code? Div width changing while scaling though it hardcoded 198px.
Without borders all is ok, but I have to use borders.

#horizontal-multilevel-menu {
  border-right: 1px solid #769510;
  border-left: 1px solid #cde67b;
}
#horizontal-multilevel-menu {
  margin: 0;
  padding: 0;
  background: #a0bf38;
  min-height: 52px;
  width: 100%;
  list-style: none;
  font-size: 18px;
  margin-left: auto;
  margin-right: auto;
  width: 1000px;
}
#horizontal-multilevel-menu a {
  display: block;
  padding: 5px 10px;
  text-decoration: none;
  text-align: center;
  padding: 15px 40px !important;
}
#horizontal-multilevel-menu div {
  float: left;
  border-left: 1px solid #769510;
  border-right: 1px solid #cde67b;
  width: 198px;
}

1

2

3

4

5

A: May be you need box-sizing to correct this issue.

* {
  box-sizing: border-box;
}
#horizontal-multilevel-menu {
  border-right: 1px solid #769510;
  border-left: 1px solid #cde67b;
}
#horizontal-multilevel-menu {
  margin: 0;
  padding: 0;
  background: #a0bf38;
  min-height: 52px;
  width: 100%;
  list-style: none;
  font-size: 18px;
  margin-left: auto;
  margin-right: auto;
  width: 1000px;
}
#horizontal-multilevel-menu a {
  display: block;
  padding: 5px 10px;
  text-decoration: none;
  text-align: center;
  padding: 15px 40px !important;
}
#horizontal-multilevel-menu div {
  float: left;
  border-left: 1px solid #769510;
  border-right: 1px solid #cde67b;
  width: 199px;
}

1

2

3

4

5


text:
Q: WPF календарь: снять выделение с определенных дат Как снять выделение с определенных дат в обработчике SelectedDatesChanged?
Я прямо в этом обработчике из SelectedDates удаляю ненужные даты,
но визуально это не видно. Из коллекции нужные даты удаляются, но по прежнему остаются выделенными.
Может его как-то обновить можно?
Добавлено:
Задача проста: нужно снять выделение с определенных дат, причем список этих дат определяется по первой выделенной дате, т.е. все происходит в обработчике SelectedDatesChanged
Вот обработчик:
private void calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
//формируется deniedDates
    foreach (var deniedDate in deniedDates)
    {
        calendar.SelectedDates.Remove(deniedDate);
    }
}

A: NotifyPropertyChanged выполняете после изменения данных?
Так же когда объявляете ItemsSource, там должен быть модификатор Mode равный TwoWay. Как то так ItemsSource="{Binding ViewBooks, Mode=TwoWay}.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deleting an image when deleting an item using multer Ok so I am using multer to upload an image of an item that a user submits.  However when the user deletes the item the image file is still on the server.
I have been trying to figure this out and I am not sure if its the way findByIdAndRemove() is deleting the user item before I am making the call to remove the image or what but I am getting the error saying that it cant find the file name of undefined. I am using a promise thinking it would allow me to do this but I am not sure of where else to go.  I am new at this and learning as I go. Here is my delete route:
router.delete("/item/:id", middleware.isLoggedIn, (req, res) => {
  Promise.all([
    (Item.findByIdAndRemove(req.params.id),
    fs.unlinkSync("./public/uploads/" + req.item.image))
  ])
    .then(() => {
      return res.render("products");
    })
    .catch(err => {
      return console.log("err", err.stack);
    });

Any suggestions?


text:
Q: can node.js read php sessions for each user? Hi,
I have a php based forum that uses mysql to store credentials. As the user logs in with their username and password, php compares the input data with the values in the database and if they match it creates a php session. I want to create a node.js application that allows the user to enter it if they are already logged in on the forum which begs the question, can nod.js read the data from the php session to display the correct user name on the front end of the application?
Right now I came up with this workaround on my javascript client side file:
const setUsername = (username) => {
    username = <?php echo $username; ?>;
    socket.emit('add user', username);
  }

but since its client side this would allow anyone to change the source code on their side and input the name they want which is a serious security issue.
Thank you.

A: you can save php session in the database (default location for php sessions is file system) see session_set_save_handler() function for more details.
And then you can easily retrieve this session from the database from nodejs side using the appropriate DB driver (if you use MySQL then here is the implementation for mysql)


text:
Q: If a graph is k-connected, does it mean it has at least one group of k separators? This question is about clarifying some terms. I am trying to make sure that I understand them correctly.
If a graph is k-connected, then the removal of < k vertices keeps the graph connected. Thus, if removing some k vertices disconnects it, do we call these k vertices a separator?
If I am correct, then a graph can have several separators but all of them must have the same size = k. Am I right?

A: To answer the question in your title; yes.  If a graph is $k$-connected then it must have at least one group of k-separators.  This is why complete graphs are excluded when defining $k$-connectivity on the basis of the smallest subset of vertices that can disconnect the graph when removed; because complete graphs have no separators.
Your intuition is correct and I would only modify your last statement to be precise:
A $k$-connected graph can have several minimal separators, each of which must be of size $k$.  You can also have non-minimal separators of size $> k$.


text:
Q: JPA and Oracle DB: Distinct query with pagination leads to Error: ORA-00909: Invalid amount of arguments Im running a spring backend with an oracle database.
I use the specification API to perform queries:
@Slf4j
public class ContentSpecification implements Specification<Content> {

  private final transient ContentFilter filter;

  public ContentSpecification(final ContentFilter filter) {
    this.filter = filter;
  }

  @Override
  public Predicate toPredicate(
      @NonNull final Root<Content> root,
      @NonNull final CriteriaQuery<?> query,
      @NonNull final CriteriaBuilder builder) {
    final List<Predicate> predicates = new ArrayList<>();

    if (!isEmpty(filter.getTerm())) {
      // ... not relevant

      predicates.add(builder.or(title, subtitle, body, keywords));
    }

    query.distinct(true);

    return builder.and(predicates.toArray(new Predicate[0]));
  }
}

  public PagedModel<ContentModel> getContent(
      final String term,
      final Integer page,
      final Integer size) {

    final int pageSize = size == 0 ? MAX_VALUE : size;

    return pagedAssembler
        .toModel(
            repository.findAll(
                new ContentSpecification(
                    new ContentFilter(term)),
                PageRequest.of(page, pageSize)),
            contentAssembler);
  }

This is working perfectly with H2 and MySQL Database.
But as soon as im using an Oracle database it wont work:
spring:
  datasource:
    driver-class-name: oracle.jdbc.OracleDriver
    initialization-mode: never
    url: <url>
    username: <user>
    password: <pw>
  jpa:
    database-platform: org.hibernate.dialect.Oracle12cDialect
    hibernate:
      ddl-auto: validate
    properties:
      hibernate:
        format_sql: true
        current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
    show-sql: true

The console output im getting is the following:
2021-12-07 15:24:22.487  INFO [my-service,4d641a9f03674994,4d641a9f03674994,false] 14244 --- [nio-8082-exec-7] d.b.b.p.p.content.ContentController      : get content: null, null, null, 0, 5
Hibernate:
    select
        *
    from
        ( select
            distinct content0_.id as id2_3_,
            content0_.version as version3_3_,
            content0_.status as status9_3_,
            content0_.status_date as status_date10_3_,
            content0_.subtitle as subtitle11_3_,
            content0_.title as title12_3_,
        from
            content content0_
        where
            content0_.status=? )
    where
        rownum <= ?
Hibernate:
    select
        distinct count(distinct content0_.id,
        content0_.version) as col_0_0_
    from
        content content0_
    where
        content0_.status=?
2021-12-07 15:24:22.508  WARN [my-service,4d641a9f03674994,4d641a9f03674994,false] 14244 --- [nio-8082-exec-7] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 909, SQLState: 42000
2021-12-07 15:24:22.508 ERROR [my-service,4d641a9f03674994,4d641a9f03674994,false] 14244 --- [nio-8082-exec-7] o.h.engine.jdbc.spi.SqlExceptionHelper   : ORA-00909: Invalid amount of arguments
2021-12-07 15:24:22.514 ERROR [my-service,4d641a9f03674994,4d641a9f03674994,false] 14244 --- [nio-8082-exec-7] d.b.b.p.p.ApplicationExceptionHandler    : runtime exception:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    ... 111 common frames omitted
Caused by: java.sql.SQLSyntaxErrorException: ORA-00909: Ungültige Anzahl von Argumenten
    at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:509) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:461) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1104) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:550) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:268) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:655) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:270) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:91) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:807) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:983) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1168) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3666) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.T4CPreparedStatement.executeInternal(T4CPreparedStatement.java:1426) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3713) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1167) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.2.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.2.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    ... 148 common frames omitted
Caused by: oracle.jdbc.OracleDatabaseException: ORA-00909: Ungültige Anzahl von Argumenten

    at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:513) ~[ojdbc8-19.3.0.0.jar:19.3.0.0.0]
    ... 165 common frames omitted

As soon as I remove either the distinct or the pagination it will also work with the oracle db.
Is there a solution for oracle to get the distinct running together with the pagination?
EDIT
So it seems like oracle fails with the count query.
Just for comparison, with H2 the following sql is
getting generated:
Hibernate:
    select
        distinct content0_.id as id2_3_,
        content0_.version as version3_3_,
        content0_.status as status9_3_,
        content0_.status_date as status_10_3_,
        content0_.subtitle as subtitl11_3_,
        content0_.title as title12_3_,
    from
        content content0_
    where
        content0_.status=? limit ?
Hibernate:
    select
        distinct count(distinct (content0_.id,
        content0_.version)) as col_0_0_
    from
        content content0_
    where
        content0_.status=?

A: The cause of the error ORA-00909: invalid number of arguments is the statement providing the count of the rows
select
        distinct count(distinct content0_.id,
        content0_.version) as col_0_0_
    from
        content content0_
...

This construction COUNT(DISTINCT expr,[expr...]) maight be allowed in MySQL
but is illegal in Oracle.
As your dialect is Oracle12cDialect I'd suspect a problem in the implementation of this dialect in case of more than one identifying columns in the entity. See e.g. here for correct SQL  solutions.
Also note that the first DISTINCT in this query is possible, but completely irrelevant as a query with count will produce only one row-
Having said that you should IMO make some effort in your data model that will make the usage of distinct not necessary.  IMHO the right approach.

A: Actually the failing query:

    select
        distinct count(distinct (content0_.id,
        content0_.version)) as col_0_0_
    from
        content content0_
    where
        content0_.status=? ```

is a query which spring-data issues to get the total amount of records available (please check: org.springframework.data.jpa.repository.support.SimpleJpaRepository#executeCountQuery - actually, it would worth to provide the full stacktrace). And it seems that your Content entity has composite PK, i.e. (id, version) (again, no entity definition provided), but HBN experiences some difficulties with such queries: https://hibernate.atlassian.net/browse/HHH-11042


text:
Q: How do I query for a variable attribute of a django model? I know I can use getattr(mymodel, myvar) to get a variable attribute from a model. However, this doesn't work if I want to also be able to get attributes from related models using django's double underscore notation.
How would I accomplish something like the following?
mymodel.get('relation__relation_attr')

Thanks!

A: Reduce is your friend:
#we take a model:
m=Material.objects.all()[0]

#now I navigate to some attr:
m.uf.mp.nom

#we get:
u'Programació multimèdia i dispositius mòbils'

#I write attr path as string:
str="uf__mp__nom"

#I invoke reduce to get attr value through path:
reduce( getattr, [ m ] + str.split("__" ) )

#we get same result, txan txan!!
u'Programació multimèdia i dispositius mòbils'

Another example:
>>> m.uf.mp.cicle.nom
u'Desenvolupament d aplicacions multiplataforma'
>>>
>>> str="uf__mp__cicle__nom"
>>>
>>> reduce( getattr, [ m ] + str.split("__" ) )
u'Desenvolupament d aplicacions multiplataforma'

write your own function to encapsulate it.


text:
Q: Office add-in ribbons: same tab with 2 addins I'm trying to make two word add-ins' groups to appear in the same tab (Tools) but they both create unique tabs (there's two 'Tools' tabs).  I saw this video but I'm using the Visual Designer, not XML.
Can I edit the designer code in some way to make this work?

A: http://blogs.msdn.com/b/vsto/archive/2008/03/10/share-a-ribbon-customization-between-office-applications.aspx
Office 2007
Create the Ribbon

*

*Create a 2007 Excel, Outlook, PowerPoint, or Word project in Visual Studio. For the purpose of these steps, create a C# project and name the project RibbonStarterProject.

*Add a Ribbon (Visual Designer) item to the project. For the purpose of these steps, accept the default name "Ribbon1".

*Save and close the project.

Create a Class Library Project

*

*Create a new class library project in Visual Studio. For the purpose of these steps, name the project SharedRibbonLibrary.

*Add a project reference to the Microsoft.Office.Tools.Common.v9.0 assembly.

*On the Project Menu in Visual Studio, click Add Existing Item.

*In the Add Existing Item dialog box, browse to the "RibbonStarterProject" project directory, select the Ribbon.cs file, and click Add.
Ribbon1.cs is copied to the project directory and appears beneath the project node in Solution Explorer.

*Double-click Ribbon1.cs.
The Ribbon designer appears.

*From the Office Ribbon Controls tab of the Toolbox, drag a button onto group1.

*Click button1 to select it.

*In the Properties window, set Modifiers to Public.
Note:  By default, controls that you add to the Ribbon are Internal. That makes them only accessible to code inside the same assembly. However, when you access these controls, you will be accessing them through an assembly reference. Therefore, to reach them from code, you must make them public. More on this soon.

*Right-click the Ribbon designer, and then click Properties.

*In the Properties window, click the RibbonType property, and then select the Ribbon ID's of the applications or Outlook Inspector windows in which you want the Ribbon to appear. For more information about this property, see the MSDN reference topic for the RibbonType property.

*In Solution Explorer, right-click Ribbon1.cs, and then click View Code.

*Change the namespace of the class to "SharedRibbonLibrary".

*Repeat this step for the Ribbon1.designer.cs file.

*Compile and save the SharedRibbonLibrary project. You can now use the resulting assembly in any VSTO project that supports the Ribbon.

Consume the Ribbon Customization

*

*Create 2007 Excel, Outlook, PowerPoint, or Word project.

*Add a reference to the SharedRibbonLibrary assembly.

*Add the following code to the ThisAddin, ThisWorkbook, or ThisDocument class of your project. This code overrides the CreateRibbonExtensibilityObject method and returns the Ribbon to the Office application.
protected override Microsoft.Office.Core.IRibbonExtensibility
CreateRibbonExtensibilityObject()
{
     return new Microsoft.Office.Tools.Ribbon.RibbonManager(
     new Microsoft.Office.Tools.Ribbon.OfficeRibbon[] { new
        SharedRibbonLibrary.Ribbon1() });

}

*Add a new class to the project. Accept the default name "Class1.cs".

*Replace the code in the Class1 file with the following:
 partial class ThisRibbonCollection :    Microsoft.Office.Tools.Ribbon.RibbonReadOnlyCollection
{
 internal SharedRibbonLibrary.Ribbon1 Ribbon1
 {
     get { return this.GetRibbon<SharedRibbonLibrary.Ribbon1>(); }
 }
}

Ok – You are done! You can now access the Ribbon and the button that you added to the Ribbon in your code.  Lets try by handling an event in the consuming project.
Handle the Button Click Event

*

*Add the following code to the startup event handler of project.
Globals.Ribbons.Ribbon1.button1.Click += new EventHandler<Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs>(button1_Click);

*Add the following event handler to your project:
void button1_Click(object sender,
Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs e)
{
System.Windows.Forms.MessageBox.Show("I can handle events!");
}

*Run the project.

*When the Office application opens, click the Add-Ins tab, and then click your button.
A message that says "I can handle events!" appears.
Office 2010 implementation: http://blogs.msdn.com/b/vsto/archive/2010/06/23/sharing-a-ribbon-customization-between-office-projects-in-visual-studio-2010-mclean-schofield.aspx
The 2010 implementation actually add's two Ribbons - one for each Add-In. I believe the article is only applicable to Add-Ins on the same Ribbon in different Office products (eg Word and Excel) not two Excel Add-ins.
The only other avenue I've found is a 3rd party component: http://www.add-in-express.com/creating-addins-blog/2012/11/05/excel-addin-shared-ribbon-tabs/


text:
Q: Magento 2 error: We're sorry, an error has occurred while generating this email I am getting below error in magento 2 local system.

We're sorry, an error has occurred while generating this email.

A: The first thing you need to do is go to your .htaccess file. Uncomment
SetEnv MAGE_MODE developer
The error message is 90% of the time misleading and most likely you have an xml parsing issue. Either way turning on the developer environment and clearing the cache will pull the error.
Without seeing your error log it'd be hard to give an exact diagnosis. Some users will say sendmail will fix this error but generally this is because the error is trying to be emailed to you and that is because you are not in the correct developing environment to debug the issue. This could be because you are in default or production mode which is not ideal for fixing issue.
The sendmail module is meant to allow a site to operate and if any issues do occur with the site then the developer can be notified and hopefully the error hasn't caused a full site rendering issue. This way a site can still operate unbeknown to users and the issue can be resolved by a qualified developer behind the scenes.

A: *

*Enable developer mode using command line php bin/magento deploy:mode:set developer

*Clear cache using command line php bin/magento cache:flush

*Reload the front end page

*After reloading the page the message will change to

Error filtering template: Unable to write file into directory
  \C:/xampp/htdocs/Magento/pub/media/catalog/product\cache\f073062f50e48eb0f0998593e568d857/m/b.
  Access forbidden.

*Follow this link to fix
https://magento.stackexchange.com/questions/170376/magento-2-unable-to-write-file-into-directory-access-forbidden

*Clear cache

*Reload the front end page again

*If you see another message after enabling developer mode you can google it.


text:
Q: mysql deadlock when saving product with website ids through console command I have a project with 10+ websites, and when my product import runs I need to assign the correct website association. The problem is that something which appears to be a deadlock occurs when magento tries to save the association records to the catalog_product_website table. I created a simple command to test this behavior.
Important things to note:

*

*If I don't assign website ids everything works fine.

*When doing this manually from the adminhtml area the same queries are run with the same data and there are no errors (errors only occur when doing this from CLI)

*I have been able to reproduce this behavior on two separate environments with identical results

*On both environments I have tested this with Magento 2.1.7 and with Magento 2.1.8

My code:

namespace Vendor\Module\Console\Command;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TestProductCommand extends Command
{

    /**
     * @var State
     */
    protected $appState;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var ProductFactory
     */
    protected $productFactory;

    /**
     * @inheritDoc
     */
    public function __construct(
        State $state,
        ProductRepositoryInterface $productRepository,
        ProductFactory $productFactory,
        $name = null
    ) {
        parent::__construct($name);

        $this->appState = $state;
        $this->productRepository = $productRepository;
        $this->productFactory = $productFactory;
    }

    /**
     * @inheritDoc
     */
    protected function configure()
    {
        $this
            ->setName('test:product')
            ->setDescription('Test product creation');
    }

    /**
     * @inheritDoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->appState->emulateAreaCode(Area::AREA_ADMINHTML, [$this, 'createProduct'], [$input, $output]);
    }

    public function createProduct(InputInterface $input, OutputInterface $output)
    {
        try {
            $code = $this->appState->getAreaCode();
            echo "Area code: " . $code . "\n";
            //$output->writeln("<info>Area code:</info> " . $code);
        } catch (\Exception $e) {
            $output->writeln("No area code");
            return;
        }

        /** @var Product $product */
        $product = $this->productFactory->create();
        $sku = 'testsku';
        $productId = $product->getResource()->getIdBySku($sku);

        if ($productId) {
            $product->load($productId);
        }

        $product
            ->setSku($sku)
            ->setName('Test product')
            ->setAttributeSetId($product->getDefaultAttributeSetId())
            ->setTypeId(Type::TYPE_SIMPLE)
            ->setUrlKey('test-product-testsku')
            ->setPrice(110.00)
            ->setWebsiteIds([4]);

        $this->productRepository->save($product);

        $output->writeln("Product id: " . $product->getId());
    }
}

It doesn't matter if I save through the product repository or directly using $product->save();, the result is the same: I get a lock wait timeout exception. The query which causes the timeout is:
INSERT INTO `catalog_product_website` (`product_id`,`website_id`) VALUES  ('1','4')

InnoDb lock information shows that at this point there are two connections: a 'sleeping' connection which is holding the lock on 'catalog_product_entity', and an active connection which is trying to run the aforementioned query but which is waiting for the lock to release (which will never happen before the transaction completes).
Now i know that the usual response is to use show processlist; to find and kill the locking query. This doesn't work because both queries are part of the same transaction so killing the locking query also kills the overall product save transaction.
I have also run SHOW ENGINE INNODB STATUS\G during the lock wait to try to find more information, but there is no mention of deadlocks or foreign key errors in the output.
Google has not been a huge help so far (I learned a whole bunch about MySQL in the last few days but it hasn't solved my problem yet).
So my question is: has anyone had any similar experiences and/or does anyone know how I can solve this issue?


text:
Q: Retrieving Google User Information once logged in (Meteor) I've not been able to show my google users name or profile picture. This is what I have so far...
Accounts.onCreateUser(function(options, user){
    if (options.profile) {
        options.profile.picture = "https://www.googleapis.com/plus/v1/people/" + user.services.google.id;
        user.profile = user.services.google.picture;
    }
    return user;
});

and I'm showing this in my profile template
            {{#if currentUser}}
                <img scr="{{currentUser.profile.picture}}" alt="{{currentUser.username}}">
            {{/if}}

I'm not sure what seems to be the problem. What if I want to get more information from the user such as gender, etc?
This is what happens when you type Meteor.user() in the console
 Object
_id: "BoH9pAN8G7Xj2cWkT"
profile: Object
name: "redacted"
__proto__: Object
__defineGetter__: function __defineGetter__() {
__defineSetter__: function __defineSetter__() {
__lookupGetter__: function __lookupGetter__() {
__lookupSetter__: function __lookupSetter__() {
constructor: function Object() {
get __proto__: function () {
hasOwnProperty: function hasOwnProperty() {
isPrototypeOf: function isPrototypeOf() {
propertyIsEnumerable: function propertyIsEnumerable() {
set __proto__: function () {
toLocaleString: function toLocaleString() {
toString: function toString() {
valueOf: function valueOf() {
__proto__: Object
__defineGetter__: function __defineGetter__() {
__defineSetter__: function __defineSetter__() {
__lookupGetter__: function __lookupGetter__() {
length: 1
name: "__lookupGetter__"
__proto__: function () {
__lookupSetter__: function __lookupSetter__() {
constructor: function Object() {
get __proto__: function () {
hasOwnProperty: function hasOwnProperty() {
isPrototypeOf: function isPrototypeOf() {
propertyIsEnumerable: function propertyIsEnumerable() {
set __proto__: function () {
toLocaleString: function toLocaleString() {
toString: function toString() {
valueOf: function valueOf() {

A: I had the same problem, after being authenticated with google (with the package accounts-google), I wanted to get more information about the user, especially the profile picture.
Sadly a :
Meteor.startup(function () {
   console.log(Meteor.user());
});

in the client js would output me the same result than yours, I could not access to nothing but
{{currentUser.profile.name}}

I connected to the database with Robomongo and looked for the "users" table. Surprisingly, all the fields got from google were here.

I thought that maybe the client had no access to all of those fields by default. So I added a publication in the server js file to get all of the current user data. Then made the client js file subscribing to the publication.
Server JS :
Meteor.publish("userData", function () {
   return Meteor.users.find({_id: this.userId});
});

Client JS :
Meteor.subscribe("userData");

Then I was able to get all the fields needed
Client HTML :
{{currentUser.services.google.id}}
{{currentUser.services.google.email}}
{{currentUser.services.google.picture}}


text:
Q: Can calling the getter of a super class reduce efficiency? I have two classes :
abstract class Employee{
    protected int id;

    public int getId(){
        return id;
    }
}

class Manager extends Employee{
}

In the course of the execution of the rest of my application I create lots of employee objects and call their getId() method many times.
The execution time is around 8 seconds. But if I add the following method to Manager :
    @Override
    public int getId(){
        return super.id;
    }

..the same program(keeping everything else constant) now runs in half as much time. I tested both versions  multiple times and got the same results. Can anyone think of a reason for this?

A: When you run a micro-benchmark, you are very susceptible to how you have performed the benchmark and what code can be optimised away. This means that code which is basically the same can so subtle but relatively large differences in performance.  However if you did the test a little differently or use a different update of Java you might find a very different result.
When you override a method in a sub-class you effectively make the class virtual.  This means you can call Employee.getId() or Manager.getId() and it needs to check the type to determine which class method to call.  The fact the methods are the same doesn't help.  The JVM can be reasonably smart and inline the method, but since your method is trivial the very simple check of the type could means the difference in performance.  .
It is also possible that this change turns of other optimisation. For example, an "infrequent" is only inlined if it is 35 bytes long.  This can cause a problem with try/catch blocks.  The try/catch block in itself doesn't slow down the code but can make the method bigger and mean it is no longer inlined.  In your case, having a, overriden method can mean the calling code is a little bigger when your method is inlined and it is not optimised as aggressively.
Lastly I would check you code with the latest JVM. e.g. Java 7 update 40.  You might find that this version doesn't show a difference in which case I would put it down to a bug in your version of the JVM.

A: Quite interesting,
To just confirm myself, I created test case, to replicate the behaviour, Given below the test case and  test results
Case 1 when not overriding the method
Test Result
Run 1 - Creating 100000000 Employees        Time taken to complete operation  :501 (ms)
Run 2 - Creating 100000000 Employees        Time taken to complete operation :507 (ms)
Run 3 - Creating 100000000 Employees        Time taken to complete operation :502 (ms)
Case 2  -When overriding the method in sub class,
@Override
        public int getId(){
            return super.id;
        }

Test Result

Run 1 - Creating 100000000 Employees          Time taken to complete   operation :486 (ms)
Run 2 - Creating 100000000 Employees           Time taken   to complete operation :497 (ms)
Run 3  - Creating 100000000 Employees           Time taken to complete operation :478 (ms)
Case 3  - overriding the method, but not using super keyword
  @Override
        public int getId(){
            return id;
        }

Test Result
Run 1 - Creating 100000000 Employees
         Time taken to complete operation :457 (ms)
Run 2 - Creating 100000000 Employees
         Time taken to complete operation :471 (ms)
Run 3 -     Creating 100000000 Employees
         Time taken to complete operation :471 (ms)
Observation:
There is minimal improvement when overriding the method/using directly(case 2 and case 3) ; but as best practise, most of the cases the variable would be declared private and method will be protected. If the variable itself protected, then you would need super key
---------- Full Test code   for reference  -----
public class TestEff {

    public static void main(String[] args) {
        System.out.println( " Creating 100000000 Employees ");
        long st = System.currentTimeMillis();
        for(int i=0;i<100000000;i++){
            Manager mgr = new Manager();
            int id =mgr.getId();
        }
        long et = System.currentTimeMillis();
        long t = (et-st);
        System.out.println(" Time taken to complete operation :"+t);
    }
}

abstract class Employee{
    protected int id;

    public int getId(){
        return id;
    }
}

class Manager extends Employee{
      @Override
        public int getId(){
            return super.id;
        }
}


text:
Q: DIsplaying element in ListView using SimpleCursor Loader I have the following fragment, which appears in a tab.
public class Tab3Fragment extends Fragment {

    SQLiteDatabase db;
    DBHandler dbHandler =  new DBHandler(getContext(), null, null, 4);
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab3_frag, container, false);

        db = dbHandler.getReadableDatabase();

        String [] columns = {Contract.Student_Table.STUDENTS_COLUMN_ID, Contract.Student_Table.STUDENTS_COLUMN_NAME};
        Cursor mCursor = db.query(Contract.Student_Table.TABLE_NAME, columns, null,
                null, null, null, null);
        String[] from = new String[]{Contract.Student_Table.STUDENTS_COLUMN_NAME};
        int[] to = new int[]{R.id.student_view};

        SimpleCursorAdapter mCurAdapter = new SimpleCursorAdapter(getContext(),android.R.layout.simple_list_item_1, mCursor, from, to,0);

        ListView mMyListView = view.findViewById(R.id.simple_list);
        mMyListView.setAdapter(mCurAdapter);

        return view;
    }
}

And I have the following XML file (tab3_frag)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#c2f6ff"
    android:orientation="vertical">

    <ListView
        android:id="@+id/simple_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/student_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

However my code doesn't seem to work and I can't spot the error. No crashing or errors, just nothing appears in my tab. I'd appreciate any help that could guide me through what I may be doing wrong.

A: below class is a separate class for perform all operation.
public class DBHelper extends SQLiteOpenHelper{

//USER TABLE
public static final String USER_TABLE_NAME = "MyTableTwo";
public static final String USER_COLUMN_USER_ID = "id";
public static final String USER_COLUMN_USER_NAME = "Item_Name";
public static final String USER_COLUMN_USER_ADDRESS = "Weight";
public static final String USER_COLUMN_USER_CREATED_AT = "MRP";
public static final String USER_COLUMN_USER_UPDATED_AT = "BARCODE";

public DBHelper(Context context,
                String dbName,
                Integer version) {
    super(context, dbName, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    tableCreateStatements(db);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE_NAME);
    onCreate(db);
}

private void tableCreateStatements(SQLiteDatabase db) {
    try {
        db.execSQL(
                "CREATE TABLE IF NOT EXISTS "
                        + USER_TABLE_NAME + "("
                        + USER_COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + USER_COLUMN_USER_NAME + " VARCHAR(20), "
                        + USER_COLUMN_USER_ADDRESS + " VARCHAR(50), "
                        + USER_COLUMN_USER_CREATED_AT + " VARCHAR(10) DEFAULT " + getCurrentTimeStamp() + ", "
                        + USER_COLUMN_USER_UPDATED_AT + " VARCHAR(10) DEFAULT " + getCurrentTimeStamp() + ")"
        );

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
public List<MyTableTwo> getMyItems() {
    List<MyTableTwo> mySuperList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT  * FROM " + USER_TABLE_NAME ;
    Cursor c = db.rawQuery(selectQuery, null);
    if (c != null) {
        c.moveToFirst();
        while (c.isAfterLast() == false) {
            MyTableTwo myTable = new MyTableTwo();
            myTable.itemName = (c.getString(c.getColumnIndex("Item_Name")));
            myTable.weight = (c.getString(c.getColumnIndex("Weight")));
            myTable.mrp = (c.getString(c.getColumnIndex("MRP")));
            myTable.barcod = (c.getString(c.getColumnIndex("BARCODE")));

            mySuperList.add(myTable);
            c.moveToNext();
        }
    }
    return mySuperList;
}

public Long insertUser(MyTableTwo user) throws Exception {
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(USER_COLUMN_USER_NAME, user.itemName);
        contentValues.put(USER_COLUMN_USER_ADDRESS, user.barcod);
        contentValues.put(USER_COLUMN_USER_CREATED_AT, user.weight);
        contentValues.put(USER_COLUMN_USER_UPDATED_AT, user.barcod);

        return db.insert(USER_TABLE_NAME, null, contentValues);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

private String getCurrentTimeStamp() {
    return String.valueOf(System.currentTimeMillis() / 1000);
}

}

A: change this things
 db = dbHandler.getReadableDatabase();

Change following things
make separete layout for textview like
list_template.xml
<TextView
    android:id="@+id/student_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TextView" />

then after change this things ..
int[] to = {R.id.student_view};

    SimpleCursorAdapter mCurAdapter = new SimpleCursorAdapter(getContext(),R.layout.list_template, mCursor, from, to,0);


text:
Q: View override does not work in partner community I have a lightning component that overrides the view action on Contact and redirects the user to the Account detail page. It works well in Lightning Experience and Salesforce1 mobile app but does not work in Community (partner central template). For brevity, I have minimized the code to the bare bones relevant for the question. Am I missing something?
Component
<aura:component controller="ContactController"
implements="forceCommunity:availableForAllPageTypes, lightning:actionOverride, force:hasRecordId">

<aura:attribute name="accountId" type="String" default="0010l000005qbUiAAI" />
<aura:dependency resource="markup://force:navigateToSObject" type="EVENT"/>

<aura:handler name="init" value="{!this}" action="{!c.redirectToAccount}"/>

Controller
({
    redirectToAccount : function(component, event, helper) {
        var accountId = component.get('v.accountId');
        helper.moveToAccount(accountId);
    }
})

Helper
({
    moveToAccount : function(accountId) {
        var navigate = $A.get("e.force:navigateToSObject");
        navigate.setParams({'recordId': accountId});
        navigate.fire();
    }
})

A: The docs for the lighnting:overide mention to work only for lighnting experience and SF1 .
It does not mention for communities .Communities lightning container is quite different and hence I fear this is not yet supported for communities .


text:
Q: Magento 2 - losing the theme after module:enable So in Magento 2, I seem to lose all of the static assets after I install a module. This is what happens:
bin/magento module:enable [module name or --all]

Which of course tells me:

To make sure that the enabled modules are properly registered, run
  'setup:upgrade'.

Now the issue is when I run:
bin/magento setup:upgrade

All of the pregenerated static files are gone. The whole admin and store frontend breaks.
Then I have to run a bunch of commands to process and re-generate all of the required files. Now, please tell me I am making a noob mistake here. I might be on the wrong mode etc.
How do you guys handle this?

A: We can run the setup upgrade command and keep the static content:
php bin/magento setup:upgrade --keep-generated

One more thing, if we want the static content to re-generate on fly automatically and create the symlink, we need to delete static folders(_requirejs, adminhtml, frontend), DON'T delete .htacess. Make sure our application mode is developer or default. Refresh the page, it takes time to re-generate the static content on fly. And then, we don't need to run the static command every time.


text:
Q: Conditional Compile of Generic Methods Currently working on a 2-way lookup association generic, sorted by TKey. At some point I hope to have access like the following:
public class Assoc<TKey, TValue>
{
     public TKey this[TValue value] { get; }
     public TValue this[TKey value] { get; }
}

But obviously when TKey == TValue this will fail. Out of curiosity, is there a conditional compile syntax to do this:
public class Assoc<TKey, TValue>
{
     [Condition(!(TKey is TValue))]
     public TKey this[TValue value] { get; }

     [Condition(!(TKey is TValue))]
     public TValue this[TKey value] { get; }

     public TKey Key(TValue value) { get; }

     public TValue Value(TKey value) { get; }
}

A: No, there is no conditional compiltation based on Generic types.
Generics substitutions are performed at runtime, not compile time.
This is one of the differences between .NET generics and C++ templates.
Generics also don't have the concept of specialization that C++ templates have.
http://msdn.microsoft.com/en-us/library/c6cyy67b.aspx


text:
Q: is minify improve performance of angular js or just loading performance? I have 40-60 scripts in my index. most of us angular
I want in production to make them as a 1 script only
is it possible? all the logic will works?
which library is the best for it?
is it good for performance or only for loading performance

A: You will want to use something like webpack or SystemJS. These will bundle you JS files all into one file and can minify/uglify this code as well.
Doing this will improve the page loading times as there are less requests to load, and minifying will shrink the filesize down. Uglifing is just to make the js harder to interpret for someone trying to look at your code.
The performance of your angular app will not be improved by doing this however.
Something you can do to increase angular performance on production is turning of debug info, like so:
myApp.config(['$compileProvider', function ($compileProvider)
{
    $compileProvider.debugInfoEnabled(false);
}]);

According to the angular.js docs, this is good practise in production and should result in a performance boost.
You may also want to look in one time binding, and using a "track by" in any ng-repeats as other ways of improving performance.

EDIT :
The above tips on angular performance all assume you are using angular.js as opposed to the newer Angular 2+


text:
Q: how to prevent an image to move while scrolling in mobile app I am developing a mobile app. I use JavaScript for the code and some jQuery mobile (1.4.5).
My problem is that when I scroll, my images follow the scroll. I don't have this problem in the web version, but on my phone the images are not fixed.  I would like my images to be fixed in the specific positions I want while I am scrolling on any device.
Let me explain briefly my code:

*

*When I open my app, some images appear in their places.  For this, I simply use:

<img src="js/image.jpg" style="position: absolute; top:105px; left:10px;"  width="110" height="85">
which works fine, this image stays in place even in the mobile app.

*

*then later, others pictures have to appear. For this, I use this function:

function im2(a,b,c,d){var x = document.createElement("IMG");
 x.setAttribute("src", a);
x.setAttribute("style",b);
 x.setAttribute("width", c);x.setAttribute("height",d );
document.body.appendChild(x);
}

Then to call the image:
<im2("js/image2.jpg","position: fixed; top:210px ; left:165px","280","35")>
Then when I scroll, this image is not fixed anymore on mobile (works fine in web ) ... :-(

*

*So, I tried this CSS to stick the image, in order to disable it from moving

<style>
img.sticky {
  position: -webkit-sticky;
  position: sticky;
}
</style>

In the Javascript, I use the same function im2 : im2(w, etc){ x.setAttribute("class", w); etc}
Then, I call the function like this:
im2("sticky","js/image2.jpg","position: fixed; top:210px ; left:165px","280","35") and .... nothing stick.
I presume this is because of the jqm layer that gives this unexpected result.
So, what should I do /write?

A: For some unknown reasons it works ... images stay fixed .. now??
The problem remains the same while I swipe from page to page. In another post, I found this solution that sounds promising. I cannot directly talk with the user or put a comment as I am 2 hours away. Here is the jQuery code that should work, but it doesn't with me.
Where should I put this line ?
$('img').on('dragstart', function(event) { event.preventDefault(); });

Here is the script for swiping I use:
<script>
$(document).on('swipeleft', '.ui-page', function(event){
    if(event.handled !== true) // This will prevent event triggering more then once
    {
        var nextpage = $.mobile.activePage.next('[data-role="page"]');
        // swipe using id of next page if exists
        if (nextpage.length > 0) {
            $.mobile.changePage(nextpage, {transition: "slide", reverse: false}, true, true);
        }
        event.handled = true;
    }
    return false;
});

$(document).on('swiperight', '.ui-page', function(event){
    if(event.handled !== true) // This will prevent event triggering more then once
    {
        var prevpage = $(this).prev('[data-role="page"]');
        if (prevpage.length > 0) {
            $.mobile.changePage(prevpage, {transition: "slide", reverse: true}, true, true);
        }
        event.handled = true;
    }
    return false;
});


text:
Q: _registerComponent(…): Target container is not a DOM element I have the problem :

_registerComponent(…): Target container is not a DOM element.

This is the code :
The homeMaster.Html Code :
<!DOCTYPE html>

         <title></title>
         <meta charset="utf-8" />
         <link rel="stylesheet" type="text/css" href="..\Content\bootstrap.min.css" />
         <link rel="stylesheet" type="text/css" href="..\PageStyle\MasterPageCss.css" />

                 <app></app>

router.jsx Code :
"use strict";

var App = React.createClass({
  render: function() {
    return (

Simple SPA

<IndexLink to="/" activeClassName="active">Home</IndexLink>

<Link to="/stuff" activeClassName="active">Stuff</Link>

<Link to="/contact" activeClassName="active">Contact</Link>

{this.props.children}

    )
  }
});

var Home = React.createClass({
    render: function() {
        return (

HELLO

Cras facilisis urna ornare ex volutpat, et
        convallis erat elementum. Ut aliquam, ipsum vitae
        gravida suscipit, metus dui bibendum est, eget rhoncus nibh
        metus nec massa. Maecenas hendrerit laoreet augue
        nec molestie. Cum sociis natoque penatibus et magnis
        dis parturient montes, nascetur ridiculus mus.

Duis a turpis sed lacus dapibus elementum sed eu lectus.

        );
    }
});

var Contact = React.createClass({
    render: function() {
        return (

GOT QUESTIONS?

The easiest thing to do is post on
            our forums.

        );
    }
});

var Stuff = React.createClass({
    render: function() {
        return (

STUFF

Mauris sem velit, vehicula eget sodales vitae,
            rhoncus eget sapien:

Nulla pulvinar diam

Facilisis bibendum

Vestibulum vulputate

Eget erat

Id porttitor

        );
    }
});

ReactDOM.render(
  <ReactRouter.Router>
    <ReactRouter.Route path="/" component={App}>
      <ReactRouter.IndexRoute component={Home} />
      <ReactRouter.Route path="stuff" component={Stuff}>
      </ReactRouter.Route>
      <ReactRouter.Route path="contact" component={Contact} />
    </ReactRouter.Route>
  </ReactRouter.Router>,
  ReactRouter.destination);

The error is :
Uncaught Error: _registerComponent(...): Target container is not a DOM element.
    at invariant (react.js:18350)
    at Object._registerComponent (react.js:11043)
    at Object._renderNewRootComponent (react.js:11066)
    at Object.wrapper [as _renderNewRootComponent] (react.js:12349)
    at Object._renderSubtreeIntoContainer (react.js:11146)
    at Object.render (react.js:11166)
    at Object.wrapper [as render] (react.js:12349)
    at router.jsx [sm]:70
    react.js:18357

The homeMaster.html doe's not recognizance the router.jsx file ,
Because it can't figure the target container DOM_Element.
I tried to put the .jsx file to compile before the html shows up.
And do async.

A: Your render call is attempting to use ReactRouter.destination as the DOM element to attach your application to. Unless you are setting that variable somewhere that isn't visible in the provided code, the issue is that that value is undefined, not a DOM element.
The second argument to ReactDOM.render should be a DOM element that exists in the page, i.e. given the following HTML:

You would attach your application to the #app div by calling:
ReactDOM.render((
  <ReactRouter.Router>
    ...
  </ReactRouter.Router>
), document.querySelector('#app'));


text:
Q: phpBB - login NOT case sensitive How can you make the username case insensitive, and give the possibility to login with both email and username?
can't seem to find anything under administration.. is it possible to change in the cms?

A: Well, change the login query to
$emailOrUser = mysql_real_escape_string($_POST['emailorusername']);
$password = mysql_real_escape_string(phpBB_password_hash_function($_POST['password']));

$loggedIn = mysql_query("...
                        where (email = '" . $emailOrUser . "' or lowercase(username) = '" . strtolower($emailOrUser) . "')
                        and (password = '" . $password . "')");

Or if you can't or don't want to program, take a look here since it's a freely downloadable mod for phpBB that lets you login with email.
You can also change the user table to a case-insensitive collation, but that might produce unexpectable results, just as my query. I don't know whether phpBB lets you create two accounts if the casing differs (user vs USER, are that two different valid accounts?).

A: Perhaps try with a filter of some sort (filter the imput).


text:
Q: Triangle problem - finding the angle Please look at the following figure:

All the angles are in degrees. I have to find $x$.

I am really no good at solving geometry problems. I tried to search the internet for similar problems and came up with this: https://www.duckware.com/tech/worldshardesteasygeometryproblem.html . The two problems mentioned on the page are very similar so I tried to see if the solutions to them can be applied to this problem but it didn't help. I have zero idea about the problem given my inexperience in these kind of geometry problem.
Any help is appreciated. Thanks!

A: The angle in question does not seem to be a rational number of degrees. It is approximately
$$x\approx17.877987144333100702669230434486544610886743725521319531393624°$$
It is characterized by
$$1216\,\cos^6x - 3264\,\cos^4x + 2916\,\cos^2x - 867 = 0$$
Since this is a cubic equation in $\cos^2x$ you could write down an explicit formula for the solution of that in terms of radicals, take the square root, then the arc cosine of that, and would end up with an explicit exact formula for the angle in question. Not a nice formula, though, and you'll need complex numbers along the way even though the final result is real:
$$x=\arccos\sqrt{
\frac{17}{19}-\frac{1+\sqrt{-3}}{152} \sqrt[3]{\frac{-17+19\sqrt{-3}}2}
-\frac{7 (1-\sqrt{-3})}{76 \sqrt[3]{-68+76\sqrt{-3}}}
}$$
The condition for the sine has a bit easier coefficients:
$$1216\sin^6x - 384\sin^4x + 36\sin^2x - 1=0$$
But basing the explicit formula on that cubic equation has little effect on the overall complexity; it still looks as complicated as it does with the cosine.
I found this by executing the construction using exact algebraic numbers. The cosine in particular relates to the dot product of the unit length direction vectors of the two lines. For the negative result, I looked at the continued fraction representation, which should have had a notable step if this were a rational number. I also tried finding a minimal polynomial of degree up to 24, so it seems that $x$ is probably not even algebraic.

A: I think it's sufficient to handle this with coordinate geometry. I'm going to place the lower left vertex of the triangle at the origin, and the lower right vertex at $(1,0)$. Let's name all five of the small triangles making up the figure, starting at the top, triangle $\alpha$. Then, going around the perimeter clockwise, the triangle containing your angle $x$ will be called $\beta$, then $\gamma$ is the upper triangle with a vertex at the lower right vertex of the whole thing, then $\delta$, and finally $\varepsilon$.
So I'll say that the whole triangle is $\alpha+\beta+\gamma+\delta+\varepsilon$, and any of the smaller ones may be described as the sum (union) of a subset of the five named ones. Let's also name $A$ as the common vertex of $\alpha$, $\beta$, and $\varepsilon$, and $B$ as the common vertex of triangles $\alpha$, $\beta$, and $\gamma$. What's crucial to our discussion is the problem of finding the slope of the line segment $\overline{AB}$.
Let's make some preliminary observations. The big triangle is isosceles, having angles of 80 at both vertices on the horizontal axis. (I'm going to omit the degree sign from here on.) Since the angle of 80 shows up again and again, I'm going to use the notation $T=\tan80$, $S=\sin80$, and $C=\cos80$. So we see that the top vertex has coordinates $(\frac12,T/2)$. Notice also that there's another $(80,80,20)$ isosceles triangle, it's the triangle $\delta+\varepsilon$, which has the point $A$ as the top one of its vertices. So we have similar triangles,
and we can get the length $\ell$ of the segment from the origin to $A$. Using leg/base, we get
$$
\frac{\frac12\sec80}1=\frac1\ell\,,\qquad\ell=2C\,.
$$
Thus the coordinates of $A$ are $(2C^2,2CS)$.
Now $B$ is at the intersection of the line $Y=X/\sqrt3$, because $\tan30=1/\sqrt3$, and the line of slope $T$ passing through $(1,0)$, so its equation is $Y=-T(X-1)$. Solve these two first for $X$, then for $Y$:
$$
X=\frac T{T+\frac1{\sqrt3}}\,,\qquad Y=X/\sqrt3=\frac T{1+\sqrt3T}\,.
$$
From this, the slope $m$ of $\overline{AB}$ is
$$
\frac{\frac T{1+\sqrt3}-2CS}
{\frac{\sqrt3T}{1+\sqrt3T}-2C^2}
=\frac{T-2CS(1+\sqrt3T)}{\sqrt3T-2C^2(1+\sqrt3T)}\,,
$$
which works out numerically to $m=.2147833$. Now we need the angle between this and a line of slope $1/\sqrt3$, so we get
$$
\tan x=\frac{\frac1{\sqrt3}-m}{1+\frac m{\sqrt3}}=\frac{1-\sqrt3m}{\sqrt3+m}
=.3225670\,,
$$
which gives $x=17.8779872^\circ$. I did all these numerics on my HP15-C !


text:
Q: c language regex matching mutiple parts of a string I have a c program where I can't get the regular expression matching to work the way I want. Basically, I want to match the 1st char (W or M) in testStr and the name of the log file as the second match (TESTY.LOG).  Here is what I have so far:
#include    <stdio.h>
#include    <stdlib.h>
#include    <regex.h>
#define     MAX_MATCHES 2
.....
char testStr[20]="W TESTY.LOG ";
char temp[100];
int reti;
regex_t regex;
regmatch_t matches[MAX_MATCHES];
int i;
int numchars;

/* Compile regular expression */
reti = regcomp(&regex, "^([W|M])[[:space:]]([A-Z|0-9|\.]{1,})[[:space:]]*$", REG_EXTENDED);
/* Execute regular expression */
reti = regexec(&regex, testStr, MAX_MATCHES, matches, 0);
if (!reti) {
  for (i=0; i < MAX_MATCHES; i++) {
    numchars = (int)matches[i].rm_eo - (int)matches[i].rm_so;
    strncpy(temp,testStr+matches[i].rm_so,numchars);
    temp[numchars] = '\0';
  }
}

When I run this in gdb, I see the following for matches:
(gdb) display matches
1: matches = {{rm_so = 0, rm_eo = 15}, {rm_so = 0, rm_eo = 1}}
2: temp = "W TESTY.LOG"
and
2: temp = "W"
So, I'm getting the first char OK but I am not getting just the log file name for the second match.  I use regex in perl but I'm new to regex in ansi c.  I feel like I'm missing something basic here.

A: Match 0 is the part of the string matched by the entire regex (Perl's $&). Match i for i > 0 is the part of the match corresponding to capture number i, the same as Perl's $1, $2, …. You have two captures, so you should expect three matches. But you specify MAX_MATCH as 2, so the last match is discarded.

Also, the regular expression
^([W|M])[[:space:]]([A-Z|0-9|\.]{1,})[[:space:]]*$

is a little odd. I think you should reread the documentation about character classes in regular expressions -- in this case, it is the same in Perl as it is in Posix extended REs. [W|M] matches any of the three characters W, | or M. Similarly, [A-Z|0-9|\.]{1,} matches one or more of a letter, a digit, the character | or the character ..
The backslash is irrelevant since it only escapes the . in the string literal, where escaping is unnecessary. If you had compiled with warnings enabled, -Wall, your C compiler would probably have warned you that the escape sequence is not legal. If you had actually passed the backslash on to the regex library, it would have interpreted it as another possible match for the character class.
Also, {1,} can be conveniently written as +, both in Perl and in Posix Extended REs.
In short, what you probably wanted was:
reti = regcomp(&regex, "^([WM])[[:space:]]([A-Z0-9.]+)[[:space:]]*$", REG_EXTENDED)

You could also use
reti = regcomp(&regex, "^([WM])[[:space:]]([[:alnum:].]+)[[:space:]]*$", REG_EXTENDED)


text:
Q: How to develop multiserver web applications? I'm wondering how to develop multiserver web applications (ASP.NET). Any articles, books ?

A: Here is the MSDN Article on how do just that:
http://support.microsoft.com/kb/815162


text:
Q: Spring MVC does not render html with angularjs directive the angularjs feature called directive cause to problems in spring mvc. If I use thymeleaf to render a html with elements such

i got a error like
org.xml.sax.SAXParseException: Attribute name "ui-view" associated with an element type "div" must be followed by the ' = ' character.

is there an elegant workaround or should I use something else than thymeleaf?
Edit:
Many thanks for your answers, they helped me a lot.
Either you code xml or you use some workaround. open your application.properties and add following
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

A: Just put the below code. basically what it is saying is that every attribute in HTML should have a value. When the browser renders it, it will anyway look like below.

Update: You can also use directive in a class or as an element.


text:
Q: Firestore listen only to root component Please take a look at this example:

As you see I have a collection called "new_letters" and inside there I have documents, which also have collections and in those also documents, so basicly a long chain of data segments always.
My goal would be to have a listener which checks the amount of documents inside of "new_letters" and my idea would be the simple one following:
var counter = firebase.firestore().ref("new_letters").onSnapshot(snapshot => {
   return snapshot.size
});

My problems are the following:

*

*Im afraid of long bills and therefore I only want to check the amount of the data, not every subcollection of subdocument included in the collection "new_letters". If I do the listener like above, will I only download the 3 documents or will this also include the "inbox"-collection which is inside of the second document for example?

*Incase Point 1 is true and I download all data, including each "inbox" inside every document in "new_letters", is the only alternative making a counter for example in the firebase.database() and listening only to that?

Im looking for a solution which is the least recource-consuming.


text:
Q: Monthly trend comparison using tables in Google Data Studio I'm quite new to GDS and I've been experimenting with the comparison date range to see the increase in % between current and previous month
I've managed to get a slight result but it's not showing the correct % increase which I have manually calculated to confirm.
The values are

No of Reviews (calculation)
July - 379 reviews / 314 positive reviews = 82.85%
August - 480 reviews / 458 positive reviews = 95.42%
Manually Calculated Difference = 12.57%
GDS Comparison Difference = 15.2%

The date column itself is formatted as "YYYYMMDD" and I've tried the comparison and calculation field options on the metric but to no avail
It feels like I am getting a comparative % rather than a direct increase
Any help/guidance would be greatly appreciated as I have tried the GDS forum several times but there is very little activity on there
Thanks so much
Dan

A: It's not ideal but to do this in GDS you need to create a new column in Google Sheets which is literally the values you need from the previous month. I.e.
date      |reviews|pos reviews|prev month reviews|prev month pos reviews|
2019-08-01|480    |458        |379               |     314              |

You can then create 2 calculated fields for this month % positive and last month % positive and a 3rd for the difference.
There are other wyas you can try to do this but they get a bit messy and manual so that's probably a good starting point. GDS is great in some ways (cost being one!) but a little limited in others!

A: On the style on your table, under show compare, check Show Absolute Change to get the exact difference.


text:
Q: How to get an sbatch script to run on many unique servers? I am trying to get a python script that isn't too intense to run on a lot of servers to parallelize the process I am doing as it involves a lot of io tasks which takes a lot of time if I do it serially in one process. I am trying to split it up across 10 servers as that gets the task done in a reasonable amount of time. I wrote the sbatch script below to do so but I keep getting silent errors that show up when I check on the job using sacct. I am quite new to using slurm so any help will be greatly appreciated!
#! /bin/bash
#SBATCH -A account
#SBATCH -N 10
#SBATCH -n 300
#SBATCH -O
#SBATCH --ntasks-per-node=30

for i in {0..300}; do  # total 300
  echo $i;
  srun python script.py $((i * 20000)) 20000 $i &
done

sacct output:
       JobID    JobName  Partition    Account  AllocCPUS      State ExitCode
------------ ---------- ---------- ---------- ---------- ---------- --------
336284       program__+      debug    account         20  COMPLETED      0:0
336284.batch      batch               account          2  COMPLETED      0:0
336284.exte+     extern               account         20  COMPLETED      0:0
336284.0         python               account         20     FAILED      1:0


text:
Q: How to show % values with decimals in LWC standard datatable I have a Discount__c custom field with data type Percent(15, 3) and it has a values of 1.219%
I am trying to fetch and display the value 1.219% in standard datatable under "DISCOUNT" column.
{ label: 'DISCOUNT', fieldName: 'Discount__c', type: 'percent', cellAttributes: {alignment: 'center'}}

But my datatable playground displaying column value as 122% instead of 1.219%, which is multiplying the value with 100 and rounding the value.
If i give type: 'number' in JS my datatable playground is displaying correct value like 1.219 but i want to display the % symbol for each value in the "DISCOUNT" column along with 3 decimals like 1.219%.
Playground link :- https://developer.salesforce.com/docs/component-library/tools/playground/iBfK8QPn5/2/edit
HTML
    <template>
        <lightning-datatable
            data={data}
            columns={columns}
            key-field="id">
        </lightning-datatable>
    </template>

JS Code
    import { LightningElement } from 'lwc';

    const columns = [
         {label: 'Opportunity name', fieldName: 'opportunityName', type: 'text'},
         {label: 'DISCOUNT', fieldName: 'discount__c', type: 'percent',
               cellAttributes:{ alignment: 'center'}},
         {label: 'Amount', fieldName: 'amount', type: 'currency',
               cellAttributes:{ alignment: 'center'}, typeAttributes: { currencyCode: 'EUR',
               alignment: 'center'}},];

    const data = [{
                    id: 'a',
                    opportunityName: 'Cloudhub',
                    discount__c: 1.219,
                    amount: 25000

                },
                {
                    id: 'b',
                    opportunityName: 'Quip',
                    discount__c: 1.219,
                    amount: 740000
                }];

    export default class DatatableExample extends LightningElement {
         data = data;
         columns = columns;
    }

He is the sample playground code link playground
Any suggestions please...

A: Percentage fields are always stored as a fraction of 1. "Per cent" literally means "one part per hundred", so 1% is actually 0.01. Storing the data this way simplifies calculations using the value (try a formula field on Opportunities Amount * Probability, you'll see what I mean).
If you have a value of 1.219%, it should be downloaded to the client as 0.01219. The value 1.219 means 121.9% in a percentage format. If not, there's something wrong with how you're retrieving the value. You should add a typeAttributes of maximumFractionDigits set to at least 3, in order to show all the fraction digits. I've updated your playground for you.

A: I do not like to change data so I add the datatable type percent-fixed.
Solution I have done:
import percentfixed from './percentfixed.html';
export default class MyDatatable extends LightningDatatable {
    static customTypes = {
        percentfixed : {
            template : percentfixed,
        }
    }
}

Then:
percentFixed.html:
<template>
    <lightning-formatted-number value={value} format-style="percent-fixed" maximum-fraction-digits="2"></lightning-formatted-number>
</template>

then you can use you new datatable component with new type percentFixed on column.

A: The only solution I can think is dividing the table field(discount) value per 100.
const data = [{
        id: 'a',
        opportunityName: 'Cloudhub',
        discount__c: 1.219/100,
        amount: 25000

    },
    {
        id: 'b',
        opportunityName: 'Quip',
        discount__c: 1.219/100,
        amount: 740000
    }];
    console.log(data);

And then use type percent.
Please let me know.


text:
Q: Weight initialization in neural networks Hi I am developing a neural network model using keras.
code

def base_model():
    # Initialising the ANN
    regressor = Sequential()
    # Adding the input layer and the first hidden layer
    regressor.add(Dense(units = 4, kernel_initializer = 'he_normal', activation = 'relu', input_dim = 7))
    # Adding the second hidden layer
    regressor.add(Dense(units = 2, kernel_initializer = 'he_normal', activation = 'relu'))
    # Adding the output layer
    regressor.add(Dense(units = 1, kernel_initializer = 'he_normal'))
    # Compiling the ANN
    regressor.compile(optimizer = 'adam', loss = 'mse', metrics = ['mae'])
    return regressor

I have been reading about which kernel_initializer to use and came across the link- https://towardsdatascience.com/hyper-parameters-in-action-part-ii-weight-initializers-35aee1a28404
it talks about glorot and he initializations. I have tried with different intilizations for weights, but all of them give the same results. I want to understand how important is it do a proper initialization?
Thanks

A: I'll give you an explanation of how much weights initialisation is important.
Let's suppose our NN has an input layer with 1000 neurons, and suppose we start to initialise weights as they are normal distributed with mean 0 and variance 1 ().
At the second layer, we assume that only 500 first layer's neurons are activated, while the other 500 not.
The neuron's input of the second layer z will be the sum of :

so, it will be even normal distributed  but with variance .
This means its value will be |z| >> 1 or |z| << 1, so neurons will saturate. The network will learn slowly at all.
A solution is to initialise weights as  where  is the number of the inputs of the first layer. In this way z will be  and so less spreader, consequently neurons are less prone to saturate.
This trick can help as a start but in deep neural networks, due to the presence of hidden multi-layers, the weights initialisation should be done at each layer. A method may be using the batch normalization
Besides this from your code I can see you'v chosen as cost function the MSE, so it is a quadratic cost function. I don't know if your problem is a classification one, but if this is the case I suggest you to use a cross-entropy function as cost function for increasing the learning rate of your network.


text:
Q: Fit equation with \cases in page width using \resizebox I'm trying to fit an equation with several cases into my page width. The pain is that one case is awfully long. I used the \resizebox{} approach (see solution here), which would work, if there would be no \begin{cases}.
I learned that \resizebox creates a 'new' box and within this box there is no math environment, which is the reason why the solution math content starts with an $, to trigger the inline math mode. My problem is that \begin{cases} is not suitable for the inline math mode, and I receive a 'Missing $ inserted.' error.
Do you have an alternative approach to solve this issue. Adding another \begin{equation} within the box does not work. The work compiles but I would love to see a smoother solution than latex putting $ by itself. - Thanks!
Code looks like this:
\begin{equation}
\resizebox{.9\hsize}{!}{
  r(b_{i,t}^C,p_{market,t})= \begin{cases}
    -(b_{i,t}^C - p_{market,t})^2,      & \text{if} b_{i,t}^C > p_{market,t}\\
    -(b_{i,t}^C - p_{grid})^2,          & \text{if} b_{i,t}^C < p_{market,t} \\
    \frac{p_{market,t}}{100} + \theta,  & \text{if} b_{i,t}^C = p_{market,t} \\
    \frac{p_{market,t}}{100} + 2\theta, & \text{if} b_{i,t}^C = p_{market,t} \text{and} b_{i,t}^C < min(b_{i,t-j}^C,.., b_{i,t-1}^C) \quad|  b_{i,t-j}^C=p_{market,t-j}
 \end{cases}
 }
\end{equation}

A: You can split the long condition into three lines.
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
  r(b_{i,t}^C,p_{\mathrm{market},t})=
  \begin{cases}
    -(b_{i,t}^C - p_{\mathrm{market},t})^2,
      & \text{if } b_{i,t}^C > p_{\mathrm{market},t} \\[2ex]
    -(b_{i,t}^C - p_{\mathrm{grid}})^2,
      & \text{if } b_{i,t}^C < p_{\mathrm{market},t} \\[2ex]
    \frac{p_{\mathrm{market},t}}{100} + \theta,
      & \text{if } b_{i,t}^C = p_{\mathrm{market},t} \\[2ex]
    \frac{p_{\mathrm{market},t}}{100} + 2\theta,
      & \begin{aligned}[t]
        &\text{if } b_{i,t}^C = p_{\mathrm{market},t} \text{ and} \\
        &b_{i,t}^C < \min(b_{i,t-j}^C,\dots, b_{i,t-1}^C) \\
        &\mid b_{i,t-j}^C=p_{\mathrm{market},t-j}
        \end{aligned}
  \end{cases}
\end{equation}

\end{document}

Note \mathrm{market}, \mathrm{grid}, \dots and \min.

A: The following solution shortens some of the expressions by putting p^*=p_{market}. This, in turns, allows displaying the conditions for the final case in just two rows.

\documentclass{article}
\usepackage{mathtools}         % for 'dcases' env.
\newcommand\vn[1]{\mathrm{#1}} % use mathrm display variable names
\begin{document}

\noindent
Put $p^*_t=p_{\vn{market},t}$. Then
\begin{equation}
r(b_{i,t}^C,p^*_t)=
\begin{dcases}
  -(b_{i,t}^C - p^*_t)^2         & \text{if $b_{i,t}^C > p^*_t$} \\
  -(b_{i,t}^C - p_{\vn{grid}})^2 & \text{if $b_{i,t}^C < p^*_t$} \\
  p^*_t/100 + \theta             & \text{if $b_{i,t}^C = p^*_t$} \\
  p^*_t/100 + 2\theta            & \text{if $b_{i,t}^C = p^*_t$ and} \\
       & b_{i,t}^C < \min(b_{i,t-j}^C,\dots, b_{i,t-1}^C)
       \mid b_{i,t-j}^C=p^*_{t-j}
\end{dcases}
\end{equation}

\end{document}


text:
Q: Why the absence of curly brackets after FOR loop in finding factorials in C This is one of the code to find the factorial of a given non negative integer. When I use the curly brackets after FOR loop for this code, the program runs very slowly. I know that for loops can be used without curly brackets for single line of code , but my code consists of two lines within the for loop. Can someone explain the reason for this ?
#include <stdio.h>
void main()
{

  int input,i,fact=1;

  //read user input//
  printf("Enter the number :");
  scanf("%d",&input);

  for(i=1;i<=input;i++)

   fact=fact*i;
   printf("value of factorial %d is %d",input,fact);

 }

A: I have used rextester c compiler to analyze the run time of your program and I could see,
without curly brackets running time : 0.18 sec and
with curly brackets running time : 0.16 sec, which might vary time to time for approx +/- 0.05 sec. And if you are using or not using a curly brackets for the single line code in a loop which I guess should not affect the run time of the program.
You can use some other compiler and try running your code.

A: you are absolutely right when saying

for loops can be used without curly brackets for single line of code

more precisely for loop will run only one line of code if not provided with  any curly braces
so your code
for(i=1;i<=input;i++)
   fact=fact*i;

printf("value of factorial %d is %d",input,fact);

will be same as
for(i=1;i<=input;i++)
  {
   fact=fact*i;
  }

   printf("value of factorial %d is %d",input,fact);

but here you are putting braces ( {} ) around both fact=fact*i; and printf("value of factorial %d is %d",input,fact);
so just like @Some programmer dude said in comments section, in this case both of these statements will be executed on each iterations of the loop and thus will be comparatively slower than the first one. But still that should not make big of a difference in terms of total execution time.


text:
Q: Svelte / SvelteKit importing an npm library returns error when trying to work with Leaflet I'm trying to learn Svelte / SvelteKit by porting over an existing Angular application. The app should show a Leaflet map with a heatmap layer as overlay. The map part works and is robust, even when I navigate or refresh Svelte handles it fine. The heatmap on the other hand only loads when the app initializes for the first time as you can see here:

However When I refresh I get this error and the whole Map.svelte component doesn't load at all anymore with the following error message in the console:
Uncaught (in promise) TypeError: Leaflet.heatLayer is not a function

I suspect it has to do with the way the lifecycle handles imports, because in my Angular app the imports don't have to be done in a life cycle method in order for them to work, whereas the only way to get Leaflet to even render in SvelteKit I have to do an async import.
Can anyone clarify what's going on with the Leaflet.heatlayer error and how I can fix it?
Map.svelte

Things I've tried:

*

*including 'leaflet-heat.js' from node_modules in a

A: I had this same issue on refresh, you need import the module inside the on mount. It's not the same as your code. But you get that point.
    onMount(async () => {

        const leafletModule = await import('leaflet');
        L = leafletModule.default;


text:
Q: Bidirectional one-to-one association: Hibernate fetches entities twice I have two entities,Contract and Customer between which there is defined a bidirectional one-to-one relationship:
In Customer.hbm.xml:
....
<many-to-one name="contract" class="Contract" fetch="select">
    <column name="CONTRACTID" not-null="true" unique="true" />
</many-to-one>

In Contract.hbm.xml:
...
<one-to-one name="customer" class="Customer" property-ref="contract" />

When iterating over a collection Customer entities (fetched in some HQL query) and for each customer accessing a field of contract, Hibernate does two additional statements for each 'customer':

*

*Lazy fetch of contract which is OK for me as I am going to optimize the lazy fetching with batch-size attribute later on.

*Again fetching the Customer object with SELECT ... FROM Customer WHERE CONTRACTID=?
How to tell Hibernate to use the customer instance which is already present in the session?
EDIT:
If this is not possible because the Customer is fetched by CONTRACTID instead of Customer's primary key in 2.), this scenario imposes another N+1 problem, right?

A: I have decided to use the following workaround:
1) changing the one-to-one in Contract to an <set... (one-to-many) with lazy="true", access="field" and inverse="false". The property is named customers instead of customer
2) in the java class Contract I introduced the new customers property, but without new setter and getter (that's why we need the access="field".
3) changed getter of the old single value property to return the first element of the customers set, if and only if it is not null and has size=1
4) changed the old setter to initialize a new HashSet and add the only customer to it.
This way the entity API did not change and I have the illusion that it is mapped as one-to-one ;-). Nevertheless, I would appreciate another solution


text:
Q: How to protect IP-sensitive data in files generated by- and used by- users I'm working on an offline windows application that generates and loads key results as files. However, these files provide key insights into how our product works internally. To make matters worse my users will for sure be tech savvy. So if I do not encode it, we give away our magic. So given this problem, I have some questions:

*

*Is there an encryption method commonly used to make files unreadable (or at least hard to read) except for (multiple instances of) a certain application?

*How hard is it to read what assets (like private keys) are baked into a .dll file?


text:
Q: Webpack error when building Nextjs app in AWS Amplify My SSR Next 11 app fails to build in Amplify with this error:
HookWebpackError: processor is not a function
> Build error occurred
Error: > Build failed because of webpack errors
  at /codebuild/output/src527327235/src/myApp/node_modules/next/dist/build/index.js:397:19
  at async Span.traceAsyncFn (/codebuild/output/src527327235/src/myApp/node_modules/next/dist/telemetry/trace/trace.js:60:20)
  at async Object.build [as default] (/codebuild/output/src527327235/src/myApp/node_modules/next/dist/build/index.js:77:25)

It does build and run fine locally so I'm not sure where this Webpack error is coming from. What would be causing this?
amplify.yml
version: 1
frontend:
  phases:
    preBuild:
      commands:
        - yarn install
    build:
      commands:
        - yarn build
  artifacts:
    baseDirectory: .next
    files:
      - "**/*"
  cache:
    paths:
      - node_modules/**/*

I'm using yarn but also tried with npm and got the same error.
package.json
...
{
  "name": "myApp",
  "version": "0.1.1",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "export": "next build && next export"
  },
  "dependencies": {
    "@apollo/client": "3.5.9",
    "@bugsnag/js": "7.16.1",
    "@bugsnag/plugin-react": "7.16.1",
    "apollo-link-retry": "2.2.16",
    "autoprefixer": "10.4.2",
    "aws-amplify": "4.3.14",
    "aws-appsync-auth-link": "3.0.7",
    "aws-appsync-subscription-link": "3.0.9",
    "boring-avatars": "^1.6.3",
    "graphql": "16.3.0",
    "lodash.debounce": "4.0.8",
    "moment": "2.29.1",
    "next": "11.1.2",
    "postcss": "8.4.6",
    "react": "17.0.2",
    "react-cookie-consent": "7.3.1",
    "react-div-100vh": "^0.7.0",
    "react-dom": "17.0.2",
    "react-icons": "4.3.1",
    "react-player": "2.9.0",
    "react-slick": "^0.28.1",
    "slick-carousel": "^1.8.1",
    "tailwindcss": "3.0.23"
  },
  "devDependencies": {
    "babel-eslint": "10.1.0",
    "eslint": "7.32.0",
    "eslint-config-airbnb": "19.0.2",
    "eslint-config-next": "12.0.10",
    "eslint-config-prettier": "8.3.0",
    "eslint-plugin-import": "2.25.4",
    "eslint-plugin-jsx-a11y": "6.5.1",
    "eslint-plugin-react": "7.28.0",
    "eslint-plugin-react-hooks": "4.3.0"
  },
  "description": "",
  "main": "index.js",
  "repository": "",
  "author": "",
  "license": "MIT"
}

A: Updating to "next": "12.1.5" solved the issue.


text:
Q: Use SQS queueName instead of URL in case of AmazonSQS I have the following code to receive messages from SQS:
        ReceiveMessageRequest receiveMessageRequest = new
                ReceiveMessageRequest();
        receiveMessageRequest.setQueueUrl(queueUrl);
        receiveMessageRequest.setMaxNumberOfMessages(sqsBatchSize);

            ReceiveMessageResult messageResult = sqsClient.receiveMessage(receiveMessageRequest);

Is there any way I can pass the queueName instead of passing the queueURL in the ReceiveMessageRequest object?

A: Oddly, there isn't.
Well, it's not actually that odd.  Queue names are only unique at the region level within each AWS account (not globally unique in one account or across multiple accounts) and it's possible for another account to grant you permission to access their queue, so the queue name by itself is not enough information to identify which queue you intend to access.  The account number and region are also needed.  (The region wasn't originally a consideration, in the early days of SQS, since there was only one region.)
Presumably for this reason, the SQS Query API (the web service used by the SDKs) requires the Queue URL be included in the request.  It's a value that uniquely identifies a queue, because the account, region, and queue name are all embedded in it.
The queue could alternately have been identified by ARN, and this would make sense too, but it's possible that ARNs hadn't even been invented yet back when SQS was first launched over a decade ago. SQS was the first-ever AWS service, and this blog post about it, from 2006 contains a screen shot that's priceless classic old school Amazon.  The active tab at the top of the screen is hard to read but it appears to say "Make Money."


text:
Q: Android FragmentActivity inside Tabhost? I'm trying to implement an app with the following specs:
A tabhost inside a main fragmentActivity.
In each of those tabs, there is a fragment.
In tab B, I have a ListFragment. I want to be able to click on a list element and have a new fragment open in the same tab OVER the list. But I do not want this fragment to take over the entire screen; I still want to be able to switch tabs with the new fragment open. I also want to be able to close the new fragment and see the list again.
How should I go about implementing this? I tried replacing the fragment of tab B with a fragmentActivity so I could handle the transition between the fragments, but the tabhost complained.
Is there some way to launch another fragment (that takes over the current fragment's location in the activity) from tab B? I want to be able to close the new fragment and go back to the list of tab B.
Update: I figured it out! There's something called fragment backstacks.

A: Answer: use fragment backstacks! you can do it from within the fragment you want to replace!
http://developer.android.com/guide/topics/fundamentals/fragments.html


text:
Q: MYSQL View Slowed Down I have a mysql view that slowed down when the database it was interpreting became overloaded due to a programming flaw. I fixed that flaw and cleared the database back down to a very small size.
I have a database with identical tables and identical data on the same host/server. It has the same view. The query for that view finishes well under 1sec, but the query of the problem view takes 20+sec.
Is there a cache or something else that I may need to clear to fix this?

   select
        `income`.`id` AS `id`
    from
        (`clientsWithIncome`
        left join `income` ON (`income`.`client` = `clientsWithIncome`.`client`))

The above is the most simplified form of the query that gives me the problem. I can perform this on one database and get results in under one second, and then on the problem database it takes 20 seconds.
delimiter $$

CREATE TABLE `income` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `index` varchar(45) DEFAULT NULL,
  `client` varchar(45) DEFAULT NULL,
  `entity_type` varchar(45) DEFAULT NULL,
  `date_received` varchar(45) DEFAULT NULL,
  `preparer` varchar(45) DEFAULT NULL,
  `date_began` varchar(45) DEFAULT NULL,
  `date_prepared` varchar(45) DEFAULT NULL,
  `date_assembled` varchar(45) DEFAULT NULL,
  `date_signed` varchar(45) DEFAULT NULL,
  `date_fed` varchar(45) DEFAULT NULL,
  `date_state` varchar(45) DEFAULT NULL,
  `notes` text,
  `status` varchar(45) DEFAULT NULL,
  `year` varchar(45) DEFAULT NULL,
  `highlight` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=93442 DEFAULT CHARSET=latin1$$

And the VIEWs:
delimiter $$

CREATE ALGORITHM=UNDEFINED DEFINER=`xxxxxxxxxxx`@`localhost`
            SQL SECURITY DEFINER VIEW `clientsWithIncome` AS
  select  `income`.`client` AS `client`
    from  `income`
    where  (`income`.`year` = (year((curdate() + interval 1 month)) - 1))
    union
  select  `contacts`.`client` AS `client`
    from  `contacts`
    where  (`contacts`.`tax_returns` = 1)$$

delimiter $$

CREATE ALGORITHM=UNDEFINED DEFINER=`xxxxxxxxxxxx`@`localhost`
          SQL SECURITY DEFINER VIEW `currentIncome` AS
 select  `income`.`id` AS `id`,
       `income`.`index` AS `index`,
       `clientsWithIncome`.`client` AS `client`,
       `income`.`entity_type` AS `entity_type`,
       `income`.`date_received` AS `date_received`,
       `income`.`preparer` AS `preparer`,
       `income`.`date_began` AS `date_began`,
       `income`.`date_prepared` AS `date_prepared`,
       `income`.`date_assembled` AS `date_assembled`,
       `income`.`date_signed` AS `date_signed`,`income`.`date_fed` AS `date_fed`,
       `income`.`date_state` AS `date_state`,`income`.`notes` AS `notes`,
       `income`.`status` AS `status`,`income`.`year` AS `year`,
       `income`.`highlight` AS `highlight`
    from  (`clientsWithIncome`
            left join  `income`
                 on(((`income`.`client` = `clientsWithIncome`.`client`)
                and  (`income`.`year` = (year((curdate() + interval 1 month)) - 1))))
          )$$

A: My answer turned out to be what I thought it was. Some sort of caching.
I performed the following from PHPmyAdmin:
Check table
Repair table
Optimize table
Flush table
Now the queries are performing wonderfully.

A:
year varchar(45) DEFAULT NULL,

There is a YEAR datatype; use it.
Add INDEX(year)
Add INDEX(client)
Add INDEX(tax_returns)
If those suggestions don't help enough, come back with...
Please provide SHOW CREATE TABLE for the other table.
Please provide EXPLAIN SELECT ...
Use NOT NULL on columns that you will always set.


text:
Q: How to fix One or more indexers are invalid. Make sure your Magento cron job is running? I am new to magento platform and I have installed magento on a shared linux server and when I logged into my admin panel I saw this message and I don't know how to set cron jobs on my linux server.

A: You using terminal and enter command bin/magento indexer:reindex.
This command create new index of magento in your database.
You can read more about setup cron job in Magento2 at  http://devdocs.magento.com/guides/v2.0/config-guide/cli/config-cli-subcommands-cron.html

A: To work with XAMPP installed on Windows,
First redirect to PHP folder in XAMPP by :
cd C:\xampp\php

Then enter following command :
php C:\xampp\htdocs\magento2\bin\magento indexer:reindex

This will help you to remove the error.

A: when you use wamp in windows7 for magento, you can open the cmd run as administrator and type code below to fix that warning.
C:\wamp\bin\php\php7.0.4>php C:\wamp\www\magento2\bin\magento indexer:reindex

Note: Here, magento2 is project name

A: C:\xampp\php>php C:\xampp\htdocs\magento2\bin\magento indexer:reindex
run this command ... (magento2 is project name)


text:
Q: A doubt about the parts of the spectrum of tensor products Let $\mathcal{H}$ be any complex Hilbert space of infinite dimensional. By an operator $T$ I mean a linear bounded transformation from $\mathcal{H}$ into $\mathcal{H}$, i.e, $T:\mathcal{H}\rightarrow\mathcal{H}$ is a linear transformation, such that $\left\|Tx\right\|\leq \beta \left\|x\right\|$, for some $\beta\geq 0 $ in $\mathbb{C}$. The sets $\mathcal{N}(T)$ and $\mathcal{R}(T)$ denote the kernel and the range of $T$. Also, $\mathcal{B}[\mathcal{H}]$ is the set the of all operators defined in $\mathcal{H}$.
The spectrum of $T$ is the set $\sigma(T) = (\lambda \in\mathbb{C}: \mathcal{N}(\lambda I - T)\neq 0 $ or $\mathcal{R}(\lambda I - T)\neq \mathcal{H} )$, where $I\in\mathcal{B}[\mathcal{H}]$ is the identity operator (i.e., the spectrum of $T$ is the set of all $\lambda$ such that $(\lambda I - T)$ fail to have a bounded inverse on $\mathcal{R}(\lambda I - T)=\mathcal{H}$). A classical partition of the spectrum is:
i. Point Spectrum: $\sigma_{P}(T) = (\lambda \in \mathbb{C}: \mathcal{N}(\lambda I - T) \neq 0)$.
ii. Continuous Spectrum: $\sigma_{C}(T) = (\lambda \in\mathbb{C}: \mathcal{N}(\lambda I - T)= 0 , \mathcal{R}(\lambda I - T)^{-}=\mathcal{H}$ and $\mathcal{R}(\lambda I - T)\neq \mathcal{H} )$, where $\mathcal{R}(.)^{-}$ denotes the closure of $\mathcal{R}(.)$.
iii. Residual Spectrum: $\sigma_{R}(T) = (\lambda \in\mathbb{C}: \mathcal{N}(\lambda I - T)= 0 $ and $ \mathcal{R}(\lambda I - T)^{-}=\mathcal{H})$.
Let $\otimes$ denote the tensor product. Consider $T=(A\otimes B)\in\mathcal{B}[\mathcal{H}\otimes\mathcal{H}]$, where $A\in\mathcal{B}[\mathcal{H}]$ and $B\in\mathcal{B}[\mathcal{H}]$. It is well known that $\sigma(T) = \sigma(A\otimes B) = \sigma(A)\sigma(B)$. My questions are:
a. $\sigma_{C}(T) = \sigma_{C}(A)\otimes \sigma_{C}(B)$ ?
b. $\sigma_{R}(T) = \sigma_{R}(A)\otimes \sigma_{R}(B)$ ?
Thank you very much for your attention.

A: Let me first show that there are problems with various parts of the spectrum here, hence your concerns are well-grounded.
The first is, citing Ichinose in the Transactions from 1978 here and here, that
$$\sigma_{ess}(A\otimes B) = \sigma_{ess}(A)\sigma(B)\cup\sigma(A)\sigma_{ess}(B)$$
showing that equalities like your a. and b. may not always be true.
Further, here is an example of Ichinose showing a funny fact: Let $H=l^2$, $Ae_n=-e_{n-1}$ be the negated left-shift $(Ae_1=0)$. Let $\tau_n\to 0$, $\max |\tau_n|<1$ and define $Be_n:=\tau_n e_{n+1}$.
Then the point spectrum of $B$ is empty, the point spectrum of $A$ is the open circle $|\lambda|<1$. There will be however many elements in the kernel of $(A+I)\otimes(B+I)$: in fact, for every $y\in H$,
$$\sum_{n=1}^{\infty}e_n\otimes B^{n-1}y$$
belongs to the kernel of this operator.
Hence, the point spectrum of the tensor product cannot be recovered from the point spectra of the original operators. Since the residual spectrum is the (conjugate of) the point spectrum of the adjoint, it follows that your claim b. cannot hold, i.e., in general
$$\sigma_R(A\otimes B) \neq \sigma_R(A)\cdot\sigma_R(B),$$
or even
$$\sigma_R(A\otimes B) \neq \sigma_R(A)\cdot\sigma(B)\cup\sigma(A)\cdot\sigma_R(B).$$


text:
Q: Having Wirless adapter problems in BackTrack 5 R3 I am trying to get a wireless connection on BackTrack 5 R3, but as soon as I boot up the BackTrack VM, the light on the adapter turns off.  Drivers are installed and the VM detects the USB device. I am using an Asus N-13 wireless adapter to connect. It works fine on Ubuntu 12.10 (my host), and Windows 7. However, when I boot the BackTrack VM the adapter light goes off. Here is proof of drivers and USB detection.
lsusb
Bus 002 Device 002: ID 80ee:0021 VirtualBox USB Tablet
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 0b05:17ab ASUSTek Computer, Inc.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root h

ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:9c:d5:dc
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe9c:d5dc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:758 errors:0 dropped:0 overruns:0 frame:0
          TX packets:609 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:381917 (381.9 KB)  TX bytes:159317 (159.3 KB)
          Interrupt:10 Base address:0xd020

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:853 errors:0 dropped:0 overruns:0 frame:0
          TX packets:853 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:299027 (299.0 KB)  TX bytes:299027 (299.0 KB)

wlan0     Link encap:Ethernet  HWaddr 08:60:6e:cd:f8:2c
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lsmod
Module                  Size  Used by
nls_utf8               12493  1
isofs                  39187  1
vboxvideo              12511  1
drm                   183453  2 vboxvideo
vboxsf                 38096  0
dm_crypt               22236  0
snd_intel8x0           33017  0
8192cu                503302  0
snd_ac97_codec        104623  1 snd_intel8x0
ac97_bus               12602  1 snd_ac97_codec
snd_pcm                72878  2 snd_intel8x0,snd_ac97_codec
snd_seq_midi           13132  0
i2c_piix4              12983  0
snd_rawmidi            24215  1 snd_seq_midi
snd_seq_midi_event     14076  1 snd_seq_midi
snd_seq                50403  2 snd_seq_midi,snd_seq_midi_event
snd_timer              23911  2 snd_pcm,snd_seq
snd_seq_device         13817  3 snd_seq_midi,snd_rawmidi,snd_seq
ppdev                  12840  0
snd                    52787  7 snd_intel8x0,snd_ac97_codec,snd_pcm,snd_rawmidi,snd_seq,snd_timer,snd_seq_device
psmouse                72465  0
serio_raw              13027  0
joydev                 17161  0
lp                     13321  0
parport_pc             31867  0
soundcore              12534  1 snd
snd_page_alloc         13709  2 snd_intel8x0,snd_pcm
vboxguest             190596  5 vboxsf
mac_hid                13037  0
parport                34960  3 ppdev,lp,parport_pc
dm_mirror              21585  0
dm_region_hash         15035  1 dm_mirror
dm_log                 17871  2 dm_mirror,dm_region_hash
aufs                  162169  0
usbhid                 41119  0
hid                    79842  1 usbhid
pcnet32                40553  0

iwconfig
lo        no wireless extensions.

wlan0     unassociated  Nickname:"<WIFI@REALTEK>"
          Mode:Auto  Frequency=2.412 GHz  Access Point: Not-Associated
          Sensitivity:0/0
          Retry:off   RTS thr:off   Fragment thr:off
          Encryption key:off
          Power Management:off
          Link Quality:0  Signal level:0  Noise level:0
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:0   Missed beacon:0

eth0      no wireless extensions.

A: Try to connect with wireless using wicd it will help you.
to open it type this at terminal wicd &
or application --> internet -->wicd


text:
Q: Why is typecasting not supported for boolean in Java Why is boolean typecasting not supported in Java?
Why can't I perform something like this:
    int i = 1;
    boolean b = (boolean)i;

Similarly for other primitive datatypes like long,double etc.

A: Because boolean is not numeric type, while the int, char, byte, etc. - are.