text:
Q: Magento 1.9 Adminhtml Form Block not visible This question is asked for many times, but none of the solution worked for me. I tried referring core modules to correct the errors in my config files, but it helped me little. Following are the code snippets:
config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Package_OriginalPricing>
            <version>1.0.1</version>
        </Package_OriginalPricing>
    </modules>

    <global>

        <helpers>
            <originalpricing>
                <class>Package_OriginalPricing_Helper</class>
            </originalpricing>
        </helpers>

        <blocks>
            <originalpricing>
                <class>Package_OriginalPricing_Block</class>
            </originalpricing>
        </blocks>

        <models>

            <originalpricing>
                <class>Package_OriginalPricing_Model</class>
                <resourceModel>originalpricing_resource</resourceModel>
            </originalpricing>

            <originalpricing_resource>

                <class>Package_OriginalPricing_Model_Resource</class>

                <entities>
                    <csvprice>

originalpricing_csvprice

                    </csvprice>
                </entities>

            </originalpricing_resource>

        </models>

        <resources>

            <originalpricing_setup>
                <setup>
                    <module>Package_OriginalPricing</module>
                </setup>
            </originalpricing_setup>

            <originalpricing_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </originalpricing_write>

            <originalpricing_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </originalpricing_read>

        </resources>

    </global>

    <admin>

        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <originalpricing before="Mage_Adminhtml">Package_OriginalPricing_Adminhtml</originalpricing>
                    </modules>
                </args>
            </adminhtml>
        </routers>

    </admin>

    <adminhtml>

        <layout>
            <updates>
                <originalpricing>
                    <file>originalpricing.xml</file>
                </originalpricing>
            </updates>
        </layout>

        <menu>
            <catalog>
                <children>

                    <originalpricing module="originalpricing" translate="title">

                        <title>Original Price CSV</title>
                        <sort_order>10</sort_order>

                        <children>
                            <index translate="title">
                                <title>Upload CSV</title>
                                <sort_order>1</sort_order>
                                <action>adminhtml/originalpricing</action>
                            </index>

                            <removeproducts translate="title">
                                <title>Remove CSV</title>
                                <sort_order>2</sort_order>
                                <action>adminhtml/originalpricing/removeproducts</action>
                            </removeproducts>
                        </children>

                    </originalpricing>

                </children>
            </catalog>
        </menu>

    </adminhtml>

</config>

originalpricing.xml
<?xml version='1.0'?>

<layout version="0.1.0">

    <adminhtml_originalpricing_index>
        <reference name="content">
            <block type="originalpricing/adminhtml_originalpricing_assign" name="orig_assign_products" />
        </reference>
    </adminhtml_originalpricing_index>

</layout>

Controller
class Package_OriginalPricing_Adminhtml_OriginalpricingController extends Mage_Adminhtml_Controller_Action
{

    public function indexAction ()
    {
        $this->_title($this->__('Catalog'))->_title($this->__('Upload CSV'));
        $this->loadLayout();
        $this->_setActiveMenu('catalog/catalog');
        $this->renderLayout();
    }

}

Block Assign
class Package_OriginalPricing_Block_Adminhtml_Originalpricing_Assign extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();

        $helper = Mage::helper('originalpricing');

        $this->_objectId = 'id';
        $this->_blockGroup = 'originalpricing';
        $this->_controller = 'adminhtml_originalpricing';
        $this->_mode = 'assign';
        $this->_headerText = $helper->__('Upload CSV');

        $this->_updateButton('save', 'label', $helper->__('Upload & Save'));

        $this->_removeButton('back');
    }
}

Form
class Package_OriginalPricing_Block_Adminhtml_Originalpricing_Assign_Form extends Mage_Adminhtml_Block_Widget_Form
{

    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(array(
                'id' => 'edit_form',
                'action' => $this->getUrl('*/*/assign'),
                'method' => 'post',
                'enctype' => 'multipart/form-data'
            )
        );

        $helper = Mage::helper('originalpricing');

        $form->setUseContainer(true);

        $this->setForm($form);

        $fieldset = $form->addFieldset('assign_form', array(
            'legend' =>$helper->__('Upload CSV for Products')
        ));

        $fieldset->addField('sku_list', 'textarea', array(
            'label'     => $helper->__('SKU(s)'),
            'class'     => 'required-entry',
            'required'  => true,
            'name'      => 'sku_list',
            'note'     => $helper->__('Enter Product SKU separated by (,) comma'),
        ));

        $fieldset->addField('csv_file', 'file', array(
            'label'     => $helper->__('CSV File'),
            'class'     => 'required-entry',
            'required'  => true,
            'name'      => 'csv_file',
            'note'     => $helper->__('Choose a .csv file to be uploaded'),
        ));

        return parent::_prepareForm();
    }

}

Everything is working fine on my local but not on live server.

A: I am posting answer to my question after two days of frustration and useless changes... The problem was not in my code but the the site had Compilation enabled from System >> Tools >> Compilation so I recompiled magento and suddenly all started to work. This was working on my local just because of the same reason that my local donot have Compilation enabled


text:
Q: Return different views same controller in ASP.NET MVC I want to send the user to one of two different pages depending on the value of isCustomerEligible. When the value of that variable is set to false, it does call Index but then returns the view for Customer and not the view for Index.
public ViewResult Index()
{
    return View();
}

public ViewResult Customer()
{
    DetermineCustomerCode();
    DetermineIfCustomerIsEligible();
    return isCustomerEligible ? View() : Index();
}

A: All you need to do is to return the View that you require.
If you want to return a View that has the same name as the action you are in you just use return View();
If you wish to return a View different from the action method you are in then you specify the name of the view like this return View("Index");
 public ViewResult Index()
    {
       return View();
    }

    public ViewResult Customer()
    {
        DetermineCustomerCode();
        DetermineIfCustomerIsEligible();
        return isCustomerEligible ? View() : View("Index");
    }

A: If you just return View() it will look for a view with the same name as your action.  If you want to specify the view you return you have to put the name of the view as a parameter.
public ViewResult Customer()
{
    DetermineCustomerCode();
    DetermineIfCustomerIsEligible();
    return isCustomerEligible ? View() : View("Index");
}

If you want to actually make the Index event fire and not just return its view you have to return a RedirectToAction() and also change the return type to ActionResult
public ActionResult Customer()
{
    DetermineCustomerCode();
    DetermineIfCustomerIsEligible();
    return isCustomerEligible ? View() : RedirectToAction("Index");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove swipeable gesture in NavigationTabBar I have used this library to add Instagram like layout but I would like to remove the swipe able gesture in the tabs and switch tabs only when the tab is clicked. I am unable to find anything in the functions.
public class TabsActivity extends android.support.v4.app.FragmentActivity {

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);
    initUI();
    }

    private void initUI() {
    if (getIntent().getBooleanExtra("LOGOUT", false)) {
        finish();
    }
    List<Fragment> fragments = new ArrayList<>();
    TabsActivityAdapter dashPagerAdapter = new TabsActivityAdapter(getSupportFragmentManager(), fragments);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.vp_horizontal_ntb);
    viewPager.setAdapter(dashPagerAdapter);
    viewPager.setOffscreenPageLimit(2);

    viewPager.getAdapter().notifyDataSetChanged();
    final String[] colors = getResources().getStringArray(R.array.tabcolors);

    final NavigationTabBar navigationTabBar = (NavigationTabBar) findViewById(R.id.ntb_horizontal);

    final ArrayList<NavigationTabBar.Model> models = new ArrayList<>();
    models.add(
            new NavigationTabBar.Model.Builder(

                    getResources().getDrawable(R.drawable.home),
                    Color.parseColor(colors[0]))
                    .selectedIcon(getResources().getDrawable(R.drawable.home))
                    .title("Home")
                    .badgeTitle("NTB")
                    .build()
    );

    models.add(
            new NavigationTabBar.Model.Builder(
                    getResources().getDrawable(R.drawable.group),
                    Color.parseColor(colors[1]))
                    .selectedIcon(getResources().getDrawable(R.drawable.group))
                    .title("Groups")
                    .badgeTitle("with")
                    .build()
    );
    models.add(
            new NavigationTabBar.Model.Builder(
                    getResources().getDrawable(R.drawable.profile),
                    Color.parseColor(colors[3]))
                    .selectedIcon(getResources().getDrawable(R.drawable.profile))
                    .title("Profile")
                    .badgeTitle("icon")
                    .build()
    );
    navigationTabBar.setBgColor(Color.parseColor("#424242"));
    navigationTabBar.setActiveColor(Color.parseColor("#ffffff"));
    navigationTabBar.setInactiveColor(Color.parseColor("#9E9E9E"));
    navigationTabBar.setModels(models);
    navigationTabBar.setViewPager(viewPager, 0);
    navigationTabBar.setAnimationDuration(0);
    navigationTabBar.setIsSwiped(false);
    navigationTabBar.setBehaviorEnabled(false);

    navigationTabBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(final int position) {
            navigationTabBar.getModels().get(position).hideBadge();

        }

        @Override
        public void onPageScrollStateChanged(final int state) {

        }
    });

    }
}

activity_tabs.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">

<android.support.v4.view.ViewPager
    android:id="@+id/vp_horizontal_ntb"
    android:layout_width="match_parent"
    android:layout_height="0dp"

    android:layout_weight="1"/>

<devlight.io.library.ntb.NavigationTabBar
    android:id="@+id/ntb_horizontal"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    app:ntb_badge_gravity="top"

    app:ntb_badge_position="right"
    app:ntb_badged="true"
    app:ntb_scaled="true"
    app:ntb_tinted="true"
    android:isScrollContainer="true"
    app:ntb_active_color="#3d3939"
    app:ntb_title_mode="all"
    app:ntb_titled="true"
    app:ntb_swiped="false"/>
</LinearLayout>

If anyone could suggest an alternative library if this doesn't work. Any help would be appreciated.

A: Try setting navigationTabBar.setIsSwiped(false); in code or from xml
<devlight.io.library.ntb.NavigationTabBar
android:id="@+id/ntb"
android:layout_width="match_parent"
android:layout_height="50dp"
app:ntb_swiped="false"
...../>


text:
Q: Terraform helm_release destroys all other helm releases We have three services that we are trying to deploy to a k8s cluster with Terraform helm_release. Each service has something similar to
release.tf
resource "helm_release" "someService" {
  count = var.deploy_apps ? 1 : 0
  name = "someService"
  version = "2.1.3"
  namespace = "app"
  timeout = 600
  values = [yamlencode({
    image = {
      tag = var.terraform_version
    }

    envVars = {
      k8env = local.environment
    }
  })]
}

variables.tf
variable "deploy_apps" {
  type = bool
  default = true
  description = "deploy someService"
}

With the only difference being the service name. Each service is in its own Git repo, each repo has its own variables.tf file which contains its own deploy_apps variable, and they are all deployed to the same namespace.
When any of the services is deployed, it destroys the other two.
How can we prevent that from happening?


text:
Q: intersection of decreasing compact sets is again compact I am following a real analysis course and I would like to discuss some definitions and results about metric spaces.
First of all, the definition of compact set. I the course we defined it as follows:
A subset $A$ of a metric space $(X,d)$ is called compact if for every open cover of $A$ there exist a finite sub-cover.
Why such a definition ? It doesn't seem natural to me.
The next question is about an exercise. Let $(X,d)$ be a metric space and consider a decreasing sequence of compact subsets $X \supset A_0 \supset A_1 \supset ...$, then show that ${\bigcap}_{i=0}^{\infty} A_i$ is again compact.
Is it sufficient to show that ${\bigcap}_{i=0}^{\infty} A_i$ is bounded and closed ? If yes, then ${\bigcap}_{i=0}^{\infty} A_i$ is closed because any intersection of closed sets is again closed and ${\bigcap}_{i=0}^{\infty} A_i$ is bounded because it is contained in $A_0$. But if this is true I didn't use the decreasing hypothesis. Where am I wrong ?
Thank you for your help and comments.

A:
Is it sufficient to show that ${\bigcap}_{i=0}^{\infty} A_i$ is bounded and closed ?

No, this is not sufficient. There exist sets which are bounded and closed, yet they are not compact. For example, the set $(0,1)$ is abounded closed subset of the space $(0,1)$, yet the set is not compact.
There are two ways I see that you can solve the question:
Option 1:
There is a theorem that states that a closed subset of a compact set is compact. This means all you need to prove is that the intersection in question is closed, and since it is a subset of $A_1$, a compact set, you are done.
Option 2:
If you cannot yet use the above theorem (this is probably the case, since otherwise, the problem is way too easy), you can just go from definitions. That is, start with an open cover for ${\bigcap}_{i=0}^{\infty} A_i$, and try to find some finite subcover. In order to do that, think about this fact:
Any open cover of ${\bigcap}_{i=0}^{\infty} A_i$, along with the set $X\setminus {\bigcap}_{i=0}^{\infty} A_i$, is an open cover of $A_1$...


text:
Q: Drools 6.4.0 rule inheritance - multiple rules extends one parent I am trying to package multiple drl files each one has multiple rules extending same parent rule BaseRule.
Getting NullPointerException while calling
kbuilder.add(ResourceFactory.newFileResource(file), ResourceType.DRL);

Looks like the logic used below is not correct in KnowledgeBuilderImpl - sortRulesByDependency()
    for (RuleDescr ruleDescr : packageDescr.getRules()) {
        if (ruleDescr.isQuery()) {
            queries.add(ruleDescr);
        } else if (!ruleDescr.hasParent()) {
            roots.add(ruleDescr);
        } else {
            if (pkg.getRule(ruleDescr.getParentName()) != null) {
                // The parent of this rule has been already compiled
                compiledRules.add(ruleDescr.getParentName());
            }
            List<RuleDescr> childz = children.get(ruleDescr.getParentName());
            if (childz == null) {
                childz = new ArrayList<RuleDescr>();
                children.put(ruleDescr.getParentName(), childz);
            }
            childz.add(ruleDescr);
        }
    }

    for (String compiledRule : compiledRules) {
        List<RuleDescr> childz = children.remove( compiledRule );
        roots.addAll( childz );
    }

compiledRules list contains BaseRule name multiple times because more than one rule extending BaseRule.
After first time remove, next time it is going to return NULL and that will cause NullPointerException in roots.addAll
Any idea why there is no check to avoid this case?


text:
Q: Error while connecting to databse - nodejs and mongodb I am a biginner to nodejs and mongodb. I encountered the following error while trying to connect to database:
(node:10124) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool. (E:\node js workspace\URL-Shortner\server\node_modules\mongodb-core\lib\topologies\server.js:562:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection. (E:\node js workspace\URL-Shortner\server\node_modules\mongodb-core\lib\connection\pool.js:316:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket. (E:\node js workspace\URL-Shortner\server\node_modules\mongodb-core\lib\connection\connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
(node:10124) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10124) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
i am trying to build a url shortner. This is the code.
index.js-
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const mongoURI = "mongodb://localhost/url-shortner";
const connectOptions={
keepAlive: true,
reconnectTries: Number.MAX_VALUE
};
mongoose.connect(mongoURI,connectOptions,(err,db)=>{
if(err) console.log('Error',err);
console.log('Connected to MongoDB');
});
const app = express();
require("./models/UrlShorten");
app.use(bodyParser.json());
require("./routes/urlshorten")(app);
const PORT = 7000;
//Start server on Port 7000
  app.listen(PORT, () => {
console.log(`Server started on port`, PORT);
});

urlshorten.js-
const mongoose = require("mongoose");
const validUrl = require("valid-url");
const UrlShorten = mongoose.model("UrlShorten");
const shortid = require("shortid");
const errorUrl='http://localhost/error';
module.exports = app => {
app.get("/api/item/:code", async (req, res) => {
const urlCode = req.params.code;
const item = await UrlShorten.findOne({ urlCode: urlCode });
if (item) {
  return res.redirect(item.originalUrl);
 } else {
   return res.redirect(errorUrl);
 }
});
 app.post("/api/item", async (req, res) => {
 const { originalUrl, shortBaseUrl } = req.body;
 if (validUrl.isUri(shortBaseUrl)) {
 } else {
   return res
     .status(401)
     .json(
       "Invalid Base Url"
     );
 }
 const urlCode = shortid.generate();
 const updatedAt = new Date();
 if (validUrl.isUri(originalUrl)) {
   try {
     const item = await UrlShorten.findOne({ originalUrl: originalUrl });
     if (item) {
       res.status(200).json(item);
     } else {
       shortUrl = shortBaseUrl + "/" + urlCode;
      // console.log("Shorturl: "+shortUrl);
        const item = new UrlShorten({
         originalUrl,
         shortUrl,
         urlCode,
         updatedAt
       });
       await item.save();
       res.status(200).json(item);
     }
    } catch (err) {
    res.status(401).json("Invalid User Id");
   }
  } else {
   return res
     .status(401)
     .json(
       "Invalid Original Url"
     );
 }
});
};

This is the schema:
Schema({
originalUrl: String,
urlCode: String,
shortUrl: String,
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }

});
Thank you.

A: You haven't start your mongodb service,
Start it with command: sudo mongod and then try to start your server.


text:
Q: twig form_widget value variable doesn't work {{ form_widget(form.category,{value:"3"}) }} //works!!
{{ form_widget(form.category,{value:'3'}) }} //works!!
{{ form_widget(form.category,{value:3}) }} // doesn't work !!

{{lastCatId}} // echos 3 !!!

{{ form_widget(form.category,{value:"lastCatId"}) }} //doesn't work ???
{{ form_widget(form.category,{value:'lastCatId'}) }} //doesn't work ???

I know after symfony 2.3. Value has to be quoted or double quoted. But I don't know why the variable doesnt work

A: never mind. I found the problem
{{ form_widget(form.category,{'value' : lastCatId|number_format }) }}
I had to cast it to int.


text:
Q: Nested loop results in table, Python I need to loop a computation over two lists of elements and save the results in a table. So, say that
months = [1,2,3,4,5]
Region = ['Region1', 'Region2']

and that my code is of the type
df=[]
for month in month:
    for region in Region:
        code
        x = result
        df.append(x)

What I cannot achieve is rendering the final result in a table in which the rows are regions and coumns are months
                 1            2          3          4          5

    Region1      a            b          c          d          e

    Region2      f            g          h          i          j

A: Assuming that there is the right numbers of items in result
result = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
months = [1, 2, 3, 4, 5]
Region = ['Region1', 'Region2']
df = pd.DataFrame([[Region[i]] + result[i*len(months): ((i+1)*len(months))] for i in range(len(Region))], columns=["Region"] + months).set_index("Region")

Output
         1  2  3  4  5
Region
Region1  a  b  c  d  e
Region2  f  g  h  i  j

This part
[[Region[i]] + result[i*len(months): ((i+1)*len(months))] for i in range(len(Region))]

is equivalent to something like this
res = []
for i in range(len(Region)):
    row = [Region[i]] + result[i*len(months): ((i+1)*len(months))]
    res.append(row)

where I use the length of Region to slice result in equals part for each row. And I add the name of the region at the begging of the row.

A: Another solution - more lines of code:
import pandas as pd
import ast
months = [1,2,3,4,5]
Regions = ['Region1', 'Region2']

df = pd.DataFrame()
for region in Regions:
    row = '{\'Region\': \'' +  region +'\', '
    for month in months:
        # put your calculation code
        x = month + 1
        row = row + '\'' + str(month) + '\':[' + str(x) + '],'
    row = row[:len(row)-1] + '}'
    row = ast.literal_eval(row)
    df = df.append(pd.DataFrame(row))
df

A: This might work, depending on what and how y want the results.
import pandas as pd
months = [1, 2, 3, 4, 5]
Region = ['Region1', 'Region2']

df = pd.DataFrame(columns=[1, 2, 3])  # just to put in something
value = 59
for r in Region:
    value += 5
    for m in months:
        df.loc[r, m] = chr(m+value)


text:
Q: Display collaboration with biblatex I would like to display the "collaboration" field of biblatex when present, for example:
@article{Aad2011150,
title = "TITLE",
author= {Aad, Georges and others},
collaboration = {ATLAS}
...
}

is shown as "G. Aad and others, TITLE, ...". I would like to have "G. Add and others (ATLAS collaboration), TITLE ..."
For other cases when the author is not present I would like to have: "ATLAS collaboration, TITLE ..."
is it possible? I'm using
\usepackage[backend=bibtex, style=numeric-comp,backref, sorting=none, firstinits=true]{biblatex}

I cannot use biber.

A: Since you can't use biber, no new fields such as collaboration can be introduced. For your entry example it seems that the group of physicists working on ATLAS actually go by the name "ATLAS collaboration". When they publish under this institutional name, wrap it in braces in the author list:
author = {{ATLAS collaboration}},

For articles where members of the group publish under their individual names, you can identify them as part of the ATLAS collaboration using the existing authortype field:
authortype = {ATLAS collaboration},

Here's an example.
\documentclass{article}
\usepackage[backend=bibtex,maxnames=1]{biblatex}

\DefineBibliographyStrings{english}{%
  andothers = {and others}}

% adapted from biblatex.def
\renewbibmacro*{author}{%
  \ifboolexpr{ test {\ifuseauthor} and not test {\ifnameundef{author}} }
    {\printnames{author}%
     \iffieldundef{authortype}
       {}
       {\setunit{\addspace}%
        \usebibmacro{authorstrg}}}
    {}}

\DeclareFieldFormat{authortype}{\mkbibparens{#1}}

\begin{filecontents}{\jobname.bib}
@article{key1,
  author = {Aad, Georges and Brown, Bob and Doe, John},
  authortype = {ATLAS collaboration},
  title = {Authors from institution},
  journal = {Journal name},
  year = {1994}}
@book{key2,
  author = {{ATLAS collaboration}},
  title = {Institutional author},
  year = {1980}}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\textcite{key1} showed that... \textcite{key2} showed that...
\printbibliography
\end{document}

A: arXiv has provided some bibliography style files that accommodate e-print fields and collaboration fields: https://arxiv.org/help/hypertex/bibstyles/


text:
Q: How to make a for loop to go through two arrays in MATLAB I want to make a for loop that goes from 0 to 180, and then back again to -180. I tried the following:
for a=0:1:180 && 179:-1:-180

but this is not possible in MATLAB.
I have tried to use the && and || statements, but both don't work. I don't know any other ways to combine the two arrays. Any ideas?

A: You misunderstand the && and || operators. What you want is the following:

Go from 0 to 180 in steps of 1 AND then go from 180 to -180 in steps of -1.

However for any two statements A and B (both A and B need to be scalar values!), the command A && B does the following:

Return True, if both A and B are True, return False otherwise.

This is a logical AND, while you want to go through your first array AND through your second array after that. Though both is some kind of AND, you can't use && for your purpose.
Now, when you call for a=0:180, MATLAB does the following:

*

*Create the vector 0:180, that is [0, 1, 2, ..., 180].

*Run all the content inside the loop for each element in the vector created in 1).

So, what you want to do is create an array that contains the numbers [0, 1, 2, ..., 179, 180, 179, 178, ..., -179, -180]. You can do that by concatenating the arrays [0:180] and [179:-1:-180]. You should read about concatenation in MATLAB in their documentation. So, long story short, you for loop should be
for a=[0:180, 179:-1:-180]


text:
Q: Manejo de errores en Angular con inject Hace poco pregunté cómo obtener los errores js en Angular 1.6 pero ahora estoy teniendo un problema al intentar inyectar $http al factory. Me tira el siguiente error:
Circular dependency found: $rootScope <- $http <- $exceptionHandler <- $rootScope <- $route

Y esto fue lo que estuve realizando hasta ahora:
var app = angular.module("app", []);
app
  .controller("ctrl", function($scope) {
    // controller
  })
  .factory('$exceptionHandler', ['$log', '$http', function($log, $http) {
    return function myExceptionHandler(exception, cause) {
      $log.warn(exception, cause);
      // muestro sólo esto y ya tira error
      console.log($http);
    }
  }]);

A: en vez de inyectar $http directamente dentro del interceptor, intento inyectar desde el $injector y usarlo directamente para obtener $http.
var app = angular.module("app", []);
app.factory('$exceptionHandler', ['$log', '$injector', function($log, $injector) {
    return function myExceptionHandler(exception, cause) {
        var $http = $injector.get('$http');
        $log.warn(exception, cause);
        // muestro sólo esto y ya tira error
        console.log($http);
    }
}]);


text:
Q: Why the result of this code is the same when the arg is different? Feel free to make this post as a duplicate if there's already an answer for it because I haven't found the answer.
Here's the code (first code):
#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int val;
} yay;

yay* New (int val)
{
    yay *Node=(yay*) malloc (sizeof (yay));
    Node->val=val;

    return Node;
}

void chg (yay *lol) {lol->val=9;}

int main ()
{
    yay *boi=New (5);
    printf ("%d\n", boi->val);
    chg (boi);
    printf ("%d\n", boi->val);

    return 0;
}

The result of the code above is:
5
9

And my question is, why it isn't
5
5

?
I mean, from what I know, to change val of boi requires void chg (yay **lol) and chg (&boi); in main (), not void chg (yay *lol). I don't understand much of pointer apparently.
What's the difference with this one (second code)?
...
void chg (yay **lol) {(*lol)->val=9;}

int main ()
{
    yay *boi=New (5);
    printf ("%d\n", boi->val);
    chg (&boi);
    printf ("%d\n", boi->val);

    return 0;
}

A: Boi points to memory location(eg. 0x1233) in heap which has val 5.. u pass the same memory location (0x1233) in chg function and modify the value of same heap location to 9.. thats why u see the boi->val is 9..


text:
Q: jQuery find() Question: What will return eg: $('#MyForm').find('.classA .classB') if an element has both classes? I want to find all elements in a form with one or more classes assigned to them.
eg: something like:
var formElements = $('#MyForm').find('.classA .classB')

if some elements have classA assigned and some elements have classB assigned, will an element having both be returned more than once?

A: No; selectors either do or don't match a given element.  The retrieval mechanism doesn't go out multiple times and build multiple lists.
Besides, you're not specifying "all classA and classB elements", you're specifying "classB elements within classA elements".  What you're implying would look like:
var formElements = $('#MyForm').find('.classA, .classB')

A: No.
In general, jQuery will never give you the same element more than once.


text:
Q: Is the definition of gap of a Hamiltonian, i.e. difference between two distinct eigenvalues, restrictive? The spectral gap of a quantum model or a Hamiltonian, in the context of whether it is a gapped or gapless model, is often defined as the difference between the two lowest distinct eigenvalues of the Hamiltonian in the thermodynamic limit. (1) Is this definition restrictive in the sense that it excludes the case below?
Consider a Hamiltonian in the thermodynamic limit (or even in a finite but large size) has a finite set of distinct eigenvalues below a large spacing characterized by a parameter $\Delta$. That is, its eigenvalues arranged in increasing order are:
$$ \{ \lambda_0,\lambda_1,...,\lambda_n,\lambda_n+\Delta,...\}. $$
Now, suppose that $(\lambda_n-\lambda_0) \ll \Delta$. Can $\Delta$ then be consider a spectral gap for which $\{\lambda_0,...,\lambda_n \}$ corresponds to the groundstate manifold?
(2) I would also like to ask if it is important to have the notion of spectral gap tied with the energy associated with local quantum fluctuations. By this I mean, for example, random spin-flip due to quantum fluctuations in spin systems. Suppose $\delta \ll \Delta$ is the energy associated to local quantum fluctuations. Consider $(\lambda_{i+1} - \lambda_i) \leq \delta$ for  $i=0,..,n$. Does this make the model gapless even if the system can only be excited up to the $n$th eigenstate by local quantum fluctuations?

A: (1) In the thermodynamic limit (TDL), if the eigenvalues $\lambda_0,...,\lambda_n$ are distinct then there is no degeneracy and the gap is viewed as $\lambda_1 - \lambda_0$.
For finite systems, this does not apply, one can have small gaps (due to finite size effects, which may vanish in the TDL). Therefore a gap is essentialy a thermodynamic property. It is a question of whether you have a continuum of modes above your ground state.
(2) Spin-flips are a great example, there are models where a spin-flip 'costs' no energy therefore, $\delta=0$ and this is a gapless mode. However, if there any excitation costs finite amount of energy, your model is gapped.


text:
Q: Isabelle and Scala I am looking at creating an Eclipse PDE and need to communicate with with Isabelle. I do find some publication stating that Scala can be used to communicate to Isabelle.
I am looking for an example how to use Scala to create proves in Isabelle.

A: For posterity, quoting myself from an older answer:

Isabelle itself is implemented in Standard ML, but for communicating with the external world, it uses a protocol called PIDE (= Prover IDE). The reference implementation of PIDE is bundled with Isabelle and written in Scala, so it can be used with any JVM language. The primary application of PIDE is Isabelle/jEdit, which uses the jEdit editor to build an IDE for Isabelle, including markup, continuous checking, ...

By reusing the underlying protocol, you can implement your own application on top of Isabelle.
As far as I'm aware, the current most advanced example for this is Leon, which is an automated verification & synthesis toolkit for Scala programs. Internally, it uses libisabelle to communicate with Isabelle. (Full disclosure: I'm the author of libisabelle.) An overview of how this works is given in a paper.
libisabelle itself is available as a stand-alone library including some basic documentation that should allow you to get started. See the repository for more details. In essence, it allows you to

*

*manage Isabelle installations from within Scala (download, unpacking)

*abstract over different Isabelle versions (currently supported: 2016 and the 2016-1 release candidates)

*lifecycle management of an Isabelle session (building, starting, stopping)

*treat Isabelle/ML functions as Scala functions

*goodies like Isabelle term syntax in Scala (term"$n > 0 --> ($b & ${HOLogic.True})")

There is no built-in routine to set up a goal state and apply some proof steps, but the necessary infrastructure is all there.


text:
Q: how can I read an updating file? I am trying to read a log file for streaming.Also that file is appending new records.
while(true){
for (line <- Source.fromFile(filename).getLines()) {
    pub.publish(topic, line)}}

With this above code it again read file from the beginning . How I can overcome this situation.Next time I want it read from the upcoming records not the entire records

A: This question has been answered here: Java IO implementation of unix/linux "tail -f"
I am not familiar with scala, but it seems that the logic is simple and clear enough to convert into scala syntax. Hope this could help.

A: BufferedReader to the rescue
I have solved this problem using java.io.BufferedReader.
Short solution
while (true) {

   if (reader.readLine() != null) {
    //keep reading and pushing the data to function f
    f(reader.readLine())
   } else {
    Try {
     Thread.sleep(checkingTime)
    }
   }//end of if

  }//end of while

More Info
Lets say stream.txt is the file which is getting updated continuously by another process.
Now if we want to read progressively from the file without starting from the start.
The trick is BufferReader's readLine method returns null when it reaches EOF, wait when it gives null and start checking if anything is written to the file using readLine and the start reading using same readLine.
Here is the code snippet for progressive reading.
object ProgressiveReader {

 def read(file: File, checkingTime: Long = 1000)(f: String => Unit): Unit = {

  import java.io._

  val reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))

  while (true) {

   if (reader.readLine() != null) {
    //keep reading and pushing the data to function f
    f(reader.readLine())
   } else {
    Try {
     Thread.sleep(checkingTime)
    }
   }//end of if

  }//end of while

}

 //usage
 def main(args: Array[String]): Unit = {
  read(new File("stream.txt")) { str =>
   println(str)
  }
 }

}


text:
Q: What does "associative up to homotopy" mean for $A_\infty$-algebras? I'm reading Keller's Introduction to A-infinity algebras and modules to learn about $A_\infty$-algebras. For reference, an $A_\infty$-algebra $A$ is a graded $k$-vector space $A = \bigoplus_{i\in\mathbb{Z}}A^i$ equipped with linear maps $m_n:A^{\otimes n}\to A$ each of degree $2-n$ satisfying the Stasheff identities
$$\sum_{r+s+t = n} (-1)^{r+st}m_{r+1+t}(\boldsymbol{1}^{\otimes r}\otimes m_s \otimes \boldsymbol{1}^{\otimes t}) = 0$$
The map $m_1$ is a differential on $A$ and $m_2$ is a product on $A$ satisfying the graded Leibniz identity, making it a (not necessarily associative) differential graded algebra.
When describing the  Stasheff identities for low values of $n$, it's written in the document I linked above (and other places I've read defining $A_\infty$-algebras) that for $n=3$ the identity
$$m_2(\boldsymbol{1}\otimes m_2 - m_2\otimes \boldsymbol{1}) = m_1m_3 + m_3(m_1 \otimes\boldsymbol{1}\otimes\boldsymbol{1}+\boldsymbol{1}\otimes m_1\otimes \boldsymbol{1} + \boldsymbol{1}\otimes \boldsymbol{1}\otimes m_1)$$
and the fact that
$$ m_1m_3 + m_3(m_1 \otimes\boldsymbol{1}\otimes\boldsymbol{1}+\boldsymbol{1}\otimes m_1\otimes \boldsymbol{1} + \boldsymbol{1}\otimes \boldsymbol{1}\otimes m_1) = \delta(m_3)$$
where $\delta$ is the differential of $\mbox{Hom}(A^{\otimes 3}, A)$, implies that $m_2$ is "associative up to homotopy". I've been trying to find a precise description of what this actually means but I've not been able to find anything. My assumption is that it means $m_2$ is homotopic to an associative product, but that somehow doesn't feel completely correct.
I realise that $m_2(\boldsymbol{1}\otimes m_2 - m_2\otimes \boldsymbol{1})$ is the associator of $m_2$, so that when it's equal to $0$ then this means that $m_2$ is an associative product, but I'm not sure how this coupled with the fact that $m_1m_3 + m_3(m_1 \otimes\boldsymbol{1}\otimes\boldsymbol{1}+\boldsymbol{1}\otimes m_1\otimes \boldsymbol{1} + \boldsymbol{1}\otimes \boldsymbol{1}\otimes m_1)$ is a coboundary has anything to do with homotopies.
If someone could help me understand I would really appreciate it!

A: You asked about the algebraic point of view. If $(C, d_C)$ and $(D, d_D)$ are chain complexes with differentials of degree 1 and $f, g: C \to D$ are chain maps, then they are chain homotopic, or just homotopic, if there is a sequence of maps $H: C_n \to D_{n-1}$ such that
$$
f-g = d_D H + H d_C.
$$
This is an equivalence relation, and one consequence is that $f$ and $g$ induce the same map on homology.
That's the situation here: one chain complex is $(A, m_1)$ and the other is $(A \otimes A \otimes A, m_1 \otimes 1 \otimes 1 + 1 \otimes m_1 \otimes 1 + 1 \otimes 1 \otimes m_1)$, and the two chain maps $m_2(m_2 \otimes 1)$ and $m_2(1 \otimes m_2)$. The Stasheff identity for $n=2$ says that $m_2$ induces a multiplication on the homology of $A$ with respect to $m_1$, and the $n=3$ identity implies that at the level of homology, the multiplication is associative. (Being an $A_\infty$-algebra is much stronger than just being associative at the level of homology, though.)


text:
Q: Magick.net crashes but doesn't throw any errors in Windows I have a C# program where I'm using Magick.Net Q8 X64
7.10.1
I am building the program in VS2013 in Windows 7 on a VMware machine. Runs fine.  I'm able to loop through hundreds of images.
But when I run the program on a full Windows 7 machine I get a black screen.  No error message, no memory issue, no BSOD, just completely goes black.  Where I have to reboot the machine.
I know the first couple lines of the code runs because it creates the directories.  But as soon as it gets to the magick.net part, I think that's when it dies.
foreach (var file in d.GetFiles("*.jpg"))
        {
            using (MagickImage image = new MagickImage(file.FullName))
            {
                MagickGeometry sizeThumb = new MagickGeometry(142, 142);
                MagickGeometry sizePreview = new MagickGeometry(600, 600);

                // make sure we respect the aspect ratio
                sizeThumb.IgnoreAspectRatio = false;
                sizePreview.IgnoreAspectRatio = false;

                //rotate the image right way up
                image.AutoOrient();

                //resize for preview & write it
                image.Resize(sizePreview);
                image.Write(previewPath + file.Name);

                //resize for thumb & write it
                image.Resize(sizeThumb);
                image.Write(thumbPath + file.Name);

                //dispose of the image from memory
                image.Dispose();
                i++;
                Console.WriteLine(i);
            }
        }

A: Before doing any Magick.Net operations on images (like resize) try to disable the gpu acceleration for this operations by using OpenCL.IsEnabled = false.


text:
Q: Initialize all Flutter class instances with same ID and no need to provide argument I am working on a flutter app and wanted one of my classes to have the same id property. This is because I can have either an event or an exception, but I would like the same function to manage both. To do this, I have a switch statement that checks res.id to determine which type of event it is. The response can either be an Event instance or an Exception instance.
Exception is an import class and I'd rather not have to wrap it in an Event instance so I thought I could just hardcode id = EventIds.error. This way every error will have an id that matches an error event - thus it can be accessed and dealt with in the original switch statement.
My issue is I don't want to have to go all throughout my code and add a new argument to each instantiation. See the code below.
Exception.dart
class Exception {
  /// Always initialize with id that is error id
  /// This is for onCaptureEvent
  int id = EventIds.error;
  int code = 0;
  String message = 'no error';
  String? method;
  String? details;

  Exception(id, this.code, this.message, [this.method, this.details]);
}

Instantiation Current
Exception ex = new Exception(-93, 'Unable to validate')

I want to be able to have every instance of Exception have an id of EventIds.error WITHOUT having to go through every instantiation in my code and add it like so:
Exception ex = new Exception(EventIds.error, -93, 'Unable to validate')

Is this achievable in Flutter?

A: It was really simple. I just needed to write out my Exception class like so:
Exception.dart
class Exception {
  /// Always initialize with id that is error id
  /// This is for onCaptureEvent
  int id = EventIds.error;
  int code = 0;
  String message = 'no error';
  String? method;
  String? details;

  Exception(this.code, this.message, [this.method, this.details]);
}

This way the instances will always use the default value for id. This is also safer bc now the user cannot change the ID if they wanted to provide another argument (Exception(supplied_id, code, message)) because it will throw a syntax error saying the second argument is supposed to be a string.


text:
Q: I am trying to fix this error but nothing is working I have an error with web packs and nextjs.
import NextDocument, { Html, Head, Main, NextScript } from 'next/document'
import theme from '../libs/theme.js'

export default class Document extends NextDocument {
  render() {
    return (
      <Html lang="en">
        <Head />
        <ColorModeScript initialColorMode={ theme.config.initialColorMode }  />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

Error: ReferenceError: Cannot access 'WEBPACK_DEFAULT_EXPORT' before initialization.
   9 |   <Head />
> 10 |   <ColorModeScript initialColorMode={ theme.config.initialColorMode }  />
     |                                      ^
  11 |   <body>
  12 |     <Main />
  13 |     <NextScript />

Does anyone know a fix? Thanks in advance!

A: As mentioned in the comments above try moving your script into the <body> (or into the <Head/>)
<Head />
<body>
  <ColorModeScript initialColorMode={ theme.config.initialColorMode }  />
</body>


text:
Q: How to find all newest record for one type? I have a table like this:
id type value date
1  A    10    2018-08-01
2  A    20    2018-08-02
3  A    30    2018-08-04
4  B    11    2018-08-01
5  B    12    2018-08-02
6  C    11    2018-08-01

I would like get one latest record for one type:
id type value date
3  A    30    2018-08-04
5  B    12    2018-08-02
6  C    11    2018-08-01

How can I write this sql?

A: If you have ties with date, then you can use limit clause with subquery :
select t.*
from table t
where id = (select t1.id
            from table t1
            where t1.type = t.type
            order by t1.date desc
            limit 1
           );

A: use  max()function and subquery
select t.* from tableA t inner join

   ( select type ,max(value) as value, max(date) as d_date from tableA

    group by type ) as t1 on t.date =t1.d_date and t.type=t1.type


text:
Q: c++ - Euler Project - Level 03 I'm going through the level 03' euler project.
Here is my code and I still dont understand why it doesnt work.
Is it a mathematics Problem?
There is a compilation but the result is false. There are all of a number's factors, and not only the primes..
Could someone have a look on it?
Thanks
BR
    #include <iostream>
    #include <string>
    #include <vector>
    #include <cmath>
    #include <cstdint>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void facteursden(std::vector<uint64_t>& facteursden, uint64_t number)
{

    uint64_t i = 2;

    for (i = 1; i <= number; ++i) {
        if (number % i == 0) {
            facteursden.push_back(i);
        }
    }
}
//////////////////////////////////////////////
uint64_t factprem(uint64_t n)
{
    uint64_t i = 1;

    for (i = 1; i*i < n; ++i) {
   if (n % i != 0)
 return 1; }
return 0;
}

///////////////////////////////////////////////////////////////////////////
int main()
{

    std::vector<uint64_t> monTableau1;
    facteursden(monTableau1, 49);
uint64_t i = 0;
for (i = 0; i < (uint64_t)monTableau1.size(); ++i) {
if (factprem(monTableau1[i]) == 1) {
std::cout << monTableau1[i] << std::endl; }}

return 0 ;
}

A: There are two mistakes in
uint64_t factprem(uint64_t n)

1. In for loop start from
i=2

instead of i=1
2.Function should look like this
uint64_t factprem(uint64_t n)
{
uint64_t i = 1;

for (i = 2; i*i <=n; ++i) {
   if (n % i == 0)
 return 0; }
return 1;
}


text:
Q: Fatal authentication error while trying to connect to postgres from Java code When i try to connect to Postgres from bash it works well without asking for password:
psql -U postgres

When i try to connect from Java code it says:
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"

How i am trying to connect:
 con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydb?autoReconnect=true", "postgres", "");

What i am doing wrong?


text:
Q: Caching user specific data at database level or session Should user specific data be cached at the database level or inside JSF sessions scope ?

A: There is no one size fits all answer to that question.  In a distributed app, state can be stored client side (cookies, etc...), on the application tier in memory, or in more persistent storage like a database.  You also don't have to pick one - you can combine.
Instead, there are considerations for your user state data:

*

*In memory session data is simple but you have to be concerned with footprint - a large memory footprint with many users can be problematic.  If you're storing MBs of data with a large number of users, consider persistent storage.

*In memory session state can be problematic for services that you want to scale out to many application tier servers.  It can be mitigated with load balancing affinity but that inhibits scalability as well.

*In memory state should hold just that state - user data should be persisted.  Always ask yourself what if this application tier goes down - do we care about that state?  Can the user recover?  What's the experience?  Persistent storage has that advantage.

*Databases are better for storing large amounts of data but you can incur round trips to retrieve it.

*Databases are better for user specific date that needs to span sessions.

*Client side cookies are an option but you have to keep the size very small since they're sent with requests.

*Just like databases, client side cookies can span sessions if needed.

There's other combinations like in memory caches that read and write through to a database and cache data for a certain lifetime.  That's an option if the data doesn't absolutely have to be up to date.
Another different approach is RESTful apps.
Don't hold state at all in the services - everything goes back to persistent storage and the resources are cacheable outside the app server (akamai, client etc...).  It typically leads to more scalable applications (even if a single operation may not be as fast).  At that point, persistent storage options define how you scale.


text:
Q: Predefined Classes in Ant Design I am using Ant Design in my React project but did not totally understand how it works. Does Ant Design have predefined classes like Bootstrap? For example, if I wanted to center elements in Bootstrap I would do something like that?
class="d-flex justify-content-center"

A: Yes Antd have predefined classes like bootstrap
If you want to center element use  justify="center" It will work only on Row
but you can customize the antd  element by using @emotion/styled package.
You need to inspect the button and get the button class from the element tab

Now you need to create a custom style for the button
Step 1: you need to import @emotion/styled
import Styled from "@emotion/styled";
Step 2 : Now Override the CSS of the Button
const CustomButton = Styled(Button)`
.ant-btn-primary{
 background-color: #4BA461;
}
`

Step 3 Now use this CustomButton where you want like
 <CustomButton>Register</CustomButton>

Installation Process

npm install --save @emotion/styled

 or

yarn add @emotion/styled

You can learn more about emotion/styled from https://emotion.sh/docs/install

A: Yes, here in Ant Design CSS properties are applied in attributes like center='sm' and In bootstrap, CSS properties are applied in classes like justify-content-sm-center.
please follow this URL https://ant.design/components/grid/#API


text:
Q: Default interface methods are only supported starting with Android 7.0 (Nougat) I upgraded to Android Studio 3.1 and I'm getting the following error:

Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner)

Message{kind=ERROR, text=Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle.DefaultLifecycleObserver.onCreate(android.arch.lifecycle.LifecycleOwner), sources=[Unknown source file], tool name=Optional.of(D8)}

Here is my Gradle configuration:
compileSdkVersion 27
//buildToolsVersion '27.0.3'
defaultConfig {
    minSdkVersion 16
    targetSdkVersion 27
     multiDexEnabled true
     //...
   }

As you can see, I am targeting 27 which is already ahead of 24 that it's complaining about. What exactly should I do to fix this? If I change to 1.8 Java, won't I be missing a lot of customers? Why was I not getting this error before I upgraded Android Studio?
I do not know if this is about the LifecycleObserver class I recently put in. It was in Kotlin and now I changed it to Java, but I still get the same error after cleaning the project:
public class LifeCycleAwareObserver implements LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void  onAppBackgrounded() {
        AnalyticsUtils.trackStartSession(true);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        AnalyticsUtils.trackStartSession(false);
    }
}

How can I trace where the error is coming from so I can fix it?
Here are my version dependencies:
project.ext {

        firebase_version = '12.0.0'

        supportlib_version = '27.0.2'

        room_version = '1.0.0'

        espresso_version = '3.0.1'

        archLifecycleVersion = '1.1.1'
    }

A: You should use Java 8 to solve this. Based on the Android documentation, you can do this by clicking menu File → Project Structure.
And change Source Compatibility and Target Compatibility.

And you can also configure it directly in the app-level build.gradle file:
android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

A: As CommonsWare mentioned, for reference add this inside the android {...} closure in the build.gradle for your app module (app level) to resolve the issue:
android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

A: Use this code in your build.gradle file:
android {
    compileOptions {
        incremental true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

A: In the app-level Gradle file, you have to write this code:
android {
...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

They come from JavaVersion.java in Android.

An enumeration of Java versions.
Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html
After 9: http://openjdk.java.net/jeps/223

A: Update your build.gradle(Module:app) add compileOptions block and add JavaVersion.VERSION_1_8
apply plugin: 'com.android.application'

android {
    .................
    .........................
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

A: My project uses ButterKnife and Retro lambda. Setting JavaVersion.VERSION_1_8 will not work. It always blamed the ButterKnife static interface function until I found this Migrate from Retrolambda.
TL;DR
Just add JavaVersion.VERSION_1_8 and completely remove retrolambda from your project. It will build successfully.

A: Changing the minSdkVersion from 19 to 21 solved the issue for me.
defaultConfig {
    applicationId "com.example"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 23
    versionName "1.0"
    vectorDrawables.useSupportLibrary = true
}

A: You can resolve this issue by downgrading the Source Compatibility and *Target Compatibility Java version to 1.8 in the latest Android Studio version 3.4.1.

*

*Open the Module Settings (Project Structure) window by right clicking on the app folder or Command + Down Arrow on Mac

*Go to Modules → Properties

*Change Source Compatibility and Target Compatibility version to 1.8

*Click on Apply or OK. That's it. It will solve your issue.
Also you can manually add in file build.gradle (Module: app):
android {
...

compileOptions {
        sourceCompatibility = '1.8'
        targetCompatibility = '1.8'
    }

...
}

A: apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.0"

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.example.architecture"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'androidx.room:room-runtime:2.2.5'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    annotationProcessor 'androidx.room:room-compiler:2.2.5'
    def lifecycle_version = "2.2.0"
    def arch_version = "2.1.0"

    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
    implementation "androidx.cardview:cardview:1.0.0"
}

Add the configuration in your app module's build.gradle
android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

A: This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.


text:
Q: How to generate a single random number given a continuous PDF in Python? I have a given PDF of the number that needs to be generated: p(z) = N (1 + (1-z)^2) /z
where z is restricted from some minimum z0 to 1 and proper N for normalization.
I need to generate single numbers which follow this distribution and I have no idea where to even start. I have searched around but only found solutions where PDF is for discrete values, not continuous ones.
I have searched for already implemented methods in numpy and scipy but I have failed to find anything useful, but I might have missed something.

A: Here you have a PDF that is decreasing on a closed interval, namely [z0, 1]. Moreover, the range of the PDF increases as z0 decreases, making a naïve rejection sampler such as the following inefficient:
def rejection(z0):
   pdfz0=pdf(z0,z0) # For pdf, see below
   while True:
      x=random.uniform(z0,1)
      if random.random()*pdfz0 < pdf(x,z0):
         return x

There is a way to deal with this, though, and this is called the inversion-rejection method, described in Devroye, L., "Non-Uniform Random Variate Generation" (1986), chapter 7, section 4. This method requires finding the PDF and the CDF of the distribution (and also requires the PDF to be decreasing on a closed interval, as is the case here). The following code uses the SymPy library to find the PDF and the CDF.
#
# Using SymPy to find the CDF
#

pdfunnorm=((1 - z)**2 + 1)/z
# 1 divided by the `N` in your question (a normalization constant)
pdfnorm=integrate(pdfunnorm,(z,y,1))
ppdf=(pdfunnorm/pdfnorm).simplify()
pprint(ppdf)
pcdf=integrate(ppdf.subs(z,t),(t,y,z)).simplify()
pprint(pcdf)

The PDF and CDF can thus be written as follows. An unnormalized PDF is also shown
because the algorithm below works whether or not the PDF is normalized (integrates to 1 on its domain):
def unnormpdf(z,y):
   return (1+(1-z)**2)/z

def pdf(z,y):
   return -(2*(z - 1)**2 + 2)/(z*(y**2 - 4*y + 4*math.log(y) + 3))

def cdf(z,y):
   return (y**2 - 4*y - z**2 + 4*z + 4*math.log(y) - 4*math.log(z))/(y**2 - 4*y + 4*math.log(y) + 3)

Now we use the inversion-rejection algorithm for decreasing PDFs on [0, 1]. Note that the method shifts some of the variables from [0, 1] to [z0, 1] before passing them to the unnormpdf and cdf functions. Again unnormpdf need not integrate to 1 on its domain.
def inversionRejection(unnormpdf, cdf, z0):
   # Devroye, L., "Non-Uniform Random
   # Variate Generation", p. 336.
   u=random.random()
   r=2
   x=1/r
   # NOTE: Here, x is scaled
   # and shifted from [0, 1] to [z0, 1]
   # before passing to CDF
   while u<cdf(z0+x*(1-z0),z0):
      x/=r
   # Version of x that is scaled
   # and shifted from [0, 1] to [z0, 1]
   shiftedx=z0+x*(1-z0)
   while True:
      v=random.uniform(1,r)
      w=random.random()
      y=x*v
      shiftedy=z0+y*(1-z0)
      if w<=unnormpdf(shiftedy,z0)/unnormpdf(shiftedx,z0): # (**)
         return shiftedy

In the case of your PDF, certain terms on the right-hand side of (**) can cancel out even if the normalized PDF is used, leaving an expression without logs and without z0:
      if w<=shiftedx*((shiftedy - 1)**2 + 1)/(shiftedy*((shiftedx - 1)**2 + 1)):

Here are timings on my machine:
In [209]: timeit inversionRejection(pdf,cdf,0.001)
6.7 µs ± 31.5 ns per loop (mean ± std. Dev. Of 7 runs, 100000 loops each)

In [210]: timeit inversionRejection(unnormpdf,cdf,0.001)
6.8 µs ± 103 ns per loop (mean ± std. Dev. Of 7 runs, 100000 loops each)

In [211]: timeit rejection(0.001)
129 µs ± 1.77 µs per loop (mean ± std. Dev. Of 7 runs, 10000 loops each)

Alternatively, the following algorithm (from Devroye's book p. 312)
takes advantage of the fact that your density is decreasing and
defined on a closed interval. Moreover, it only requires the
(normalized) PDF and not also the CDF.

def monbounded(pdf, z0):
   # For decreasing densities on [0, 1]
   m = pdf(0, z0)
   while True:
    u=random.random()
    if u<1/(1+math.log(m)):
      x=random.uniform(0,1/(m))
      if random.random()*m <= pdf(x,z0): return x
    else:
      x=math.exp(u*(1+math.log(m))-1)/m
      if random.random() <= x*pdf(x,z0): return x

def transpdf(x, z0):
   xpos=z0+x*(1-z0)
   return pdf(xpos,z0)*(1-z0)

def transmonbounded(z0):
   # For the PDF in your question.
   # Transform [z0,1] to [0,1].
   return z0+monbounded(transpdf, z0)*(1-z0)


text:
Q: Measure time of execution in F# Please post code for displaying time in F#. I noticed that you can measure it from F# interactive with #time directive, but I don't know how to execute program from FSI
Thanks

A: I would just use the .NET Stopwatch class.
let stopWatch = System.Diagnostics.Stopwatch.StartNew()
...
stopWatch.Stop()
printfn "%f" stopWatch.Elapsed.TotalMilliseconds

A: From msdn:

By itself, #time toggles whether to display performance information.
  When it is enabled, F# Interactive measures real time, CPU time, and
  garbage collection information for each section of code that is
  interpreted and executed.

So to test you function you have to open F# interactive console and execute your function in it (one way to do it is to select your function, right click and chose Execute in Interactive)
Then make a call to your function in Interactive like that for example:
// define your function first either in interactive console or in your document:
let square x = x * x

// in interactive
#time
square 10
#time

You will see how much of real time and CPU time were spent on computation and a bit of information from garbage collector

A: Check out the timer function in the F Sharp Programming wikibook. It is defined like this:
let duration f =
    let timer = new System.Diagnostics.Stopwatch()
    timer.Start()
    let returnValue = f()
    printfn "Elapsed Time: %i" timer.ElapsedMilliseconds
    returnValue

Whilst being used like this:
let sample() = System.Threading.Thread.Sleep(2)

duration ( fun() -> sample() )
// or
duration sample

A: You could also create custom computation expression to hide actual measuring logic, e.g.:
timer {
   // your code goes here
}

See more examples here: https://fsharpforfunandprofit.com/posts/computation-expressions-bind/


text:
Q: Powershell invoke-sqlcmd "select query_hash" I'm trying to build a small tool in Powershell to select some data. One of the things I would like to get out is the query_hash, but when I do this with Powershell its not returning the same value as in SQL Management Studio.
In SQL Management Studio it shows like 0xFFCEA347FBFC247D7 but Powershell shows it like this {50, 123, 144, 118...}
Anybody who can tell me what I'm doing wrong?


text:
Q: Android Studio: Where is the Compiler Error Output Window? When I 'Run' my project in Android Studio, in the 'Messages' window, I get:
Gradle:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':play01:compileDebug'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

It says > Compilation failed; see the compiler error output for details.
So where is the "compiler error output"? And/Or how do I run with --stacktrace option?

A: In android studio 2.2.3 you can find output in the gradle console as shown below

A: This answer is outdated. For Android 3.1 Studio go to this answer
One thing you can do is deactivate the external build. To do so click on "compiler settings icon" in the "Messages Make" panel that appears when you have an error. You can also open the compiler settings by going to File -> Settings -> Compiler. (Thanx to @maxgalbu for this tip).

Uncheck "Use External build"

And you will see the errors in the console
EDIT: After returning to "internal build" again you may get some errors, you can solve them this way: Android Studio: disabling "External build" to display error output create duplicate class errors

A: I am building on what Jorge recommended.
Goto File->Settings->compiler.
Here you will see a field to add compiler options where you plug in --stacktrace

A: For Android Studio 3.1, select the icon below the Build one in the Build window.

By Android Studio 3.3 (possibly in 3.2.1), the icon has changed, though the location is the same:

The build window should open when you run a build action (e.g. from the Build menu). If you don't see it, you can try the "Build" button along the bottom of the window (also visible in the above screenshots), or through the menus View → Tool Windows → Build.

A: Run
gradlew --stacktrace

in a terminal to see the full report
for me it was

Task :app:compileDebugJavaWithJavac FAILED
      javacTask: source release 1.8 requires target release 1.8

so i added
 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

in app.gradle file / android
and the build completed successfully

A: It's really straightforward to set up! Just go to the Compiler settings at Android Studio 2.2.3 and set the --stacktrace command:

Then run the app again

A: Are you on Windows? Launch cmd, find your project folder and run "gradlew build". This should already give you more output than the IDE, you can also use --info, --stacktrace and --debug there.

A: Just click on the "Build" node in the Build Output

From some reason the "Compilation failed" node just started being automatically selected and for that the description window is very unhelpful.

A: In my case I prefer to open the Terminal window on the bottom left, and run gradlew build --info :

A: You can also see the error in the Build window by clicking on the toggle button.

A: For Android Studio v4.0
As others have mentioned, the "Messages" window that was evidently present in AS 3.* no longer exists in 4.0 (or else it's hidden very, very well). After wasting far too much time on this, I've found another way to view those compile errors:

*

*Open your Gradle tool window. By default, it's on the right edge toward the top:

If you don't see it there, use View > Tool Windows > Gradle.

*In the Gradle window, open your app's root option and run Tasks > build > build:

*The Run tool window should open automatically, where you'll see details about the cause of the build error:

If it doesn't open automatically, you can access it through View > Tool Windows > Run.
Hopefully that gives you all the info you need. If not though, try:

*Go to File > Settings > Build, Execution, Deployment > Compiler. In the Command-line Options, add --scan.

Apply and OK, then try the Gradle build over again.

A: If you are in android studio 3.1, Verify if file->Project Structure -> Source compatibility is empty. it should not have 1.8 set.
then press ok, the project will sync and error will disappear.

A: In my case i had a findViewById reference to a view i had deleted in xml
if you are running AS 3.1 and above:

*

*go to Settings > Build, Execution and Deployment > compiler

*add --stacktrace to the command line options, click apply and ok

*At the bottom of AS click on Console/Build(If you use the stable version 3.1.2 and above) expand the panel and run your app again.

you should see the full stacktrace in the expanded view and the specific error.

A: after the convert android to androidx.
change Import library problem will sol.
Like this:
import androidx.appcompat.widget.Toolbar;  <<  like this

import androidx.annotation.NonNull;  <<  like this
import androidx.appcompat.app.ActionBarDrawerToggle;   <<  like this
import androidx.drawerlayout.widget.DrawerLayout;     <<  like this
import androidx.recyclerview.widget.RecyclerView;      <<  like this
import androidx.appcompat.app.AppCompatActivity;       <<  like this

A: Follow these steps!

*

*Go to File

*Then click on Settings

*Then under "Build, Execution, Deployment" go to Compiler

*Add this in "Command-line Options" and press OK

*Now normally run your test/app again and when you will encounter error this time, you will see highlighted messages like this :

*Clicking on "Run with --scan" or "Run with --stacktrace" will give error in more detail.

A: I solved this error "Compilation failed to see the compiler error output for details"
The solution is very Simple:   Add in a Gradle below a line of code
implementation 'com.google.android.gms:play-services-ads:15.0.0'


text:
Q: WooCommerce custom PHP code to change Add To Cart button text I want to update the default 'Add To Cart' text to be more suitable for my website. I have created a child theme using Astra, installed it, and then on the Theme Editor in WordPress I added a new function to my functions.php file that should have done the trick
add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_product_add_to_cart_text' );
function woocommerce_custom_product_add_to_cart_text() {
    return __( 'Check it out', 'woocommerce' );
}

From all the examples online it should be this easy. I just read from another post that this may be deprecated now? Should this still work, anything else I can check? I want this to be the button text globally on all products but each product still shows 'Add To Cart'. I saved and then reloaded my website but do not see any changes

A: add_filter( 'woocommerce_product_add_to_cart_text', 'mujuonly_add_to_cart', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'mujuonly_add_to_cart', 10, 2 );

function mujuonly_add_to_cart( $text, $class ) {
    return __( 'Check it out', 'woocommerce' );
}

Tested OK with WC 4.9


text:
Q: My decipher call is returning an invalid response when trying to implement Ceasar cipher, why? functionmovingShift() performs a variation of the Caesar shift. The shift increases by 1 for each character (including spaces character).
Function demovingShift() should decipher returned string backwards.
I can't figure out the algorithm to decipher the returned string.
My code works only for the first few words. Then as "shift" variable grows negative the logic breaks.

let u = "I should have known that you would have a perfect answer for me!!!";

function movingShift(s, shift) {
 let arr = [];

 s.split("").forEach((x, idx) => {
  let source = x.toUpperCase().charCodeAt(0);
  if (source < 65 || source > 90) {
   arr.push(x);
   shift++;
   return;
  }
  let index = (source - 65 + (shift)) % 26 + 65;
  let letter = String.fromCharCode(index);
  x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
  shift++;
 })

 let cipher = arr.join("");
 return cipher;
}

let v = movingShift(u, 1);

function demovingShift(v, shift) {
 shift = -1;
 let arr = [];
 v.split("").forEach((x, idx) => {
  let source = x.toUpperCase().charCodeAt(0);
  if (source < 65 || source > 90) {
   arr.push(x);
   shift--;
   return;
  }
  let index = (source - 65 + (shift)) % 26 + 65;
  let letter = String.fromCharCode(index);
  x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
  shift--;
 })
 return arr.join("");
}

console.log(movingShift(u, 1));
console.log(demovingShift(v, 1));

Returned string from the first function :
J vltasl rlhr zdfog odxr ypw atasl rlhr p gwkzzyq zntyhv lvz wp!!!

Returned string from decipher function:
I sho;ld ha<e k45=4 :.a: ?5; =5;2* .a<+ a 6+8,+): a49=+8 ,58 3+!!!

A: There are two mistakes in your code.
1) First inside demovingShift you need to change shift = -1 to shift = -1 * shift;.
2) Change let index = (source - 65 + (shift)) % 26 + 65; to let index = (source - 65 + (shift)) % 26 + 65; because now shift is negative its possible that (source - 65 + (shift)) value may became negative which will give incorrect character. So we can use (source + 65 + (shift)).
You can test it below.

let u = "I should have known that you would have a perfect answer for me!!!";

function movingShift(s, shift) {
  let arr = [];

  s.split("").forEach((x, idx) => {
    let source = x.toUpperCase().charCodeAt(0);
    if (source < 65 || source > 90) {
      arr.push(x);
      shift++;
      return;
    }
    let index = (source - 65 + (shift)) % 26 + 65;
    let letter = String.fromCharCode(index);
    x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
    shift++;
  })

  let cipher = arr.join("");
  return cipher;
}

function demovingShift(v, shift) {
  shift = -1 * shift;
  let arr = [];
  v.split("").forEach((x, idx) => {
    let source = x.toUpperCase().charCodeAt(0);
    if (source < 65 || source > 90) {
      arr.push(x);
      shift--;
      return;
    }
    let index = (source + 65 + (shift)) % 26 + 65;
    let letter = String.fromCharCode(index);
    x === x.toLowerCase() ? arr.push(letter.toLowerCase()) : arr.push(letter);
    shift--;
  })
  return arr.join("");
}

let v = movingShift(u, 1);
console.log(u);
console.log(v);
console.log(demovingShift(v, 1));


text:
Q: Unexpected result from "greater than" comparison of values from a text input I'm experiencing a strange JavaScript/jQuery math bug when trying to determine whether one value is greater than another.
Here is a link, using jsFiddle, to my code: http://jsfiddle.net/qxeTj/
$("#Quantity").live("focusout", function() {
    var qty = +$(this).val();
    var stock = +$('#StockLvl').val();
    if (qty > stock) {
        $('#Result').html("
Quantity: " + qty + "

Stock: " + stock + "
" + "
Not Enough Stock.
");
    }
    else if (stock > qty || stock == qty) {
        $('#Result').html("
Quantity: " + qty + "

Stock: " + stock + "
" + "
Enough Stock.
");
    }
});

Example of problem:
When I focus out of the input field, if it has a value of 1 or 2, it works fine. It even works if I have a value of 3, 4, 5, 6, 7, 8, 9.
But the problem is then when I use values from 10-19 or 100-199 or 1000-1999 and so forth. It say's it has enough stock when it shouldn't.

A: You're comparing strings. Convert them to numbers first.

var qty = Number( $(this).val() );
var stock = Number( $('#StockLvl').val() );

or
var qty = +$(this).val();
var stock = +$('#StockLvl').val();

or
This way will be safest in your case.
var qty = parseInt( $(this).val(), 10 );
var stock = parseInt( $('#StockLvl').val(), 10 );

A: You are dealing with string comparison not number. Put a parseInt around the values and you will get the expected result.


text:
Q: What is the purpose of $watch in angularjs What is the purpose of $watch in angularjs. Can anyone explain me how it works and what is the purpose of $watch. Thanks in advance

A: The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:

*

*A value function

*A listener function

Here is an example:
$scope.$watch(function() {},
              function() {}
             );

The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed. Here is an example:
$scope.$watch(function(scope) { return scope.data.myVar },
              function() {}
             );

This example valule function returns the $scope variable scope.data.myVar. If the value of this variable changes, a different value will be returned, and AngularJS will call the listener function.
The listener function should do whatever it needs to do if the value has changed. Perhaps you need to change the content of another variable, or set the content of an HTML element or something. Here is an example:
$scope.$watch(function(scope) { return scope.data.myVar },
              function(newValue, oldValue) {
                  document.getElementById("").innerHTML =
                      "" + newValue + "";
              }
             );

This example sets the inner HTML of an HTML element to the new value of the variable, embedded in the b element which makes the value bold. Of course you could have done this using the code {{ data.myVar }, but this is just an example of what you can do inside the listener function.
Hope help ful to you.

A: Take a look at the Angular docs, they are generally pretty good and include examples.

$watch(watchExpression, listener, [objectEquality]);
Registers a listener callback to be executed whenever the
  watchExpression changes.

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch


text:
Q: Is it advisable to store things such as list of cities on the db? Hi I'm using CakePHP and I'm wondering if it's advisable to store things that don't change a lot in the database lik the list of cities?

A: If your application already needs a database, why would you keep data anywhere else?
If the list doesn't change (per installation) and it's reasonably small and frequently used, then it might be worth reading it once on initialization and caching the result to improve performance and reduce the load on the database.

A: You get all sorts of queries and retrievals out of the box, the same way you access any other of your data. Databases are as cheap as flat files today, but you get a full service.

A: I see this question has had an answer accepted - I still want to chime in with my $0.02
The way I typically do for arrays of static data (country list, timezone list, immutable sets you would use enum for...) is to use this array datasource.
It allows you to map relationships between db models and array based models and to use the usual find syntax / Containable on the relationships.
http://github.com/jrbasso/array_datasource

A: If it is pretty much a static list, then you can store it either in the db or a file, but keep it in memory for use. In other words, load it once whether from db or file. What you don't want to do is keep taking a hit loading it. Especially if you use it on most page views. Those little bits of time add up if you have a large number of visitors.
The flip side, of course, is if you find yourself doing this for large lists or lots and lots of little lists. Then you could run into problems of keeping too much in memory.
Bill the Lizard is right about it being important whether or not the list links to other tables. If it does, then you will need it in the db if you need queries that will include it.


text:
Q: Why doesn't HTML inserted with JS respond to clicks? See this screenshot. I have a list of things to bring to college. I have a text input with an add button. When you type something into the input and click add, it gets added. However, when I click the close button of the item that got added, it doesn't work. The alert('test') also doesn't show up, so I guess that the new close icon isn't responding to clicks. How can I get it to work? Here's my code:
Javascript
  $("#packing_list_css .close").click(function() {
    $(this).closest('li').hide();
    alert('test');
  });
  $("#everyday_ul button").click(function() {
    new_item = $("#everyday_ul :text").val();
    new_item.trim();
    if (new_item.length != 0)
      $("
×" + new_item + "
").insertBefore( "#everyday_ul :text" );
  });

HTML

Everyday

  <% everyday.each do |item| %>

× <%= item %>

  <% end %>
  <input type="text"><button class="btn btn-link">Add</button>

A: Because you:

*

*Get all the elements that match #packing_list_css .close in the document

*Bind an event handler to each of them

*Add a new element that matches that selector

The new element didn't exist for steps 1 and 2 so it never gets an event handler bound to it.
Bind the event handler to #packing_list_css, let the click event bubble up to it, and check to see what was actually clicked.
$("#packing_list_css").on("click", ".close", function() {


text:
Q: AngularJS Promises with Synchronous Http calls I am facing an issue with the then function not being called in one of my controllers when doing multiple synchronous http calls.
In the below code, the console.log(data) statement in my controller is not being executed as the control never comes to the then function.
********************controller file
function MyController($scope, $location, $timeout) {

    function submit($event) {
      Myservice.getDetails(productid).then(function(data){
        console.log(data)
      });
    }

angular.module('myModule')
    .controller('MyController', MyController);
})(window.angular);

******************  MyService
(function (angular, mySecondService) {
  'use strict';

  function MyService($http, $q, $log, $location, mySecondService{

    function getDetails(pId) {
      byodCheckerData = [];
      mySecondService.httpTkn().then(function(Tkn){
          var request = {
            method: 'GET',
            url: 'getDetails',
            headers: {auth: Tkn},
            params: {Id:pId}
          };

          return $http(request).then(function(resp){
            return resp;
          })
      })
    };

    return {
      getDetails: getDetails;
  }

angular.module('myModule')
.factory('MyService', MyService);

})(window.angular);

*********************************** MySecondservice
(function (angular) {
  'use strict';
  function mySecondService($log, $http, $q) {
    var ts = this;
      function httpTkn(){
          defer = $q.defer();
          var authReq = {
            method: 'GET',
            url: 'getTkn'
          };
         return $http(authReq).then(function (response) {
              defer.resolve(response.data.tkn
        return response.data.tkn;
            },
            function (error) {

              return error;
            });
      };

    ts.httpTkn = httpTkn;
  }

  angular.module('myModule')
    .service('mySecondService', mySecondService);

})(angular);.

A: Can you try below code :
function getDetails(pId) {
    var defered = $q.defer();
    byodCheckerData = [];
    mySecondService.httpTkn().then(function(Tkn) {
        var request = {
            method: 'GET',
            url: 'getDetails',
            headers: { auth: Tkn },
            params: { Id: pId }
        };

        $http(request).then(function(resp) {
            defered.resolve(resp);
        });
    });
    return defered.promise;
}

Note that , you need to return promise so that the function works when the $http values is resolved


text:
Q: Join meta doesn't join main site automatically? Now this account joined this site(meta), but when I move to Stackexchange.com, the page asks me to join the community, is it normal? if so, is it also apply to other sites?
(I remember this account joined the community from meta.stackexchange.com, but not from Stackexchange.com, now I visit stackexchange.com and still ask me to join the community, as if main and meta are different sites)
(I test again: login to meta.stackexchange.com with google successfully, then move to Stackexchange.com, but in Stackexchange.com I'm not logged in. When I login to Stackexchange.com again the site asks me to join the community, sorry I dun know how to capture screen and can only describe the story with words!)

A: stackexchange.com is not the main site for meta.stackexchange.com. It's a read-only portal of network activity.
Having said that yes, please post a screenshot if at all possible (use the snipping tool on Windows... I forget what the Mac keyboard shortcuts are). You should be automatically getting a user on stackexchange.com if you don't already have one but are logged in... or at least you should see a "log in" link rather than "join this community".


text:
Q: How can I find the potential created by spherical capacitor with dielectric material? If we have a spherical capacitor with inner radius or r1 and outer radius of r2, with charges (+/-)q on them and there is a dielectric material (with constant e) in between them with.
What kind of a potential would this create outside the entire capacitor? in the region with the dielectric? and inside the entire thing?

A: Using the Gauss's law (see this Link), the solution is as follow,
$$
\Phi (r) = \left\{ {\begin{array}{*{20}{c}}
{\frac{q}{{4\pi \varepsilon {r_1}}}\,\,\,\,for\,\,\,r \le {r_1}}\\
{\frac{q}{{4\pi \varepsilon r}}\,\,\,\,for\,\,\,{r_1} \le r \le {r_2}}\\
{0\,\,\,\,\,\,\,for\,\,\,r \ge {r_2}}
\end{array}} \right.
$$

A: This is quite simple as this is a standard equation for the capacitance. You will have
$$C=\epsilon C_0$$
being $C_0$ the capacitance in vacuum. For a full set of formulas in different geometrical configurations see here.

A: You can write down these fields directly without calculating anything because the field of a charged sphere is the same as that of a point charge outside the sphere and zero inside the sphere.
http://hyperphysics.phy-astr.gsu.edu/hbase/electric/potsph.html


text:
Q: Discard duplicated array object base on property value myArr = [{"name":"abc"},{"name":"efg"},{"name":"abc"}]

How to eliminated array that have redundant property value?

A: If you can use Underscore then here is inbuild function _.uniq
var myArr = [{"name":"abc"},{"name":"efg"},{"name":"abc"}];
var newArr = _.uniq(myArr, 'name');

Output:
[{"name":"abc"},{"name":"efg"}]

DEMO


text:
Q: Making index i to row and index j to column and index k = 0 or k = 1 depending on following I have a 3D matrix as following:
a = [[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 2, 3, 4, 5], [3, 2, 3, 4, 3, 4], [4, 3, 4, 5, 4, 3], [5, 4, 5, 6, 5, 4]]]

When I loop over the matrix I want the first index i to represent the row of a, the second index to represent the column an the third index k to just be 0 or 1 depending on: k = 0 in which case the value is the row index of the cell is pointing to, or the k = 1 the value is the column index.
The problem is that everyting is opposite: the index i is now representing what I want k to be, the j is the row which should be the column and k is the column.
for i in a:
    #I want i to represent the row
    for j in i:
        #I want j to represent the column


text:
Q: Creating a box framework for inside the formula environment For a list of things to be used inside the formula environment, I want to create boxes stacked over each other. I basically want to write
$$ A := "Box with lines like 'A is a number', 'A is bigger than 3',... " $$

What I come up with is is
\newcommand{\mybox}[2]{\stackrel{\fbox{$#1$}}{\fbox{$#2$}}}

but it pretty much sucks when it comes to what I really want. It's only two boxes and they don't even touch each other. Their length depends on the content. It should look more like a shelf. The length of all boxes should fit (the height might depend on the content). Also, the box should be oriented such that the := is in the vertical center. But if I want to use my construction for more than two boxes I have to do stupid things like
\mybox{statement 1}{\mybox{and statement 2}{statement 3}}

A: What about a simple tabular?
\documentclass{article}
\usepackage{colonequals}

\begin{document}

\begin{equation}
  A \colonequals
  \begin{tabular}{|c|}
    \hline
    statement 1\\\hline
    and statement 2\\\hline
    statement 3\\\hline
  \end{tabular}
\end{equation}

\end{document}

Result:

Edit: Making a n-ary function:
\documentclass{article}
\usepackage{colonequals}

\usepackage{kvsetkeys}

\makeatletter
\newcommand*{\boxes}[1]{%
  \begingroup
    \toks@={%
      \begin{tabular}{|c|}%
      \hline
    }%
    \comma@parse{#1}\box@entry
    \the\toks@
    \end{tabular}%
  \endgroup
}
\newcommand*{\box@entry}[1]{%
  \toks@=\expandafter{\the\toks@
    #1\tabularnewline
    \hline
  }%
}
\makeatother

\begin{document}

\begin{equation}
  A \colonequals
  \boxes{
    statement 1,
    and statement 2,
    {statement 3, 4 and 5},% comma needs to be protected by braces
    another statement,
  }
\end{equation}

\end{document}

Result:

The contents of the tabular is first written in a token register. That avoids trouble
with cell groups and empty lines at the end.
Edit: Further reading:

*

*Token registers: Victor Eijkhout, TeX by Topic, Chapter 14: Token lists,
CTAN:info/texbytopic/TeXbyTopic.pdf

*Package documentation of kvsetkeys, Section 1.7: Comma separated lists, CTAN:macros/latex/contrib/oberdiek/kvsetkeys.pdf


text:
Q: Android RSS reader GUI problem I have an RSS reader which display the titles of a RSS feeds in a list. on clicking the title the main source page of the title should open...
the following code works fine for a small list but if i have a long list which contains feeds from more than one website the application stops and i have to force close it.
can anybody help me to fix it please.
@Override
        protected void onListItemClick(ListView l, View v, int position, long id) {
            super.onListItemClick(l, v, position, id);
            Intent viewMessage = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(messages.get(position).getLink().toExternalForm()));
            this.startActivity(viewMessage);
        }

A: It's possible, depending on how many pages you're parsing, you'll want to start an asynchronous task.  Basically you'll start a new thread separate from your UI thread so you won't have to force close the application.  Read more about asynchronous tasks here:
http://developer.android.com/reference/android/os/AsyncTask.html
Also - if you implement error checking you'll be able to continue to run the application if you do get an exception from parsing.


text:
Q: Multiple bibliographies, different entries with same authors and year I have two separate bibliographies, one for publications and one for working papers. They are in separate bib files.
The problem is that I have one working paper and one publication, both with same authors and in the same year. The way they are produced now prints next to author names (2020a) on the publications bibliography and (2020b) on the working papers bibliography. What I want is to have (2020) on publications bibliography (since it is the only entry with those authors and year in that refsection) and (2020) on working papers bibliography (again since it is the only entry with those authors and year in that refsection).
How do I do that?
On the preamble I have
\usepackage[style=apa, sorting=ydnt]{biblatex}
\addbibresource{publications.bib}
\addbibresource{working.bib}

On the main part I have
\begin{refsection}
\nocite{*}
\printbibliography[keyword={published},title={Publications}]
\end{refsection}
\begin{refsection}
\nocite{*}
\printbibliography[keyword={working},title={Working papers}]
\end{refsection}


text:
Q: C# Speaker Output Device *Advanced* Settings I have a C# (WPF) application which checks for all output devices (Speakers) and I need to check the Bit Depth and Sample Rate of the output device. Has anyone worked with this or know of a way to do so?
I have been searching around, but found nothing similar...
Any help is much appreciated.
Thanks

A: The output device is not bound to a particular bit depth or sample rate, it plays whatever it is asked to. Do you mean to find the currently playing values ? Or to get the maximum bit depth and sample rate the device can handle ?


text:
Q: Django - How to pass queryset to the template using a class based UpdateView? Is there a way to pass a queryset into the fields collection (shown in the views.py)? My intend is to populate a select HTML element with only active members. Or is there any other way or best practice to solve this?
views.py:
class Orders_update(UpdateView):
    model = Order
    active_members = Member.objects.all().filter(active=True)
    fields = ['order_text', 'customer', 'active_members']
    template_name = "orders/orders_update.html"
    success_url = '../../../orders'

orders_update.html:
{% extends "base.html" %}
{% load widget_tweaks %}
{% block content %}

Order - Update

<form class="form-group" style="width:200px" action="" method="post">{% csrf_token %}

        {{ form.order_text|add_class:"form-control" }}
        {{ form.customer|add_class:"form-control" }}
        {{ form.active_members|add_class:"form-control" }}
        <input class="form-control" type="submit" value="Update" />

</form>
{% endblock %}

models.py:
from django.db import models
from django.utils import timezone

class Order(models.Model):
    customer = models.ForeignKey('Customer')
    member = models.ForeignKey('Member')
    order_text = models.CharField(max_length=200)
    pick_up = models.CharField(max_length=200)
    destination = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    changed_date = models.DateTimeField(blank=True, null=True)

    def created(self):
        self.changed_date = timezone.now()
        self.save()

    def __str__(self):
        return self.order_text

class Customer(models.Model):
    company_name = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=timezone.now)
    changed_date = models.DateTimeField(blank=True, null=True)

    def created(self):
        self.changed_date = timezone.now()
        self.save()

    def __str__(self): return self.company_name

class Member(models.Model):
    lastname = models.CharField(max_length=20)
    firstname = models.CharField(max_length=20)
    created_date = models.DateTimeField(default=timezone.now)
    changed_date = models.DateTimeField(blank=True, null=True)
    active = models.BooleanField(default=True)

    def created(self):
        self.changed_date = timezone.now()
        self.save()

    def __str__(self):
        return self.lastname

A: It sounds like you want to restrict options for the Order.members field to those with active=True.
You can do this by creating a model form, and changing the queryset in the __init__ method.
from django import forms

class OrderForm(forms.ModelForm):
    class Meta:
        fields = ['order_text', 'customer', 'members']

    def __init__(self, *args, **kwargs):
        super(OrderForm, self).__init__(*args, **kwargs)
        self.fields['members'].queryset = Member.objects.all().filter(active=True)

Then update your view to use your model form by setting form_class.
class Orders_update(UpdateView):
    model = Order
    form_class = OrderForm
    ...

Finally, the field is call member, so you should change the template to:
{{ form.member|add_class:"form-control" }}

As an aside, it's not recommended to use a relative url like '../../../orders'. It would be better to use reverse_lazy. For example, if the name of the URL pattern is orders, then you can use:
success_url = reverse_lazy('orders')