text:
Q: How many price types available in magento 2
*

*How many price types available in Magento 2.x.x

*How it can be loaded on the checkout page?

*What is the difference between group price and tier price in Magento 2

A: There are total of 6 types of prices available in Magento2 listed as below:

*

*Special Price

*Tier Price

*Grouped Price

*The minimum price of composite

*products Price range of composite products

*Manufacturer price (MSRP)

Magento represents these prices as price types (e.g. final price, minimum price, maximum price, regular price) and is separate from the actual price in the code. For example, Special Price is represented by the final price type in the code.
If you want this price values on checkout page then you need to write foreach loop code for each item added into the cart and then you can get its various kind prices for each individual item as below:
Get Simple Price values:
$finalPrice   = $item->getProduct()->getFinalPrice();
$regularPrice = $item->getProduct()->getPrice();
$specialPrice = $item->getProduct()->getSpecialPrice();

Get Group/Tier Price values:
First create block file to define getTierPrice() function:
namespace Namespace\TierPrice\Block;

use Magento\Catalog\Api\Data\ProductTierPriceInterface;
use Magento\Catalog\Api\ScopedProductTierPriceManagementInterface;

class TierPrice extends \Magento\Framework\View\Element\Template
{
    /**
     * @var ScopedProductTierPriceManagementInterface
     */
    private $tierPrice;

    public function __construct(
        ScopedProductTierPriceManagementInterface $tierPrice
    ) {
        $this->tierPrice = $tierPrice;
    }

    /**
     * Get Tier price by the customer group
     *
     * @return ProductTierPriceInterface[]
     */
    public function getTierPrice($sku, $customerGroupId=1)
    {
        return $this->tierPrice->getList($sku, $customerGroupId);
    }
}

Then you can get tier price value in its associated phtml file by calling block function as below:
$tierPrices = $block->getTierPrice($sku, $customerGroupId);

There is a very thin difference between the group prices and tier prices. Customer group prices are a component of tier pricing and are set up in a similar way. The only difference is that customer group prices have a quantity of 1.
I hope this helps you to understand the fundamentals of magento2 price types.
If you have any further query feel free to ask.
Happy to help!
Thanks.


text:
Q: Error on pip install boto3 I'm trying to run:
pip install boto3

But I'm getting this error:
DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
OSError: [Errno 1] Operation not permitted: '/tmp/pip-ueLGpf-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

A: Try
pip install --ignore-installed boto3

redpajama_set_name: RedPajamaStackExchange


text:
Q: PostgreSQL Transaction Isolation READ UNCOMMITTED I want to try transaction isolation using PostgreSQL with pgadmin. First I inserted a new record inside BEGIN but without COMMIT.
BEGIN;
INSERT INTO my_table(id,value) VALUES (1,'something');

//UNCOMMITTED

Then, I tried to read the uncommitted data
BEGIN TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SELECT * FROM my_table
COMMIT;

But I couldn't find the new record. What's wrong?

A: PostgreSQL does not support dirty reads (READ UNCOMMITTED). As @a_horse_with_no_name pointed out, the manual says:

The SQL standard defines one additional level, READ UNCOMMITTED. In PostgreSQL READ UNCOMMITTED is treated as READ COMMITTED.

This is fitting with the rule in the standard that the database must treat unsupported isolation levels as the strongest supported level.
There is no supported way to read uncommitted tuples from an in-progress transaction in PostgreSQL. If there was you'd be able to get things like duplicate values for primary keys and general chaos so it wouldn't be very useful anyway.
There are a few ways in-progress transactions can communicate and affect each other:

*

*Via a shared client application (of course)

*SEQUENCE (and SERIAL) updates happen immediately, not at commit time

*advisory locking

*Normal row and table locking, but within the rules of READ COMMITTED visibility

*UNIQUE and EXCLUSION constraints

It's possible to see uncommitted tuple data using superuser-only debug facilities like pageinspect, but only if you really understand the innards of the datastore. It's suitable for data recovery and debugging only. You'll see multiple versions of data in a wall of hexadecimal output.

A: Lospejos, if you BEGIN a transaction and do an insert you can run a SELECT to see the rows because you are inside your transaction, other people can´t see this row. But if you issue another BEGIN it is another transaction, so don´t do it, just do (BEGIN, INSERT, SELECT, COMMIT). If you select your row and notice it is wrong do ROLLBACK in order to discard this row. The fact that Postgress don´t accept UNCOMMITED READ is a pity. I use this in DB2 and Teradata for instance. Specially if you want to see what other transaction is doing in a table without waiting it to COMMIT.


text:
Q: Even with /Zf, not all names are in MAP file I'm building a project for Wintel-32 with Visual Studio's MASM (it's called ML). I request map file generation in linker options. I'm specifying the /Zf option for the assembler (make all symbols global). Yet not all functions appear in the generated map file. Looks like only ones that are imported by other modules appear.
EDIT: there's a bunch of functions that are used only statically (i. e. within the same source file). They are not eliminated from the executable and they shouldn't be. But they don't appear in the MAP file. I want them there.
Those names can be seen if I call dumpbin /symbols on the object file (but only with the /Zf). Yet linker strips it from the final executable's map for some reason. The linker options /MAP and /MAPINFO:EXPORTS are there. What am I missing?
EDIT: and /OPT:NOREF too.

A: Probably the following options are enabled in your project.
- COMDAT generation i.e. Function-Level Linking during compilation.
- /OPT=NOREF linker optimization during linking.
Both the above options tell the compiler/linker to discard unused functions.
For example, update the command invoking the MASM linker ML, with the /OPT linker option as follows to retain even unused functions in the final executable:
ML [you-options] <your-file-name>/link /OPT:REF


text:
Q: How to handle a Promise call to Firestore and call agent.add() I am trying to make a call to a Cloud Firestore Beta from DialogFlow inline editor and then call agent.add(...) and I don't understand what I need to do to make it work.  The call on its own works great and I am getting the correct values however the execution continues and the Promise even after returning does not continue to execute the agent.add() part.  Here is my code:
function foodcatHandler(agent){
  if (request.body.queryResult.allRequiredParamsPresent === true) {
    var foodIDsRef = firestore.collection('foodcats').doc('foodIDs');
    var category = request.body.queryResult.parameters['category-codes'];
    console.log(category);
    var catVal;
    foodIDsRef.get().then( doc => {
        console.log("Promise returned");
        catVal = doc.get(category);
        agent.add("Sounds like a plan");
        agent.add("Here are all the restaurants serving " + category + " in your area.");
        agent.add(new Card({
            title: `Foody`,
            text: `The easiest way to order is now even simpler!!`,
            buttonText: 'Order Now!',
            buttonUrl: 'https://beta.foody.com.cy/' + pcode + '?categories=' + catVal
            })
        );
    });
  }

}
The part that does not work is the agent.add() statements.  The console outputs some times work and others not.  Can someone help me to resolve this?
After researching a bit online I found the solution which is the following:
return foodIDsRef.get().then( doc => ...

Apparently you need to return the promise and that will allow the agent to continue the dialog.

A: The solution is that you need to return a Promise back.  That is at the point where the call to the DB is made just use the return keyword.


text:
Q: How to send a dictionary parameter to a URL.Action() in asp.net MVC3 Say I have a action method.......
public ActionResult DisplayXml(int viewId, Dictionary<string,string> parameter, string dataFormat )
        {
            string xml = "";
            return Content(xml, "text/xml");
        }

and in view I did.......
<iframe title="Xml" class="ResultDisplay"
        src = "@Url.Action("DisplayXml", "OutputData", new {viewId = Model.ViewId, parameter = Model.Parameter, dataFormat = Model.DataFormat })">
</iframe>

Here parameter is a dictionary and I am getting null.
How I can send it?????

A: You're trying to pass and arbitrary dictionary as a parameter in a querystring?
Its a pretty unusual requirement to need to serialize the contents of a dictionary to a query string parameter and back again. When generating querystring parameters, MVC will just call .ToString() on the values, and the Dictionary<,> object just uses the default implementation (which returns it's type)
Since this requirement is so uncommon, there's nothing built in to do this.. You can quite easily serialize the dictionary yourself to a string (perhaps json?) and then, change the parameter variable in your action to be a string. You'll have to deserialize the value back to a dictionary after that.
Before I provide much more of an example, I want to check you're absolutely sure this is what you want to do
Update:
Here is way of doing that (requires json.net):
    public ActionResult DisplayXml(int viewId, string parameterJson, string dataFormat )
    {
        var parameter = JsonConvert.DeserializeObject<Dictionary<string,string>>(parameterJson);

        string xml = "";
        return Content(xml, "text/xml");
    }

And use:
<iframe title="Xml" class="ResultDisplay"
        src = "@Url.Action("DisplayXml", "OutputData", new {viewId = Model.ViewId, parameterJson = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Parameter), dataFormat = Model.DataFormat })">
</iframe>


text:
Q: i7 laptop automatic overheat shut-down? I am using Asus N82JQ laptop with i7-720QM, 4GB RAM, 1GB nVidia GT335 and 5400rpm HDD. I am using cooling pad under the laptop. I live in Greece, where the temperature of the air is easily around 40`C. Previously I was using Win 7 Home Premium. Laptop has always been warm on the top and from time to time the fans were like turbines of an Airbus, but it was working fine.
Recently I installed new Win 7 Ultimate. It was a clean install from original Win 7 DVD, not from factory recovery CD, which is full of bloat-ware.
I am using the same programs as before, however the computer is overheating:

*

*it is extremely hot on the top,

*around the fan one cannot touch it,

*when watching video, I am experiencing problems. Video freezes for moments, sound is cracking,

*fans are working all the time on 100%  even though they should work so only for 45sec, then they should slow down,

*last few days the computer even shut-down while watching on-line movies. The case has been so hot, that I could not rest my palms on the laptop.

I cannot open the case, because I will loose the guarantee, so I cannot clean the dust from inside.
What are the possibilities to correct this? It should be a software problem, because with previous Win7HP the computer was working fine.
I am not a computer expert, but hopefully I can follow advice if it will be given.

A: Have you installed your drivers from Windows update or from the OEM? Check your Power Plan, you might wanna try setting the maximum processor speed from the default 100% to lower (happened to me, I can only reach 80% without overheating)
As for the dust, you can try those gas-duster, no need to actually open your case

A: I've never been in your situation, but here are a few things I've came up with:

*

*install an additional CPU fan

*make sure that the cooling pad layout 'fits' the layout of the back of your laptop (see where the holes, through which the air flows, are)

*install SpeedFan and monitor the temperature of your CPU / GPU / HDD. SpeedFan has an option to run a specified program when a temperature on a certain device reachex x degrees Celcius (Configuration: Events).
//those advices apply only if the cause is the overheating.

A: I have the very same Asus machine as you and am encountering exactly the same problem, just as you described it. Something to do with the display adapter is my suspicion. Like you I live in a very hot country (Borneo, Malaysia 4 degrees from the equator). I think the layout on the motherboard might be responsible as All those hot components are very close together. I am a graphics designer and media consultant and when I use video or graphical software, or even view graphically intense video material through the internet, this power failure is most likely to occur. I have tried many solutions but nothing works so far. Technicians have checked every component on the laptop and can find nothing wrong. The power failure is not very often, and very intermittent. But my view is that it should NEVER happen. I have lost files for clients I was working on because of this and had to redo the work. Have you checked your battery? I recently replaced the battery and the instances of failure greatly reduced. I think batteries wear out sooner on this machine due to the heat. It runs much hotter than my other laptop (Sony Vaio).

A: It is possible that your thermal compound is dry, try to change it. You can go to a computer service, or you can guide yourself from youtube videos to learn how to dissasembly your laptop.
Also try to clean the dust from intake and outake vents of your laptop. The use of cooling pads is not always a successful solution because the fans dont match with intake laptop vents, you can try Cooler Master NotePal U3 because fans can be placed anywhere on the cooling pad.


text:
Q: Truly random numbers I have two questions here:

*

*Please explain me the meaning of truly random number. I Read many articles but I was not able to understand the meaning.

*Please explain me the code behind Rand() function in any language preferably c++

A: *

*A truly random number is such that was determined by a physically random event (unpredictable events in nature). e.g. (radioactive decay of an atom, atmospheric noise, etc). The reason this is such is because the computer does not have the capability of being truly random on its own, however, nature is. So if the computer measures some random value in nature then the number is "truly random," but pseudo  is where the computer generates a seed (C++ uses time to generate seed) and the random number appears to be random, but could be predicted.

"The computer uses a function to calculate random numbers. That means: having the same seed, we get the same row of random numbers every time. Therefore pseudo random numbers." – Ralph M. Rickenbach

*C++ uses time, number of seconds since midnight Jan 1, 1970. So when you tell the computer to produce a random number it takes the number of seconds since Jan 1, 1970 (a very large number, the seed), sends it through an algorithm, and then chops it up accordingly to satisfy the range you specified.

This causes the computer to read its clock to obtain the value for the seed automatically.
  Function time returns the number of seconds that have passed since midnight on January 1, 1970. This value is converted to an unsigned integer and used as the seed to the random number generator.

This is of course a simplification, more can be read online. Below are references.
References:
Truly random
c++ docs

A: A short summary:
A true random number is a number you cannot calculate under any circumstances that is generated by some event, while a random number calculated by the Rand() function is calculated.
There are multiple ways to calculate such a number, some being more complex than others.
See this question for more details on how it works in (objective- in this case) C.


text:
Q: VisualSFM install mac issue Installing VisualSFM on mac with the Dan Monaghan installer and halfway through the build I get an error that reads:

libsiftgpu.so failed to build. Halting.

What caused this and how do I fix it?

A: Googling found many with similar issues, was able to combine pieces from different solutions and get it working.

Why the error occurs:

The program tries to build & install a siftgpu function on line 246 of the vsfm_os_x_installer.sh file.

But that link is dead.

Step 1:
Manually insert a sift_gpu.zip file into your /users/USERNAME/ directory.

Step 2:
After the sift_gpu.zip file is in your users/USERNAME directory, Ninorian changed the following lines (in the vsfm_os_x_installer.sh file) and it worked for me too:

Search for :  sed -i '' Replace with: sed -i

Step 3:
The sift_gpu.zip file opens a directory called SiftGPU-master, and we need to change the name to SiftGPU, so add this line above line 262 like this:

(line 261) mv SiftGPU-master SiftGPU

(line 262) cd SiftGPU

Step 4:
I got this far, but kept getting errors that said "file or directory not found", and this was remedied by changing the file extension on line 356 in the vsfm_os_x_installer.sh file* (hat-tip to this Github build issue support ticket)

From this:

cp ../patches/SparseBundleCPU.patch src/pba/

To this:

cp -R  /users/USERNAME/downloads/VisualSFM_OS_X_Installer-master/patches/SparseBundleCPU.patch src/pba

After that, everything finished installing smoothly,
But I couldn't run it yet.

Step 5:

This 5-minute VisualSFM Mac install YouTube tutorial helped.
Here are the steps:

*

*You need to add 2 scripts to your ~/.bash_profile, go into terminal and type: nano ~/.bash_profile and then paste those two scripts at the bottom of that file.

*Save and close ~/.bash_profile

*Then go into the /users/USERNAME/vsfm/bin folder and copy libpa.so AND libsiftgpu.so and paste them into your /users/USERNAME/ directory.

*Create a new folder in /users/vsfm directory called /users/vsfm/sift

*Move the SiftGPU folder from your users/USERNAME/ directory into your /users/vsfm/sift directory

From there, go to users/USERNAME/vsfm/bin/ and double-click on VisualSFM, and if all went well the program should start running and open up, ready for use.

This was a pain in the ass to troubleshoot but it's over and done and I hope this helps anybody.


text:
Q: In Appcelerator Studio, how do I create new scopes? I've used Sublime Text for a few years, and its theming is based on TextMate, which Appcelerator Studio says its theming is also based on. In ST3, you build a syntax-highlighting theme in a .tmTheme file and you extend the pool of scope definitions in a .tmLanguage file.
I'd like to use the same syntax highlighting in both programs, but I can't find out how to get Appcelerator Studio to see the same scopes as ST3.
Can someone point me to information that would help me solve this dilemma?


text:
Q: How to open binary files in r Can anyone help me how to open little endian and big endian binary files in r. or any code in r to covert binary files in to geotiff.
library(ggplot2)
library(viridis)
library(viridisLite)
library(digest)
library(raster)
file("D:/dddd/binary/CMORPH+MWCOMB_DAILY-025DEG_20170301", "rb")
ls(zz)
ls()
column.names=readBin(zz, character(), n=10)
column.names
varnames = readBin(zz, character(), n=4)
varnames
datavals = readBin(zz, integer(), size = 4, n = 600, endian = "little")
readvals = datavals[1:200]
writevals = datavals[201:400]
mathvals = datavals[401:600]
rdata = cbind(readvals, writevals, mathvals)
colnames(rdata) = varnames


text:
Q: MySQL datetime format I am creating a registration page in HTML, PHP, and MySQL. I want to add a hidden field in the registration to be used as join date.
Is it better to have the hidden field containing the current date and time or assigning a variable the current datetime and using that in the SQL insert statement instead?
Anyways, if the following hidden form field is used, what would the date format be to store the datetime as 2010-07-06 07:55:12?
<input name="joindate" type="hidden" id="joindate"  value="<?php echo date(''); ?>">

A: Try
 echo date('Y-m-d g:i:s',time()); //PHP

Our Better MySQL use datetime filed and call `NOW()
 INSERT INTO registration (Name,Date) VALUES ('Jarlsberg Cheese',NOW()) ;

In your SQL Statements
I hope this helps

A: Don't use a hidden field, assign a variable to the current date/time (or use the NOW() function in MySQL) and use that as the join date.
The reason being that someone could easily use a tool like Firebug to edit that hidden join date field and put a value you didn't intend into your database.

A: You can even do it in SQL: insert into user (...,joindate) values (...,NOW());
That way you don't have to fiddle with formatting..
Edit: But if you don't like this, there is no point in passing this value to the client and back. Just set it when you create your insert query. Using the hidden field you are risking that someone actually changes your value and sets it to something unexpected..

A: The date format that you have mentioned is a valid MySQL datetime. In PHP you can echo it like this:
date('Y-m-d H:i:s')

Or, with your example:
<input name="joindate" type="hidden" id="joindate"  value="<?php echo date('Y-m-d H:i:s'); ?>">

A: In line with Eric Petroelje:
Create a field with the Type timestamp and set as Default value CURRENT_TIMESTAMP. Then you don't even have to mention this field in your insert-statement. It just inserts the time and date of the insert.
Simple. :)

A: Yes, you can create a column in your database table either with TIMESTAMP, DATETIME or even VARCHAR datatypes and insert into it the date and time using the now() function. It works just fine. Goodluck!!!
INSERT INTO table_name(Some_column,Date_column) VALUES ('Ephraim Tarfa',now()) ;


text:
Q: JAR file—nothings happens when I run it I'm trying to run a JAR file and nothing happens? Any idea why? Did I maybe do the export wrongly?
Some guidelines would be very welcome!
update
I sorted it!! Thanks for yr brainstorming anyway! I wasn't adding the file with the visual-material (gif-files). I think I added in the code a try-catch that check if there is any available map if there's not it'll shut down.

A: Jar files can only be executed if they contain a META-INF/MANIFEST.MF that specifies the main class (entry point) into your application. Otherwise you have to specify the class manually on the command line.
e.g. it contains
Main-Class: com.mycompany.App

Then you can just say:
java -jar MyApp.jar

Normally you would create a manifest.txt containing this line and package it in your jar like so:
jar cfm MyApp.jar Manifest.txt com/mycompany/*.class

Java 6 also implements a parameter on the jar tool which will create/modify the entry point in an existing jar's MANIFEST.MF if you prefer.
jar cfe MyApp.jar com.mycompany.App com/mycompany/App.class


text:
Q: Access an element in a vector of pairs by a key besides find_if() or iterators So i have a vector of pairs which contains another vector of pairs written like this (The same as a 2D vector but the 'int' serves somewhat like a key to the element):
struct Item
{
    string word = "";
    int count[3] = {0, 0, 0};
};

vector< pair<int, vector< pair<int, Item> > > > MyWords;

Currently, the way I access a unique element given the two integer keys is like this:
//Find the pair with a key == key1 in the main vector
auto it1 = find_if(MyWords.begin(), MyWords.end(),
           [](const pair<int, vector<pair<int, Item> > >& element){
               return element.first == key1;
           });

//Find the pair with a key == key2 in the vector that has a key == key1
auto it2 = find_if(it1 -> second.begin(), it1 -> second.end(),
           [](const pair<int, Item>& element){
               return element.first == key2;
           });

//Access the element using the returned iterator
it2 -> second.count[0] = A_Number_Here;

I'm trying to find a better way to access an element like using the keys like an index (The keys start from 0). Unfortunately, using [] results to a segmentation fault:
MyWords[key1].second[key2].second.count[0] = A_Number_Here;

Any other ideas? I know that there are other STL Containers like map and set but I'm currently trying to do it with a vector.
By the way, I would also like to ask what is the time complexity of find_if()?
Edit: The keys of the pairs may not be consecutive (0,1,2,3 ...)

A:
I'm trying to access an element by using the keys like an index.
  Unfortunately, I always receive a segmentation fault.
MyWords[key1].second[key2].second.count[0] = A_Number_Here;

Any other ideas?

First of all, its tedious to do such a vector-data structure. You should probably, re-think of data-structure requirements and should come up with something lighter. Secondly, There is nothing wrong in your way of accessing. Its correct. SEE THIS
Probably, you are providing wrong keys(key1 and key2) to access the vector content. One thing to note that, the key-pair that you introduced will not work as expected, since std::vector is not std::map.
When you do MyWords[key1]. and rest....., and for instance Key1 = 0, you are accesing the first element of the vector MyWords, where the first int could be any value.(not necessarily 0, as you mentioned you have an unsorted vector). I think you are assuming this to happens and trying some values greater than MyWords.size().
The solution to your problem is to either use the iterator based looping/ accessing, which will only show what you have got inside or stick with std::find_if, as it will return end of vector iterator, in case of key not being found inside.
#include <iostream>
#include <vector>
#include <algorithm>

struct Item
{
   std::string word;
   std::vector<int> count; // changed to vector array
};
using Pair = std::pair<int, std::vector< std::pair<int, Item> > >;

int main()
{
   std::vector< Pair > MyWords =
   {  //int, <std::pair<int,          Item            > > >
      {1   , {        {    4,  Item{"String1", {1,2,3}} } }       },
      {0   , {        {    5,  Item{"String2", {5,2,8}} } }       },
      {2   , {        {    8,  Item{"String3", {1,7,9}} }, {    9,  Item{"String4", {11,77,99}} } }       }
   };

   for(const auto& bigPair: MyWords)
   {
      std::cout << "Key : " << bigPair.first;

      for(const auto& smallPair: bigPair.second)
      {
         std::cout << "\nValues: " << smallPair.first << "\t";

         std::cout << smallPair.second.word << " "
                  << smallPair.second.count[0] << " "
                  << smallPair.second.count[1] << " "
                  << smallPair.second.count[2] ;
      }
      std::cout << "\n\n";
   }

   return 0;
}

I would also like to ask what is the time complexity of find_if()?

std::find_if can have an time complexity, up to linear in the distance between first and last iterator, according to the predicate you provide, which will search for each element until a match is found.
As an alter native you could use std::lower_bound with a custom lambda/ predicate(to only return when finds a match, otherwise it will also returns the iterator pointing to next greater element in the vector, if available) after you sorted the MyWords vector according to the first value(key). std::lower_bound has only time complexity of O(longn), which will be much faster than std::find_if.


text:
Q: Distribution of the product of a standard normal and uniform distribution Given that $X\sim N(0,1)$ and $Z\sim \operatorname{Unif}(\{\pm1\})$. Prove that $Y = XZ$ is a standard Gaussian distribution.
My approach:
I started trying to find the pdf of them. I found that:
$$f_Y(y)=\int_{-\infty}^\infty f_Z(z)f_X\left(\frac{y}{x}\right) \frac{1}{x} \, dx=\int_{-\infty}^\infty \frac{\exp(-\frac{(x/y)^2}{2})}{x\sqrt{2\pi}}\,dx$$
and I can't seem to find finish the calculation.
So I moved on to the MGF approach with:
$$M_{ZX}(t)=E[e^{zxt}] = \int_{-1}^{1}\int_{-\infty}^\infty \exp(zxt)\frac{\exp(-x^2/2)}{\sqrt{2\pi}}\frac{1}{2} \, dx \, dz = \frac{1}{2}\int_{-1}^{1}\exp(\frac{1}{2}(zt)^2) \, dz$$
and again, I can't finish it...
All of the answers seems to lead up to erfi functions...
edit: additional info: $Z$ and $X$ are independent of each other

A: Reading the text I understand that Z is a discrete rv taking the values $\pm1$ with probability $\frac{1}{2}$ so,
simply observe that $Y=-X\sim N(0;1)$ (it's trivial but you can derive the result with fundamental transformation theorem)
so $f_Z(z)=1/2\phi(z)+1/2\phi(z)=\phi(z)$


text:
Q: Dataframe: index values to compare I have a dataframe (below).
I would like to compare the two values in the index column.
The first index value is the value of the last index.
The second index value is the value of index based on condition criteria (index which corresponds to 1).
In other words, how do I have d2 in the same format as d1 (I would like d2 to be able to the value of index corresponding to 1)? (as afterwards I would like to calculate the numeric difference between d1 and d2)(Something like df1.index[-1]-df1.index[ ]).days = 3)
Thanks in advance
import pandas as pd
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-3-23', '2021-3-24', '2021-3-25', '2021-3-26'],
"x": ['nan', 1, 'nan', 'nan', 'nan' ]})
df1['date'] = pd.to_datetime(df1['date'])
df1.set_index('date', inplace=True)
df1

date         x
2021-03-22  nan
2021-03-23  1
2021-03-24  nan
2021-03-25  nan
2021-03-26  nan

d1 = df1.index[-1]
d1
Timestamp('2021-03-26 00:00:00')

d2=df1.x[df1.x == 1]
d2
date
2021-03-23    1
Name: x, dtype: object

(I would like to have d1-d2 =3)

PS In case, this is a followup question to Dataframe: index values difference calculation

A: # subtract the index (which are datetime) and take the difference as days
(df1.index[-1] - df1[df1.x == 1].index).days[0]

>>> 3


text:
Q: Making Polymer.dart elements appear, and using style with Polymer.dart I am on my first Dart project. I already managed to make working tabs.
But I am having trouble making my polymer element appear in the web browser.
The output should be a light grey ribbon, like in Office 2007+.
The only thing I can see is a 0x0px light grey vertical line.
If I use classic HTML and CSS (no templating) it works.
I don't understand what I am doing wrong.
Here is my HTML:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>CVWebkit</title>
        <link rel="stylesheet" type="text/css" href="CVWebkit.css" media="screen" />

          <polymer-element name="zone-ruban">
                <template>
                <link rel="stylesheet" type="text/css" href="./CVWebkit.css"/>

                  <template repeat="{{zone in zones}}">

                      <template repeat="{{fonction in fonctions}}">

                        {{fonction}}
                      </template>

                </template>

                </template>
              </polymer-element>

And here is my Dart code (cvwebkit.dart):
import 'dart:html';
import 'dart:async';
import 'packages/polymer/polymer.dart';
import 'packages/observe/observe.dart';

void main() {
  querySelectorAll(".onglet")..onClick.listen(ouvrirOnglet);
}

@CustomTag('zone-ruban')
class ZoneRuban extends PolymerElement with Observable {
  final List zones = toObservable(['navigation', 'composants', 'propcompo', 'utilisateur']);
  final  List fonctions = toObservable(['Navigation', 'Composants', 'Propriétés du composant', 'Données utilisateur']);
  ZoneRuban.created: super.created();
}

The CSS :
.ruban {
    background-color: transparent;
    top:0px;
    height: 100%;
    border-right: 1px solid grey;
    position: inherit;
}

#navigation{
    width:10%;
}

#composants{
    width:25%;
    left:10%;
}

#propcompo{
    width:40%;
    left:35%;
}

#utilisateur{
    width:25%;
    left:75%;
}

.titre_ruban {
    left:0%;
    width:100%;
    bottom:0px;
    position:inherit;
    text-align:center;
    color:gray;
    text-shadow : 0px -1px 1px #000 ;
    height:15%
}

.contenu_ruban {
    top:0px;
    height:85%;
    left:0px;
    width:100%;
    vertical-align:central;
    position:inherit;
}

.user_menu {
    display:none;
}

Any idea why the ribbon isn't appearing?

A: I guess you need something like
:host {
  display: block;
}

in your elements CSS.


text:
Q: Agenda jobs go to locked state and never run I'm using Agenda for job processing. I'm facing an issue with the locking mechanism. I don't know how it works.
If I define a job that is going to run at 12 AM then at 12 AM lockedAt updated with the current time and the job does not run.
I'm using PM2 for the production process manager.
I have initialized agenda like this:
let agenda = new Agenda({ db: { address: config.getDbConnectionString() }});


text:
Q: How to programmatically navigate the Schema View in Visual Studio 2008? I'm planning to develop an Add-in for Visual Studio 2008 that will allow me to programmatically create basic procedures for tables in a Database Project.
However I'm stuck in the very early stage because I can't find a way to programmatically navigate the schema view of the Database Project.
Does anyonw know how do I do it?

A: Are you referring to "VS Team System - Database Edition" projects? I came across this blog post the other day about using T4 templates with such a project.


text:
Q: Finding a subgraph which is k-connected Let $k > 2$ and let G be a graph with $|G| = n \geq 2k − 1$. Prove that if
$e(G) \geq (2k − 3)(n − k + 1) + 1$ then $G$ contains a subgraph $H$ such that $H$
is $k$-connected.
Note a graph $G$ is $k$-connected if
$1)$ $|G|\geq k+1$
$2)$ No set of at most $k-1$ vertices disconnects $G$
My idea is to remove the vertex of least degree at each step and use induction. However, in general, I don't feel comfortable with the definition of $k$-connectedness, so here goes:
The base case $k=3$ is trivial as then $G$ turns out to be $K_5$ and $K_5$ is $3$-connected (it is actually even $4$-connected)
For the inductive step (backward induction), we have that we can remove some edges (it will make the problem tougher) so that we can assume that $e(G)=(2k − 1)(n − k ) + 1$. Hence the minimal degree will be less than $\frac{2e(G)}{n}$
So after removing a vertex $v$ of minimal degree we have at least $((2k − 1)(n − k ) + 1)\frac{n-2}{n}$ edges
But then as $((2k − 1)(n − k) + 1)\frac{n-2}{n} \geq (2k − 3)(n − k + 1) + 1$
Hence in the graph with the vertex $v$ removed we have that we can find a $(k-1)$-connected graph.
I tried to then join this vertex of least degree to the found subgraph, but failed to finish the argument.
Would be very grateful if anyone could assist me and also if you could provide me with some insight on the $k$-connectedness

A: As is noted in the comments, your argument doesn't give a proper proof of the base case since if $k = 3$ you only know that $n \geq 5$ not that $n = 5$. In fact, as far as I can tell this really is a problem.
Because of this issue, I think it's simpler to use induction on $n$. So we fix $k > 2$ and first let $n = 2k-1$.
As you noted, we can assume without loss of generality that $e(G) = (2k-3)(n-k+1)+1 = k(2k-3) + 1 = \frac{(2k-1)(2k-2)}{2} = \binom{n}{2}$. So $G = K_n \supseteq K_{k+1}$ and hence $G$ certainly has a $k$-connected subgraph.
Now, for the induction step, suppose the claim holds for all graphs $G$ with $|G| = n \geq 2k-1$ and consider the case $|G| = n+1$. If $G$ has a vertex of degree less than $2k-3$ then we can apply the induction hypothesis to the graph obtained by removing this vertex from $G$. So we just want to show that there is such a vertex. For a contradiction, suppose instead that $\delta(G) > 2k-3$ and $G$ has no $k$-connected subgraph.
In particular, $G$ is itself not $k$-connected so, by Menger's theorem, we can find $X \subseteq G$ such that $|X|<k$ and $G \setminus X$ has two components whose vertex sets are $V_1$ and $V_2$ respectively. Let $G_i = G[V_i \cup X]$ be the graph with vertex set $V_i \cup X$ whose edges are the ones appearing between the relevant vertices in $G$.
If $v \in V_i$, then $v$ has at least $2k-2$ neighbours in $G_i$ and hence $|G_i| \geq 2k-1$. Hence, we can apply the induction hypothesis to $G_i$. If $G_i$ contains a $k$-connected subgraph so does $G$ and we are done. Otherwise, by the induction hypothesis, $e(G_i) \leq (2k-3)(|G_i| - k + 1)$.
Notice that every edge of $G$ appears in at least one of the $G_i$ so this leads us to
\begin{align*}
e(G) \leq& e(G_1) + e(G_2) \\
\leq& (2k-3)(|G_1| + |G_2| - 2k + 2)
\end{align*}
Now $|G_1 \cap G_2| = |X| \leq k-1$ so $|G_1| + |G_2| = |G| + |G_1 \cap G_2| \leq n + k - 1$. All in all we then have,
$$e(G) \leq (2k-3)(n-k+1).$$
This contradicts our original assumption, so $G$ must have a vertex of degree at most $2k-3$ and we are done.


text:
Q: Proper class inheritence in css? I'm getting confused with class inheritance for css. I have this:

sometimes I want to change the color and class name of a li element, right now I'm doing this:
#grok li, .red {
  background-color: red;
  margin: 5px;
  padding: 5px;
  cursor: hand;
  cursor: pointer;
  text-align: left;
}

#grok li.green {
  background-color: green;
  margin: 5px;
  padding: 5px;
  cursor: hand;
  cursor: pointer;
}

#grok li.blue {
  background-color: blue;
  margin: 5px;
  padding: 5px;
  cursor: hand;
  cursor: pointer;
}

in other words, all the definitions are the same except for their color. Can I compact it into something like this:
#grok li {
  background-color: white;
  margin: 5px;
  padding: 5px;
  cursor: hand;
  cursor: pointer;
  text-align: left;
}

#grok li.red {
  background-color: red;
}

#grok li.green {
  background-color: green;
}

#grok li.blue {
  background-color: blue;
}

? That would be a lot more pleasant to work with. My only requirement is that I be able to find an element in my ul item by class name, so when I'm using jquery with this, I need to be able to find an element with class name 'li.blue' etc (otherwise I wouldn't need these separate classes).
Thanks

A: Yes, you can. The latter rules are more specific than the initial, so they will override it.
AFAIK you don't need cursor:hand anymore.


text:
Q: Multi Array Counting values of sub-arrays I have multi-dimensional array:
$array = array(
array(
"id" => 1,
"value" => 100
),
array(
"id" => 1,
"value" => 200
),
array(
"id" => 1,
"value" => 300
),
array(
"id" => 2,
"value" => 2
),
array(
"id" => 2,
"value" => 5
),
array(
"id" => 3,
"value" => 10.50
),
);

I need to get new multi-dimensional array, like this:
$newArray = array(
array(
"id" => "1",
"sum_of_values" => 600
),
array(
"id" => 2,
"sum_of_values" => 7
),
array(
"id" => 3,
"sum_of_values" => 10.50
),
);

I mean, key [sum_of_values] should counts values in sub-arrays with the same key [id].
I've tried this:
$cnt = count($array);

            $finalArray = array();
            $tempArray = array();
            for($i = 0; $i < $cnt; $i++){
                if($array[$i]["id"] == $array[$i++]["id"]){

                    $search = $array[$i]["id"];
                    $column = "value";

                    $sum = array_sum(
                                    array_map(
                                        function($data) use ($column) {
                                            return $data[$column];
                                        },
                                    array_filter(
                                        $array,
                                        function($data) use ($search) {
                                            return fnmatch($search, $data["id"]);
                                        }
                                    )
                                    )
                    );

                    $tempArray = array(
                        "id" => $array[$i]["id"],
                        "sum_of_values" => $sum
                        );

                    $finalArray[] = $tempArray;

                    } else {
                        $tempArray = array(
                            "id" => $array[$i]["id"],
                            "sum_of_values" => $array[$i]["value"]
                            );
                        }
            }

And it works, it counts values of sub-arrays with same [id]. But the problem is not returning sub-arrays, key [id] of which doesn't have same examples. In my case - sub-array with [id] = 3 will not return. Also, sub-arrays with [id] = 1 and [id] = 2 will repeat [n-n/2] times.
I think, that problem is in using cycle - for ($i = 0; $i < $cnt; $i++) and condition if ($array[$i]["id"] == $array[$i++]["id"]), because it looks stupid, but i can't find anything else.

A: Your function seems too complicated. How about this?
$result = array();
foreach ($array as $item) {
    if (!empty($result[$item['id']]))
        $result[$item['id']]['sum_of_values'] += $item['value'];
    else
        $result[$item['id']] = array(
            'id' => $item['id'],
            'sum_of_values' => $item['value']
        );
}

If you print_r($result) you get:
 Array
(
    [1] => Array
        (
            [id] => 1
            [sum_of_values] => 600
        )

    [2] => Array
        (
            [id] => 2
            [sum_of_values] => 7
        )

    [3] => Array
        (
            [id] => 3
            [sum_of_values] => 10.5
        )

)

A: Just as an alternative: this is a sitter for array_reduce():
$totals = array_reduce($array, function($reduction, $current){
    $id = $current["id"];
    if (empty($reduction[$id])){
        $reduction[$id] = ["id"=>$id, "sum_of_values"=>0];
    }
    $reduction[$id]["sum_of_values"] += $current["value"];
    return $reduction;
}, []);

I prefer this sort of approach to generic looping/processing: I think it's a bit cleaner. But mileage varies, obviously.


text:
Q: .width() not working in jQuery I want to do something like this in JQuery
if($(this).width() < 400px){
      //do something
}

But it didnt work like that....mhm how is it correct?

A: width() returns a plain number, and even if not your code would have an undefined symbol since 400px is not in quotes - instead use it like this:
if($(this).width() < 400){
      //do something
}


text:
Q: How can i change date format(sed command) I have log file, and here is output:
2014109 13:42:17;10.8.0.6;/home/spy/www/index.html;13

yearmonthday
I need to change date format -> 2014109 to 20141009.
I change Oct format to 10, using sed:
sed -i 's/Oct/10/g;

How can i use sed for day format?

A: If the first field is only 7 digits, insert a zero before the last digit:
sed -r -i 's/^([0-9]{6})([0-9])\b/\10\2/'


text:
Q: Please Help with Syncing 2 Linear Actuators I am a complete noob in regards to electrical wiring and scoured countless hours on the internet for help. I bought 2 DC12V 16inch Stroke Linear Actuators and connected it with a 20 AMP 12V - DC Motor Rocker Switch (dpdt?) and a 12V 6A AC DC power supply. The purpose was for a standing desk. It works really well but i noticed that it's not synced (i am aware that it's not possible to get it perfectly synced).

I read online that i am able to buy a DC speed controller to control the speed so I bought a 12V-40V 10A PWM DC Motor Speed Controller but it did not fix the issue. I wired the power supply directly into the speed controller P+/- and connected a wire from the dpdt that previously used to connect the power supply to the M+/- slot in the speed controller. Is it possible if I just buy an additional speed controller and connect a linear actuator to each controller in the M+/- slot and then plug the power supply where the linear actuators were previously plugged in the dpdt? For P +/-, i would introduce new wires for each controller and then crimp the wires together (- to -, + to +) and plug it to the dpdt to try and control each actuator separately. Do I need to use a relay? I'm confused as how to wire that together if necessary.
Sorry if this is very confusing as I don't know the correct way to explain it.
Thanks in advance!

A: For your application it would be advisable to use 2 such linear actuators with a dedicated controller and with position feedback for synchronized operation.
Since you have already purchased 2 actuators (without position feedback) and also a separate speed control unit, you would need to carry out the following:

*

*Run both actuators at the same voltage for the same period and check the difference in travel.

*Run the faster one through the speed control unit to reduce it's speed to match. Make a mark on this actuator to confirm that that's the one to be used with the speed control unit after final assembly.

*Assemble, check for synchronized movement, and fine tune if necessary.

*Always ensure that the desk is uniformly loaded.
Here's the schematic.

A: Here is a way to add feedback to each linear actuator.
The red rectangle is the movable portion of the desk.
The green circle is a code disk that is attached to a fixed part of the desk.
The blue line is a string or fishing line that is attached to the movable portion of the desk and is looped around the code disk assembly.
As the desk rises, or lowers, the code disk spins.
The string and pulley on code disk could be replaced by a rack and pinion gear assembly.

edit: silly me ... all you need is a tilt sensor, not position feedback


text:
Q: using metatags gem - need to create different tags for each category I'm using the metatags gem - https://github.com/kpumuk/meta-tags
When it's just adding metatags to the categories pages I can do this and it works:
  def show

    @page_title = 'x'
    @page_description = 'x'
    @page_keywords = 'x'

    if params[:city_id]
      @city = City.friendly.find(params[:city_id])
      @category = Category.friendly.find(params[:id])
      @suppliers = Supplier.for_city_and_category(@city, @category)
                            .order_by_rating.includes(:reviews)
      @review_count = 0
      @suppliers.each { |supplier| @review_count += supplier.reviews.visible.count }
    else
      @category = Category.friendly.find(params[:id])
      @suppliers = @category.suppliers.order_by_rating.includes(:reviews)
      @review_count = 0
      @suppliers.each { |supplier| @review_count += supplier.reviews.visible.count }

      render 'categories/show_all'
    end
  end

However, there are different categories, and I'd like to use different metatags depending on the category. I've tried:
  def show

    if Category.name == 'Cars'
      @page_title = 'x'
      @page_description = 'x'
      @page_keywords = 'x'
    end

    if params[:city_id]
      @city = City.friendly.find(params[:city_id])
      @category = Category.friendly.find(params[:id])
      @suppliers = Supplier.for_city_and_category(@city, @category)
                            .order_by_rating.includes(:reviews)
      @review_count = 0
      @suppliers.each { |supplier| @review_count += supplier.reviews.visible.count }
    else
      @category = Category.friendly.find(params[:id])
      @suppliers = @category.suppliers.order_by_rating.includes(:reviews)
      @review_count = 0
      @suppliers.each { |supplier| @review_count += supplier.reviews.visible.count }

      render 'categories/show_all'
    end
  end

...but it isn't right. I'm not sure how to correctly allocate metatags to individual categories....

A: Show
I think you've got your show action confused:
def show

    if Category.name == 'Cars'

This will never yield the result you want, as the class Category has no instantiated state. Only when you have an instance of the class will you be able to call the .name method:
def show
   @category = Category.find params[:id]

   if @category.name == "cars"
      ...
   end
end

--
Meta
I would do this:
#app/controllers/categories_controller.rb
Class CategoriesController < ApplicationController
   after_action :set_tags

   def show
      @category = Category.find params[:id]
      @page_title = @category.name
   end

   private

   def set_tags
      set_title_tag @page_title
   end
end

If you wanted to manually set the tags depending on what was returned from the db, you could do this:
#app/controllers/categories_controller.rb
Class CategoriesController < ApplicationController
   def show
      @category = Category.find params[:id]
      case @category
         when "car"
            @page_title = "x"
         when "not car"
            @page_title = "y"
      end
   end
end


text:
Q: PHP/Apache runs as which user on Ubuntu Server I have a PHP script (in /var/www) that is supposed to write down the logs of operation in a file deploy.log (also in /var/www) and perform operations on a file situated in other directories of the system (Like /home/<user>/repo/my-repo.git and /srv/pr). However, it is not doing so currently. When I change the permission of my log file to 777, the PHP is able to write it to that file. For obvious reasons, I'm unable to keep the permissions at 777.
I read somewhere that the files you wish to operate on should have the same permissions as the user that runs the PHP files. So how do I find out PHP runs under which user? If that's not the correct approach, how can this be resolved?
I'm using Ubuntu 14.x on Amazon EC2.
I also tried setting sudo chown -R ubuntu:ubuntu /var/www for the entire www folder but my PHP script still doesn't write to the log file.

A: The user that runs apache/php is www-data.
Run sudo chown -R www-data:www-data /var/www/deploy.log to make the file editable by the web server.
The other files you want to perform operations on also need to be writable by the webserver.


text:
Q: Timestamp conversion to EPOCH time in Oracle SQL I have input date as a column in table "22/03/2022 06:59:59"
I need to convert into EPOCH time -
Expected output- "1647932399"  timezone(jakarta, Indonesia)
reference link- https://www.epochconverter.com/
time zone of input data is - UTC +7:00(Jakarta)
Tried with this-SQL CODE
SELECT (CAST(SYS_EXTRACT_UTC(to_timestamp('22/03/2022 06:59:59','dd/mm/yyyy HH:MI:SS' )) AS DATE) - TO_DATE('01/01/1970','DD/MM/YYYY')) * 24 * 60 * 60 FROM DUAL;

Result displayed is 1647907199
But didn't get the expected output

A: 1647932399 is the epoch for 2022-03-22 06:59:59 UTC. Your start time is 22-03-22 06:59:59 Asia/Jakarta, which is 22-03-21 23:59:59 UTC, and the epoch for that is 1647907199 - which is what you're getting. So your result is correct; but risky.
You are relying on implicit conversion.
to_timestamp('22/03/2022 06:59:59','dd/mm/yyyy HH:MI:SS') gives you a plain timestamp, with no time zone information. When you then do SYS_EXTRACT_UTC(...) the plain timestamp is implicitly converted to a timestamp with time zone using your session time zone - which happens to be Jakarta, it seems. So it works - for you, in this session. If you change your session time zone, or more likely if someone else runs the same code from a session with a different time zone, then the reslut will be different.
To be more explicit, you can convert your string to a plain timestamp, then declare that it represents a Jakarta time, and then convert that to UTC:
sys_extract_utc(from_tz(to_timestamp('22/03/2022 06:59:59', 'DD/MM/YYYY HH24:MI:SS'), 'Asia/Jakarta'))

21-MAR-22 23.59.59.000000000 UTC

There are then basically two ways to convert that to an epoch number; either cast it to a date, subtract 1970-01-01 as a date, and manipulate the resulting number of days (as in your question):
select
  round(
    (
      cast(
        sys_extract_utc(from_tz(to_timestamp('22/03/2022 06:59:59', 'DD/MM/YYYY HH24:MI:SS'), 'Asia/Jakarta'))
          as date)
        - date '1970-01-01'
     ) * 24 * 60 * 60
  ) as result
from dual;

1647907199

Or leave it as a timestamp, subtract 1970-01-01 as a timestamp, and manipulate the resulting interval:
select
  (extract(day from diff) * 24 * 60 * 60)
  + (extract(hour from diff) * 60 * 60)
  + (extract(minute from diff) * 60)
  + extract(second from diff)
  as result
from (
  select sys_extract_utc(from_tz(to_timestamp('22/03/2022 06:59:59', 'DD/MM/YYYY HH24:MI:SS'), 'Asia/Jakarta'))
    - timestamp '1970-01-01 00:00:00' as diff
  from dual
);

1647907199

Note that either way you can easily get the short result that was the basis for your previous question, by truncating the number or extracting just the days, without explicitly subtracting the 23:59:59 part. Either gives you 19072.
db<>fiddle


text:
Q: Scala Spark. Create object with default value by DataType I have a list of org.apache.spark.sql.types.DataType objects, say,
val tps = [FloatType, LongType, FloatType, DoubleType],
which I receive from dataframe like this:
val tps = dataFrame.schema
      .filter(f => f.dataType.isInstanceOf[NumericType])
      .map(f => f.dataType)

and for every type in this list I need to create an object of the corresponding type with default value:
[0.0, 0l, 0.0, 0.0].
How can I do that?
I tried doing
tps.map(t => t.getClass.newInstance())

, but it didn't work out, because private members (can not access a member of class org.apache.spark.sql.types.LongType$ with modifiers "private"), and because this statement tries to create objects of DataType, and I need objects of the corresponding types for them.
I'm fairly new to scala, can someone help?

A: I have for testing purposes something like this
object RowSampleMaker {

  var makerRunNumber = 1

  def apply(schema: StructType): Row = new GenericRowWithSchema(schema.map(field => {
      makerRunNumber += 1
      field.dataType match {
        case ShortType => makerRunNumber.toShort
        case IntegerType => makerRunNumber
        case LongType => makerRunNumber.toLong
        case FloatType => makerRunNumber.toFloat
        case DecimalType() => d(makerRunNumber)
        case DateType => new Date(System.currentTimeMillis)
        case TimestampType => new Timestamp(System.currentTimeMillis)
        case StringType => s"arbitrary-$makerRunNumber"
        case BooleanType => false
        case StructType(fields) => apply(StructType(fields))
        case t => throw new Exception(s"Maker doesn't support generating $t")
      }
    }).toArray, schema)

  implicit class RowManipulation(row: Row) {

    def update(fieldName: String, value: Any): Row = new GenericRowWithSchema(
      row.toSeq.updated(row.fieldIndex(fieldName), value).toArray,
      row.schema
    )
  }
}

You can add types, and replace the randomness for 0. Or have another method call .zero which returns all neutral values.
The update method on the implicit class is because I generally update a couple of the values for the purpose of testing.
You'd call RowSampleMaker(schema).update("field1", value1).update("field2", value2)
For each row you want to generate and then create a dataframe off that

A: I followed hints from @fd8s0's answer, and this is what I came up with:
  def mapToDefault(dataType: DataType): Number = {
    val defaultVal = 0.0
    dataType match {
      case ShortType => defaultVal.toShort
      case IntegerType => defaultVal.toInt
      case LongType => defaultVal.toLong
      case FloatType => defaultVal.toFloat
      case DoubleType => defaultVal.toDouble
      case t => null
    }
  }

...

val defaultValues = dataFrame.schema
    .filter(f => f.dataType.isInstanceOf[NumericType])
    .map(column => mapToDefault(column.dataType))

Thus, mapToDefault method will do the job of creating instance of given DataType with default value (for numeric types only, in my case).


text:
Q: The GET method is not supported for this route. Supported methods: POST after submitting form All the get request are working well but when I try to login through form with post request then it's not working and getting "The GET method is not supported for this route. Supported methods: POST." error.SSL is also implemented to the site using Let's Encrypt.
Below is login form
<form method="post" action="{{route('login-action')}}">
    {{csrf_field()}}

Login Form

        <input type="email"  name="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" placeholder="Email" value="{{old('email')}}" autofocus required />

        @if ($errors->has('email'))

                            {{ $errors->first('email') }}

        @endif

        <input type="password" name="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" placeholder="Password" required  />

        @if ($errors->has('password'))

                            {{ $errors->first('password') }}

        @endif

        <button type="submit" class="btn btn-default submit" style="background: #F1931B;">login</button>

</form>

Route is below
Route::post('/login-action','adminController@login_action')->name('login-action');


text:
Q: how we can use variables, which are described inside the loop, out side the loop in python Below is my code. Here, I am trying to read the variable gobs(x) from an input file and then I want to use it for other calculations, eg., computing error(x). But, I found, I can read it from input file properly within the loop, but when trying to use it outside the loop, only the first data is getting transferred. For all 100 data, which I read as gobs(x) inside the loop, it is showing the value of last data only, when I am using it outside the loop.
code started below
constant = 99

x0=50

z0=5

def gsyn (x):

     return (constant*z0)/(z0**2+(x-x0)**2)

with open ('Grav_H_Cyln_v3_output.txt') as finp:

    lines=finp.readlines()

    for line in lines:
        g=float(line)
        x=line
    def gobs (x):
        return g
    print (gobs(x)) # here, gobs(x) is printing properly

def error(x):

    return (gsyn(x)-gobs(x))

for i in range (1, 100, 1):

    x=i

print (error(x)) # here, only the first value of gobs(x) is coming

print ('stop')

A: This seems like a very odd solution to what is fundamentally a very simple problem. Make gobs a dictionary so you can set or retrieve gobs[x] at will.
gobs = dict()
with open ('Grav_H_Cyln_v3_output.txt') as finp:
    lines=finp.readlines()
    for line in lines:
         g=float(line)
         gobs[line] = g
         print (gobs[line])

A: You could try creating a vector gobs[] outside the loop, and filling it up within the loop over lines.
That should do.

A: Instead of reassigning the value of x on each iteration of your loop, append i to a list that is declared outside of the if-block scope.
x = []
for i in range (1, 100, 1):

     x.append(i)

print(x)


text:
Q: Spark: How to set spark.yarn.executor.memoryOverhead property in spark-submit In Spark 2.0. How do you set the spark.yarn.executor.memoryOverhead when you run spark submit.
I know for things like spark.executor.cores you can set --executor-cores 2. Is it the same pattern for this property? e.g. --yarn-executor-memoryOverhead 4096

A: spark.yarn.executor.memoryOverhead has now been deprecated:

WARN spark.SparkConf: The configuration key
  'spark.yarn.executor.memoryOverhead' has been deprecated as of Spark
  2.3 and may be removed in the future. Please use the new key 'spark.executor.memoryOverhead' instead.

You can programmatically set spark.executor.memoryOverhead by passing it as a config:
spark = (
    SparkSession.builder
        .master('yarn')
        .appName('StackOverflow')
        .config('spark.driver.memory', '35g')
        .config('spark.executor.cores', 5)
        .config('spark.executor.memory', '35g')
        .config('spark.dynamicAllocation.enabled', True)
        .config('spark.dynamicAllocation.maxExecutors', 25)
        .config('spark.yarn.executor.memoryOverhead', '4096')
        .getOrCreate()
)
sc = spark.sparkContext

A: Please find example.
The values can also be given in Sparkconf.
Example:
./bin/spark-submit \
--[your class] \
--master yarn \
--deploy-mode cluster \
--num-exectors 17
--conf spark.yarn.executor.memoryOverhead=4096 \
--executor-memory 35G \  //Amount of memory to use per executor process
--conf spark.yarn.driver.memoryOverhead=4096 \
--driver-memory 35G \   //Amount of memory to be used for the driver process
--executor-cores 5
--driver-cores 5 \     //number of cores to use for the driver process
--conf spark.default.parallelism=170
 /path/to/examples.jar


text:
Q: Push notification using firebase api is not working properly in background state I have configure the firebase api for getting the push Notification in iOS . Its working in foreground but not properly in background state . I do not want to used to the notification tag as it will not work in killed state in android .
I need to get that in background also in order to acknowledge it to server.

A: Iam using this :-
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        Messaging.messaging().shouldEstablishDirectChannel = true
        Messaging.messaging().delegate = self
         if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self

            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        application.beginBackgroundTask(withName: "showNotification", expirationHandler: nil)
        application.registerForRemoteNotifications()

        return true
    }
  func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        let token = Messaging.messaging().fcmToken
        print("FCM token: \(token ?? "")")
        Constants.kUserDefaults.set(token, forKey: appConstants.fcmToken)

    }
    func applicationReceivedRemoteMessage(_ remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
    }
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        InstanceID.instanceID().instanceID { (result, error) in
            if let error = error {
                print("Error fetching remote instange ID: \(error)")
            } else if let result = result {
                print("Remote instance ID token: \(result.token)")
                Constants.kUserDefaults.set(result.token, forKey: appConstants.fcmToken)
            }
        }
        Messaging.messaging().apnsToken = deviceToken as Data

    }
    private func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        completionHandler([UNNotificationPresentationOptions.alert,UNNotificationPresentationOptions.sound,UNNotificationPresentationOptions.badge])
    }
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for remote notifications with error: \(error)")
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        switch application.applicationState {
        case .inactive:
            print("Inactive")
            //Show the view with the content of the push
            completionHandler(.newData)

        case .background:
            print("Background")
            //Refresh the local model
            completionHandler(.newData)

        case .active:
            print("Active")
            completionHandler(UIBackgroundFetchResult.newData)
        }
        print(userInfo)

        guard let data: [String: Any] = userInfo as? [String: Any] else {
            return
        }
        print(data)
         let aps = data["aps"] as! NSDictionary
        let contentDict = aps["alert"] as! NSDictionary
         print(contentDict)
        let body = contentDict["body"] as! String
        let titleData = contentDict["title"] as! String
        print(titleData)
        createNotification(title: titleData, body: body)

        completionHandler(.newData)
    }

    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        application.registerForRemoteNotifications()
    }
    @available(iOS 10.0, *)
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        print("Handle push from background or closed")
        // if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
        print("\(response.notification.request.content.userInfo)")
    }

    func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
        print("Received data message: \(remoteMessage.appData)")
        guard let data: [String: Any] = remoteMessage.appData as? [String: Any] else {
            return
        }
// Handle Notification data
        let contentDict = data["alert"] as! NSDictionary
        print(contentDict)
        let body = contentDict["body"] as! String
        let titleData = contentDict["title"] as! String
        print(titleData)
        createNotification(title: titleData, body: body)

    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler([.alert, .badge, .sound])
    }
    func createNotification(title: String, body: String) {
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil)
        //  content.title = "RedIron"
        // content.body = "Confirm"
        content.sound = UNNotificationSound.default()
        content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)

        let request = UNNotificationRequest.init(identifier: "pushNotif", content: content, trigger: nil)

        let center = UNUserNotificationCenter.current()
        center.add(request)
    }
   func applicationDidBecomeActive(_ application: UIApplication) {
       UIApplication.shared.applicationIconBadgeNumber = 0

    }
// and make sure on backend they have also set
content_available : true
priority : high
// on your project, In capabilities > background mode switch on > click on remote notifications and background fetch.
// its Works for me


text:
Q: COUNTIFS not returning correct count I have a Google Sheet with two tabs: Output and Data. Output has a layout of results/aggregations and data has the information I used. I want to count all instances of two texts in a Data column and return that in Output but my formula is not working. I'm not sure what I'm doing wrong. Please help.
In this example, the value from the formula in C2 of Output sheet should be two since there were two resources created in January of 2021 as per the Data sheet.
Data Sheet

Output Sheet

A: use:
=ARRAYFORMULA(COUNTIFS(Data!B:B, "*"&D2:D21&"*", Data!B:B, "*"&E2:E21&"*"))


text:
Q: Where statement in include does not filter I'm trying to get a list with the items that contain "a" in the name. I'm using entity framework. I have 5 records with an "a" but 5 records without an "a".
In the return are all the items. That means that the include statement works but the where statement doesn't work.
I have tried several options but it still doesn't work.
Option 1
I think that this piece of code is the most "correct" one (even without working).
  return _context.StockLists
                .Where(x => x.CompanyId == id)
                .Include(e => e.Stocks)
                .Where(c => c.Stocks.Any(x => x.Name.Contains("a"))).ToList();

Her is no error code. When I run it, the program loaded 10 stocks. This is incorrect because I said in the where that I only want the stocks with an "a" in their name. He loads 10 stocks while this must be 5. Output number of stocks
Option 2
Another solution that I have tried is:
 return (IEnumerable<StockList>)_context.StockLists.Where(c => c.Stocks.Any(i => i.Name.Contains("a")))
            .Select(c => new
            {
                c,
                Stocks = c.Stocks.Where(i => i.Name.Contains("a"))
            })
            .ToList();

The error code here is:
> System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List`1[<>f__AnonymousType0`2[AandelenApplicatie.Data.Poco.StockList,System.Collections.Generic.IEnumerable`1[AandelenApplicatie.Data.Poco.Stock]]]' to type 'System.Collections.Generic.IEnumerable`1[AandelenApplicatie.Data.Poco.StockList]'.'

Option 3
A third option that I've tried is:
      return _context.StockLists
                .Include(b => b.Stocks.Where(p => p.Name.Contains("a")))
                .ToList();

Here crashes my application with the error:
System.InvalidOperationException: 'Lambda expression used inside Include is not valid.'

I suppose that something is wrong with the statement but I can't find an answer to it.
Thanks for your help.


text:
Q: Google search Java API How do we get more Google search results in Java against the query by using Google API which returns JSON?  I have used the API but it only returns top 4 results.  What I want is to get more results i.e. the top 100 results.

A: Have you considered reading the documentation from google? It can be found here:
http://code.google.com/apis/customsearch/v1/overview.html
It talks about the API operations and models which should have some information on the parameters of the search function.


text:
Q: How to wrap ionic-card with fixed size? I've a bunch of ionic-card(I guess the kind of element isn't relevant) to display.
I initially tried to display them in an ion-grid:
<ion-content>
  <ion-grid>
    <ion-row>
        <ion-col  *ngFor="let trip of trips$ | async" size-lg="3" size="6" size-sm="12">
            <ion-card class="trip" class="ion-no-padding" [routerLink]="[trip.id]">
              <img [src]="trip?.coverImageUrl ? trip.coverImageUrl: '/assets/img/defaultImage.jpg'" style="width: 100%" />
              <ion-card-header>
                <ion-card-title>{{trip.name}}</ion-card-title>
                <ion-card-subtitle>{{trip.startDate.toDate() | date}}</ion-card-subtitle>
              </ion-card-header>
            </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

but when I'm resizing the image, the size of each cards varies until I hit the breakpoint. In my case, I would like to have the elements being exactly 150px width and fits as much as possible on one line.
By example, if somebody comes with an ultra-wide monitor, I don't want to have only 12 elements in the width that are stretched.
How to achieves this?

A:
I would like to have the elements being exactly 150px width and fits as much as possible on one line.
By example, if somebody comes with an ultra-wide monitor, I don't want to have only 12 elements in the width that are stretched

Not exactly related to Ionic but you can achieve that using CSS Grid layout for example.
Please take a look at this working Stackblitz demo.

<ion-header>
    <ion-toolbar>
        <ion-title>Home</ion-title>
    </ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
    <div class="grid">
        <div *ngFor="let item of items" class="grid-item">
            {{ item }}
        </div>
    </div>
</ion-content>

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}

.grid-item {
  width: 150px;
  height: 150px;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  justify-self: center;
  align-self: center;
}

This can be done in a lot of different ways but if you're curious to learn more about CSS Grid Layout, I'd recommend taking a look at the Guides section: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout#guides


text:
Q: 'str' object has no attribute 'push_link' I know this might seems to be a common problem, but I just can't seem to resolve this issue. Here is the code:
def init():
    global pushbullet_client, wanted_pokemon
    # load pushbullet key
    with open('config.json') as data_file:
        data = json.load(data_file)
        # get list of pokemon to send notifications for
        wanted_pokemon = _str( data["notify"] ) . split(",")
        # transform to lowercase
        wanted_pokemon = [a.lower() for a in wanted_pokemon]
        # get api key
        api_key = _str( data["pushbullet"] )
        if api_key:
            pushbullet_client = api_key

# Safely parse incoming strings to unicode
def _str(s):
  return s.encode('utf-8').strip()

# Notify user for discovered Pokemon
def pokemon_found(pokemon):
    # get name
    pokename = _str(pokemon["name"]).lower()
    # check array
    if not pushbullet_client or not pokename in wanted_pokemon: return
    # notify
    print "[+] Notifier found pokemon:", pokename
    # Locate pokemon on Google Maps
    google_maps_link = "http://maps.google.com/maps?q=" + str(pokemon["lat"]) + "," + str(pokemon["lng"]) + ',20z'
    notification_text = "Pokemon Finder found " + _str(pokemon["name"]) + "!"
    disappear_time = str(datetime.fromtimestamp(pokemon["disappear_time"]).strftime("%I:%M%p").lstrip('0'))+")"
    location_text = "Locate on Google Maps : " + google_maps_link + ". " + _str(pokemon["name"]) + "will be available until" + disappear_time + "."

    push = pushbullet_client.push_link(notification_text, google_maps_link, body=location_text)`

I get the 'str' object has no attribute 'push_link' error. What do I do?

A: You are attempting to call what I assume are functions for a specific class, but on a string.
api_key = _str( data["pushbullet"] )
if api_key:
    pushbullet_client = api_key

pushbullet_client has api_key assigned to it, which is a string. The default string object does not have a push_link attribute so it is throwing that error.


text:
Q: creating a file in bash, how do I utilize 2>/dev/null in case it is not possible to create? I am creating a script which will calculate some different information about directories.  I have to give the option to the user to create a file.  Many different file checks are done, but one in particular is giving me grief:
if the file name is checked and does not exist, the script is to try to create it.  If the creation fails, the user is to be notified that it couldn't be created.
So I have a variable (file) which is the name the user has given to the file he wishes to create.  I then use:
echo -n "Creating the file: '$file'"
touch "$file"
if [ -e "$file" ]; then
  echo "..........File created"
  else echo"...........Creation failed"
fi

Does the >2/dev/null go after the touch line?  What would be the proper syntax to suppress the error message, and only display Creating the file:(file).........Creation failed?
Thanks so much

A: You need to use 2> and not >2 to redirect standard error.
touch "$file" 2> /dev/null

But even with this change your script has a bug:
Suppose the touch fails because the file exists but you do not have permission to touch it. Next you check if the file exists using the -e check which returns true and you print File created which is incorrect.
To fix this you need to check the return value of touch command as:
if  touch "$file" 2> /dev/null ; then
echo "..........File created"
else
echo "..........File failed"

A: You actually want:
touch "$file" 2> /dev/null

(note 2> rather than >2)


text:
Q: DataGridView и DataSet. Баг C# или так и должно быть? Например, есть форма с элементом DataGridView dataGridView1. Имеется файл ds.xml с данными датасета 'DSMain' с одной таблицей 'DTMain' с несколькими столбцами, строки в таблице 'DTMain' еще не заполнены. Далее:

DataSet ds = new DataSet("DSMain");
ds.ReadXml("ds.xml");
dataGridView1.DataSource = ds.Tables["DTMain"];

Также есть метод для сохранения ds, например, при выборе пункта меню 'Сохранить':

void SaveDataSet()
{ ds.WriteXml("ds.xml",XmlWriteMode.WriteSchema); }

Запускаю программу, и бьюсь с такой проблемой. Если внести значение в ячейку новой (последней) строки датагрида и нажать кнопку-стрелку 'Вправо', а затем выбрать 'Сохранить', то никаких изменений во всей строке не сохранится, то есть она останется пустой. А если хотя бы раз нажать 'Enter' на строке датагрида, то при изменении остальных ячеек в этой строке, все изменения будут сохраняться. Пользуюсь студией 2010 C# Express. Кто что думает об этом? Это баг или у меня кривые руки? И как решить данную проблему?
A: Подозреваю, что так и должно быть, это вроде как в MS Access сделано: если вы нажимаете вправо, то вы остаётесь в той же строке и, как бы считается, что вы всё ещё редактируете запись. Дело в том, что это не просто таблица, а редактор записей. Мне даже кажется, что сталкивался с чем-то подобным очень очень давно, когда ещё был .NET 1.0. Просто надо перед сохранением как-то закончить редактирование. Я не спец по .NET, но уверен, что такой метод должен быть. Что-нибудь вроде EndEdit или ApplyЧтоТо, AcceptChanges или что-то в этом духе. Посмотрите также на состояние самого DataSet. Возможно надо его пнуть, чтобы он счёл нужным принять изменения.
Возможно они:
DataSet.AcceptChanges
DataGridView.EndEdit
A: Похоже, дело не в DataSet, а в гриде. Для диагностики ситуации попробуйте подписаться на DataTable.TableNewRow и посмотрите, вызывается ли обработчик при (или до) нажатии кнопки "Вправо" или нет. Если не вызывается - точно проблема в гриде. В этом случае нужно в обработчике "Сохранить" что-нибудь вызвать у грида, чтобы он применил к источнику данных изменения, внесённые пользователем.
Иначе, попробуйте DataRow.EndEdit().


text:
Q: Converted long to time off by 1 minute I have a portion of code that finds a saved time in milliseconds that has been saved by a user previously. When the time is taken from memory then converted to a Simple Date Format for some reason the time gains 1 minute. I can't figure out why this would occur though. Following is the code for retrieving the time and converting it
time = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getFloat(String.valueOf(id)+"TIME", 0);
            String dateString = new SimpleDateFormat("hh:mm a").format(new Date((long) time));
            mPickedTimeText.setText(dateString);

and the portion of code where the time is saved
    this.time = time.getTimeInMillis();
    PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    Editor editor=prefs.edit();
    editor.putFloat(String.valueOf(id)+"TIME", time);
    editor.commit();
    finish();

Thanks in advance!

A: The float datatype doesn't have enough precision to represent time to the accuracy of one minute. Store the time as long instead.
editor.putLong(String.valueOf(id)+"TIME", time);

time = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getLong(String.valueOf(id)+"TIME", 0);
String dateString = new SimpleDateFormat("hh:mm a").format(new Date(time));


text:
Q: angularFire unable to $add data to firebase I am using angularFire and trying to save data from a form to firebase with $add. Any help would be greatly appreciated. The console logs all work, I am able to retrieve the data in the console. Sorry for all of the code... I wanted to be sure I provided all the material needed.
app.js:
    var creativeBillingApp = angular.module('creativeBillingApp', ['ngRoute', 'firebase']);

    creativeBillingApp.constant('FIREBASE_URI', "https://XXXX.firebaseIO.com/");

    creativeBillingApp.controller('MainCtrl', ['$scope', 'groupsService', function( $scope,  groupsService, $firebase ) {

    console.log('Works')

    $scope.newGroup = {
     name: '',
     status: ''

    };

   $scope.addGroup = function(newGroup){

   console.log(newGroup);

groupsService.addGroup();
  $scope.newGroup = {
    name: '',
    status: ''

  };
};
 $scope.updateGroup = function (id) {
   groupsService.updateGroup(id);
 };

 $scope.removeGroup = function(id) {
   groupsService.removeGroup(id);
 };
}]);

creativeBillingApp.factory('groupsService', ['$firebase', 'FIREBASE_URI',
  function ($firebase, FIREBASE_URI) {
    'use strict';
    var ref = new Firebase(FIREBASE_URI);
    return $firebase(ref).$asArray();

var groups = $firebase(ref).$asArray();

var getGroups = function(){
  return groups;
};

var addGroup = function (newGroup) {
  console.log(newGroup)
  groups.$add(newGroup);
};

var updateGroup = function (id){
  groups.$save(id);
};

var removeGroup = function (id) {
  groups.$remove(id);
};
return {
  getGroups: getGroups,
  addGroup: addGroup,
  updateGroup: updateGroup,
  removeGroup: removeGroup,
}

}]);

index.html:
         <form role="form" ng-submit="addGroup(newGroup)">

              Group Name
              <input type="text" class="form-control" id="groupName" ng-model="newGroup.name">

              Group Status
              <select class="form-control" ng-model="newGroup.status">
                <option value="inactive">Inactive</option>
                <option value="active">Active</option>
              </select>

           <button type="submit" class="btn btn-default">Submit</button>
          </form>

This is the error I am getting:
TypeError: undefined is not a function
at Scope.$scope.addGroup (http://localhost:9000/scripts/app.js:35:19)

and the app.js line 35 is in reference to groupsService.addGroup(); from the app.js code given above.

A: Firstly, you are returning in your service after you create your $FirebaseArray. You are also creating another $FirebaseArray after that.
return $firebase(ref).$asArray();

Remove that return statement. That is causing your service to return early and none of the attached methods will apply to your service.
In groupService.addGroup() you are calling push, which is not a function on $asArray. You need to call .$add(). The newGroup argument is also not being passed in the controller.
The $.push method is available on the base of the $firebase binding. When you using a $FirebaseArray the $add method pushes a new record into Firebase.
See the docs for more info.
Plunker Demo
var addGroup = function (newGroup) {
  console.log(newGroup)
  groups.$add(newGroup);
};

Then in your controller you can simply call:
$scope.addGroup = function(newGroup){
  groupsService.addGroup(newGroup);

  $scope.newGroup = {
    name: '',
    status: ''
  };
};


text:
Q: Spring + MongoDB Use nonReactive and Reactive repository at once I have a SpringBoot + Mongo application, implemented with non-reactive Repositories (extends MongoRepository<MyDocument, String>) and everything works fine.
Now I need to implement an auditing system and I wanted to develop it by using Mongo's ChangeStreams and Spring's Reactive Change Streams (reference). I tried to create 3 classes to achieve this:
MongoMessageListener
@Component
@Slf4j
public class MongoMessageListener implements MessageListener<ChangeStreamDocument<Document>, MyDocument> {

    @Override
    public void onMessage(Message<ChangeStreamDocument<Document>, MyDocument> message) {

        OperationType operationType = message.getRaw().getOperationType();

        log.info("Operation type is : {}", operationType);

        log.info("Received Message in collection: {},message raw: {}, message body:{}",
                message.getProperties().getCollectionName(), message.getRaw(), message.getBody());
    }
}

MongoListenerConfig
@Configuration
@Slf4j
public class MongoStreamListenerConfig extends AbstractReactiveMongoConfiguration {

    @Bean
    MessageListenerContainer changeStreamListenerContainer(
            MongoTemplate template,
            MongoMessageListener consentAuditListener,
            ErrorHandler errorHandler) {

        MessageListenerContainer messageListenerContainer =
                new MongoStreamListenerContainer(template, errorHandler);

        ChangeStreamRequest<ParentContentDocument> request =
                ChangeStreamRequest.builder(consentAuditListener)
                        .collection("my_document_collection")
                        .filter(newAggregation(match(where("operationType").is("update"))))
                        .fullDocumentLookup(FullDocument.UPDATE_LOOKUP)
                        .build();

        messageListenerContainer.register(request, MyDocument.class, errorHandler);
        log.info("> Mongo Stream Listener is registered");
        return messageListenerContainer;
    }

    @Override
    protected String getDatabaseName() {
        return "myDatabase";
    }

    @Bean
    ErrorHandler getLoggingErrorHandler() {
        return new ErrorHandler() {
            @Override
            public void handleError(Throwable throwable) {
                log.error("Error in creating audit records {}", throwable.getMessage());
            }
        };
    }
}

MongoStreamListenerContainer
public class MongoStreamListenerContainer extends DefaultMessageListenerContainer {

    public MongoStreamListenerContainer(MongoTemplate template, ErrorHandler errorHandler) {
        super(template, Executors.newFixedThreadPool(15), errorHandler);
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }
}

I also added a repo which extends ReactiveMongoRepository<MyDocument, String>
When I try to run my application it raises multiples errors of ClassNotFoundException ([...] 'reactiveStreamsMongoClient' threw exception; nested exception is java.lang.NoClassDefFoundError: com/mongodb/internal/connection/InternalConnectionPoolSettings) , or @Autowired to import repositories into Services not satisfied (Autowired(required=true)})
In my Main.java class I tried to set both @EnableMongoRepositories(basePackages = "com.my.path.to.repository")  and @EnableReactiveMongoRepositories("com.my.path.to.reactive.repository") , but nothing seems to work.
I doubted I could't squeeze together non-reactive and reactive repos, but I found this SO question and some more, so I guess you can.
I tried to follow this Spring project step-by-step, but I always get ClassNotFound errors.
In my pom I have
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-mongodb</artifactId>
 <version>2.5.3</version>
</dependency>
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
 <version>2.5.3</version>
</dependency>
<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongodb-driver-reactivestreams</artifactId>
 <version>4.6.1</version>
</dependency>
<dependency>
 <groupId>io.projectreactor</groupId>
 <artifactId>reactor-core</artifactId>
 <version>3.4.19</version>
</dependency>

I really cant' see what I'm missing: if it's just some configurations or if I can't mix non-reactive and reactive repos (even though I found users say you can). Any help will be VERY much appreciated, it's driving me a bit crazy! Thank you so much!

A: As you asked in one of my old Question, I will share what I did on my webflux project. I'm using an old library written in web MVC in my project where the non-reactive mongo is used.
I'm using the following dependencies;
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>

my reactive mongo config looks like this. here I'm using the mongo URI connection string to connect, you can also use user/pass for this
@Configuration
public class ReactiveMongoConfiguration extends AbstractReactiveMongoConfiguration {

  private final NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();

  @Override
  @Bean
  @Primary
  public MongoClient reactiveMongoClient() {
    ConnectionString connectionString = new ConnectionString(MY_DB_URI_KEY);
    return MongoClients.create(MongoClientSettings.builder().applyConnectionString(connectionString)
        .streamFactoryFactory(NettyStreamFactoryFactory.builder().eventLoopGroup(eventLoopGroup).build()).build());
  }

  @Bean
  @Primary
  public ReactiveMongoTemplate reactiveMongoTemplate() {
    return new ReactiveMongoTemplate(reactiveMongoClient(), getDatabaseName());
  }

  @Override
  protected String getDatabaseName() {
    return new ConnectionString(MY_DB_URI_KEY).getDatabase();
  }

  @PreDestroy
  public void shutDownEventLoopGroup() {
    eventLoopGroup.shutdownGracefully();
  }
}}

My old web MVC library contains non-reactive mongo bean that looks like this,
@Configuration
public class MongoConfigurations {

    @Bean
    public MongoTemplate mongoTemplate() {
            ConnectionString connectionString = new ConnectionString(MY_DB_URI);
            MongoClient mongoClient = MongoClients.create(connectionString);
            mongoTemplate = new MongoTemplate(mongoClient, connectionString.getDatabase());
            return mongoTemplate;
    }
}

on my main application I excluded following auto configurations;
exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class }

now you can use both reactive an non-reactive mono templates by injecting. :)


text:
Q: Java process that invoke pkzip taking long time to zip I must use pkzip in my java program to zip (since standard java zip routine does not work on mainframe), I think it zip correctly, however it take a long time to finish. Here is mycode
 Runtime myruntime = Runtime.getRuntime();
 Process newproc = myruntime.exec("c:\\app\\pkzipc.exe -add c:\\output\\test.zip c:\\doc\\foo.pdf c:\\doc\\bar.doc"");

foo.pdf and bar.doc are about 20MB each, if I execute this via commandline, then it take about a second to zip, but when I use the java, it take 30 min to 1 hours to finish the zipping. Any idea why?

A: You need to make sure that you are reading from the standard output and error streams of the child process. If pkzip generates output then it will be buffered by the operating system, and if the buffer fills up then you can expect the child process to block until the buffer is cleared.
The Process object has methods for obtaining the input, output and error streams. Create new threads that read from the output and error streams and either pipe them to System.out and System.err, or just discard the output if you don't care about it.

A: Try using Java's java.util.zip API for manipulating .zip files, take a look at the tutorial.


text:
Q: How to filter models in django database Hello i created movies website , this is my models.py
CATEGORY_CHOICES = (
    ("A","ACTION"),
    ("D","DRAMA"),
    ("C","COMEDY"),
    ("R",'ROMANCE'),

class Movie(models.Model):
      title = models.CharField(max_length=100)
      slug = models.SlugField(max_length=255,
      title_english = models.CharField(max_length=100)
      descritpion = models.TextField(max_length=1000)
      image = models.ImageField(upload_to="movies")
      category = models.CharField(choices=CATEGORY_CHOICES,max_length=1)
      language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30)
      status = models.CharField(choices=STATUS_CHOICES,max_length=2)
      year_of_production = models.TextField(max_length=1000)
      view_count = models.IntegerField(default=0)

and this is my views.py
def home(request):
    user = request.user
    Movies_obj = models.Movie.objects.all().order_by('-id')[:10]
    return render(request,'index.html',{'user':user,'movies':Movies_obj})

in views.py i order last 10 movies , now i want to show only this movies which is DRAMA or Comedy how to filter it ?

A: Category field has values A or D so you need to filter category field with those values.
models.Movie.objects.filter(category__in=['A', 'D']).order_by('-id')[:10]


text:
Q: how to configure webpack HMR with express package.json scripts:
 "scripts": {
    "build": "webpack --config config/webpack.prod.config.js",
    "dev": "webpack --config config/webpack.dev.config.js && nodemon ./dist/server.js",
    "start": "nodemon ./dist/server.js"
  }

and this is main file:
server.js
import express from "express";
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from './config/webpack.dev.config';

const app = express();
const compiler = webpack(config);

app.get("/", (req, res) => {
    res.send("Hello");
});

app.use(webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath
}));

app.use(webpackHotMiddleware(compiler));

app.listen(4000, () => console.log("Listening to port 4000"))

my webpack config divided in three files:

*

*config/webpack.common.config.js

*config/webpack.dev.config.js

*config/webpack.prod.config.js

this is webpack common config:
webpack.common.config.js
module.exports = {
    entry: {
        server: './server.js'
    },
    output: {
        path: path.join(__dirname, '../dist'),
        publicPath: "/",
        filename: '[name].js'
    },
    target: 'node',
    externals: [new nodeExternals()],
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin()
    ]
}

this is webpack dev config:
webpack.dev.config.js
module.exports = merge(common, {
    entry: {
        server: ['webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', './server.js']
    },
    mode: 'development',
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ]
})

this is webpack dev config:
webpack.prod.config.js
module.exports = merge(common, {
    mode: 'production'
});

finally this is the error:

what is the problem? how to config the hot reload in webpack and express?

A: add "devServer" property to your webpack:
devServer: {
    contentBase: "dist",
    hot: true,
    stats: { colors: true }
  },

then add this to the entry point of webpack. in your project it is server.js
 require("webpack-hot-middleware/client?reload=true");


text:
Q: Is it possible to call an overridden method from self type? Consider this:
 class Foo { def foo = "foo" }
 trait Bar { self: Foo =>
    override def foo = "bar"
 }

I was pleasantly surprised to find out that this is possible, and works as expected:
new Foo with Bar foo

returns "bar". The question is whether it is possible for Bar.foo to invoke Foo.foo, like one would often do in the "ordinary" inheritance case.  override def foo = super.foo + "bar" does not work (says "foo is not a member of AnyRef), and neither does override def foo = self.foo + "bar" (it ends up just calling itself, and results in infinite recursion).
I tried a few other combinations (like self.Foo.foo, Foo.this.foo etc.), but without any luck.
Is this just impossible?

A: No. It is impossible to call overridden method from a self type.
Firstly the trait Bar is not a successor of class Foo so it is not possible using super.foo.
And secondly it is also not possible using self.foo since self is actually of type Bar with Foo. It can be shown by printing the program after typer:
$ scalac -Xprint:typer test.scala
[[syntax trees at end of                     typer]] // test.scala
package <empty> {
  class Foo extends scala.AnyRef {
    def <init>(): Foo = {
      Foo.super.<init>();
      ()
    };
    def foo: String = "foo"
  };
  abstract trait Bar extends scala.AnyRef { self: Bar with Foo =>
    def /*Bar*/$init$(): Unit = {
      ()
    };
    override def foo: String = "bar"
  };
  class FooBar extends Foo with Bar {
    def <init>(): FooBar = {
      FooBar.super.<init>();
      ()
    }
  };
  object TestApp extends scala.AnyRef {
    def <init>(): TestApp.type = {
      TestApp.super.<init>();
      ()
    };
    def main(args: Array[String]): Unit = {
      val a: FooBar = new FooBar();
      scala.this.Predef.println(a.foo)
    }
  }
}

So with self.foo you are trying to access the method foo of the trait Bar. Such behavior matches the Scala Specification (PDF):

The sequence of template statements may be prefixed with a formal
  parameter definition and an arrow, e.g. x =>, or x: T =>. If a formal
  parameter is given, it can be used as an alias for the reference this
  throughout the body of the template. If the formal parameter comes
  with a type T, this definition affects the self type S of the
  underlying class or object as follows: Let C be the type of the class
  or trait or object defining the template. If a type T is given for the
  formal self parameter, S is the greatest lower bound of T and C. If no
  type T is given, S is just C. Inside the template, the type of this is
  assumed to be S.

It is possible to access the method using reflection but I think that it is not what you are looking for.

A: I am not aware of any particular syntax to disentangle the base class and the mixed-in trait.
There is, however, an easy solution to achieve the result manually by distinguishing the overridden method from the default implementation in the base class:
class Foo { def foo = defaultFoo; def defaultFoo = "foo" }
trait Bar { self: Foo => override def foo = self.defaultFoo + "bar" }

As expected
new Foo with Bar foo == "foobar"
new Foo foo == "foo"

A: You make your trait extend Foo instead of using the self type:
class Foo {def foo = "foo"}
trait Bar extends Foo {
  override def foo = super.foo + "bar"
}
new Foo with Bar foo // barfoo

See also this answer.


text:
Q: Acer AOD260 No webcam after restoring? I have an Acer Aspire One D260 32-bit netbook.
I've restored the computer a few times & for awhile now, the webcam hasn't restored. I cannot find the webcam in "devices" & am unsure what to do to get it working again.
I'm obviously not tech savvy, so any advice would be amazing :)

A: first off by restore do you mean you have done a System restore from your recovery Partition OR Recovery Disk?
And you do not see the Webcam in the Device Manager? have you looked under the Imaging Device under device manager by clicking the + symbol?  Do you see any yellow questions marks in device manager? if you do then it means the webcam may not be installed.
Here is your Drivers List GO under the Camera Section and download and install one by one until your webcam works OR if you know which mntfr is your Webcam then just download that specific driver from the list:
http://support.acer.com/us/en/product/default.aspx?tab=1&modelId=2438
Hope that Helps.