text:
Q: Scala - calling a method with generic type parameter given a string value that determines the correct type I am designing an API interface in a 2-tier architecture. It takes a string parameter fieldName from URL and returns a JSON string. fieldName refers to a field in my database table. You can think of its signature as:
def controller(fieldName: String): String

In the controller, I would like to call a method in my data access layer to perform the following query:
SELECT fieldName, SUM(salary) FROM Employee GROUP BY fieldName

because the type of the field varies, the type of the query result will be different. This method is parametrized by a generic type parameter T which corresponds to the type of the field with name fieldName.
def getTotalSalaryByField[T](fieldName: String): Map[T, Long]

*

*if fieldName is "age", T should be Int.

*if fieldName is "name", T should be String.
and so on.

given a particular fieldName at runtime, how do I call this method giving it the correct type?
I don't want to write a lot of if-else or pattern matching statements to select the type. It would look like this:
fieldName match {
    case "age" => serializeToJson(getTotalSalaryByField[Int]("age"))
    case "name" => serializeToJson(getTotalSalaryByField[String]("name"))
    ...
    // 100 more for 100 more fields
}

This is ugly. If I were to write this in Python, it will take only one line:
json.dumps(getTotalSalaryByField(fieldName))

Is Scala somehow not suitable for rest backend programming? because this seems to be a common pattern people will encounter, and static typing gets in the way. I would like to see some suggestions as to how I should approach the whole problem in scala-ish way, even if it means remodeling, rewriting the DAL and controllers.
EDIT:
@drexin, the actual signature of the DAL method is
def myDAOMethod[T](tf: Option[TimeFilter], cf: CrossFilter)
    (implicit attr: XFAttribute[T]): Map[T, Long]

T is the type of fieldName. Long is the type of y. As you can see, I need to select a type to be T based on fieldName from url parameter.
EDIT:
added some code and made the usecase clear

A: There is a difference between knowing the type of a variable at compile time and at runtime.
If the fieldName is not known at compile time (i.e. it's a parameter), and if the type of the column varies by fieldName, then you are not going to be able to specify the return type of the method at compile time.
You will need to use a DAO method that returns AnyRef, rather than one which returns T for a compile-time-specified type T.
Old answer:
The database access library can return the values without needing to know their type, and your code needs to do the same.
You are looking to use a DAO method which takes a type param T:
def myDAOMethod[T](tf: Option[TimeFilter], cf: CrossFilter)
    (implicit attr: XFAttribute[T]): Map[T, Long]

... but as you state, you don't know the type T in advance, so this method is inapplicable. (T is used to convert the database column data into a String or an Int).
Your DAO should offer an untyped version of this method, something more like:
def doSelect(tf: Option[TimeFilter], cf: CrossFilter): Map[AnyRef, Long]

What database access library are you using?

A: If you are using Play framework then I would recommend you to use Play JSON APIs.
https://www.playframework.com/documentation/2.1.1/ScalaJson
Instead of
def getTotalSalaryByField[T](fieldName: String): Map[T, Long] = ???

you can write
def getTotalSalaryByField(fieldName: String): Map[JsValue, Long] = ???

since all types like JsNumber, JsString, JsNull are inherit from the generic JSON trait, JsValue.
wrap your queryResult with Json.toJson()
OR
def getTotalSalaryByField(fieldName: String): JsObject = ???

A: I think you have three options here:

*

*use pattern matching (which is something you wanted to avoid)

*use AnyRef and then try to guess proper type at runtime; maybe serializeToJson can do it itself?

*use Type Providers: http://docs.scala-lang.org/overviews/macros/typeproviders.html
Third option is probably what you are looking for, but it bases on experimental scala features (i.e. macros). What I imagine it would be doing is connecting to your database during the compilation phase and inspecting the schema. If you are generating schema using some separate sql file(s) then it should be even easier. Then macro will generate all boilerplate with proper types hard-coded.
Probably you won't find working example for exactly what you need but there is one for RFC files which you can use as inspiration: https://github.com/travisbrown/type-provider-examples

A: I'm not 100% sure I understand your question, so apologies if I'm answering something else entirely.
You need Scala to be able to guess the type of your field based on the expected return type. That is, in the following code:
val result : Map[String, Long] = myDAOMethod(tf, cf)

You expect Scala to correctly infer that since you want a Map[String, Long], your x variable is of type T.
It seems to me that you already have everything you need for that. I do not know what XFAttribute[T] is, but I suspect it allows you to transform entries in a result set to instances of type T.
What's more, you've already declared it as a implicit parameter.
Provided you have an implicit XFAttribute[String] in scope, then, the previous code should compile, run, and be type-safe.
As a small improvement, I'd change the signature of your method to use context bounds, but that's primarily a matter of taste:
// Declare the implicit "parsers"
implicit val IntAttribute: XFAttribute[Int] = ???
implicit val StringAttribute: XFAttribute[String] = ???

// Empty implementation, fill it with your actual code.
def myDAOMethod[T: XFAttribute](tf: Option[TimeFilter], cf: CrossFilter): Map[T, Long] = ???

// Scala will look for an implicit XFAttribute[Int] in scope, and find IntAttribute.
val ages: Map[Int, Long] = myDAOMethod(tf, cf)

// Scala will look for an implicit XFAttribute[String] in scope, and find StringAttribute.
val names: Map[String, Long] = myDAOMethod(tf, cf)

I'm not sure whether your question implies that you'd also like to strongly tie the String "age" to the type Int. That's also possible, of course, but it's another answer entirely and I don't want to pollute this question with unnecessary rambling.


text:
Q: Adding view programmatically doesn't work I have a parent custom layout (child of LinearLayout) that I inflate programmatically.
In the constructor I add another layout to be a child of my parent layout like this:
public ExtendedContentLinearLayout(Context context) {
    super(context);
    this.context = context;

    this.setClickable(false);

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mTrigger = inflater.inflate(R.layout.nav_menu_board_expandable_children_outer, this, true);
    mTrigger.setOnClickListener(this);
    mTrigger.setBackgroundResource(R.color.da_blue);

}

The parent layout and the "trigger" layout (The child just added above) are working and shown fine.
Once the user touches this "trigger" layout, I want to add a new child to the parent - another layout with more content and thus I need to parent layout to expand and include the newly added layout but this is not working!
Clicking the trigger layout doesn't add a new layout (At least not shown on screen). This is the click call (the click event is working):
   @Override
    public void onClick(View v) {
        App.disableTouchEventForDefaultDuration();

    Log.d("CLICKED", "CLICKED");

    LinearLayout mContent = new LinearLayout(context);
    mContent.setOrientation(HORIZONTAL);
    mContent.setBackgroundResource(R.color.da_indicator_pink);
    mContent.setVisibility(VISIBLE);
    ExtendedContentLinearLayout.this.addView(mContent);

}

A: I ended up creating the layout in XML and then inflating it using:
 View view = inflater.inflate(this.layout, null, false);

and then adding this view using
addView(view)
this works just fine for me

A: mContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

Please try above code , try for WRAP_CONTENT as well as MATCH_PARENT

A: In my case, layout.post worked
ExtendedContentLinearLayout.this.post( new Runnable() {
    @Override
    public void run() {
        ExtendedContentLinearLayout.this.addView(llhItem);
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: using XSL to create XHTML from XML - a table with predefined width Imagine the below XML
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>
<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>
<book>
  <title lang="eng">A book</title>
  <price>39.95</price>
</book>
<book>
  <title lang="eng">Another Book</title>
  <price>39.95</price>
</book>

</bookstore>

I need to create an XSL stylesheet that displays this XML file in XHTML with only 2 books per row. The number of books in the XML file could change at any time so the XSL needs to be able take this into account. I've thought one solution of this would be to put the data into a table, however I can't rack my brains enough to figure a valid way of creating this. Possible ideas were to perform a modulus 2 check or divide total books by 2, but still unable to conclude how this might be written to create valid code. Below is my intial solution to display all books one after the other in one long column.
    <?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:template match="/">

        <link rel="stylesheet" type="text/css" href="css/theStyle.css" />

                <xsl:for-each select="/bookstore/book">

<xsl:value-of select='title' />

<xsl:value-of select='price' />

                </xsl:for-each>

</xsl:template>

Any tips/pointers/solution greatly appreciated. (Doesn't necessarily require table as solution, I just thought this might be one option)

A: Solution
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">

        <link rel="stylesheet" type="text/css" href="css/theStyle.css" />

          <xsl:apply-templates select="bookstore/book"/>

  </xsl:template>
  <xsl:template match="book[position() mod 2 = 1]">

      <xsl:value-of select='title' />

a mod 1

      <xsl:value-of select='price' />

  </xsl:template>
  <xsl:template match="book[position() mod 2 = 0]">

      <xsl:value-of select='title' />

a mod 0

      <xsl:value-of select='price' />

  </xsl:template>

</xsl:stylesheet>

Result

    <META http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/theStyle.css">

Harry Potter

a mod 1
29.99

Learning XML

a mod 0
39.95

A book

a mod 1
39.95

Another Book

a mod 0
39.95

Explanation
You could use a loop and xsl:if to achieve the same result but templates are much more powerful. You can think of them as functions only applied to a matched argument. It definitely helps to reduce the indentation of your code and separate the templates for odd and even books from each other.


text:
Q: Optimize Custom Drawables I'm drawing some custom shapes behind a textview to make it appear it's a notepad.  It draws a repeating bitmap across the top, as well as a white background under the text, and a secondary "note" page under the rest to add a little dimension and layering.  See the screenshot:

Now, this is with setDrawingCacheEnabled(true) for the TextView this drawable is applied to.  With this method call applied, the scrolling is VERY smooth, exactly what I want.  Without it, the black background disappears, but the scrolling is very choppy.  Any idea on how to cache this view so that scrolling is smooth without destroying my UI?

A: Seems this function only works with solid colors, as defined in the documentation which I should have read before posting.  I find it hard to believe there's nothing that caches complex views and drawables to work as well as that function does, but, whatevs. Live 'n learn.


text:
Q: Android Studio 3.5.1 can't run app on any device by adb I am trying to debug app on my Android Studio(version 3.5.1).
My environment is MacOS 10.14, Macbook Pro.
When I run app on AVD, everything works fine.
However, when I run app on real device, I always get this error:
android studio app installation failed
Also, after the installation failed, the device disappeared in adb devices list:
enter image description here
I have to reconnect the device, then I can see it in adb list again.
I have tried:

*

*restart Android Studio

*reinstall Android Studio

*reconnect and tried three different android device (all of them not working, and they work fine on other macbook)

*install Android File Transfer

Is there anyway to troubleshooting my Android Studio ADB connection problem?
Thanks.

A: I have same issue with my MacBook Pro (2019). I really don't understand why but you can debug your app in your device (see logs, and use breakpoint) with this easy workaround.

*

*Connect your device

*Build your app (Make project button) but not run it

*Open finder and go to MyProject/build/outputs/MyProject-debug.apk

*Send APK file to your device

*Install this APK directly from your device

*Start app and you can see logs in logcats et you can attach debugger to your app

A: I find a new solution and it's work fine for me now !!
In fact my mistake it that is used brew to install adb and android studio. To solve this issue i removed manually all files references of android studio and all references of adb. When i did that i found 2 references of adb in my Mac and i think that was the problem.
So remove all and re-install android studio with the DMG provided by google.
Enjoy


text:
Q: Android: how to set system wide properties Starting from this official statement that all xyAndroid versions previous API 11 doesn't support the java.net.ProSelector way to get the current proxy configuration, I would like to know if it's possible to transparently change in some way the properties that the ProxySelector class uses to store the proxy (If I'm not wrong, the ProxySelector implementation could be something like these).
The properties should be changed system wide, in order that all the 3rd party applications can access the current proxy configuration using the java.net.ProxySelector class.
Is it possible?
I'm trying to work on a OSS library so that every user with "not so much" old devices can finally set the proxy for all the well written applications.

A: Each Android app runs it its own VM, so you won't be able to set system properties that span across all applications.
This is by design. Android apps are sand boxed. No one should be able to install an app that interferes with how my app connects to the network. Imagine if a rogue app could force all HTTP traffic through their proxy, and suck up all your user names and passwords.
If you want to affect network at an OS-wide level, you'll need to get into the Android platform source code. You can't do it as an application.


text:
Q: When using hitTest:withEvent method - decide if tap was initiated I'm trying to override hitTest:withEvent in a custom view. This is a container view with many subviews.
Attached to this "superView" is a gesture recognizer. On top of this view sit many subviews (which in turn have more and more subviews) I decided to over ride hitTesh:withEvent in order to decide which view should get the events - and in which cases the superview should get the event in order to trigger the gesture.
Problem I am having is that hitTest will return the superview in cases where a tap gesture would be initialized in  a subview. In that case I would like to "retroactively" disregard the tap action - and again "invoke" hitTest:withEvent on the superview. the superview could then decide to pass the "true" responder to this event.
How can I do it:
Example:
// In the container view

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{

// the default view that would have been returned
  UIView *v = [super hitTest:point withEvent:event];

  // if nil than touch wasn't in this view so disregard
  if (v == nil)
  {
    return nil;
  }

  // if the touch was on a control than I don't want to take care of it
  if ([v isKindOfClass:[UIControl Class]])
  {
    return v;
  }

  // now here is where I need to fix

  // I am only interested in a touch event that would initiated a pan gesture
  // if the event was a tap for intance - than return [super hitTest:point withEvent:event]
  // for instance if a uitableview cell was tapped - I don't want to mask the event
  if (event wouldn't initiate a pan)
  {
    return v;
  }
  return self;
}


text:
Q: basic http connection between wamp and Android  I have an app that talks to my wamp server using http req and response .
I have set my serveripaddress as  xx.xxx.xx.xx:8080/ and am using it in the app , to ping my database .. ( for ex: user login) ..
But , I don't think the communication is taking place after the click activity ...
What other modifications are required ?
HttpClient httpclient = new DefaultHttpClient();
                      HttpPost httppost = new HttpPost(serveripaddress.servipaddr+"register.php");
THANKS

A: You need to call
httpclient.execute(httppost);

to actually send the request.
Check out this SO post for an example of how to work with HTTP operations in Android.


text:
Q: Significance of > commands in Stata I am reading a textbook on finance and it has applications that use Stata. There are commands that begin with a . which is the default starter in the Stata command window and these commands I can run just fine. However there are other commands that begin with a > and when I enter these commands with the default . Stata will not recognize them. I havent used this package for a long time, so I dont know what I'm missing here.

A: The > sign at the start of a physical line in discussions of Stata is just a continuation sign produced in Stata output showing that the text on that physical line follows on from the previous line. In  typing such commands you should always omit the > markers.
If you see this
. sysuse auto,
> clear

it just is equivalent to
. sysuse auto, clear

Count the opening . not the >. What is above is one command (not two).
Real examples will be (much) longer, but that is the principle.


text:
Q: stub_request must return array in body I would like test my service with rspec but i got a error in my return body undefined method 'each' for "invoices":String because in my original method i parse an array in the response
I would like know how can i test this method and send a array in return body
My method in service:
def generate_invoices
      invoices_ids = []
      response = HTTParty.get('https://books.zoho.com/api/v3/invoices?organization_id='\
        "#{ENV['ZOHO_ORGANISATION_ID']}&cf_lc_contract_id_startswith=#{@contract_id}&"\
        'cf_facture_final=true', headers: { 'Authorization' => "Zoho-oauthtoken #{@access_token}" })

      response.code == 200 ? response : raise_error(response.body)

      response['invoices'].each do |invoice|
        invoices_ids.push invoice['invoice_id']
      end

      invoices_ids.join(',')
      end

stub request i tried:
stub_request(:get, 'https://books.zoho.com/api/v3/invoices?cf_facture_final=true'\
          "&cf_lc_contract_id_startswith=123&organization_id=#{ENV['ZOHO_ORGANISATION_ID']}")
          .with(headers: { 'Authorization' => 'Zoho-oauthtoken access_token' })
          .to_return(status: 200, body: { 'invoices' => [{ "invoice_id": '123' }] }.to_json,
                     headers: {})

A: Try this at the end of your call:
.to_return(status: 200, body: '{"invoices" => [{ "invoice_id": "123"}]}', headers: {})


text:
Q: C# App.config vs Settings File This may sound like a trivial question, however I have looked over the web briefly and what I found was that app.config is basically an older mechanism for storing Application key/pairs of data for the application.
What I want to know is there any reason we (as .NET developers) would opt to use app.config over a Settings file ?
-Can someone please provide some pros and cons on both so we can use them properly.
thanks again

A: App.config for desktop applications and Web.config for web applications are part of .NET configuration system. Primarily they are used to control .NET framework settings in respect to our application. These are such configuration settings as substitutions of versions of assemblies (section <assemblyBinding>), substitution of .NET framework version (<startup>) etc. (see msdn for the full app.config schema.) One section is dedicated for custom settings of application developers (<appSettings>). There is also a possibility to create custom sections. So, when we need to store settings we can either piggy-back on the app.config or create our own separate configuration files.
Here are pros and contras of using app.config:

*

*Pro: There is already a standard API in .NET to read settings from appSettings section. If you only need just a couple of config settings, it is much easier to use this ready API than to develop and test your own class to read your config files. Also, app.config file is already included in VS project for you.

*Pro: There is a standard hierarchy of machine.config/app.config. If you plan such settings that can be set machine-wide and overridden or left as-is for individual applications, you should use app.config.

*Pro/Con: App.config is cached in run-time. If you anticipate updates of it while your application is running, you need to specifically request refresh of certain section of config file. For web.config the web app is automatically restarted when something is changed in the file. This is quite convenient.

*Con: app.config is stored in the same directory as your .exe file. Normally it will be in a subfolder of C:\Program Files. This directory is extra protected in Windows 7 from writing. You need to be member of Administrators group to write there and if your UAC (User Access Control) level in Control Panel is not set to 0 (which normally is not), you will be asked by the OS to confirm writing to c:\Program Files. So, users without Administrator rights will not be able to change configuration in app.config. Same goes for changing your settings programmatically: your application will get exception when attempts to write app.config if it runs not under an admin user on Windows 7. Your own config files usually go to C:\ProgramData\ or c:\Users subfolder (on Windows 7). These locations are friendlier to writing by users or programs.

*Con: If user edited your app.config file and accidentally corrupted it, the whole application will not start with some obscure error message. If your separate config file is corrupted, you will be able to provide more detailed error message.
In conclusion: app.config gives you easier (faster development) approach, mostly suitable for read-only settings. Custom settings file gives you more freedom (where to store file, validation/error handling, more flexibility with its schema) but requires more work during development.

A: You have it backwards, the settings file (or ini file as they were originally called) was the mechanism used to hold application settings (key/value pairs) prior to Windows 95. With the release of Windows 95 it was recommended that application settings be moved into the Windows Registry (which proved problematic since if you screwed up your registry your Windows may no longer be able to start).
The .config file came into play with .Net. The XML format allows more dynamic and complex settings configurations than simple key/value pairs.
The modern user/settings file is an XML extension of the .config file (settings that can override certain settings in the .config under specific conditions).


text:
Q: Top-level expression evaluation at compile time Is there any way to ensure, that an expression like the following would be evaluated at compile time?
myList :: [Int]
myList = sort [3,2,0,1]

A: If what you're evaluating is an instance of Lift, you can evaluate it at compile time using TemplateHaskell:
{-# LANGUAGE TemplateHaskell #-}

module Sort where

import Data.List
import Language.Haskell.TH.Syntax

myList :: [Int]
myList = $(lift (sort [3,2,0,1] :: [Int]))

If you want, you can check what it has compiled to with -ddump-splices:
$ ghc -ddump-splices sort
[1 of 1] Compiling Sort             ( sort.hs, sort.o )
sort.hs:9:12-41: Splicing expression
    lift (sort [3, 2, 0, 1] :: [Int]) ======> [0, 1, 2, 3]


text:
Q: Size of finite subset of $\mathbb{N}$ such that the sum of reciprocals is a given positive integer Let $\mathbb{N}$ denote the set of positive integers. For every integer $k\in\mathbb{N}$ let $m(k)$ denote the minimal size of a finite set $S\subseteq \mathbb{N}$ such that $\sum_{j\in S}j^{-1}=k$.
What is the asymptotic growth of $m(k)$?

A: Ernie Croot showed that for all large $N$, every positive integer below
$$
\sum_{n\le N} \frac 1n - \Big(\frac{9}{2}+o(1)\Big) \frac{(\log \log N)^2}{\log N}
$$
can be represented as a sum of unit fractions with denominator below $N$.  Clearly
no integer larger than $\sum_{n\le N} 1/n$ can be so represented.  This gives the desired asymptotic growth for $m(k)$:  namely
$$
m(k) = \exp(k-\gamma+ o(1)).
$$


text:
Q: Batch File Not Accepting Parameter in the form of %1, %2 I have a simple script that does ftp uploading, the key thing is that I want to pass parameters such as host name, username, password etc into the bat file.
This is my script
@ftp -i -s:"%~f0"&GOTO:EOF
open %1
%2
%3
!:--- FTP commands below here ---
lcd "%4"
cd  %5
binary
put "%6"
disconnect
bye

Now, when I call the script from command line and pass in the %1, %2 ... the %1, %2 content won't get replaced by my command line parameters. This is my command line:
ftp.bat "first" "second" "third" "forth" "five" "six"

Instead of  %1 becomes first, %2 becomes second and so on, the %1 remains %1, so essentially I am opening a ftp side with the name %1 which is completely nonsensical.
Anything I do wrong?

A: That's because, at the point where you're actually processing the file, it's not a batch script at all.
It's an FTP script, which does not do any of that fancy substitution.
You can get your desired effect with a temporary file (based on the original file to avoid clashes) thus:
@setlocal enableextensions enabledelayedexpansion
@echo off
set tmpfl=%~f0.tmp
echo>"%tmpfl%" open %1
echo>>"%tmpfl%" %2
echo>>"%tmpfl%" %3
echo>>"%tmpfl%" lcd "%4"
echo>>"%tmpfl%" cd %5
echo>>"%tmpfl%" binary
echo>>"%tmpfl%" put "%6"
echo>>"%tmpfl%" disconnect
echo>>"%tmpfl%" bye
type "%tmpfl%" && rem ftp -i -s:"%tmpfl%"
del /q "%tmpfl%"
endlocal

The type line is in there for debugging. When you're happy with the script, change:
type "%tmpfl%" && rem ftp -i -s:"%tmpfl%"

to:
ftp -i -s:"%tmpfl%"

A: The problem is that you're passing the file in question to the ftp as a set of commands with the -s switch - "%~f0" expands to be the fully qualified file name of the batch file.  As a result the ftp client is parsing the file verbatim, it doesn't replace %1, %2, etc with the parameters.  That is done by the batch file handler, not the ftp client.
What you can try is writing a temporary file using "echo open %1 > temp.txt", etc, and then use that as an input to the ftp client.
The following appears to work well enough on my system:
echo open %1 > temp1.txt
echo %2 >> temp1.txt
echo %3 >> temp1.txt
rem !:--- FTP commands below here ---
echo lcd "%4" >> temp1.txt
echo cd  %5 >> temp1.txt
echo binary >> temp1.txt
echo put "%6" >> temp1.txt
echo disconnect >> temp1.txt
echo bye >> temp1.txt
@call ftp -i -s:"temp1.txt"&GOTO:EOF


text:
Q: Python 3, difference between print("x:\n{}".format(x)) and print("x:\n",x)? import numpy as np
x = np.array([[1, 2, 3], [4, 5, 6]])
print("x:\n{}".format(x))
print("x:\n",x)

what is the difference between print("x:\n{}".format(x)) and print("x:\n",x) ?
I do not understand the concept of print("x:\n{}".format(x)) and how it works!
when you say .format  what is the dot referring to? to what ever is inside ""?
why we need {}?
Thanks

A: The curly braces are to contain "replacement" fields that describe to the format engine what should be placed in the output. That is, they are special characters the parser uses to determine how to format a particular string object.
If you had multiple arguments to your print function the utility becomes a little clearer:
import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[1, 2, 3], [4, 5, 6]])
z = np.array([[1, 2, 3], [4, 5, 6]])

print("x:\n", x, y, z)

Out:
x:
 [[1 2 3]
 [4 5 6]] [[1 2 3]
 [4 5 6]] [[1 2 3]
 [4 5 6]]

And:
print("x:\n{}\n\n{}\n\n{}".format(x, y, z))

Out:
x:
[[1 2 3]
 [4 5 6]]

[[1 2 3]
 [4 5 6]]

[[1 2 3]
 [4 5 6]]

Or even:
a_list_of_terms = ['the', 'knights', 'who', 'say', 'ni']

print("{}".format(a_list_of_terms))

Out:
['the', 'knights', 'who', 'say', 'ni']

Or you can unpack a list using * for:
print("We are {} {} {} and we demand a shrubbery.".format(*a_list_of_terms))

Out:
'We are the knights who and we demand a shrubbery.'

You can find the official documentation here


text:
Q: How to skip a column? I have textual table:
   13.5         0.12557         0.04243         -0.0073         0.00377
     14         0.12573            0.05        -0.00697         0.00437
   14.5         0.12623         0.05823        -0.00703           0.005
     15         0.12853          0.0686        -0.00627         0.00493
   15.5          0.1299         0.08073        -0.00533          0.0063

where I would like to match all numbers, except those in first column.
I've tried to use negative lookbehind without success:
(?<!^)[\d.E-]+

How to match all numbers except those in first column(13.5, 14, 14.5, 15, 15.5)?

A: Note that in case you do not care about data validation, you may do without a regex here:
var results = line.Split(new[] {"\r", "\n"}, StringSplitOptions.RemoveEmptyEntries)
            .Select(v => v.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries).Skip(1))
            .SelectMany(x => x);
Console.WriteLine(string.Join(",",results));
// => 0.12557,0.04243,-0.0073,0.00377,0.12573,0.05,-0.00697,0.00437,0.12623,0.05823,-0.00703,0.005,0.12853,0.0686,-0.00627,0.00493,0.1299,0.08073,-0.00533,0.0063

In case you want to only match those numbers when the data are numbers, you may use
    var results2 = Regex.Matches(line, @"(?m)(?<!^[\p{Zs}\t]*)(?<=[\p{Zs}\t])-?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?")
            .Cast<Match>()
            .Select(m => m.Value);

See the C# demo.
The -?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)? float/integer number regex is explained here.
Pattern details

*

*(?m) - a multiline modifier that makes ^ match start of the line

*(?<!^[\p{Zs}\t]*) -  a negative lookbehind that  fails the match if there is a start of the string followed with 0+ horizontal whitespace chars after it imediately to the left of the current location

*(?<=[\p{Zs}\t]) - a positive lookbehind that requires a horizontal whitespace before a

*-?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)? - integer/float number regex:

*

*-? - an optional - char

*[0-9]* - 0+ digits

*\.? - an optional . char

*[0-9]+ - 1+ digits

*(?:[eE][-+]?[0-9]+)? - an optional sequence of:

*

*[eE] - a e or E char

*[-+]? - an optional - or + char

*[0-9]+ - 1+ digits.


text:
Q: How to control order of Batch Build → Build All I have a C++ solution with 4 projects and 24 configurations. The projects are cryptest, cryptlib, cryptdll and dlltest. And then there's a partial cross product of x86, x64, debug, release, DLL export, and DLL import.
There's a not-so-apparent dependency that I can't seem to express under the UI or by modifying the project files by hand. The dependency is all the DLL related projects depend upon cryptest, Release Win32.
Visual Studio allows us to build all configurations by selecting the Build menu, and then Batch Build... → Select All → Build. When I perform a Build All, the first configuration built is:
------ Build started: Project: cryptlib, Configuration: DLL-Import Debug x64 ------
Performing Custom Build Step
 Assembling: c:\Documents and Settings\cryptopp-5.6.3\x64masm.asm
Performing Custom Build Step
Compiling...
pch.cpp
...

As can be seen above, the machinery chooses cryptlib, DLL-Import Debug x64 as its first choice. I want the following order:

*

*cryptlib, Release Win32

*cryptest, Release Win32

*Don't care about remaining 22....

The problem is I cannot tell Visual studio that all Win32 and x64 DLL projects depend upon the Win32 cryptest.
How can I control the order of Batch Build → Build All?

Currently I have to run through Build All twice. The first ends with:
========== Build: 20 succeeded, 4 failed, 0 up-to-date, 0 skipped ==========

The second run ends with:
========== Build: 4 succeeded, 0 failed, 20 up-to-date, 0 skipped ==========

When reordering the solution file's GlobalSection(ProjectConfigurationPlatforms) with a text editor (and placing them in the exact order I want), these are the kind of warm and fuzzy results I encounter. The 24 configurations will build with Build All under Visual Studio 2005, but Build All does nothing (literally, nothing) under Visual Studio 2008 after testing an upgrade.
And when I manually try to build a project (right click project, then Build), I get a result like:
1>------ Skipped Build: Project: cryptlib ------
1>
2>------ Skipped Build: Project: cryptest ------
2>

With no reasons or explanations. It sure would be nice if Visual Studio provided a log file in an attempt to decipher the behavior.

A related issue is Visual Studio selects << some project >> as the default Startup project with no declarative way to change it. That means a particular project needs to be the first one listed in the solution file, and that cannot change.

I'm having a hard time finding a solution that is amicable to both Visual Studio 2005 (how the source files are distributed) and a post-Visual Studio 2010 upgrade (how some folks use it).
I can kind of find some information on the subject, like Project settings changes with VS2010 from a blog. But its not really clear how to effect a dependency change as described above, and the blog only applies to VS2010 or above.

A: Create a x86 and x64 project for cryptest and cryptlib.
For each x86/x64 project pair, use Add As Link to link to all the files in the other project so you only have just one copy of each file.
...links shown with the red arrows...

Configuration Manager
Use Configuration Manager to build x86 only for the x86 projects, and x64 only for the x64 projects.
Also use the dropdown for each Platform and remove the extra platform that does not apply to the corresponding project.
Also ensure that for x86 builds you are not building x64 targets, and for x64 builds you are not building x86 targets by unchecking the appropriate Build checkbox.

Dependencies
Create dependencies as such:

*

*cryptlib32 depends on nothing

*cryptest32 depends on cryptlib32

*cryptlib64 depends on cryptlib32 and cryptest32

*cryptest64 depends on cryptlib64

*all your remaining projects depend on cryptlib32/64 and cryptest32/64 as appropriate

...one example...

Result
This should produce the results you want.
Testing
In my test project, this worked as expected.  I named all my code with the prefix ClassLibraries, and just added lib and test on the end to mimic your config, and final is just any project after the first two projects...
The x86 lib and test build first, x64 lib and test next, and all the other stuff follows...
------ Rebuild All started: Project: ClassLibraryLib32, Configuration: Debug x86 ------
  ClassLibraryLib32 -> C:\Users\Kory\Source\KoryG-Code\Solution1\ClassLibraryLib32\bin\x86\Debug\ClassLibraryLib.dll
------ Rebuild All started: Project: ClassLibraryLib32, Configuration: Release x86 ------
  ClassLibraryLib32 -> C:\Users\Kory\Source\KoryG-Code\Solution1\ClassLibraryLib32\bin\x86\Release\ClassLibraryLib.dll
------ Rebuild All started: Project: ClassLibraryTest32, Configuration: Release x86 ------
  ClassLibraryTest32 -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryTest32\bin\x86\Release\ClassLibraryTest.dll
------ Rebuild All started: Project: ClassLibraryTest32, Configuration: Debug x86 ------
  ClassLibraryTest32 -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryTest32\bin\x86\Debug\ClassLibraryTest.dll
------ Rebuild All started: Project: ClassLibraryLib64, Configuration: Debug x64 ------
  ClassLibraryLib64 -> C:\Users\Kory\Source\KoryG-Code\Solution1\ClassLibraryLib64\bin\x64\Debug\ClassLibraryLib.dll
------ Rebuild All started: Project: ClassLibraryLib64, Configuration: Release x64 ------
  ClassLibraryLib64 -> C:\Users\Kory\Source\KoryG-Code\Solution1\ClassLibraryLib64\bin\x64\Release\ClassLibraryLib.dll
------ Rebuild All started: Project: ClassLibraryTest64, Configuration: Release x64 ------
  ClassLibraryTest64 -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryTest64\bin\x64\Release\ClassLibraryTest.dll
------ Rebuild All started: Project: ClassLibraryTest64, Configuration: Debug x64 ------
  ClassLibraryTest64 -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryTest64\bin\x64\Debug\ClassLibraryTest.dll
------ Rebuild All started: Project: ClassLibraryFinal, Configuration: Release x86 ------
  ClassLibraryFinal -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryFinal\bin\x86\Release\ClassLibraryFinal.dll
------ Rebuild All started: Project: ClassLibraryFinal, Configuration: Release x64 ------
  ClassLibraryFinal -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryFinal\bin\x64\Release\ClassLibraryFinal.dll
------ Rebuild All started: Project: ClassLibraryFinal, Configuration: Debug x86 ------
  ClassLibraryFinal -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryFinal\bin\x86\Debug\ClassLibraryFinal.dll
------ Rebuild All started: Project: ClassLibraryFinal, Configuration: Debug x64 ------
  ClassLibraryFinal -> c:\users\kory\Source\KoryG-Code\Solution1\ClassLibraryFinal\bin\x64\Debug\ClassLibraryFinal.dll
========== Rebuild All: 12 succeeded, 0 failed, 0 skipped ==========


text:
Q: SimpleAudioEngine file path crash I'm trying to play a .caf file using simpleaudioengine but I get an exception every time I try to reference the file. The compiler gives me the following: 'NSInvalidArgumentException', reason: '* -[NSURL initFileURLWithPath:]: nil string parameter'.
I think it's caused by an invalid file path, but I'm not sure how to fix it. I dragged the file into the resource folder in Xcode and confirmed it was included in my project folder.
This is the first time I've used simpleaudioengine in my project. The only lines I've added are the import at the top and this:
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"bgMusic2.caf"];

A: Make sure your sound bgMusic2.caf is included in your bundle resources,
Add your music file to
[project name]->[target name]->Build Phases->Copy Bundle Resources
And it should work without a problem.


text:
Q: Using a file for input in C I trying to write a program which takes a text file as input and then does a binary search with user input. The problem is, when I compile and run it, the program automatically quits and exits and never allows for user input.
I suspect it is still reading the data file somehow, but it should be running out of options. Any ideas?
The code:
#include <stdio.h>
#include <stdarg.h>

int A[100];
char search;
int i, key, len, imin, imax, KEY_NOT_FOUND;
int result;

main() {
// Scan in array length.
scanf("%d", &len);
// Scan in array integers.
for(i = 0; i < len; i++) {
    scanf("%d", &A[i]);
}

imin = 0;
imax = len - 1;

printf("Welcome to Binary Search!");
printf("\nDo you want to search for an integer? (y/n) ");
scanf("%c", &search);

while(search == 'y') {
    printf("\nDo you want to search for an integer? (y/n) ");
    scanf("%c", &search);

    result = binary_search(*A, key, imin, imax);
    printf("\n%d", result);
}
}

int binary_search(int *A, int key, int imin, int imax) {

// Test if array is empty
if(imax < imin)
    // Set is empty, so return value showing not found.
    return KEY_NOT_FOUND;
    else {
    // Calculate midpoint to cut set in half
    int imid = midpoint(imin, imax);

    // Three-way comparison
    if(A[imid] > key)
        // Key is in lower subset.
        return binary_search(A, key, imin, imid - 1);
    else if(A[imid] < key)
        // Key is in upper subset.
        return binary_search(A, key, imid + 1, imax);
    else
        // Key has been found.
        return imid;
    }
}

int midpoint(int imin, int imax) {

int imid = imax / 2;
return imid;
}

Here is the text file:
10
-144 -1 0 10 75 233 341 1000 8192 57885161

Sample Command Entry:
a.out < data.txt

Sample Output:
Welcome to Binary Search!
Do you want to search for an integer? (y/n) y
Enter the Integer: 341
341 Found!
Do you want to search for an integer? (y/n) n
The End!

EDITED because answers have not taken question into consideration. Code does not print n found yet.

A: Probably your immediate first problem is this:
 scanf("%c", &search);

%c does not skip whitespace (unlike %d), so if there's
a newline or something in the input that has not been eaten at that
point, then search will not equal 'y', and the program will exit.
There are certainly other problems, but that seems like the one
causing the confusing immediate exit. If you use a compiler flag that
asks for as many warnings as possible, the compiler may help you
find some of the other problems...
Just before you want to read the 'y', you can use a loop to eat up all non-white space characters. For example:
while(scanf("%*[ \t\r\n]") > 0)
    ;

Then, your program will read the 'y' successfully, and proceed on to the next place it's going to crash. :-)
Of course, this assumes you haven't redirected stdin. If you have redirected stdin to a file, then that file must contain the answers to the y/n questions. If you really want the data stored in a file, but the questions asked/answered interactively, then you're going to need the user to pass you the filename on the command-line, use fopen to open that, and using the resulting handle when you want to read from the file instead of the keyboard.

A: First of all your program won't wait for user input. Add getchar(); at the end of main() or slightly modify scanf:
printf("\nDo you want to search for an integer? (y/n) ");
scanf(" %c", &search);
     //^ added space

Next, your program is not reading file - implement it as mentioned above/below.

A: To read from a file in C you should use something like that :
FILE *inputfile;
char *mode = "r"; //we use r because you just want to read file
inputfile = fopen("YOURFILENAME", mode);

after that you can use "fscanf" function to read values from your file :
fscanf(inputfile, "%d", &len);

and after finish reading from file just write :
fclose(inputfile);


text:
Q: XML: SVG - How to wrap a block of text in a rectangle For example, I want to put some text on top of a rectangle.
<rect x="0" y="0" width="800" height="600" />
<text x="0" y="0">
    text text text text text text text text text text text text ... so on
</text>

But the problem is that when the text get longer and longer, it will exceed the original width of the rectangle.
In HTML we can use div to wrap the text,
in SVG how can we deal with it?

A: you may want to play with the flow* part of the svg1.2 draft specification.
http://www.w3.org/TR/2004/WD-SVG12-20041027/flow.html
For example :
<flowRoot>
<flowRegion>
<rect x="0" y="0" width="800" height="600" />
</flowRegion>
<flowDiv>
<flowPara>text text text text text text text text text text text text ... so on</flowPara>
</flowDiv>
</flowRoot>

Today, it works with inkscape, and with batik as long as the svg version is properly set.
edit: @Robert Longson It may not be standard, but it could save your day (waiting for a decent svg 2.0 implementation), given the fact inkscape and batik are available on both windows and linux, and are able to convert/rasterize from CLI...


text:
Q: Are all weapon mods compatible? Are there any weapon mods that can't be used with other ones. I know different verions of the same mod cannot be combined as they get replaced with better ones, but can all discreet mods be used together?

A: Nope! No exclusivity! All mods work together. You can mix and match to your heart's content.
Though you better have a small heart; there are only 5 mods per weapon total.


text:
Q: How to run one specific test by using tox? This is the path to the project
D:\QA\test-framework\python-client

This is a test frame work implemented by python
This is the python file that contains tests
This is the path to the test case that I need to run
D:\QA\test-framework\python-client\test_data\tests\curve.json

This is the beginning of the curve.json file.
 {

"Sklearn - Sklearn - Regression - Curve M2" : [
    {
        "dataImport": {
            "
            "
            "

]

}
This is the tox.ini file
[tox]
envlist = py38

[testenv]
deps =
    pytest
    pytest-html
    pytest-sugar
    pytest-logger
    allure-pytest
    pytest-xdist
    pytest_steps
    datetime
    oauth2client
    gspread
    aiclub
commands =
    pytest -s -v -k _workflow  --html=test_report.html --alluredir=allure-
    results/ -n auto --dist=loadfile
    allure serve allure-results
    pytest {posargs}

I need to run only this curve.json using tox command

A: The easiest way is to use -k option with a string that contains an expression that matches all tests you need to run e.g.
tox -e py38 -- -k "test_first_function or test_another_function"


text:
Q: Visual Studio - C# 'out' variable intellisense completion In C#, I often use the "Try..." methods to retrieve a value via an out variable. For example, the TryGetValue method on Dictionary. I notice that Visual Studio 2019 IntelliSense shows a reasonable out parameter type and default variable name, like out SubscriptionItem value in the example shown below. However, I can't figure out a way to autocomplete this and accept the suggested parameter definition in the manner of an expanded snippet.
Is there a way to autocomplete this without manually typing out what IntelliSense is already suggesting?

A: Since it doesn't appear Visual Studio does this yet, I've added a feature request to vote or track:
https://developercommunity.visualstudio.com/idea/1108309/c-out-variable-intellisense-completion.html
Update: this is now an issue in the Roslyn GitHub repo:
https://github.com/dotnet/roslyn/issues/46268


text:
Q: What are the triggers for the inner circle quests? I've done a few companion quests already, but there are some companions where I didn't get any quests so far. I'm beyond Skyhold and already finished one of the two main quests after that point.
I'm wondering if I missed certain triggers for some companions, or maybe I simply didn't have a high enough approval with them. I'm also wondering how the generic collection quests available for some companions (e.g. Red lyrium for Varric and Warden stuff for Backwall) relate to the actual companion quests. I got the companion quest for Varric before even fulfilling the Red lyrium quests, so I'd assume they are unrelated.
So how do I unlock each companion quest exactly? I'd appreciate reasonably spoiler-free answers, as far as that is possible in this case.

A: According to the game guide that I have (Prima, I believe, but it's at home right now), the companion quests are unlocked once you have reached the requisite approval threshold with that specific companion.  Further, the collection quests do not contribute directly to this, but they do help you to get more approval and if you have the companion with whose collection quest it is, you gain a greater amount of approval.


text:
Q: How to get extract Xpath for following? How to get exract xpath for the following name(I1888 - Child 1.1). now i am using following xpath "//span[contains(@class,'TreeTitleRed')][contains(.,'Child 1.1')]" but i need to get xpath without contains. please help me

       class ="Vegan tree"
       I1888 -Child 1.1

A: You can use the following if you want it in xpath
//span[@class='treeTitlered']

Or you can directly find the locator by using the classname
driver.findElement(By.className("treeTitlered"));

Hope this helps.

A: You can also use.
//div/child::span[1]/child::span[1]

This will surely work for you, do let me know in case of any further queries.

A: You can also use
//div/span/child::span[@class="treeTitlered"]

A: You can stick to parent  tag and locate it using its class attribute of Vegan tree.
Once done you can query its innerText property which will return I1888 - Child 1.1 text
Example code (assumes WebDriverWait just in case)
WebElement veganTree = new WebDriverWait(driver, 10)
        .until(ExpectedConditions
                .presenceOfElementLocated(By
                        .xpath("//span[@class='Vegan tree']")));

System.out.println(veganTree.getAttribute("innerText"));

Demo:


text:
Q: Sony SmartWatch - override power button and double tap functionality I am using the control and sensor api from the Sony SmartExtension SDK, while reading in the data from accelerometer if the power button or the screen is double tapped with two fingers i lose connection to the accelerometer feed. Is there any way to detect these events and override native behaviour?

A: There is no way to override double tap or hardware button on Sony Smartwatch 1 since they help with basic navigation and hardware reset. This is an inherent behavior of the watch to save battery.


text:
Q: Can parallel insert statements in sql lead to deadlock? I am having a SP that is doing a select union of many tables with no lock. This will do lot of calculations with many groupings and sumation and so will take about 2 min for its run. I need to run this for about 500 different set of data. So It totally takes about 1000 min.
To reduce this I need to run this calculation in parallel. So if i run for 4 set of data in parallel I should be done in about 250 min.
But the problem is that once i am done with this calculations I get a set of data that i need to store into a table which has some primary key constraints on 4 of its columns. So when running in parallel I am expecting some dead lock issues. So I was thinking of writing this data to a temporary table that will have the same columns but with no primary key or any constraints.
So with this I am expecting there should be no dead lock. Please advice in this regards and let me know if my understanding is right. Thank you.

A: INSERT cannot deadlock against another INSERT on the same table, because two INSERT statement on the same table will always acquire the locks in the same order. That being said, I must comment on your statement:

if i run for 4 set of data in parallel I should be done in about 250 min.

You have no reason to expect this. First and foremost such a claim denotes you ignore Amdahl's law. Second a SQL workload is already parallelism internally, the queries in your procedure use parallel plans whenever possible, see Parallel Query Processing, especially if it contains many 'groupings and summations'.
Ultimately what you're facing is an optimization task. Approach it like any other optimization task, identify the bottlenecks first. Waits and Queues is a must read as you embark this journey.


text:
Q: Get list of filenames in assets folder with Typescript How do I get all filenames in a folder using Typescript?
It's for an angular 2 project.
To be more specific, what I'm trying to do is set the images for a bootstrap carousel using images from my photos folder. Currently I'm doing this:
private _images: Image[] = []

ngOnInit(): void {
    this._images = [
        { "title": "Slide 1", "url": "../photos/carousel/gg_slide 1.jpg" },
        { "title": "Slide 2", "url": "../photos/carousel/gg_slide 2.jpg" },
        { "title": "Slide 3", "url": "../photos/carousel/gg_slide 3.jpg" },
        { "title": "Slide 4", "url": "../photos/carousel/gg_slide 4.jpg" },
        { "title": "Slide 5", "url": "../photos/carousel/gg_slide 5.jpg" }
    ]
}//ngOnInit

Then using the the images array in the html file like this:
<carousel>
    <slide *ngFor="let img of _images">
        <img src="{{img.url}}" alt="{{img.title}}">
    </slide>
</carousel>

I'd like to be able to just loop through whatever files are in the photos folder and add them to the images array.
That way all I have to do to update the carousel is to change the photos in the photos folder.

A: I have been unable to find a solution using Javascript. It appears that JS does not have the ability to read file structures. Instead you will have to keep a list on the backend in a database or create a json file that you keep up to date with all of the icons manually.
I have found this example.
As accessing file from assets folder is easy, so we can exploit it and we can store an array of icon file names in the file say, icons.json.
1. Create icons.json as following in the assets folder-
{  // ---------- icons.json---------
  "icons-array" : ["icon-name1", "icon-name2", "icon-name3"]
}

2. Keep icon-name1.svg, icon-name2.svg, icon-name3.svg file in the assets/icons folder.
3. Read icons-json file at start-up of the angular application.       How to read file at Angular Application Start-up
4.   After reading icons.json content, store value of icons-array property into a global accessible array, say     globalAccessibleIconsArray.
 5.  And use the array as-
for (const icon of globalAccessibleIconsArray) {
      this.matIconRegistry.addSvgIconInNamespace(
        'my-namespace',
        icon,
        domSanitizer.bypassSecurityTrustResourceUrl(`./assets/icons/${icon}.svg`)
      );
    }

 So, for Adding a new icon

*

*you have to put the new icon file in the assets/icon folder, and

*add the new file name in the icons.json file present in the assets folder.


text:
Q: Setting different prices for different store or website? We are currently running a one domain, one website, one store, several store views  (languages) magento install.
We are looking into setting up another domain to handle a more localized market with different prices.
So I went into the backend and first set up a new store as well as two new store views for it. I choose the same root cat. for this one.
I find that it is not possible to select the store in the scope drop down in order to edit products. So I can not change product prices based on the store only based on store views.
I want all store views under the new store to have the same price without assigning it twice for each product.
Second I went to add a new website in the backend, created a new store for it as well as a new store view. I was hoping to be able to edit prices under the website scope, but this does also not work as one is again able only to select a store view.
I might have overlooked something here. How am I to set different prices for seperate stores OR websites?
Update: So I have added a new root category to the new website store and added a product to it to test it out. I have assigned this product to both the main website store as well as the new website store.
When I go to edit view of this product and try to choose the website in the scoope selector I am not able to select website. It will only let me select a
store view instead.
We are using Magento 1.9.0.1
The bottom line is I am able to set prices for each store view under each website. But it is not possible to set a price for a website including all store views under it. This would mean that for each product on the new website we would have to set the price twice once for each store view as the new website will have two languages.
Can someone confirm if this is the way it is supposed to work or have I gone
wrong here?

A: You can just set the price for all store views belonging to that website, especially to set up different prices for same products per store view of each store. It means that if your store has many store views, you can absolutely set up various prices for the same product for each store view.
For example, if there are two store views in a store: English and Germany and you want to sell a product at two prices with its own store view currency such as £20 and €35 respectively. Magento default cannot allow you to do this thing at all. Therefore, if you want to do this one, you can use an extension like Multiple store view pricing I used to find on Magento Connect
https://www.magentocommerce.com/magento-connect/multistore-pricing-extension.html
It seems that it can also helps to set up base currency for each store view to replace for default currency as US Dollars of Magento.

A: You can set price per website basis.
you need to go to System->Configuration->Catalog.
Then in the tab "Price", set Catalog Price Scope to "Website" instead of global.

A: Ok, I found that it is possible to set the price per website.
I just got a little confused as the selector (upper left corner) did not allow
for selecting the website level but only the store view level. So I tried out
a few things and found that if one wishes to set the price on website level one
has to select one language (store view) of that website in order to set the price.
The price is then set for all store views belonging to that website.

A: You have 2 options:

*

*Set Price globally

*Set Price per website (you then can have different base currency and setup specific price in the currency rather than use the currency converter)

But even if you choose in System->Configuration->Catalog->Catalog Price Scope => Website
you still can't select the website scope in the admin product, so this can be considered as a UI bug.
Anyway if you choose any of the store view below, prices will be updated in every store view of the current website scope.

A: I use Magmi. There is a way for setting in both ecommerce (ita and eng) same price?
If i select

Global
the ecommerce set

it's correct?
Ale


text:
Q: VBA CopySheetsFromClosedWorkbook but overwrite (update) existing sheets with new values What I am trying to do is to have MACRO which will copy the data sheets from external workbook and copy (same data) them into my active workbook. I am getting unfortunately doubled sheets at the end of my active wb.,which I have to delete manually. I need a way to achieve it with VBA but to preserve the same name of sheets, but only data to be copied!
This is a code I am trying to use:
Public Sub CopySheetFromClosedWorkbook()

Dim sourceBook As Workbook
Application.ScreenUpdating = False

Set sourceBook = Workbooks.Open("C:\Users\MV\Desktop\1234\1234_CustomerVersion.xlsx")
sourceBook.Sheets("1234 - customer's form").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "1234 - customer's form"
On Error GoTo 0
sourceBook.Sheets("abcd").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
On Error Resume Next
ActiveSheet.Name = "abcd"
On Error GoTo 0
sourceBook.Close

Application.ScreenUpdating = True

End Sub

This is simplified version of the code that I am using, getting copied sheets which is not my goal.
Public Sub CopySheetFromClosedWorkbook()

Dim sourceBook As Workbook

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Set sourceBook = Workbooks.Open("C:\Users\MV\Desktop\1234\1234_CustomerVersion.xlsx")

sourceBook.Sheets("1234 - customer's form").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

sourceBook.Sheets("abcd").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

sourceBook.Close

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

A: Copy Sheets From Workbook to Workbook
The following will delete the worksheets with the names contained in the array shNames (if they exist) in the Target Workbook (tgt) and will then copy the same sheets from the Source Workbook (src) (if they exist) to the Target Workbook (tgt).
Option Explicit

Sub CopySheetFromClosedWorkbook()

    Const FilePath As String = _
      "C:\Users\MV\Desktop\1234\1234_CustomerVersion.xlsx"
    Dim shNames As Variant: shNames = Array("1234 - customer's form", "abcd")
    Dim tgt As Workbook: Set tgt = ThisWorkbook

    Application.ScreenUpdating = False

    Dim src As Workbook: Set src = Workbooks.Open(FilePath)

    Dim ws As Worksheet, i As Long

    For i = 0 To UBound(shNames)
        ' Check if Target Worksheet exists.
        On Error Resume Next
        Set ws = tgt.Worksheets(shNames(i))
        If Err.Number = 0 Then
            Application.DisplayAlerts = False
            ws.Delete
            Application.DisplayAlerts = True
        End If
        On Error GoTo 0
        ' Check if Source Worksheet exists.
        On Error Resume Next
        Set ws = src.Sheets(shNames(i))
        If Err.Number = 0 Then ws.Copy After:=tgt.Sheets(tgt.Sheets.Count)
    Next i

    src.Close False

    Application.ScreenUpdating = True

End Sub

EDIT:
This one will copy the Used Range from the Source to the Target Worksheets.
Sub CopySheetFromClosedWorkbook2()

    Const FilePath As String = _
      "C:\Users\MV\Desktop\1234\1234_CustomerVersion.xlsx"
    Dim shNames As Variant: shNames = Array("1234 - customer's form", "abcd")
    Dim tgt As Workbook: Set tgt = ThisWorkbook

    Application.ScreenUpdating = False

    Dim src As Workbook: Set src = Workbooks.Open(FilePath)

    Dim ws As Worksheet, rng As Range, i As Long

    For i = 0 To UBound(shNames)
        On Error Resume Next
        Set ws = src.Sheets(shNames(i))
        If Err.Number = 0 Then
            tgt.Worksheets(shNames(i)).Cells.Clear
            Set rng = ws.UsedRange
            rng.Copy tgt.Worksheets(shNames(i)).Range(rng.Address)
        End If
    Next i

    src.Close False

    Application.ScreenUpdating = True

End Sub


text:
Q: cyclejs extract target from input text during map operation  Main.ts

    const clickMessages$ = sources.DOM
            .select('.add')
            .events('click');

        const latitudeMinimum$ = sources.DOM
            .select('.latitudeMinimum')
            .events('input');

        const latitudeMaximum$ = sources.DOM
            .select('.latitudeMaximum')
            .events('input');

        const latituteRange$ = xs.combine(latitudeMinimum$, latitudeMaximum$);

        const newStream$ = xs.combine(clickMessages$, latituteRange$);
        const filter$ = newStream$.filter(c => { return true });
        const map$ = filter$.map(([a, [b, c]]) => { return [b.target.value, c.target.value] }
// <<--- b.target.value won't compile... was expecting to get my value from input field

A: The thing is, the target of a DOM event is of type EventTarget as you can see here https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.generated.d.ts#L3661 The generic EventTarget type only has a few methods.
In your case, you know exactly what kind of element will be in the target.
So in order to tell the compiler that your target has the value property, you need to cast it into a more concrete type (`HTMLInputElement for example https://github.com/Microsoft/TypeScript/blob/master/src/lib/dom.generated.d.ts#L5248)
I don't think you can do that in a single shot (or at least I am not aware of a technique to do that), so you would need another map.
const latitudeMinValue$ = latitudeMinimum$
  .map(event => event.target)
  .map((element: HTMLInputElemnet) => element.name)

const latitudeMaxValue$ = latitudeMaximum$
  .map(event => event.target)
  .map((element: HTMLInputElemnet) => element.name)

const latituteRange$ = xs.combine(latitudeMinValue$, latitudeMaxValue$)
  .map(/*([minValue, maxValue])*/);

An even cleaner way to do this (as we are repeating the map().map() twice, so we are not very DRY) we can use the compose operator given by xstream.
function eventToTargetValue(event$ Stream<Event>) {
  return event$.map(event => event.target)
    .map((element: HTMLInputElement) => element.value)
}

const latitudeMinValue$ = latitudeMinimum$
  .compose(eventToTargetValue)

const latitudeMaxValue$ = latitudeMaximum$
  .compose(eventToTargetValue)

const latituteRange$ = xs.combine(latitudeMinValue$, latitudeMaxValue$)
  .map(/*([minValue, maxValue])*/);

Hope it helps :)


text:
Q: When I scroll my web page, audio box just passes over the navigation bar, how to fix this issue. I don't want to show it on navigation bar This is the code I am using. Also please tell, When anyone click the image which start the music will change while playing and again change image when stop playing.
        <img id="startOrStopImg1" class="audioimage" src="short images/cdd.png" alt="চালু করুন">
        <audio id="audio" src="short images/riya.mp3" type="audio/mp3" controls>Your browser does not support the
            audio element</audio>

    This is the code I am using. Also please tell, When anyone click the image which start the music will change while playing and again change image when stop playing.

A: Try to use the CSS property z-index! Higher index brings the element closer to the top.


text:
Q: Sort items in a nested hash by their key I have a nested hash with unsorted keys:
given =  {
  "lorem" => {
     :AA => "foo",
     :GR => "foo",
     :BB => "foo"
  },
  "ipsum" => {
    :ZZ => "foo",
    :GR => "foo",
  }
}

What I'm trying to accomplish is a hash with sorted keys:
goal =  {
  "ipsum" => {
    :GR => "foo",
    :ZZ => "foo"
  },
  "lorem" => {
     :AA => "foo",
     :BB => "foo",
     :GR => "foo"
  }
}

I have experimented with .each method and sort_by
given.each { |topic| topic[:key].sort_by { |k, v| k } }

But I'm getting an error message: TypeError: no implicit conversion of Symbol into Integer
Any help is greatly appreciated!
PS: I noticed with gem pry the output is already sorted. But in IRB it's not.

A: You can use group_by, and transform_values to transform the values inside each hash, also using sort_by plus to_h:
given.transform_values { |value| value.sort.to_h }.sort.to_h

# {"ipsum"=>{:GR=>"foo", :ZZ=>"foo"}, "lorem"=>{:AA=>"foo", :BB=>"foo", :GR=>"foo"}}

You're getting an error because when iterating over a hash, you have to local variables within the block scope to use, the key and its value, you're assigning only one (topic) and trying to get its key, which would be trying to access a key in:
["lorem", {:AA=>"foo", :GR=>"foo", :BB=>"foo"}]

Which isn't possible as is an array. You can update your code to:
given.each do |topic, value|
  ...
end

But anyway you'll need a way to store the changes or updated and sorted version of that topic values.

A: given_hash =  {"lorem"=>{:AA=>"foo", :GR=>"foo", :BB=>"foo"}, "ipsum"=>{:ZZ=>"foo", :GR=>"foo"}}

Get keys
given_hash.keys
=> ["lorem", "ipsum"]

New sorted hash
new_hash = {}
given_hash.keys.sort.each do |sorted_key|
  new_hash[sorted_key] = given[sorted_key]
end

 => {"ipsum"=>{:ZZ=>"foo", :GR=>"foo"}, "lorem"=>{:AA=>"foo", :GR=>"foo", :BB=>"foo"}}

There can be a better way to do this.


text:
Q: Passing PHPSESSID in query string to maintain state in iframe - good practice? I would like to allow the user to be "logged in" and maintain state / logged in status between pages within an iframe. The iframe content is ours, and will be hosted on various clients' websites.
Since the usual session cookie will most likely be blocked as a third party cookie I am trying to find a suitable way to do this.
I am considering always passing ?PHPSESSID=xin the query string for each relevant url as a workaround.
Is this considered bad practice and are there any risks involved?


text:
Q: Can skipping `fsck` on boot impact serial-port communication? I have a bizarre serial-port (RS-232) communications issue (it appears that some data is being dropped, though I'm not sure if it's outgoing, incoming, or both) that I'm observing sporadically. I've been having trouble reproducing it, and I was just told that the few times we have seen the issue arise, the Linux machine running my app was first shut down using shutdown -fh now, which skips fsck on reboot.
Even so, the communications problem usually doesn't occur until the app performing the serial communication on the Linux machine has been running for a while--somewhere between half an hour and several hours.
Is it possible for there to be some sort of latent file-system issue that could cause instability in the serial-port communication layer?
It also appears that shortly before I see the error, the serial-port class I'm using emits a "ResourceError". The Qt document describes a resource-error as:

An I/O error occurred when a resource becomes unavailable, e.g. when the device is unexpectedly removed from the system.

Does that sound like something that could occur as the result of skipping a fsck...?
I'm using ext4 for my filesystem format.


text:
Q: Git fails to tag After running any git command dealing with tagging except for list it prints 70 to the terminal and hangs until I terminate it. It also does it when I specify a commit made. Any ideas how to resolve this?
Command Ran:
git tag -a iteration2-1

A: It can depend on the version of Git, and OS (Linux, Windows, Mac) used: see for instance "git operations occasionally hang in Jenkins on Windows".
From your previous question, if you are using Ubuntu 12.04 LTS, try and upgrade git (with a 2.2+) to see if the issue persists.
Note that git tag -a is suppose to create a tag, not to list one.
That means it should be git tag -a tagname acommit.

A: Using an annotated (-a) tag requires a message. Your git editor is likely misconfigured, and git is trying (and failing) to open the editor to type the tag message. Try passing the message on the command line, e.g., $ git tag -a iteration2-1 -m 'this is iteration2'


text:
Q: Creating a Parcelable class with a secondary constructor that takes a list as parameter in Kotlin I'm getting started with Kotlin and trying to implement a parcelable object that receives a list of strings as parameter of the secondary constructor. However, I'm getting the error:

Cannot access '< this >' before super class constructor has been called

here is my code:
class StringChecker(val stringList : List<String>) : Parcelable {

    var mStringList = stringList

    constructor(parcel: Parcel) : this(parcel.readStringList(mStringList))

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeStringList(mStringList)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<StringChecker> {
        override fun createFromParcel(parcel: Parcel): StringChecker {
            return StringChecker(parcel)
        }

        override fun newArray(size: Int): Array<StringChecker?> {
            return arrayOfNulls(size)
        }
    }

}

I understand that I cannot call the member variable mStringList before creating the object and that of course makes sense, however the readStringList method requires a string list parameter. How can I resolve this issue? Is this a problem of my design parcelable vs taking list as constructor parameter?

A: You can't use fields in secondary constructor. Use createStringArrayList() instead of readStringList(mStringList)
constructor(parcel: Parcel) : this(parcel.createStringArrayList())

A: For this specific case, you could write it as
constructor(parcel: Parcel) : this(mutableListOf<String>()) {
  parcel.readStringList(mStringList)
}

But I would prefer just to make it a factory method, not a constructor. Especially since you need it for a factory method anyway. Namely:
companion object CREATOR : Parcelable.Creator<StringChecker> {
    override fun createFromParcel(parcel: Parcel): StringChecker {
        val stringList = mutableListOf<String>()
        parcel.readStringList(stringList)
        return StringChecker(stringList)
    }

    override fun newArray(size: Int): Array<StringChecker?> {
        return arrayOfNulls(size)
    }
}

Some more: you probably don't want to have both stringList and mStringList properties, as your code currently does. If it needs to be var, just do class StringChecker(var stringList : List<String>) instead. Also look at @Parcelize.


text:
Q: Not supported (tabular model 1200 or higher required) I get the following error in Visual Studio when I'm working with SSAS Tabular project.
"Not supported (tabular model 1200 or higher required)"

*

*SQL Server 2014 Developer Edition

*Visual Studio 2015

A: Install sql server management studio 2016,
after that install sql server data tool which automatically install visual studio
this will solve your problem


text:
Q: How do I specify an existing docker-compose.yml file in my devcontainer I have an existing project with a docker-compose.yml file that runs a zookeeper and kafka image. How do I specify that the docker-compose.yml file needs to be loaded in my devcontainer.json?
Would it be possible to not modify the docker-compose file since others are using the same file, but not using VS Code. The docker-compose.yml looks like this.
---
version: '1'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:latest
    environment:
      xxxxx
    expose:
     xxxxx

  kafka:
    image: confluentinc/cp-kafka:latest
    depends_on:
      - zookeeper
    environment:
        xxxxx
    expose:
      xxxxx

Thanks!


text:
Q: I want to implement RAID 1 for my two hard disks My system configuration is:

*

*Intel Core 2 Duo 2.2 Ghz with FSB 800MHZ and 2 MB L2 Cache

*Intel D945 GCNL Motherboard, which features 4 SATA and 1 IDE

*Mileinium RAID card, with 4 SATA and 1 IDE

*2 * 500GB Samsung hard disks, 1 * 500GB Seagate hard disk

I am using Windows XP.
Question
One of the Samsung hard disks is full, and 1 Samsung and the Seagate are empty.
I want to implement RAID 1. I have tried with 2 hard disks connected to RAID adapater, and one to the motherboard. But my system would hang and did not displaying the Intel logo of the motherboard.
Please tell me the how to alter the configuration to do RAID 1 with 2 hard disks, and what the problem might be with my current arrangement?
Thanks

A: It can be very hard to convert an existing hard drive to RAID, especially when using hardware RAID cards (as compared to software RAID where you sometimes get useful convert tools).
The best thing I can suggest, and it isn't that convenient, is to backup all your data then setup RAID and then reinstall your operating system and copy the data back.
If this is Windows, you may have luck either by performing a Sysprep generalise before shutting down for the last time then just copying all the data back to the RAID array, or at a last resort doing a repair install.
Raid is something that really needs to be thought about when initially setting up a machine, it is hard to migrate to at a later date as hard drives usually need to be prepared. I hope this does help you - if you need more info about sysprep, let me know and I will write it.

A: Another suggestion is to use Acronis or similar program to make a Full Disk Image of your current hard drive, then set up your Raid 1, then use the Acronis boot CD to put the image you made onto the new raid 1 array, it is the fastest way to do what you want. This method be used if you are using software Raid.

*

*I Purchase and Install Acronis on your current installation of Windows, make a Full disk Image (all partitions), save the image to an external usb hard drive.

*Verify the Image using Acronis verify feature.

*Use the Media Builder in Acronis to make the Acronis boot cd

*Install your 2 hard drives and set up the raid array. (You never stated if you have on board raid or a controller card, so you will have to consult documentation for your hardware on how to do this)

*Boot from the Acronis CD, recover the image you made and install it on the Raid 1 Array.
http://www.acronis.com/homecomputing/products/trueimage/


text:
Q: Error message Capybara::ElementNotFound when using css selectors with dom_id in Rspec testing with Rails I'm using Rspec to test in Rails.  I'm trying to get the test to click on the edit button so that it can edit the todo list.  Since there are multiple edit links I added a dom_id in my index.html.erb file:

Listing Todo Lists

      Title
      Description

    <% @todo_lists.each do |todo_list| %>
      <tr id="<%= dom_id(todo_list) %>">
        <%= todo_list.title %>
        <%= todo_list.description %>
        <%= link_to 'Show', todo_list %>
        <%= link_to 'Edit', edit_todo_list_path(todo_list) %>
        <%= link_to 'Destroy', todo_list, method: :delete, data: { confirm: 'Are you sure?' } %>

    <% end %>

<%= link_to 'New Todo list', new_todo_list_path %>

I keep getting the error message:
  1) Editing todo lists Updates todo list with correct info
     Failure/Error:
       within "#todo_list_#{todo_list.id}" do
         click_link "Edit"
       end

     Capybara::ElementNotFound:
       Unable to find css "#todo_list_"
     # ./spec/features/todo_lists/edit_spec.rb:11:in `update_todo_list'
     # ./spec/features/todo_lists/edit_spec.rb:24:in `block (2 levels) in <top (required)>'

This is my edit_spec.rb file:
require 'rails_helper'

describe "Editing todo lists" do
  def update_todo_list(options={})
    options[:title] ||= "My todo list"
    options[:description] ||= "This is my todo list"
    todo_list = options[:todo_list]

    visit "/todo_lists"

    within "#todo_list_#{todo_list.id}" do
      click_link "Edit"
    end

    fill_in "Title", with: options[:title]
    fill_in "Description", with: options[:description]

    click_button "Update Todo list"
  end

  it "Updates todo list with correct info" do
    todo_list = TodoList.new(title: "Grocery list", description: "This is my grocery  list")

    update_todo_list(todo_list: todo_list, title: "New title", description: "New description")

    todo_list.reload

    expect(page).to_have content("Todo list was successfully updated")
    expect(todo_list.title).to eq("New title")
    expect(todo_list.description).to eq("New description")
  end
end

There isn't a problem with my controllers or models because when I try to edit a todo list when the server is launched, it works fine.  Any help would be greatly appreciated!

A: Once you only called new on your model, it wasn't saved and therefore there isn't an id. That's why error is saying:
Unable to find css "#todo_list_"

Thus you must save your model so that it'll have an id to be interpolated on the selector.
it "Updates todo list with correct info" do
  todo_list = TodoList.create!(title: "Grocery list", description: "This is my grocery  list")
  ...


text:
Q: How to make clientdownloadasync download a new file when it has changed, instead of the cached So I am writing an AutoUpdate tool for my program. So far all has worked good except when I update the file on my site, it still downloads the old version for a while. How can I make it always download the new file instead of (I guess its a cached version). Do I need to change something on my site, or can I do it within vb?
Here is the code for downloading:
Dim client As WebClient = New WebClient
AddHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
client.DownloadFileAsync(New Uri("http://www.redpoisonjb.com/timertracker.exe"), "Timer Tracker.exe")


text:
Q: What is "worried" part of speech in "I'm worried about something" First, I think the part of speech is"verb",but it is passive.then, I think it is"noun",but the sentence can't use "worried",should use "worry".

A: In this case, worried is an adjective (in other words anxious or troubled, see: https://en.oxforddictionaries.com/definition/worried).
It cannot be verb in passive, because it wouldn't make sense - it is the person (I) who is worried about something/someone else, so the pronoun I is an agent of the verb.
You can use worry as a verb in passive, for example, "a lamb was worried by a wolf.", as someone suggested here. However, the meaning of worry in this context is different, it means hunted, chased, attacked. There are more very different meanings of worry as a verb (see: https://en.oxforddictionaries.com/definition/worry)
I don't think you can use worry about in passive with the meaning to feel anxious or troubled. It is not possible to find these examples even in the dictionaries. I thought about an example: "He is constantly worried about by his parents." (active voice: His parents are constantly worried about him)  but it doesn't sound natural.


text:
Q: How to convert Microsoft ODC file/PowerQuery from Excel file with over 2 million rows of data to a CSV file? I recently used PowerQuery to clean a dataset with over 2 million rows of data. How can I now save this cleaned dataset as a usable CSV file, not a query? I cannot load the query into excel and then save it as it contains over 2 million rows of data.
Can I save the data connection as a Microsoft ODC file, open it in Access and then save it as a CSV file? Or are there any other alternatives?
NOTE: Essentially my ultimate goal is to upload the dataset into Tableau (to visualize the data). So any solution that enables this would be preferred and appreciated.

A: Use DAX Studio to export the table into CSV from the data model or PBI.
https://daxstudio.org/


text:
Q: dynamic parameter type for typescript that similar to javascript var in javascript i can do the following
function testing(someObject){
    console.log(someObject.property1);
    console.log(someObject.property2);
    console.log(someObject.property3);
}

I want to perform something similar in typescript for SomeObject parameter. I can't be bothered to declare a class. I just want to have a dynamic parameter
i tried the following but not working. It does not want to accept any as paraeter type. can someone please advise? perhaps what kind of parameter type that I need to use? thanks.
export class testing{
    test(someObject: Any){

    }
}

A: Declare like this:
export class Testing{
    test(someObject: any){
       console.log(someObject);
    }
}

You were right, you just missed the lowercase.
This is an example of a very common method used in Angular/TypeScript:
private handleError(error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    let errMsg = (error.message) ? error.message :
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
}

If you see, error is a parameter that then gets navigated by the logic within the method. This example is the most used method to handle errors in Http calls.


text:
Q: Understanding the assumptions of a Poisson regression model? Modeling plant diversity I have data on plant diversity in response to a fully crossed treatments of fertilizer and light in grassland systems:
>dput(plants)
structure(list(Fertilizer = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("F-", "F+"
), class = "factor"), Light = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("L-",
"L+"), class = "factor"), FL = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("F-L-",
"F-L+", "F+L-", "F+L+"), class = "factor"), LF = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("L-F-",
"L-F+", "L+F-", "L+F+"), class = "factor"), Diversity = c(6L,
7L, 10L, 9L, 5L, 9L, 7L, 6L, 10L, 9L, 9L, 11L, 9L, 9L, 7L, 7L,
4L, 4L, 6L, 4L, 5L, 5L, 4L, 4L, 7L, 8L, 9L, 9L, 10L, 10L, 10L,
7L)), class = "data.frame", row.names = c(NA, -32L))

In these grassland systems, there is typically a loss of species diversity in response to fertilization, which may be due to light competition. My goal is to estimate whether the loss of species can be prevented by restoring light to these areas. There were a total of 32 plots, 8 received fertilizer and light(F+L+), 8 received fertilizer and no light (F+L-), 8 received no fertilizer and light (F-L+), and 8 received no fertilizer and no light(F-L-). The number of species was counted in each plot.
This is a toy data set given to me by a colleague (which I thought was actually to practice the Poisson distribution...) , so I know virtually no more than what has been presented above.
I want to know if I can use the Poisson distribution to model this data. Thinking about the assumptions of the Poisson distribution as they relate to this example, I have a few questions:

*

*The Poisson distribution assumes the mean is equal to the variance: In this case, if I group the data by the FL column, which would be the saturated model (grouping the plots by both main effects Fertilizer and Light and their interaction, totaling 4 groups), if this were to follow a poisson distribution, would I expect:
a. The mean of each level of FL to equal the variance of that same level, or
b. The mean of all values of Diversity to be equal the variance of all values

*This question is related to the following questions but explains what I am confused about. When we talk about "events" under the poison distribution, in my case, would I think about an "event" as:
a. each species within each plot, or
b. individual plots, ignoring their grouping, or
c. individual plots, according to their grouping
*when I say grouping, I mean whether they are grouped by the main effects: Light alone or Fertilizer alone (both of which would create 2 groups) or whether they are grouped by FL (which would create 4 groups because it takes both main effects into account)

*The Poisson distribution assumes the probability of two events occurring in the same narrow interval is negligible. In my case does that mean the probability of 2 plots occurring in the same physical location (which is not possible) is negligible?

*The Poisson distribution assumes that the probability of an event within a certain interval does not change over different intervals. If I am interpreting this correctly, my design significantly violates this because the probability of having "n" number of species in a plot changes depending on the treatment, as you are going to have a different number of species in plots depending on the treatment they received?

*The Poisson distribution assumes the probability of an event in one interval is independent of the probability of an event in any other non-overlapping interval. Again, If I am interpreting an this correctly, this assumption is violated on several levels; assuming we don't know how internal or external factors (e.g. seed dispersal, influence of plants around these plots, if there is interaction between plots because of animals, ect...) other than Fertilizer andLight` influence the "probability" of having "n" number of species in a plot, we cant assume any independence, right?

A: First, you should visualize your data:

made in R by:
library(tidyverse)
ggplot(plants, aes(x=Fertilizer:Light, y=Diversity)) +
geom_boxplot(notch=TRUE, notchwidth=0.9) +
geom_jitter(position=position_jitter(0.03), color="blue", cex=2) +
ggtitle("Cardinal Diversity")

which shows clearly at least some differences between the groups.
Then your question, if we can assume a Poisson distribution for these data. I would answer with a clear no. The numbers given for Diversity is number of species observed. If your data where, for each of the species in some list, the number of individuals observed from that species, a Poisson model could make sense. Let $X_1, X_2, \dotsc, X_k$ be such counts for $k$ species (say, in one of the groups.) Then the number of species observed is given by
$$
\text{Number of species} = \sum_{i=1}^k \mathbb{I}(X_i>0)
$$
which would have a Poisson-Binomial distribution, not a Poisson distribution.  See the tag poisson-binomial.


text:
Q: Show that the McNuggets ring $A=\mathbb C[z^6,z^9,z^{20}]$ is not a UFD Let $A=\mathbb C[z^6,z^9,z^{20}]$ be the McNuggets ring. Is $A$ a unique factorisation domain?
I'm reading a solution to this question and it says,
No, since $z^{12}=z^6z^6=z^4z^4z^4$ which are two distinct factorisations so $A$ is not a UFD.
Firstly I want to ask is this ring essentially the ring of polynomials with $z^6,z^9,z^{20}$ as variables with coefficients in $\mathbb C$? If so then how can $z^4\in A$?
And secondly why does $z^{12}=z^6z^6=z^4z^4z^4$ imply it's not a UFD? Is it because $z^6$ and $z^4$ are irreducible in $A$? If so why? Thanks!

A: It looks like there may really have been a 9-piece McNuggets in the 80's, but given the circumstances I'm inclined to think someone sloppily copied a 4 into a 9.  That would fix all your problems.
Notice that a factorization in this ring would also be a factorization in $\mathbb C[z]$, so that limits factorizations to powers of $z$.
$z^4$ is clearly irreducible, since it is the lowest positive power of $z$ you can produce.
$z^6$ is higher, but the only candidate for a factor is $z^4$, and $z^2$ isn't available. So it's also irreducible.


text:
Q: How to adjust Target area for Drag & Drop in Animate CC with a Responsive Canvas I'm working on making a drag and drop more accurate than just rectangles and circles, and it seems to be going well so far. The only problem is that the target area doesn't match up with where the shape actually is.
In this demo, I have a mostly working, will drag the object, and it goes over the drop areas just fine. The only problem is that the drop areas are being translated into something that's a little bit above the drop zone (which is supposed to be the food in the dish).
The correct placement is for the tip to go into the top. The incorrect placement is to stick the tip in the side of the food.
I think it has something to do with the intersect function at the end, but I'm not sure.
This is the relevant code:
//dragger object
var dragger = this.thermometer;

//Correct and incorrect drop spaces.
var right = this.AreaCorrect;
var wrong = this.AreaWrong;

dragger.on("pressmove", function(evt){
    evt.currentTarget._goto(0);
    evt.currentTarget.x = evt.stageX;
    evt.currentTarget.y = evt.stageY;

    //can remove this whole thing in the final version
    if(intersect(evt.currentTarget.drag, right)){
        evt.currentTarget.alpha=.5;

    }else if(intersect(evt.currentTarget.drag, wrong)){
        evt.currentTarget.alpha=.2;

    }else{
        evt.currentTarget.alpha=1;
    }

    stage.update(evt);
}, this);

dragger.on("pressup", function(evt){
    //lock position of drag object and play animation if any
    dragger.x = dragger.x;
    dragger.y = dragger.y;

    //remove the alpha changes in final
    if(intersect(evt.currentTarget.drag, right)){
        dragger.mouseEnabled = false;
        dragger.play();
        exportRoot.fb_reading.gotoAndPlay(1);
        evt.currentTarget.alpha=1;

    }else if(intersect(evt.currentTarget.drag, wrong)){
        dragger.mouseEnabled = false;;
        dragger.play();
        exportRoot.fb_reading.gotoAndPlay(50);
        evt.currentTarget.alpha=1;
    }

    stage.update(evt);
}, this);

//returns true or false
function intersect(drag, target){
    var pt = drag.localToLocal(drag.x, drag.y, target);
    if(target.hitTest(pt.x, pt.y)){
        return true;
    }else{
        return false;
    }
}

Also, for some reason, sometimes (but not always), moving the anchor point of the object with the transform tool can help to move the target area.
I used the code here to update my intersect function from a codepen that I was using before.
Again, Demo link: https://mhardingfoodsafe.github.io/dragndropNEW/

A: I think this is the best way (that I've found...) to do it. What I had done was converted the buttons to movieclips, but animateCC didn't quite convert it as good as it should have. I had to delete those and make a fresh movieclip that only had one frame and one layer where the area should be.
From there, I changed the intersect function as follows:
function intersect(drag, target){
    var pt = drag.globalToLocal(target.x, target.y); //-----This line
    if(target.hitTest(pt.x, pt.y)){
        return true;
    }else{
        return false;
    }
}

It used to be localToLocal() but that was messing it up, so I made it to globalToLocal(). This was causing it to register well above the actual points, for reasons I don't know.
At this point, it's just figuring out how to scale the drop target locations while still keeping this responsive.


text:
Q: javascript split array in two arrays I am trying to split this array into two different arrays using the values inside the first array.
This is my initial array:
    "carList": [
      {
        "brand": [
          {
            "model": [
              { "motor": { "id": 1 }, "color": 10 },
              { "motor": { "id": 2 }, "color": 20 },
              { "motor": { "id": 3 }, "color": 30 },
              { "motor": { "id": 4 }, "color": 40 }
            ]
          }
        ]
      },
      { "brand": [{ "model": [{ "size": 400 }] }] },
      { "brand": [{ "model": [{ "size": 500 }] }] }
    ],

The first array must contain the model with the motor and the colors. The second should only contain the brand with the size (I can have an indeterminate number of brands).
I would like this as an output:
    "carList": [
      {
        "brand": [
          {
            "model": [
              { "motor": { "id": 1 }, "color": 10 },
              { "motor": { "id": 2 }, "color": 20 },
              { "motor": { "id": 3 }, "color": 30 },
              { "motor": { "id": 4 }, "color": 40 }
            ]
          }
        ]
      },
    ],

    "carList": [
      { "brand": [{ "model": [{ "size": 400 }] }] },
      { "brand": [{ "model": [{ "size": 500 }] }] }
    ],

When trying to split the array, I tried to create the array only with size, but I get the carList global:
const carList1 = carList.filter((x) =>
    x.brand.filter((y) => y.model.filter((z) => z.size)
   );

How I can split my array and get this output?
UPDATE
This is my more genral exemple test I can have many brand and model,
   "carList": [
      {
        "brand": [
          {
            "model": [
              { "motor": { "id": 1 }, "color": 10 },
              { "motor": { "id": 2 }, "color": 20 },
              { "motor": { "id": 3 }, "color": 30 },
              { "motor": { "id": 4 }, "color": 40 }
            ]
          },
          {
            "model": [
              { "motor": { "id": 1 }, "color": 11 },
              { "motor": { "id": 2 }, "color": 22 },
              { "motor": { "id": 3 }, "color": 33 },
              { "motor": { "id": 4 }, "color": 44 }
            ]
          }
        ]
      },
      { "brand": [
         {
           "model": [
             { "size": 400 },
           ]
         },
         {
            "model": [
             { "size": 401 }
           ]
         },
      { "brand": [{ "model": [{ "size": 500 }] }] }
    ],

A: This would be one way of doing it:

const data={"carList":[
   {"brand":[{"model": [{ "motor": { "id": 1 }, "color": 10 },
                        { "motor": { "id": 2 }, "color": 20 },
                        { "motor": { "id": 3 }, "color": 30 },
                        { "motor": { "id": 4 }, "color": 40 }]},
             {"model": [{ "motor": { "id": 1 }, "color": 11 },
                        { "motor": { "id": 2 }, "color": 22 },
                        { "motor": { "id": 3 }, "color": 33 },
                        { "motor": { "id": 4 }, "color": 44 }]}
            ]},
   {"brand":[{"model": [{ "size": 400 }]},
             {"model": [{ "size": 401 }]}]},
   {"brand":[{"model": [{ "size": 500 }]}]}
]}

const [mo,si]=["motor","size"].map(p=>data.carList.filter(e=>
  e.brand.find(b=>b.model.find(m=>m[p]))));

console.log(JSON.stringify(mo));
console.log(JSON.stringify(si));

I applied the snippet now to the updated data. The result arrays motor and sizes are calculated by applying a .filter() on the data array.
In this updated version of the script I assign a brand to the mo or si array if it somehow contains the property motor or size`.