text:
Q: WiX installer - Set ApplicationFolder from ComboBox I'm writing a WiX installer for a group of medical device SW products that must install in specific directories off the root of C:.  IE no "ProgramFolders" for these.
They run in dedicated environments and have been verified and validated using these directories.
I have a custom welcome dialog that has a combobox:
    <Control Id="TypeCombo" Type="ComboBox" X="178" Y="162" Width="120" Height="20" Property="InstallChoiceResult" ComboList="yes" Sorted="no">
      <ComboBox Property="InstallChoiceResult">
        <ListItem Text="Base dev 1" Value="1"/>
        <ListItem Text="Base dev 2" Value="2"/>
        <ListItem Text="Base dev 3" Value="3"/>
        <ListItem Text="Base Simulator" Value="4"/>
      </ComboBox>
    </Control>

The choice by the FSE sets the property "InstallChoiceResult".   After they hit next I need to set my application folder based on their choice.  IE  if they chose "Base dev 1" then I need to set APPLICATIONFOLDER to C:\BASEDEV1.  If they choose Base dev 2 then we go to C:\BASEDEV2
Being new to WiX I'm strugging with the sequence.  It seems from examining my MSI with Orca that the InstallUISequence comes AFTER the costing occurs.  When I try to set the APPLICATION folder using a group of custom actions it complains that since it is a directory it must be set before CostFinalize.
I'm sure I'm missing something simple but if my UI seems to be running AFTER that how can I set the directory I need?  My custom actions currently look like:
<CustomAction Id="SetDev1" Property="APPLICATIONFOLDER" Value="C:\BaseDev1" Execute="immediate" />
<CustomAction Id="SetDev2" Property="APPLICATIONFOLDER" Value="C:\BaseDev2" Execute="immediate" />
<CustomAction Id="SetDev3" Property="APPLICATIONFOLDER" Value="C:\BaseDev3" Execute="immediate" />
<CustomAction Id="SetDevS" Property="APPLICATIONFOLDER" Value="C:\BaseDevS" Execute="immediate" />

<InstallUISequence>
  <Custom Action="SetDev1" Before="InstallDlg2">InstallChoiceResult=1</Custom>
  <Custom Action="SetDev2" Before="InstallDlg2">InstallChoiceResult=2</Custom>
  <Custom Action="SetDev3" Before="InstallDlg2">InstallChoiceResult=3</Custom>
  <Custom Action="SetDevS" Before="InstallDlg2">InstallChoiceResult=4</Custom>
</InstallUISequence>

The general jest of what I need to do is basically this:
Display dialog (FSE chooses 1, 2, 3 or simulator)
After next is pressed, Set ApplicationFolder based on property from ComboBox
Install into the set ApplicationFolder
Any help would be very much appreciated.

A: You can set the directory values to APPLICATIONFOLDER using SetDirectory element. No need to use Custom action and bind the directory values directly to the List item. Make the Combo box property is public (All letter in uppercase).
<Control Id="TypeCombo" Type="ComboBox" X="142" Y="158" Width="120" Height="16" Property="INSTALLCHOICERESULT" ComboList="yes" Sorted="no">
    <ComboBox Property="INSTALLCHOICERESULT">
        <ListItem Text="Base dev 1" Value="C:\BaseDev1" />
        <ListItem Text="Base dev 2" Value="C:\BaseDev2" />
        <ListItem Text="Base dev 3" Value="C:\BaseDev3" />
        <ListItem Text="Base Simulator" Value="C:\BaseDevS" />
     </ComboBox>
</Control>

<SetDirectory Id="APPLICATIONFOLDER" Value="[INSTALLCHOICERESULT]" Sequence="execute" />


text:
Q: StringCollection.Count incrementing unexpectedly I'm working on a method that will trim each element in a StringCollection to remove all the excess in each element that I don't need. What is strange is when I was trying to get this method working (it does now) I noticed when introducing a breakpoint in the code that the groupsToClean.Count gets incremented with each iteration of the for loop and I can't see why.
Does anyone know why?
private StringCollection CleanUpGroups(StringCollection groupsToClean)
{
    StringCollection cleanedGroups = groupsToClean;

    for (int i = 0; i < groupsToClean.Count; i++)
    {
        if (groupsToClean[i].IndexOf(",") != -1)
        {
            string temp = groupsToClean[i].Substring(3, (groupsToClean[i].IndexOf(",") - 3));
            cleanedGroups.Add(temp);
        }
        else
            break;
    }

    return cleanedGroups;
}

Thanks for any insight!

A: Because StringCollection is a reference type. Your cleanedGroups and groupsToClean are the same object, so you add "cleaned" items to the collection from which you originally got them.
To solve this problem just create new cleanedGroups at the beginning of your method:
private StringCollection CleanUpGroups(StringCollection groupsToClean)
{
    var cleanedGroups = new StringCollection();

A: This line creates two references to the same collection:
StringCollection cleanedGroups = groupsToClean;

So when you call this, you're actually adding to the groupsToClean collection too:
cleanedGroups.Add(temp);  // adds to groupsToClean too

You'll need to replace the original occurrence with your modified one, or create a new collection.

A: StringCollection is a reference type. cleanedGroups is not a copy of groupsToClean -- it's the same instance.

A: You can convert the StringCollection to an Array to clone it
look at the MS reference:
https://msdn.microsoft.com/en-us/library/system.collections.specialized.stringcollection.copyto(v=vs.110).aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling Perl Script from Python With Argument I am working on Python 2.6.6.I looked at various examples but I am not able call perl script in Python with arguments. Perl takes couple of arguments and display it.I am new to both Perl and Python and might me missing some basic thing. I am able to call perl script without giving any argument but once I try giving any argument,It's not calling the perl script
Python :test.py
 import subprocess
 import shlex
 p=subprocess.Popen(['perl','start.pl','1','2'],stdout=subprocess.PIPE)

Perl :start.pl
use strict;
print "Called::\n";
my $name="$ARGV[0]";
print "$name\n";
my $next_name=$ARGV[1];
print "$next_name\n"

I am not sure how does perl takes the argument from python.Can someone please advice me where am I going wrong

A: There's one more step:
print(p.stdout.read())

The output of the Perl process is stored in the object p.stdout, not written to the console.


text:
Q: cassandra and anchor modeling I would like to go from an anchor model which has only( anchor, knot, tie and attributes) to physical model. i'm working on column oriented database, i'm using cassandra database.
Anyone has any document or any idea that could help me throught this passage ?

A: Anchor modeling isn't compatible with data modeling in Cassandra.
Unlike relational databases, tables in Cassandra are denormalised. You start to model your data by identifying all the application queries then design a table for each query so that reads are very fast since there are no foreign lookups and no joins -- all the data you need to satisfy a query are contained within one table.
If you're interested, we have a free hands-on tutorial for Cassandra Data Modeling here -- https://www.datastax.com/dev/modeling. Cheers!


text:
Q: Can I have a click and keyboard handler for RaphaelJS' canvas events? I am new to RaphaelJS. I am trying to add click listener and keyboard listener to the canvas with no success. Can someone please explain how to use click listener and keyboard listener on Raphael. A small example will be of great help.
Thank you.

A: Here is a click and mouseover example, you can use more jQuery in there to simplify it but I just wanted to use the document ready function. Shouldn't be too much to add a keyboard event in there:


text:
Q: allow two network adapters to act as the same device I have three network adapters on my windows 10 laptop. An internal WIFI adapter, an internal Ethernet adapter, and an external docking hub. Currently each of these adapters act as a different device, with a different IP, making it hard to port forward for my device.
I would like  to make it so no matter which way I connect my laptop to the network, it uses the same IP. I would imagine this would be done by either passing the connection from each adapter to one adapter, or configure this in the router somehow. However, configuring via the router could prove difficult as its a Cox panoramic router and utilizes the wifi.Cox.com website, which is finicky at best
I have tried creating a network bridge via control panel between the two Ethernet devices but it came up with an error that said something along the lines of "there was a problem". I also took a look around both the router page, via its IPv4, and the cox website but could not find anything that stood out.


text:
Q: Syntax for mod_rewrite to exempt urls What is the best way to tell mod_rewrite to stop processing rules on a list of urls?
Normally you would do something like this:
RewriteCond %{REQUEST_URL} !^/foo
RewriteRule a b [L]

Only if there are more rules, you need to make sure they don't apply to ^/foo again!
What's a good way to say:
RewriteCond %{REQUEST_URL} ^/foo
#no rewrite rules apply ever

A: Since RewriteRule itself can match the URI, you don't need to use a RewriteCond. One RewriteRule for which the rewritten action is just a - hyphen with the [L] flag should prevent the matching path from ever being rewritten.
# First prevent /foo from rewriting later
# This rule matches /foo and takes *no action*
RewriteRule ^foo - [L]

# Other rules may follow...
# For example a generic rewrite in common use
RewriteCond %{REQUEST_FILENAME] !-f
RewriteCond %{REQUEST_FILENAME] !-d
RewriteCond (.*) index.php?id=$1 [L]

Note: I used ^foo assuming this would be used in context of .htaccess. If you were using it at the server level, you would need to include the leading / as in ^/foo.


text:
Q: Is it possible to construct a voltage doubler that both powers an opamp and is driven by it? I have an application in which I need to drive a MOSFET in saturation to create a constant current load. I'm using an opamp in a fairly straightforward feedback circuit for this, but the current the MOSFET can conduct is limited, since my opamp is running at 3v, limiting its maximum gate drive voltage to roughly the same (the opamp is the rail-to-rail MCP6002).
Since the current required by the MOSFET gate is effectively zero, it ought to be possible to use a capacitative voltage doubler like the Dickson Charge Pump to increase the gate drive voltage. However, I would really like to minimize the number of components in this circuit.
I know an opamp can be set up as a square wave generator to drive a charge pump. If I have spare opamp circuits in my IC, is it possible for an opamp to double its own supply rail?
I tried mocking up such a circuit, but I'm fairly sure it won't work:

If I'm correct, when the opamp output goes high, the opamp is effectively shorting C2, which won't have the desired effect at all. Is there a way to reconfigure the circuit that will work?

A: As shown you have a perpetuum mobile, none of which work. You are using the opamp as the energy source for itself and that dog won't hunt.
You can do what you want if you use external switches driven by the opamp - 2 x bipolar transistors or MOSFETS. The opamp then supplies only the drive energy to turn the "switches" on and off.
Lots of ideas here but
An opamp version of the circuit below would do what you want.
The opamp (here = 555) can be powered from the output - initially its Vdd is two diode drops below Vcc_in but this rises as the circuit bootstraps its own supply.
Circuit from here

An alternative is to build a simple boost converter - oscillator (opamp or whatever) inductor, jellybean BJT transistor, a few resistors, diode, caps.Zener clamp output to regulate. Choose inductor size, frequency to suit desired power level.
Various examples here
including circuit below from here - good design notes on that page.

A: The short answer is, no you can't.
The slightly longer answer is the reason you can't : a voltage doubler will indeed double the drive voltage (minus diode losses) but it is a far from ideal voltage source; it has a high output impedance (and one that is deceptively difficult to analyze - I can't find the recent question on that at the moment) but far too high impedance to drive the amplifier powering it.
EDIT : It can probably provide the "supply current" for the opamp itself; but that current doesn't include any current provided by the opamp's output into R1, R3 and especially C2. Include these and the actual supply current is far higher.
END EDIT
If you need more voltage than a single stage of doubling can provide, you can add further capacitor/diode pairs fed from the same opamp, to build a voltage multiplier. I used a CMOS 555 timer to generate 60V from a regulated 12V supply. Unlike the circuit in Russel's answer, I omitted the transistor stage, feeding the capacitors directly from the 555 output.


text:
Q: How can I extract this text from HTML, using RSelenium? I want to scrape the 57, but if I'm only able to get the Text that says Search Result
this is the code that i use to grab the element  with RSelenium
element<- remDr$findElements(using = 'id','resultListHeadingName')
lapply(element,function (x) x$getElementText()) %>% unlist()

this is the output
[1] "Search Results:"

this is the HTML text from the Website

            Search Results: 1 - 50 of 57

A: Find the parent:
element<- remDr$findElements(using = 'xpath', "//*[@id='resultListHeadingName']/..")
lapply(element,function (x) x$getElementText()) %>% unlist()


text:
Q: How to make Internet connection sharing use system proxy? I use socks5 proxy system wide with Proxifier, when I enable Internet connection sharing between my WiFi network adapter (has Internet) and Ethernet port (no Internet), the device connected to the Ethernet port bypasses proxy and connects directly to the Internet.
how can I force connections from Ethernet port to go through my proxy?
Windows 11
I tried SStap but it's unstable.


text:
Q: Integrating html and CSS files in Spring-MVC project I am working on a Spring-MVC project. Currently I have a few classes in order and I can save the information in database and retrieve it. I now have a website template in HTML, CSS, JS, images. I would like to pull this template into my spring project. Structure is as follows. I would like to know in which order I should create the directories and where to place them, so references will be parsed without error.
Structure :
webapp/
|--resources/
|
|+-WEB-INF/
          +--web.xml
  +--classes/
  +--spring/
     |+--root-context.xml
     |+--appServlet/
         |+--servlet-context.xml
  +--views/
          user.jsp

The template I am using has this format of referencing information
img/products/name_of_image.jpg
<a href="contact.html"/>
css/css-filename.css
js/js_filename.js

The user.jsp is the landing page and I have already put the HTML code for home inside it. I would just like to know how to structure the directories so I can directly put all those files and the template will work. Thank you for your time.


text:
Q: php script for Collaborative translation? I'm looking for a PHP script to build Collaborative translation site where multiple users, can translate words/sentences and view/edit or add their comments on translations (like Launchpad translation system)..
is there anything like this ?
thanks.

A: Although it's not tailored to your specific need, an approach that would work is to set up a wiki site. You can get wikipedia's php code here or a google search will show dozens of other options.

A: http://blog.launchpad.net/general/launchpad-is-now-open-source
Launchpad itself is open source.


text:
Q: Need help in using turtle module So I'm writing a program using the turtle module. I have 2 questions:

*

*I have 4 turtles. How can I make their names show up on the screen while drawing?

*After I finish drawing, how can I exit one screen and open another within the same program?

A:
I have 4 turtles. How can I make their names show up on the screen
  while drawing?

Sure, here's a crude example:
from random import choice
from turtle import Turtle, Screen

NAMES = ['Donnie', 'Raph', 'Mickey', 'Leo']

SPEEDS = ["slowest", "slow", "normal", "fast", "fastest"]

FONT = ("Arial", 12, "normal")

MAGNIFICATION = 5
STAMP_SIZE = 20
MAXIMUM_SPEED = 10
LINE_OFFSET = 50

screen = Screen()

WINDOW_WIDTH = screen.window_width()
START, FINISH = LINE_OFFSET - WINDOW_WIDTH//2, WINDOW_WIDTH//2 - (LINE_OFFSET + MAXIMUM_SPEED)

turtles = {name: Turtle(shape='turtle') for name in NAMES}

for offset, turtle in enumerate(turtles.values(), start=-len(NAMES)//2):
    turtle.turtlesize(MAGNIFICATION)
    turtle.color("black", "white")
    turtle.penup()
    turtle.goto(START, offset * MAGNIFICATION * STAMP_SIZE)
    turtle.speed(choice(SPEEDS))
    turtle.write("", font=FONT)  # dummy write for 1st undo

winner = False

while not winner:
    for name, turtle in turtles.items():
        turtle.undo()  # unwrite name
        turtle.forward(turtle.speed() + 1)
        turtle.write(name, font=FONT)  # rewrite name
        if turtle.xcor() >= FINISH:
            winner = True
            break

screen.exitonclick()

To do better with respect to text centering and eliminating flicker, we would need one or more extra invisible turtles to just handle the text.  However, when the turtles turn, the text won't turn with them, it'll always be horizontal.


text:
Q: Displaying a LinkedHashMap in a JTable I have an Order object which among other things stores a LinkedHashList (Product : amount).
I use a LinkedHashList because I specifically want to keep the insertion order.
public class Order {
    private Map<Product, Integer> productMap;

    public Order() {
        this.productMap = new LinkedHashMap<>();
    }

    public Map<Product, Integer> getMap() {
        return this.productMap;
    }
}

In my GUI i've created a JTable with an OrderTableModel like so:
    private Class<?>[] columnClasses = { String.class, Double.class, Integer.class };
    private String[] columnNames = { "Name", "Price", "Amount" };
    private Order currentOrder;

    public OrderTableModel(Order order) {
        this.currentOrder = order;
    }
    // [...]
    @Override
    public Object getValueAt(int rowindex, int columnIndex) {
        Product selectedProduct = (Product) this.currentOrder.getMap().keySet().toArray()[rowIndex];
        switch (columnIndex) {
            case 0:
                return selectedProduct.getName():
            case 1:
                return selectedProduct.getPrice();
            case 2:
                return this.currentOrder.get(selectedProduct);
        }

However I understand that Maps weren't made to be accessed by index and that (Product) this.currentOrder.getMap().keySet().toArray()[rowIndex] is a hack.
This also has the disadvantage of making it quite slow getting a Product object from a row selection in the JTable (get the selected row, iterate again).
I've thought about using two ArrayLists linked by index but that also looks like a hack to me.
So is there a decent way to display a Map in a JTable without going though all these hoops?


text:
Q: SQL - Replace value based on specific object property I'm trying to write a conditional update statement in SQL that looks at an array of objects, and updates one object property based on another object's property. Below is an example of an object in the signal_key column that I'm trying to update.
{
  "entities": [
    {"type": "MERCHANT", "value": "AAAA"},
    {"type": "MERCHANT", "value": "CCC"}],
  "signalType": "TRANSACTION",
  "signalVersion": "0"
}

Based on the "value" string, I want to update the "type" from MERCHANT to ID. Is there a way for me to specifically check value instead of using something like LIKE that would look for a string comparison in the whole object? Below, signal_key??? indicates the portion of the query that I am asking about.
UPDATE signals
SET signal_key??? =  CASE
        WHEN signal_key??? = 'AAAA' THEN 'BBBB'
        WHEN signal_key??? = 'CCC' THEN 'DDD'
        ELSE signal_key???
    END
WHERE signal_key??? IN ('AAAA', 'CCC')

A:
Based on the length of the value string

You can use Len(my_field) to check the length
For example:
UPDATE some_table
SET some_field = CASE
        WHEN len(another_field) = 4 THEN 'BBBB'
        WHEN len(another_field) = 3 THEN 'DDD'
        ELSE 0
    END
WHERE 1=1

Edit: To update based on related data:
First create a CTE (common table expression, using with) that contains each item with the length of the associated items. In the example below the CTE contains each item id with the count (or "length") of associated items.
Then issue an update statement that uses the length table joined with the table you want to update.
with lengths (id, length) as (
    select t1.id, count(related.id)
    from test_table_1 t1
    inner join test_table_related_data related on related.parentId = t1.id
    group by t1.id
)
update t1
set t1.name = case when l.length = 1 then 'one' else 'a lot!!!' end
from test_table_1 t1
inner join lengths l on l.id = t1.id

A: To parse JSON, you should use SQL Server's JSON capabilities.
You need to use OPENJSON in a correlated subquery to find the right index to modify.
If you only want to modify a single value per row, you can do it like this.
UPDATE s
SET signal_key = JSON_MODIFY(
        s.signal_key,
        '$.entities[' + j.[key] + '].value',
        'BBBB')
FROM signals s
CROSS APPLY (
    SELECT TOP (1) j.[key]
    FROM OPENJSON(s.signal_key, '$.entities') j
    WHERE JSON_VALUE(j.value, '$.value') = 'AAAA'
) j;

Otherwise you need to rebuild the JSON array
UPDATE s
SET signal_key = JSON_MODIFY(
        s.signal_key,
        '$.entities',
        j.entities)
FROM signals s
CROSS APPLY (
    SELECT
      j.type,
      value = CASE j.value
                WHEN 'AAAA' THEN 'BBBB'
                WHEN 'CCC' THEN 'DDD'
                ELSE j.value
              END
    FROM OPENJSON(s.signal_key, '$.entities')
      WITH (
        type varchar(100),
        value varchar(100)
      ) j
    FOR JSON PATH
) j(entities);


text:
Q: Align text to the center onclick I'm looking to create a simple text editor for my website, and I want to make a button that on click, aligns text to the center. How can I achieve this? Thanks in advance!

A: You can use to jquery and a button click to button assign to CSS text-align center as like this .

$(document).ready(function(){

  $('.btncenter').on('click', function(){
    $('#cenerText').css({'text-align':'center'});
  })

});

Write some text here

<button class="btncenter">Click here for text align center about div section </button>

A: This allows you to enter text, add it to the page and center it:

$('.add').on('click', function(){
  var text = $('textarea').val();

  $('p').html(text);
});

$('.center').on('click', function(){
  var centered = document.createElement('center');
  centered.appendChild($('p')[0]);
  $('body').append(centered);
});

<textarea></textarea>

<button class='add'>
  enter text
</button>
<button class='center'>
  center
</button>

A: Add CSS style on click event. Try this. Hope it will help.

/*Java Script */
    function doCenter(){
        document.getElementById("my_text").style.textAlign="center";
    }

     <input type="button" value="Center" onclick="doCenter()"/>

     <textarea class="text_edit" id="my_text"></textarea>


text:
Q: How to prevent Ajax from removing special characters while constructing a url? I have an Ajax function that calls a get request.  I am constructing the url by using data values from ViewBag, for some reason am not understading Ajax keeps on removing the values from the special character to the end.
This is my Ajax
 $.ajax({
      url: 'api/getProvinceDatByUserID/@ViewBag.reportinPeriod&UserId=@ViewBag.userId&provinceName=@ViewBag.provinceName',
      type: 'GET',
      success: function (data) {}
});

The expected url should look like
api/getProvinceDatByUserID/Jun-2022&UserId=f8f61c2e-6cf3-454f-b3bd-bf6deae205a4&provinceName=ZAMBÉZIA

but Ajax trims the provinceName to
api/getProvinceDatByUserID/Jun-2022&UserId=f8f61c2e-6cf3-454f-b3bd-bf6deae205a4&provinceName=ZAMB&

hence my requesting failing,
How can I set Ajax to stop trimming and removing the special values and characters after it? Any help is appreciated
Update 1
I have to add the encodeUri still same trimming
url: 'api/getProvinceDatByUserID/@ViewBag.reportinPeriod&UserId=@ViewBag.userId&provinceName='+encodeURI('@ViewBag.provinceName')

Update 2
After adding encodeURIComponent to the url am no longer getting ZAMB& but am getting ZAMBÉZIA. Does ajax understand What is the ZAMBÉZIA the symbol ontop of letter E ?

A: this is how I finally solved by issue
 var provinceName = @Json.Serialize(ViewBag.provinceName);

then access the variable with the preserved special characters.
and the final url looks like
 url: 'api/getProvinceDatByUserID/@ViewBag.reportinPeriod&UserId=@ViewBag.userId&provinceName='+ provinceName ,


text:
Q: How can I prevent iOS from auto-deleting HLS content saved for offline playback? HLS offline playback was announced at this session in WWDC 2016, in iOS 10. But at about the 21:20 mark, the presenter is talking about how the downloaded files shouldn't be moved from where the AVAssetDownloadTask puts them, because the system might need to delete them if disk space is low. This possibility is also mentioned here in the documentation:

Important
If available disk space is extremely low, the operating system may automatically delete downloaded assets. Before you present to the user that an asset is available for playback, verify that the asset exists and is playable offline.

I'm building an app to play DRM'd audio content with HLS, and I want to support both streaming and downloading, so the user can save the files they want for offline playback. But if the downloaded files get deleted without the user's permission, it's kind of a crap experience.
So my question: how can I prevent the system from deleting downloaded files? Can I just move them, even though the documentation explicitly says not to? Is there a different way I can download the files? There is a new class in iOS 11, AVAssetDownloadStorageManager, that supports setting a storage management policy to default or important...is there any guarantee that the system won't delete "important" downloaded media without at least asking the user first? Roger Pantos says in Advances in HTTP Live Streaming at WWDC 2017 that the system might delete assets to make space for a software update after asking the user, but that statement doesn't mean assets won't get delete automatically for other reasons.

A: We have been moving downloaded assets from provided location to FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) for couple years and haven't seen any problems so far.
I'm not sure that it's good practice and most likely isn't.
UPD. We rewrote our downloads module from scratch and decide to give a try system to handle assets. After internal QA testing, we found that system could delete downloaded content even without notifying a user.
In the end we were forced to start moving downloaded content to app documents folder once again.


text:
Q: XmlSerializer serialize class contents I have two classes, lets call them A and B:
public class A
{
    public int foo;
    public int bar;
}

public class B
{
    public class A;
}

Now when I serialize object B the XmlSerializer is doing what you expect it to do:
<?xml version="1.0" encoding="utf-8"?>
<B>
    <A>
        <foo>0</foo>
        <bar>0</bar>
    </A>
</B>

But I would need the XmlSerializer to serialize the contents of class A but ignore the root <A> tag, like so:
<?xml version="1.0" encoding="utf-8"?>
<B>
    <foo>0</foo>
    <bar>0</bar>
</B>

I know I could just put the members of A into B but these are big classes and I would like that to be the last resort. I have tried to search MSDN/Google/the Internet but I just cant seem to get the wording right to find meaningful results so sorry if this has been asked before.
Is there any way to make the XmlSerializer not write the root tag of the class but write its members anyway?  Preferably without reorganizing classes, but if there is no other way, I will do that, too.

A: The XmlSerializer is not that flexible -- you can tell it to ignore a property, but then it ignores it completely.
Mind you, anything you would serialize this way would be hard if not impossible to correctly deserialize again later.
Why don't you just put foo and bar as properties of B instead?

A: What about:
public class A
{
    public int foo;
    public int bar;
}

public class B
{
    [XmlElement(ElementName = "ABetterName")]
    public A Inner;
}

Although this is not what you're looking for it may be preferable as it allows you to give better names to the elements

A: You can use XDocument and build the XML yourself.
Something like:
XDocument doc = new XDocument(
    new XElement("B",
        new XElement("foo", a.foo),
        new XElement("bar", a.bar)
    )
);


text:
Q: How to handle error if API is down in Angular2 (ERR_CONNECTION_REFUSED)? My catch error method is not catching error if server is down.
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this.PATH + '/signup', details, options)
    .map(res => res.json())
    .catch(res => Observable.throw(res['_body']));


text:
Q: Exact solution for non-linear Fokker-Planck equation I'm searching for exact (analytical) results for FP equation in 2 variables (such as $x$ and $p$ in 1D) with a steady state. Kramer's like (with force due to confining potential, such as harmonic potential) but with any nonlinear dissipation term (or piece-wise linear, however not $F(p) = -\gamma p$ for all $x$ and $p$). I don't need the time dependent part, only the steady state / asymptotic solution that satisfies the $L_{FP}W(x,p)=0$. For example, the following Langevin equations
$$\dot x = \omega p$$
$$\dot p = F(p)-\omega x+\sqrt{2D_p}\xi(t)$$
are equivalent to the following Fokker-Planck equation
$$[\omega(-p\partial_x+x\partial_p)+\partial_p(-F(p)+D_p\partial_p)]W(x,p)=\partial_tW(x,p)=0.$$
Notice that arbitrary choice of $F(p)$  and appropriate setting $D_p=-F(p)/p$ will satisfy the Fokker Planck equation above, as a consequence of the fluctuation-dissipation theorem. In my request I search preferably for a solution with $D=\text{const}$, thus as a consequence, inconsistent with the fluctuation dissipation - non-thermal distribution (not Boltzmann-Gibbs, also not abeying detailed balance, since fluctuation dissipation derived by assumption of detailed balance).
Any other solution which is not consistent with the fluctuation dissipation* is good as well.
* Without going into details, I've seen few papers that try to generalize the fluctuation-dissipation to non-thermal states. For my porpuses I need just inconsistensy with the "regular" one, illustated by Einstein's relation $D_p=\gamma m k_B T$ or $\frac{D_p p}{F(p)}\sim \text{const}$. Any solution that doesn't obey this relation will suffice.
EDIT1:
I've discussed briefly the topic with a professor who noted that few people did some work in the past about $F(p)=-\gamma p^3$ force, and threw the name of Haye Hinrichsen. I did a brief overview of few of his papers, however didn't find anything. Maybe I missed it, and reference to a proper solution will be good as well.
Second best solution is series solution in the form of $W(x,p)=\sum_{i,j}^\infty a_{i,j} x^i p^j$ with closed formula for $a_{i,j}$ coefficients.
EDIT2:
following the comment of @honeste_vivere I found the following article -
Dimentberg, M. F. "An exact solution to a certain non-linear random vibration problem." International Journal of Non-Linear Mechanics 17.4 (1982): 231-236.
Which solves a non-linear Langevin equation -
$$\ddot{x}+\dot{x}\left(2\alpha (1+\eta(t))+\beta_1 \left(x^2+\frac{\dot{x}^2}{\Omega^2}\right)\right)+\Omega^2x(1+\xi(t))=\zeta(t)$$
with $\eta(t)$, $\xi(t)$ and $\zeta(t)$ as Gaussian noise, and uses Stratanovich interpretation to get to the Fokker-Planck, under certain conditions on the parameters. This solution can be seen as non-linear damping and sufficient for my purposes.
Additional solutions are still more than welcome, as they will strengthen my point.


text:
Q: Magento 2 Luma Product Detailed Page resize Hy,
how can i resize the Magento 2 Luma Product Detailed Page and insert a second "New Block" on the right side like this printscreen?

Thanks for help

A: Detailed product page sources is in /vendor/magento/module-catalog/view/frontend/product
Create you own Theme.
There is documentation and developer guide. In your Theme folder create Magento_Catalog folder, where you can rewrite original .phtml's, that you need to rewrite.


text:
Q: Dependency management of outputted UMD files I'm looking to take an NPM package and output it as UMD so it can be used directly in browser, via a script tag or SystemJS import.
The issue I have is that the NPM package is a react-component library, meaning it has dependencies on react and react-dom. The package itself marks both react and react-dom as peer dependencies.
If I update webpack.config.js with
externals: ['react-spinners']

and load the umd file via a script tag
<script crossorigin src="https://unpkg.com/react-spinners@0.12.0-alpha.1/umd/index.js"></script>

I get an error say

ReferenceError: react is not defined

Is there a way to use tsc to output a UMD module and specify certain dependencies are necessary? something along the lines of
tsc --project tsconfig.umd.json --outDir umd --addDeps react,react-dom

so that when this package is loaded, it'll check both react and react-dom exist first before executing?
      <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
      <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
      <script src="https://unpkg.com/react-spinners@0.12.0-alpha.1/umd/index.js"></script>

i tried something like this but still received the same react error
build command
"build:umd": "tsc --project tsconfig.umd.json --outDir umd"

tsconfig
{
  "compilerOptions": {
    "alwaysStrict": true,
    "sourceMap": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "module": "umd",
    "jsx": "react",
    "target": "es5",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "esModuleInterop": true,
    "declaration": true,
    "lib": ["dom", "es2017", "es5", "es6", "es7"],
    "outDir": ".",
    "strict": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  },
  "exclude": ["docs/*", "webpack.config.*", "*.js", "__tests__", "examples"]
}

peer deps
  "peerDependencies": {
    "react": "^16.0.0 || ^17.0.0",
    "react-dom": "^16.0.0 || ^17.0.0"
  },


text:
Q: about string removing in C# Whats is correct to do?
check if exists, then remove?
var input = "foo #main baa";
if(input.Contains("#main")) {
   input = input.Replace("#main", "");
}

or just:
input = input.Replace("#main", "");

Well, this seem a simple question,but I really want know.
Thanks in advance.

A: Just do the replacement - if it's not there, nothing should happen.

A: The Contains check actually just makes your code slower.
Remove it.
The Contains call needs to loop through the string until it finds #main.
The Replace call then needs to do the same exact loop (it can't remember it from the Contains call).
This is a Shlemiel the Painter's algorithm.
Replace can handle strings with zero or more occurrences of the search string, so you don't need the check.

A: Just make the call to Replace().  If the substring isn't found nothing happens and you avoid an additional call to Contains().

A: I would do this:
input = input.Replace("#main", "").Replace("  "," ");

To remove any double spaces.

A: Just remove it. The only thing to check is if the string is null or not.


text:
Q: How to create a confirmation dialog for call function I am using eclipse for Android app development and i want to create a dialog box for confirmation when the call function is triggered from a button/s of the application.
For example when i press the button call i want a dialog box Are you sure you want to proceed? with yes and no.
As it is now when i press button for call it's auto dialing directly (no dial pad)
(I am not sure if this code is responsible for this)
public class AlertDialogManager {
/**
 * Function to display simple Alert Dialog
 * @param context - application context
 * @param title - alert dialog title
 * @param message - alert message
 * @param status - success/failure (used to set icon)
 *               - pass null if you don't want icon
 * */
public void showAlertDialog(Context context, String title, String message,
        Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    alertDialog.setTitle("Title");
    alertDialog.setMessage("Message");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.setIcon(R.drawable.icon);
    alertDialog.show();
}

}

A: If you want to show the number in phone dial then just  do this Intent intent = new Intent(Intent.ACTION_DIAL);
public class AlertDialogManager {
/**
 * Function to display simple Alert Dialog
 * @param context - application context
 * @param title - alert dialog title
 * @param message - alert message
 * @param status - success/failure (used to set icon)
 *               - pass null if you don't want icon
 * */
public void showAlertDialog(Context context, String title, String message,
        Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    alertDialog.setTitle("Title");
    alertDialog.setMessage("Message");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
          makeCall("12345");  //phone number you want to dial

        }
    });

    // Showing Alert Message
    alertDialog.setIcon(R.drawable.icon);
    alertDialog.show();
}

private void makeCall(String phone){
    Intent intent = new Intent(Intent.ACTION_DIAL);
    intent.setData(Uri.parse("tel:"+phone));
    startActivity(intent);
}

}

A: if I understand correctly you should implement something like this:
public void btnClick(View v) {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure you want to proceed?");
    builder.setCancelable(false);

    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            callFunction(); // THE FUNCT THAT YOU WANNA CALL
        }
    });

    builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    builder.show();
 }`


text:
Q: wordpress admin settings permalinks redirects to front page Just cloned my site from the dev domain to the live domain using MainWP. Normally after logging in the first step is to go and reset the permalinks. For some random reason /wp-admin/options-permalink.php keeps redirecting me to the front page of the site. Have looked and looked for a solution and it seems nobody else has had this problem.
Anybody have a clue as to what I should do?
I have tried deleting the .htaccess file. When that didn't work I recreated it with the default one for wordpress. I also edited the misc.php file as suggested in a similar question, which was to include $got_rewrite = true; in the got_mod_rewrite function.
I also deactivated several plugins that have anything to do with caching or redirects.

A: If i understand this problem this issue related to link mapping.
please check your .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

if it's not look like this make it one.
also,.htaccess in WordPress all you need is to delete this file and then enter wp-admin -> settings > permalinks > save.
and also, try to clear your browser's cache, it was caching files so it used the old copy may be.


text:
Q: google cast sender app does not disconnect on first try I integrated google cast support into my android application. I am able to connect and play video remotely with no problems. The only issue I seem to be running into intermittently is that sometimes in order to disconnect from the cast device I need to  disconnect then connect then disconnect again.
Any ideas as to why this behaviour is happening?
I am using the Cast Companion Library which uses the following logic to disconnect:
protected GoogleApiClient mApiClient;
.....
......
     if (null != mApiClient && mApiClient.isConnected()) {
         LOGD(TAG, "Trying to disconnect");
         mApiClient.disconnect();
         if (null != mMediaRouter) {
            mMediaRouter.selectRoute(mMediaRouter.getDefaultRoute());
         }
     }


text:
Q: How to create lagged data points for a Recurrent Neural Network? Given the following dataset, I want to process it in order to be able to fit a RNN in Keras with shape (batch_size,timesteps,features). This is a simplified example of the dataset:
X = np.array([[1,2,3,4,5],[7,8,9,10,11],[12,13,14,15,16]]).T
data = pd.DataFrame(X,columns=['feature1','feature2','outcome'])

feature1    feature2    outcome
   1           7          12
   2           8          13
   3           9          14
   4          10          15
   5          11          16

I now want to create a numpy array that reflects a lag of 2 for outcome. My goal is to predict the outcome, given the values of the previous two timesteps.
That is, I want an array that looks like this.
batch_size = 3 # for this particular dataset
timesteps = 2
features = 2
out = np.empty(shape=(batch_size,timesteps,features))
out[0] = np.array([[1,7],[2,8]])
out[1] = np.array([[2,8],[3,9]])
out[2] = np.array([[3,9],[4,10]])
y = np.array([14,15,16])
print(out)

[[[ 1.  7.]
[ 2.  8.]]

[[ 2.  8.]
[ 3.  9.]]

[[ 3.  9.]
[ 4. 10.]]]

With the outcome represented as:
print(y)
[14 15 16]

As you can see, there are a total of 3 possible combinations (shape[0]), where each combination has 2 lags (shape[1]) and two features (shape[2]).

A: You may use numpy's stride_tricks here:
from numpy.lib.stride_tricks import as_strided
v = data.iloc[:, :2].values

X = as_strided(
    v, shape=(v.shape[0] - 2, 2, v.shape[1]), strides=(8, ) + v.strides
)
y = data.iloc[2:, -1].values

X
array([[[ 1,  7],
        [ 2,  8]],

       [[ 2,  8],
        [ 3,  9]],

       [[ 3,  9],
        [ 4, 10]]])

y
array([14, 15, 16])


text:
Q: display images in repeater control from linq datasource I have a linq datasource to a repeater control in asp.net.
I want to display images stored in the database tables.
i have a category table and product table among other tables, when i used this code
<% Eval("CategoryImage")%> .

It displays System.byte[] in the browser and when I used asp image control with Eval(); it give me a usual broken image icon.
could somebody suggest me a way to insert image directly from the mysql database itself via linq datasource..
And how could I format html tags in stack overflow and asp tags too.. Thanks in advance help appreciated...

A: You can use this function
 public Image byteArrayToImage(byte[] byteArrayIn)
 {
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
 }

to convert the byte array to image.
And if you have byte array in Eval("CategoryImage") then you can call this function from Eval also.
As
<%# byteArrayToImage(Eval("CategoryImage"))%>

Not tested but it should work.
Edit 1
Here is a good link
argumentException was unhandled error when converting byte of array to image

How to convert byte array to image and display in datagrid?


text:
Q: How would I fix #block_two div in place? I've tried using the position property but that didn't work I've tried position referencing to fix the position of "#block_two" but that doesn't seem to work. The div disappears when I use fix and absolute isn't better. I also tried changing the z-index of #block_two but to no avail.

    html {
    overflow: scroll;

    }

    body {
    height: 100%;
    width: 100%;
    max-width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    margin: 0;

    }

    div#static_nav{
    font-family: Arial, sans-serif;
    padding-top: 10px;
    text-align: right;
    width: 100%;
    height: 2em;
    background-color: #3A3D3F;
    position:fixed;
    opacity: .90;
    color: red;
    vertical-align: middle;

    }

    div#static_nav a{
    color: white;
    text-decoration: none;
    padding-right: 20px;
    }

    .navbar {
    padding-right: 20px;
    padding-top: 2px;
    }

    div#container {
    margin-top: 10px
    height: 10vh
    width: 100%;
    background-color: #16BA81;
    color:;
    }

    div#block_two{
    background-color: ;
    padding-top: 10px;
    height: 100vh;
    background-image: url(/New_Website/sample_image.png);
    background-size: cover;
    }

    div#block_three{
    padding-top: 10px;
    height: 100vh;
    background-color: #E4E2E2;

    }

    div#column-left{
    padding-top: 60px;
    float: left;
    width: 33%;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    }

    div#column-right{
    padding-top: 60px;
    float: left;
    width: 33%;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    }

    div#column-center{
    padding-top: 60px;
    float: left;
    width: 33%;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    }

    div#block_four{
    padding: 10px;
    height: 100vh;
    background-color: #E4E2E2;
    }

    div#end_block{
    padding: 10px;
    background-color: #F2F2F2;
    height: 50vh;
    text-align: center;
    }

    .area_content{
    padding-left: 20px;
    padding-right: 20px;
    font-size: 20px;
    color: #3A3D3F;
    margin-left: auto;
    margin-right: auto;
    display: inline-block;
    text-align: left;
    }

    .eb_header{
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    color: #3A3D3F;
    }

    .b3_pics{
    max-width: inherit;
    height: 50%;
    }

    .b4{
    padding-top: 60px;
    max-width: inherit;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    color: #3A3D3F;
    }

    .b3_hd{
    color: #3A3D3F;
    }

          HOME
          ABOUT
          PEOPLE
          CONTACT
          LOG IN

          Hospitality

        COLUMN CENTER

          COLUMN RIGHT

       PEOPLE

        CONTACT

A: Use position:fixed; and a negative z-index

html {
    overflow: scroll;

    }

    body {
    height: 100%;
    width: 100%;
    max-width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    margin: 0;
      padding:100vh 0 0 0;

    }

    div#static_nav{
    font-family: Arial, sans-serif;
    padding-top: 10px;
    text-align: right;
    width: 100%;
    height: 2em;
    background-color: #3A3D3F;
    position:fixed;
    opacity: .90;
    color: red;
    vertical-align: middle;
      top:0;
    z-index:999;
    }

    div#static_nav a{
    color: white;
    text-decoration: none;
    padding-right: 20px;
    }

    .navbar {
    padding-right: 20px;
    padding-top: 2px;
    }

    div#container {
    margin-top: 10px
    height: 10vh
    width: 100%;
    background-color: #16BA81;
    color:;
    }

    div#block_two{
    background-color: ;
    padding-top: 10px;
    height: 100vh;
    background-image: url('http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg');
    background-size: cover;
    position:fixed;
      top:2.5em;
    z-index:-1;
      width:100%;
    }

    div#block_three{
    padding-top: 10px;
    height: 100vh;
    background-color: #E4E2E2;

    }

    div#column-left{
    padding-top: 60px;
    float: left;
    width: 33%;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    }

    div#column-right{
    padding-top: 60px;
    float: left;
    width: 33%;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    }

    div#column-center{
    padding-top: 60px;
    float: left;
    width: 33%;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    }

    div#block_four{
    padding: 10px;
    height: 100vh;
    background-color: #E4E2E2;
    }

    div#end_block{
    padding: 10px;
    background-color: #F2F2F2;
    height: 50vh;
    text-align: center;
    }

    .area_content{
    padding-left: 20px;
    padding-right: 20px;
    font-size: 20px;
    color: #3A3D3F;
    margin-left: auto;
    margin-right: auto;
    display: inline-block;
    text-align: left;
    }

    .eb_header{
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    color: #3A3D3F;
    }

    .b3_pics{
    max-width: inherit;
    height: 50%;
    }

    .b4{
    padding-top: 60px;
    max-width: inherit;
    text-align: center;
    font-size: 30px;
    font-family: Helvetica, sans-serif;
    color: #3A3D3F;
    }

    .b3_hd{
    color: #3A3D3F;
    }

          HOME
          ABOUT
          PEOPLE
          CONTACT
          LOG IN

          Hospitality

        COLUMN CENTER

          COLUMN RIGHT

       PEOPLE

        CONTACT

A: Instead of using position: fixed on the div I used background-attachment: fixed to hold the image in place and this .


text:
Q: Solving $t^2y''-t(t+2)y'+(t+2)y=2t^3$ knowing $y_1 = t, y_2 = te^t$ are solutions to the homogeneous equation $$t^2y''-t(t+2)y'+(t+2)y=2t^3\implies\\y''-\frac{t+2}{t}+\frac{t+2}{t^2}y = 2t$$
My book says that $y_1 = t, y_2 = te^t$ are solutions to the homogeneous equation.
I'm trying a solution of the form $Y = u_1t+u_2te^t$, so the wronskian is
$$W(t, te^t) = t^2e^t$$
Then, the solutions are given by:
$$u_1 = \int\frac{-te^t\cdot 2t}{t^2e^t} \ dt= -2t$$
$$u_2 =  \int\frac{t\cdot 2t}{t^2e^t} \ dt=-2e^{-t}$$
Then, the solution will be:
$$Y = u_1y_1+u_2y_2 = -2t\cdot t + -2e^{-t}\cdot te^t = -2t^2-2t$$
but my book gives $-2t^2$ as the answer. What am I doing wrong?

A: t is belong to the homogenous equation : y = c1t + c2te^t
the book only give the particular solution part. http://tutorial.math.lamar.edu/Classes/DE/HOVariationOfParam.aspx
maybe... :)


text:
Q: How to understand Erlang's receive statement? I am new to Erlang, so please go easy on me.
I am confused as to how a receive statement is executed in erlang, for instance:
loop() ->
   receive
       MessageA -> handlerA();
       MessageB -> handlerB()
   end

If a MessageA is received, and handlerA executed, after a while, MessageB is received in the processes' inbox, does handlerB gets executed?
I guess not, since I see a lot of code that recurse to execute the receive statement again:
loop() ->
   receive
       MessageA ->
          handlerA(),
          loop();
       MessageB ->
          handlerB(),
          loop()
   end

But here is a problem, if messageA's handler includes another receive statement like this:
loop() ->
   receive
       MessageA ->
          loop2(),
       MessageB ->
          handlerB(),
          loop()
   end

 loop2() ->
   receive
      MessageC ->
          handlerC()
          loop2()
      MessageD ->
          handlerD()
          loop2()
   end

In this case, does it mean if I enter MessageA's hander, I can never handle MessageB?
And how can I resolve this? By putting MessageB's handler into loop2? This doesn't look very graceful, especially when there are multiple levels of receive statements.
Is there a better way to do this?

A: The following code means "execute receiving a single message", so if you want to receive more than one, you need to loop. The typical way of doing that in Erlang is to tail-call yourself.
loop() ->
   receive
       MessageA -> handlerA();
       MessageB -> handlerB()
   end

In your last example, it looks like you have some sort of state machine, where A changes to another state, whereas B stays in the same state. It is not necessarily a problem that you can no longer receive A messages when you're in the state where you expect C and D messages, but that would depend on the problem domain.

A: You got it.
Concerning your example with loop and loop2, such an implementation means that you want to select some new behavior when you received messageA and you should discard messageB if it comes later. (beware that if you use MessageA with a capital letter it becomes a variable name and it will match any message!). In this case it makes sense, and you should add a garbage message clause to remove from the queue messageB and other unexpected messages:
loop2() ->
   receive
      messageC ->
          handlerC(),
          loop2();
      messageD ->
          handlerD(),
          loop2();
      _ ->
          loop2()
   end.

Another possibility is that you implement a kind of state machine, then you should use the OTP behavior gen_fsm.
If it is not the case, meaning you still want to catch a messageB coming later, I strongly recommend you to keep a single loop and take care of all possible messages in a single receive statement.


text:
Q: Draw lines inside the shape in p5.js js beginner and trying to make program which is change the shape of eyebrow.
I just finished to make shape by mousePressed event but I want to know how to draws lines inside the shape that I made!
Like the photo below, I made the shape of eyebrow by using p5.js functions (beginShape(), endShape(CLOSE)) but is it possible to draw lines inside the shape??
Any help appreciate!!

<html>
    <head>
        <meta charset="UTF-8">
        <script src="p5/p5/p5.min.js"></script>
        <script src="sketch7.js"></script>
    </head>
    <body>
    </body>
</html>

var brows=[];
var browsFirst=[];
var flag=0;

function Brow(x,y){
    this.x=x;
    this.y=y;
    this.clicked=function(){
        vertex(this.x,this.y);
        noFill();
        ellipse(this.x, this.y, 8,8);
    }
}
function preload(){
    img=loadImage("faceSample.jpg");
}

function setup(){
    createCanvas(970,1334);
    image(img,0,0);

}

function fillColor(){
    fill(54,50,49,80);
}

function mousePressed(){

    brows.push(new Brow(mouseX,mouseY));

    if(brows.length==1){
        beginShape();
        brows[brows.length-1].clicked();
    }
    var d=dist(brows[0].x, brows[0].y, mouseX, mouseY);
    if(d>4){
        brows[brows.length-1].clicked();
    }else{
        flag=flag+1;
        fillColor();

        endShape(CLOSE);
        if(flag==2){
            print("Completed to make polygon");
            for(var i=0; i<brows.length; i++){
                browsFirst[i]=brows[i];
            }
            brows=[];
            flag=0;
        }

    }
    if(brows.length>1){
        line(brows[brows.length-1].x,brows[brows.length-1].y,brows[brows.length-2].x,brows[brows.length-2].y);
    }

}


text:
Q: Precendence contraint not working after keeping expression I have used two task connected to the foreach loop task, they both are executing and then foreach loop is executing after keeping contraint and expression it is not working.
Below is the sample scenerio:

Now I have created a variable:
istrue value: false

in one of the precendnce contraint I have kept @istrue == false and in other @istrue == true.
For both of the presedence constraints I have selected Contraints & Expression
But now it is not executing.. below is the what I am seeing now:

How to resolve this ?

A: If you want foreach Loop cointainer to be executed if one of its precedence coinstraints will success set Logical OR. One constaint must evaluate to True in Multiple constraint section of one of them.


text:
Q: Prototype not defined when accessing children on creation of custom-tag __What I am trying todo____

Right now I am working with custom HTML5 tags. I am trying to create a tab-control element that is easy to set up. Todo this I create a parent element called 'tab-set' which works much like the 'ul' tag.
To insert tabs, you simply insert 'tab-element' tags (like 'li' tags). The tags can implement own behavior through custom prototypes which extend standardized element-prototypes such as the basic HTMLElement and are then registered with 'document.registerElement()'. At that point there are also opportunities to set callbacks that let you know whenever your element has been created or attached to something, which is what I use to do the necessary calculations on the placement of the individual tabs on the tab-control.
Let me say up-front that I've had trouble with this at first, then got it working, but upon rewriting the whole thing had troubles again for who knows why.
So, in the creation routine of the tab-set I iterate through all the child-tab-elements, calling their custom function 'setDimension', or atleast I am trying to. For some reason Chrome won't initialize the tab-element prototype (setDimension etc) before it has called both 'createdCallback' and 'attachedCallback' on my tab-set. This means that I can't call the child elements custom functions to set it's placement on creation of the tab-set.

Here you have some code samples of what I just described.

simple.html
...
<tab-set>
 <tab-element>
  guybrush
 </tab-element>
 <tab-element>
  le chuck
 </tab-element>
</tab-set>
...

tabs.js
...
tabSet = Object.create(HTMLDivElement.prototype);

tabSet.attachedCallback = function(){
 for(/** calculations here **/)
  listOfChildren[index].setDimensions(/** placement info **/);

  //
  // Chrome console: 'setDimensions' is not a function!
  //
}

tabElement = Object.create(HTMLDivElement.prototype);

tabElement.setDimensions = function(/** placement info **/){
 $(this).css(...);
}

document.registerElement('tab-set',tabSet);
document.registerElement('tab-element',tabElement);
...

The weird thing is that I have a working version of this, and yes, I have tried to emulate it's particular conditions such as for example loading the html-portion through jquery's .load() routine. But no matter what I do, I can not get this to work in my current script. What knowledge am I missing?

Thanks in advance for any help.

A: __ Solved __
All I had todo was add a link-tag inside the tab-set and have the tab-elements load it's containing style-class. I guess making the tab-elements have a css-class is somehow provoking Chrome to load their prototypes 'prematurely'.


text:
Q: How to add a specific amount of energy to a system? Say I can measure mass, temperature, and geometrical data over time.
Are there any processes that are known to add a specific amount of heat so I could model the conjugate variables (I am thinking of chemical potential, entropy, pressure).
Please no dependency cycles! I have already found plenty of those (measure heat by using known heat capacity. measure heat capacity by using known heat. ad infinitum...)


text:
Q: How to set fixed number of lines for textbox? I want the user be able to insert a biography in 6 lines or less. The problem is that TextBox in windows phone doesn't have a MaxLines property or LineCount, even newline character isn't available. So how can I solve this problem? thanks.

A: I am not a windows phone programmer but based on my experience with c#.Net, I guess we can build a logic that would do the thing:
try this:
string txtData = this.txtTextBox.Text;

        string[] splitByCRet = txtData.Split(new string[]{"\r\n"},  StringSplitOptions.None );

        if (splitByCRet.Length > 6)
        {
            //Exceeds the limit;

            MessageBox.Show("Exceeds");
        }
        else
        {
            MessageBox.Show("Ok to proceed");
        }

A: I'm not sure it's what are you looking for but try:
yourTextBox.Height = yourTextBox.LineHeight * 6;

and of course set TextWrapping of your textbox.


text:
Q: Why do typed properties in php class throw an error? With the patrial class definition of
class thisweek{
        public string $now;
        public datetime $playdate;
        public datetime $signupOpens;
        public datetime $signupCloses;
        public $isopen;

php returns the following error

Parse error: syntax error, unexpected 'string' (T_STRING), expecting
  function (T_FUNCTION) or const (T_CONST) in
  /var/www/www.satgolf.767/testing/class_golfweek.php on line 4

My understanding is that typed properties are available starting with php 7.4
I have verified version 7.4.4

dmd@B767-2:/$ php -v PHP 7.4.4 (cli) (built: Mar 20 2020 13:47:45) (
  NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c)
  Zend Technologies
      with Zend OPcache v7.4.4, Copyright (c), by Zend Technologies

What am I missing here?
Thanks;


text:
Q: Controller action throws AmbiguousMatchException at first, then NotImplementedException when one [sic] is removed I'm porting an older API project from .NET Framework 4.7.2 to .NET 5, and I would like to keep the same API signatures as the existing project to preserve API compatibility. That's proving troublesome. (For this question, ignore that context; I'm just giving it to say why I don't want to change the URL routes as Zhi Lv has suggested.)
One of the .NET 5 project's controllers has an action with this signature:
[HttpGet]
[Route("{processedId}")]
// I had also tried [Route("{processedId:int}")] -- EDIT: but missed that there was a different exception when I did.
public async Task<TypedActionResult<Question>> GetQuestionByProcessedId(int processedId)

When I attempt to access using this URL:
https://localhost:12345/api/questions/2
... I receive the following:
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:
The request matched multiple endpoints. Matches:

My.Namespace.Api.Controllers.MyController.GetQuestionsForFolder (QuestionBuilder.Api)
My.Namespace.Api.Controllers.MyController.GetQuestionByProcessedId (QuestionBuilder.Api)

That other controller action mentioned in that error has this signature:
[HttpGet]
[Route("{folderId=folderId:Guid}")]
public async Task<TypedActionResult<IEnumerable<Question>>> GetQuestionsForFolder(Guid folderId)

If I comment out the offending, "ambiguous" match and make a new call, I receive...
System.NotImplementedException: The method or operation is not implemented.

The same error appears if I flip the experiment by commenting out the intended endpoint, GetQuestionByProcessedId, and leave only GetQuestionsForFolder.
Note that I can successfully access the GetQuestionsForFolder endpoint (when it's not commented out, natch) using the following URL:
https://localhost:12345/api/questions/?folderId=87654321-1234-1234-1234-123456789012

Question
These errors seem to be in conflict. In one case, I have too many endpoints ready to serve the GET request. When I remove one of the two, I then have none.
How can I make the URL find the right controller action, and why is it seeing two and then seeing none?
To be overly clear, I am aware that I could likely merge the endpoints to resolve this issue. My question is why I have two endpoints grabbing the request and then, when one is removed, none.

A:
The request matched multiple endpoints

To solve the above error, you could set the route constraint for each endpoint.
For example:
    [HttpGet]
    [Route("{processedId:int}")] // the parameter is int type, allow the request with int parameter
    public async Task<IActionResult> GetQuestionByProcessedId(int processedId)
    {
        return Ok("value: " + processedId.ToString());
    }

    [HttpGet]
    [Route("{folderId=folderId:Guid}")] //the parameter is guid type, allow the request with guid parameter
    public async Task<IActionResult> GetQuestionsForFolder(Guid folderId)
    {
        return Ok("value: " + folderId.ToString());
    }

The result as below:

Besides, you can also add the action name in the route/request url, code as below:
    [HttpGet]
    [Route("getQuestionByProcessedId/{processedId}")] // the parameter is int type
    public async Task<IActionResult> GetQuestionByProcessedId(int processedId)
    {
        return Ok("value: " + processedId.ToString());
    }

    [HttpGet]
    [Route("getQuestionsForFolder/{folderId=folderId:Guid}")] //the paramer is guid type
    public async Task<IActionResult> GetQuestionsForFolder(Guid folderId)
    {
        return Ok("value: " + folderId.ToString());
    }

Then the request URL like this:
https://localhost:44310/api/todo/getQuestionsForFolder/87654321-1234-1234-1234-123456789012

https://localhost:44310/api/todo/getQuestionByProcessedId/2

the output as below:


text:
Q: Find control by tag on WinForm I have a dynamic Label with Tag which is created 14 Label and added in a GroupBox, then, I want to search for Label that have a Tag = "ABC", I have tried this :
var items = grouptodayerror.ControlCollection;
var finditem = items.Cast<Control>().FirstOrDefault(control => String.Equals(control.Tag, "ABC");

grouptodayerror is my GroupBox, and getting an error message
Error   1   'ControlCollection': cannot reference a type through an expression; try 'System.Windows.Forms.Control.ControlCollection' instead

I tried this too :
Label findbox = grouptodayerror.Controls.Find("ABC", true).FirstOrDefault() as Label;
  if (findbox != null)
  findbox.Text = "CDE";

But I'm getting error null reference on first line.
My question is :

*

*How can I get the ControlCollection?

*Did the second code can find a Tag or just a Text of Control?

*Is there any way to accomplish this?

Thanks in advance.

A: Can you try this one
foreach (Label lb in Controls.OfType<GroupBox>().SelectMany(groupBox => groupBox.Controls.OfType<Label>()).ToList())
        {
            if (lb.Tag.Equals("ABC"))
            {
                //Write your logic here
            }
        }


text:
Q: Why was Sauron afraid of anyone finding the ring? Since the Ring was only able to be controlled by Sauron, why would he be afraid of someone else wielding it? Everyone, even the most powerful beings, admitted they couldn't use it.
Yes, this question is more about Sauron's reaction. Another question said that Sauron was terribly afraid and I just didn't get the feeling that he was. But if he was why was he?

A: Because contrary to your assumption, the Ring could be used by other people
As said many times throughout The Lord of the Rings, and in Tolkien's letters,  Sauron was afraid that his enemies would use the Ring against him, usurp him, and take his place as ruler. Not everyone would have the necessary will power to master the Ring, but some, like Gandalf and Aragorn definitely could. The main reason the Wise did not do this is because doing so would corrupt whoever used the Ring, and you would just replace one dark lord with another dark lord.

'But I have so little of any of these things! You are wise and powerful. Will you not take the Ring?'
'No!' cried Gandalf, springing to his feet. 'With that power I should have power too great and terrible. And over me the Ring would gain a power still greater and more deadly.' His eyes flashed and his face was lit as by a fire within. 'Do not tempt me! For I do not wish to become like the Dark Lord himself. Yet the way of the Ring to my heart is by pity, pity for weakness and the desire of strength to do good. Do not tempt me! I dare not take it, not even to keep it safe, unused. The wish to wield it would be too great, for my strength. I shall have such need of it. Great perils lie before me.'
The Lord of the Rings - Book I - Chapter 2 - "The Shadow of the Past"

In the forward to the second edition, Tolkien even presents us with a hypothetical scenario where the Ring was used against Sauron, and he tells us the outcome.

The real war does not resemble the legendary war in its process or its conclusion. If it had inspired or directed the development of the legend, then certainly the Ring would have been seized and used against Sauron; he would not have been annihilated but enslaved, and Barad-dûr would not have been destroyed but occupied. Saruman, failing to get possession of the Ring, would in the confusion and treacheries of the time have found in Mordor the missing links in his own researches into Ring-lore, and before long he would have made a Great Ring of his own with which to challenge the self-styled Ruler of Middle-earth. In that conflict both sides would have held hobbits in hatred and contempt: they would not long have survived even as slaves.
The Lord of the Rings - "Foreword to the Second Edition"


text:
Q: How should one without any university mathematics background study mathematical logic? How should someone who hasn't studied any math at a university level start studying mathematical logic? (There are already questions like this but they mostly focus on book recommendation for people with already some university background)
I think I should begin with set theory (I know the basics of set theory), before actually trying to study mathematical logic. What books or other sources (preferably books) would be good for self studying set theory? Enderton's Elements of Set Theory seems like a good one.
After getting familiar with set theory, what should I study next (assuming that it's wise to begin with set theory)? A book, again by Enderton, A Mathematical Introduction to Logic, seems like a good intro to the subject.
If one wants to master mathematical logic, should one also study formal logic from philosophy's point of view?
All kinds of recommendation are welcome.

A: Raymond Smullyan's A Beginner's Guide To Mathematical Logic is a gentle but useful introduction to the topic, and you don't need any background for it. You might find it useful.
I also recommend Godel, Escher, Bach, which is not at all a logic textbook. But it incorporates many of the most important ideas of mathematical logic and the cornerstones of computational theory, and it's a really engaging and interesting book.

A: Here is Elliot Mendelson's Introduction to Mathematical Logic
https://www2.karlin.mff.cuni.cz/~krajicek/mendelson.pdf
Amazon gives it 3.5 stars
Though a nice text for symbolic logic before this text is
the Logic book by Bergman James Moore and Jack Nelson. It comes with a solution disk .


text:
Q: I want to pass a json array elements to an html page I have a json array in DAOImpl.I am giving the code here.
for (int i = 0; i <= allTickets.size()-1; i++) {
    obj.put("ticketId", allTickets.get(i).getTicketId());
    obj.put("category", allTickets.get(i).getCategory());
    obj.put("task", allTickets.get(i).getTask());
    obj.put("subject", allTickets.get(i).getSubject());
    obj.put("query", allTickets.get(i).getQuery());
    obj.put("priority", allTickets.get(i).getPriority());
    obj.put("date", allTickets.get(i).getDate());
    obj.put("modifiedDate", allTickets.get(i).getModifiedDate());
    System.out.println(obj);
    jsonArray.put(obj);
}

How can i pass this array to an html page and iterate the array and get the result in a web server.

A: You can use java script (Ajax get function) to get the Json object from the server. In the ajax success function you can then process the results of the GET request.
This way you can iterate the array and display the array items in HTML elements or you can print out HTML content on the page.


text:
Q: Xamarin Tasky Project Error While Build Android Version App I have download from Xamarin Studio Tasky Project and open it
with Visual Studio 2015 Enterprise Edition
when i build  the Solution i got these Errors in ANDROID App

with knowledge that i didn't changed any thing yet in the project.

i tried to build and clean and rebuild the project but still the it gives me an error once i build it.
while iOS version is building and running perfectly

A: Try right click on Android head > Properties > Choose Application panel. Compare the Namespace in Application panel of the Android project is equal with the namespace in the Resource Designer file (/Resources/Resource.Designer.cs). If not don't change this direct in Resource.Designer.cs file (because the file will be automatically generated). Instead, you can change the namespace in all affected files to the namespace you see in the Android Application panel or use 'using' in the affected files.

A: This error is due to Android SDK Platform of target OS API version is not installed. Make sure you install all Android APIs SDK versions, specifically the one's you're targeting in Project Settings of Android in Visual Studio.

Open Android SDK Manager and revise the below

Once you install them, restart, then open VS and clean the build output and re-build everything.

A: So, After trying to solve this problem with many ways and all of it are not the optimal solution.
i Finally find the root Solution for this Issue.
you should Uninstall any Android Build-Tools Which In The Preview Chanel in the Android SDK Manager.
after doing so, clean and rebuild the Xamarin project.


text:
Q: is it possible to generate an Android library AAR archive with Gradle, automatically fulfilled with maven JARs dependecies? I would like to find out the best way in order to generate with Gradle an Android Library AAR archive containing all the dependencies resolved by maven, thus the application doesn't have to include those dependencies, just import the AAR and everything is configured by the android library.
The jars should be placed by the Gradle task in the AAR libs/ dir.
I was doing this, before the new AAR system, with a JAR containing multiple source sets, just because it was not possible to assemble a binary android library.


text:
Q: Error 500 on Parabola and Diffbot - Private IP disallowed I'm getting this error on Parabola after using a Diffbot API for extraction. It says error-500. Private IP Disallowed. What does this mean?

A: This is a Diffbot error that indicates your query string has been incorrectly parsed in some cryptic way.  Usually it means you have double-encoded your URL parameter.


text:
Q: Node adding braces to request.body parameter When I pass data to my node application, req.body gets garbled. My client call:
$.post('/posts/#{post._id}/post', {seen_posts: seen_posts}, function(data, status) {

}

My controller function:
exports.item_posts_get = function(req, res, next) {
  console.log("SEEN POSTS");
  console.log(req.body);
  console.log(req.body.seen_posts);
}

Console:
SEEN POSTS
[Object: null prototype] {
  'seen_posts[]': [ '5f6ac9fdae396910b32011c4', '5f6ac9fdae396910b32011c4' ]
}
undefined

A: In your jQuery code try JSON.stringify({seen_posts: seen_posts}) in place of {seen_posts: seen_posts}.
In your nodejs express code put these lines shortly after where you say const app = express()
/* allow handling json and URL-encoded POST document bodies */
const bodyParser = require( 'body-parser' )
app.use( bodyParser.json() )
app.use( bodyParser.urlencoded( { extended: true } ) )
/* allow handling cookies */
const cookieParser = require( 'cookie-parser' )
app.use( cookieParser() )

This arranges to pass your data from $.post() to your server in JSON format, and parse it into req.body.  You can troubleshoot it with the Network tab of your browser devtools.


text:
Q: compare values in R with a function This is a follow up from a previous post: compare values in R when within a string of letters
I need to check if the value of CURRENT_ID is equal or equal plus 1 to the value of CURRENT_TEXT_1 or CURRENT_TEXT_2, when CURRENT_TEXT_1 or CURRENT_TEXT_2 are equal to DISPLAY_BOUNDARY. If it is, then I need in the OUTPUT column a value of 1, otherwise a value of zero.
Here are some example lines of my datafile (df) and the output I would like to obtain:
 PARTICIPANT     ITEM   CONDITION      CURRENT_TEXT_1               CURRENT_TEXT_2                 CURRENT_ID            OUTPUT
 ppt01          1         1            DISPLAY_BOUNDARY 1 the       iaRegion 4 rd 0 x width 333    7                     0
 ppt01          3         1            iaRegion 2 rd 0 x width 1    DISPLAY_BOUNDARY 9 a           11                    0
 ppt01          4         2            DISPLAY_BOUNDARY 2 aware     iaRegion 6 rd 0 x width 768    3                     1
 ppt01          6         3            DISPLAY_BOUNDARY 3 door      iaRegion 8 rd 0 x width 534    4                     1
 ppt01          9         4            DISPLAY_BOUNDARY 6 in        iaRegion 9 rd 0 x width 924    5                     1
 ppt01          48        5            DISPLAY_BOUNDARY 6 the       iaRegion 10 rd 0 x width 712   8                     0
 ppt02          3         4            iaRegion 14 rd 0 x width 756 DISPLAY_BOUNDARY 15 put        17                    0
 ppt02          7         5            iaRegion 1 rd 0 x width 334  DISPLAY_BOUNDARY 1 where       3                     0
 ppt02          8         6            DISPLAY_BOUNDARY 3 At        iaRegion 2 rd 0 x width 215    5                     0
 ppt02          35        2            iaRegion 3 rd 0 x width 524  DISPLAY_BOUNDARY 1 outside     2                     1
 ppt03          10        1            iaRegion 11 rd 0 x width 190 DISPLAY_BOUNDARY 2 school      4                     0
 ppt03          56        1            DISPLAY_BOUNDARY 8 blue      iaRegion 11 red 0 x width 383  9                     1

Is it correct to do:
ct3 <- as.numeric(gsub("DISPLAY_BOUNDARY ([0-9]+).*","\\1",df$CURRENT_TEXT_1))
ct4 <- as.numeric(gsub("DISPLAY_BOUNDARY ([0-9]+).*","\\1",df$CURRENT_TEXT_2))

df$OUTPUT <- as.numeric(mapply(function(id,x1,x2,x3,x4) id %in% c(x1+1,x2+1,x1,x2), as.numeric(df$CURRENT_ID),ct3,ct4,ct3,ct4))

I am not sure about function(id,x1,x2,x3,x4) if I need to put x3 and x4, and about ,ct3,ct4,ct3,ct4) if I need to write twice ct3 and ct4.


text:
Q: how to get alphabets assigned to numeric values used a bitmask I am trying to assign the sequence of alphabets to the bitmask numeric values like this
 1: a
 2: b
 4: c
 8: d
 .....
 2^25: z

I am looking for a function which would help me deduce the conversion, when i select c and d , it should return me a number which is 12. i.e 4+ 8.
I wrote a function which deduces the letter from the value though, but i need the reverse now, any help  on this ? I am not very sure on teh bit wise operations
For eg,
var Mask = 5;
var String = "";
var index;
for (index = 0; index < 26; index++) {
    if (Mask & (1 << index)) {
        var letter = String.fromCharCode(65 + index);
        String += driveLetter;
    }
}
alert(String);

A: It's surprisingly simple:
var mask = 0;
var string = "cd";
for (var i=0; i<string.length; i++) {
    var c = string.charCodeAt(i) - 65;
    if (i < 0 || i >= 26) throw new SyntaxError("invalid character: "+string[i]);
    mask = mask | (1 << c); // 12
}
console.log(mask);


text:
Q: How to use multiple tables in one model in yii2 I have a product model that save information to product table in the DB, but i also have price table, color table and size table in my DB and on the form i will get all product information including price, size and color through product controller and product model, now i want to know how i can save the price, size and color on the form differently in there respective table. below is a snapshot
public function actionCreate(){
$data = \Yii::$app->request->post();
$model = new Product();
$model->title = $data['title'];
$model->name = $data['name'];
}

now how can i change this table name to price or size or color to be able to save $data['size'] and $data['color'] and $data['price'] to there respective column

A: One model is associated with one database table.
As for handling multiple models of different type, there is a good article in official docs - Getting Data for Multiple Models.
Omitting the details, here is code snippet for controller:
namespace app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\User;
use app\models\Profile;

class UserController extends Controller
{
    public function actionUpdate($id)
    {
        $user = User::findOne($id);
        if (!$user) {
            throw new NotFoundHttpException("The user was not found.");
        }

        $profile = Profile::findOne($user->profile_id);

        if (!$profile) {
            throw new NotFoundHttpException("The user has no profile.");
        }

        $user->scenario = 'update';
        $profile->scenario = 'update';

        if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
            $isValid = $user->validate();
            $isValid = $profile->validate() && $isValid;
            if ($isValid) {
                $user->save(false);
                $profile->save(false);
                return $this->redirect(['user/view', 'id' => $id]);
            }
        }

        return $this->render('update', [
            'user' => $user,
            'profile' => $profile,
        ]);
    }
}

And for view:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

$form = ActiveForm::begin([
    'id' => 'user-update-form',
    'options' => ['class' => 'form-horizontal'],
]) ?>
    <?= $form->field($user, 'username') ?>

    ...other input fields...

    <?= $form->field($profile, 'website') ?>

    <?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>

This article also might be useful - Collecting tabular input. It covers collecting data from multiple models of the same type.
Also read Models section, especially Validation Rules and Massive Assignment paragraphs. You should avoid handling $_POST parameters like that.

A: You should have a model for each table. Insert the id of the product in price, color, and size tables. add product_id in all other tables. And try this:
    public function actionCreate()
{
    $data = \Yii::$app->request->post();
    $model = new Product();
    $model->title = $data['title'];
    $model->name = $data['name'];
    $model->save();
    $getlast=Yii::$app->db->getLastInsertId();

    $model = new Price();
    $model->price=Yii::$app->request->post('price');
    $model->product_id = $getlast;
    $model->save();

    $model = new Size();
    $model->size=Yii::$app->request->post('size');
    $model->product_id = $getlast;
    $model->save();
}


text:
Q: how to check user's folder permissions in classic asp Is there a way to check if a particular windows user has access to a specific directory on a network share?
Or is there a way to capture the Windows "Access denied" error that displays when a user clicks a directory they don't have access to?
Thanks in Advance for any info anyone can share on this.

A: If your asp classic code is trying to write or modify a file within a folder that the IIS user account does not have access to it will produce a 500 page error.
You can setup a Custom Error Page to capture 500 errors. Once captured you can display a friendly error, log for action, etc


text:
Q: Heat Map- how to add colour division and legend I would like to ask if anyone knows how to colour the certain counties of England + legend about the colour's meaning. Here is my code which will give me the chosen counties of England on a map. But I would like to add numbers from my excel file about how many repairs on which properties are on each county similar to the link below.
GB0 <-readRDS("gadm36_GBR_0_sp.rds")
GB1 <-readRDS("gadm36_GBR_1_sp.rds") # England, Ireland, Scotland, Wales
GB2 <-readRDS("gadm36_GBR_2_sp (1).rds")
GB3 <-readRDS("gadm36_GBR_3_sp.rds") # Cities

x<-(GB3$NAME_2=="Wirral" | GB3$NAME_2=="Sefton"|GB3$NAME_2=="Lancashire"|GB3$NAME_2=="Cheshire East"|
      GB3$NAME_2=="Blackpool"|GB3$NAME_2=="Blackburn with Darwen"|GB3$NAME_2=="Rochdale"|GB3$NAME_2=="Bolton"|
      GB3$NAME_2=="Oldham"|GB3$NAME_2=="Wigan"|GB3$NAME_2=="Salford"|GB3$NAME_2=="Knowsley"|GB3$NAME_2=="Warrington"|
      GB3$NAME_2=="Liverpool"|GB3$NAME_2=="Manchester"|GB3$NAME_2=="Stockport"|GB3$NAME_2=="Trafford"|
      GB3$NAME_2=="Halton"|GB3$NAME_2=="Tameside"|GB3$NAME_2=="Cheshire West and Chester"|GB3$NAME_2=="Bury"|
      GB3$NAME_2=="Saint Helens")

County<-GB3[x,]
plot(County)
plot(County[x,],border="blue",add=TRUE) #Notice add=T; this draws on top of current plo
text(coordinates(County),
     labels=County$NAME_3,col="red",cex=0.7)


text:
Q: How to make this slider auto play how can i make this java script code to auto play the slider and How to add mouse-over pause function

$(function() {
  $('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['', ''],
    dots: false,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
});

A: Owl Carousel has the two options you are looking for, autoplay and autoplayHoverPause.
Try this:
$('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['', ''],
    dots: false,
    autoplay: true,
    autoplayHoverPause: true,
    loop: true,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });

You can find a list of all the available options here: https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html

A: If you use this plugin https://owlcarousel2.github.io , add autoplay: true property for autoplay.
For pause on "mouseover", add autoplayHoverPause: true property:
$(function() {
  $('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['', ''],
    dots: false,
    autoplay: true,
    autoplayHoverPause: true,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
});


text:
Q: Consume JSON in Famo.us I have been working with Famo.us just for a short while but now I am in need of consuming some JSON. In jQuery I would use the getJSON method to make the JSON call and get the data back in an object. Is there a way to do this in pure Famo.us? I ask because I have only found examples of jQuery being added to the app to make that JSON call. I am not sure that this is the best practice so I figured maybe someone could point me in the right direction.
$.getJSON('data/data.json', function(json) {
  $.each(json, function(key,data){
    seriesArr.push({
      name: data.name,
      y: data.Count,
      drilldown: data.name
    });
  });
});

A: There is a Utility function in famo.us for loading an URL: Utility.loadURL
(https://famo.us/docs/utilities/Utility)
var Utility = require('famous/utilities/Utility');

Utility.loadURL('http://example.com', function (content) {

    // Check response
    if (!content) {
        return;
    }

    // Consume response
    var parsedContent = JSON.parse(content);
    ...

});

A: You can certainly use jQuery for making requests in Famo.us. Famo.us is designed as the presentation layer of the application. It does not care how the data gets in or out.
Just some things to keep in mind. When making requests, Try to time them such that all animation is complete. A request no matter the library will cause stuttering.
For instance using the setTransform callback method of a StateModifier..
state.setTransform(transform, transition, function(){
    // Make request
});

So to sum things up, You are on the right path. With vanilla Famo.us you are free to make requests with whichever other library you wish. Just do so in a timely manner!
Good Luck!


text:
Q: Eventlog creation using wix on 32bit vs 64bit OS The recommended way to create an Application Event Log using wix seems to be
 <Util:EventSource
          Name="BLAH"
          Log="Application"
          EventMessageFile="[NETFRAMEWORK40FULLINSTALLROOTDIR]EventLogMessages.dll"/>

On 64bit OS you replace it NETFRAMEWORK40FULLINSTALLROOTDIR with NETFRAMEWORK40FULLINSTALLROOTDIR64.
I have noticed that when you run a 32bit app on a 64bit OS it creates an event log with NETFRAMEWORK40FULLINSTALLROOTDIR when your use the .NET EventLog.CreateEventSource method from code.
EventMessageFile => C:\Windows\Microsoft.NET\Framework\v4.0.30319\EventLogMessages.dll

If you run a 64bit version of the app with no eventlog it will create it so
EventMessageFile => C:\Windows\Microsoft.NET\Framework64\v4.0.30319\EventLogMessages.dll

Regardless of whether the EventMessageFile has Framework or Framework64 in the path both 32bit and 64bit versions of the app can write to it merrily once it is created.
Is this supported behavior? What is the correct way to create it if one were to allow both 32bit and 64bit versions of the app side by side ?

A: The Windows event log allows you to create localized event log message files. When Microsoft is writing a service that is part of Windows they probably want to be able to localize what is written to the event log. However, almost everybody else just wants to be able to write a string in their language of choice to the event log and that is exactly what the .NET event log wrapper provides. Thus .NET provides a very generic event log message file that contains no localized messages but just a message with a single argument placeholder where the supplied string argument is inserted giving you total control of what your .NET application writes to the event log.
I would be surprised if the 32 bit and the 64 bit default event log message files in .NET (EventLogMessages.dll) contained different messages but even with this knowledge you should point your 32 bit service to the 32 bit DLL and the 64 bit service to the 64 bit DLL. And if I understand your question correctly that is exactly the behavior that your are seeing.
There are no real "side-by-side" issues with regard to the .NET event log message file. However, if you for some reason decide to create you own (perhaps localized) event log message file you could either install two copies of this file with the two services or you could share a copy you then install to %CommonProgramFiles%. However, not doing a side-by-side installation with two copies can cause problems down the road if one version is updated independently of the other.


text:
Q: XMPP programming use erlang or java? I'm interested to hear feedback from a guru out there. If you are a java programmer, I'm sure you are familiar with openfire, while erlang programmers are familiar with ejabber.  Which project has bigger community when doing programming in XMPP?

A: It all depends on what type of development you do. If you are writing bots, clients or components, it's not very important. Choose the one you are the most comfortable with.
And you'll want to test for interop with other servers.
As for the community, you can always join one of xmpp.org mailing list, jdev@jabber.org being the obvious choice for the developer.
I do find that ejabberd's community is nice and reactive. (I, however, have a bias toward erlang and ejabberd ).
You might want to check out Tigase, a java xmpp server with the momentum OpenFire has lost.

A: Here is an interesting case study from Chesspark, one of the larger XMPP sites out there:
Choosing An XMPP Server
They ultimately chose ejabberd, but you can read all about their decision processes.


text:
Q: Match textcase javascript I want to match the case of a string to that of an example string.
For example.
var str = "hello world"
var example1 = "My Text Is Great"
var example2 = "my Text Is Great"
var example3 = "My text is great"
answer1 = someGreatFunction(str,example1)//should return Hello World
answer2 = someGreatFunction(str,example2)//should return hello World
answer3 = someGreatFunction(str,example3)//should return Hello world

I hope this helps you understand what I want.
I don't want to worry about quotation marks or any form of punctuation.
But if it includes a support for that it will be great.
P.S. I haven't tried doing anything till now because I am clueless.
P.S. If you think this question is duplicate please don't mark it so. Maybe I had already looked through the solutions but didn't found anything satisfying.

A: You can use the following approach

*

*Get an array of lowerCase and upperCase indicators first

Example
"My Text Is Great".split(" ").map( s => s.toLowerCase() == s ? "L" : "U" )

*Use the flags at their specific indices to convert them to appropriate case.

Example
"hello world".split(/\s/).map((s, i) => (indicators[i] == "U" ? s.charAt(0).toUpperCase() : s.charAt(0).toLowerCase() ) + s.substring(1) ).join(" ");

Demo

function matchCase(input, master) {
  var indicators = master.split(" ").map(s => s.toLowerCase() == s ? "L" : "U");
  return input.split(/\s/).map((s, i) => (indicators[i] == "U" ? s.charAt(0).toUpperCase() : s.charAt(0).toLowerCase() ) + s.substring(1) ).join(" ");
}

var example1 = "My Text Is Great"
var example2 = "my Text Is Great"
var example3 = "My text is great"

console.log( matchCase( "hello world", example1 ) );
console.log( matchCase( "hello world", example2 ) );
console.log( matchCase( "hello world", example3 ) );


text:
Q: Communication between re usable components using services I have created two generic components called 1)list and 2)details so that i can re use them:
The components looks like this:

Now i am re using the these component in another components called SCHOOL and COLLEGE which will displayed like this:

Now

*

*If i click on the list-item(for ex school 1) from the list component present in SCHOOL component. I want to display that particular clicked item details(Ex: Name,email) on right side (i,e on details page/component).

*If i click on the list-item(for ex college 1) from the list component present in COLLEGE component. I want to display that particular clicked item details(Ex: Name,email) on right side (i,e on details page/component).
I got solution by this question . In this example communication is happening between the components using services. But in my condition i am re using the component. How can i use the services when i am re using the component.
Stackblitz DEMO

A: In your current scenario, the best would be to leverage @Input and @Output decorators.

You need to have @Input for details component which can get the contact details from its component

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent {

  @Input()
  public contact;

}

List component will emit the value on selection of any items from the list.

export class ListComponent {

  @Output()
  public select;

  public onSelect(contact){
     this.select.emit(contact);
  }

}

School and College component can get the the emitted value from the List Component and pass it to details component .

SCHOOL

      <app-list  [contacts]="contacts" ></app-list>

      <app-details></app-details>

Here is the working copy - https://stackblitz.com/edit/list-examples-mine-ilxisk


text:
Q: intersecting elements after grouping by a variable I have a data that looks as follow:
toy.dat <- data.frame(group = c(rep("A_0", 3), rep("A_1", 2),
                                rep("B_0", 3) , rep("B_1", 3)))
toy.dat$letters <- c("A", 'B', "C", "A", "D", "C", "E", "F", "A", "B", "F")

toy.dat %>%
  group_by(group) %>%
  summarise(letters = list(letters), num = n()) %>%
  mutate(group_number = gsub(".*_", "", group))

group   letters            num_elements  group_num
A_0     c("A", "B", "C")       3              0
A_1     c("A", "D")            2              1
B_0     c("C", "E", "F")       3              0
B_1     c("A", "B", "F")       3              1

I would like to group by group_numb and find the intersection of letters of those rows and add them to the data frame.
the output should give "c" for A_0 and B_0 and "A" for A_1 and B_1.

A: We may use reduce
library(dplyr)
library(purrr)
toy.dat %>% group_by(group) %>% summarise(letters = list(letters), num = n()) %>%
mutate(group_number = gsub(".*_", "", group)) %>% group_by(group_number) %>% mutate(intersect = list(reduce(letters, intersect))) %>%
 ungroup %>%
   mutate(nintersect = lengths(intersect))

-output
# A tibble: 4 × 6
  group letters     num group_number intersect nintersect
  <chr> <list>    <int> <chr>        <list>         <int>
1 A_0   <chr [3]>     3 0            <chr [1]>          1
2 A_1   <chr [2]>     2 1            <chr [1]>          1
3 B_0   <chr [3]>     3 0            <chr [1]>          1
4 B_1   <chr [3]>     3 1            <chr [1]>          1