text:
Q: Does the Primitive Obsession code smell apply to Python? Does "primitive obsession" as a poor design practice apply to development in Python? I have seen a lot of examples and discussion in the context of statically typed languages (like Java, C#), but there are also dynamically typed languages like Python. Do solutions to primitive obsession look different in Python without having explicit types?

A: The simple answer here is 'yes': primitive obsession is still an issue in dynamically typed languages.  The longer answer is that the issue is somewhat different in a dynamically typed language than a statically-typed one.  I'm going to use Python as an example.
So the first bit of nuance is that in Python and similar languages, there aren't really 'primitives' in the first place.  There are built-in types but they are objects.  I only think we can mostly ignore this, but not completely.  For most intents and purposes, they are used just like primitives are in other languages.
The other nuance is that in a dynamically-typed language, dependencies are not really defined by the type of an object, but rather by the operations it supports.  For (somewhat of a silly)  example, if I have a function that will add all the items in a sequence together, there's nothing stopping me from passing in a list of custom objects that support the __add__ method.  This effectively means it's harder to create a primitive obsessed API but as Flater noted in comments on another answer, it doesn't prevent you from improperly using 'primitives' in a sub-optimal way.
The most common primitive obsession error (IMO) that I see often is the use of primitive numeric types to represent money.  Using a decimal type is typically better than float, but it's still inappropriate.  Money has special rules and passing it around as a bare number will often result in bugs and hamper the evolution of an application.  For example, I once was talking to someone about an application they were involved in that used integer types for money.  Then later, integer type they used was too small.  They went through and changed all the integers representing money to doubles.  I consider that two mistakes.  So first off, consider trying to find every instance of an integer being used in a financial application and then determine what it's trying to represent.  That's a major PITA in itself.  Instead of using a primitive for money, a better solution is to define a Money type.  It can be stupid simple initially: don't over-design things.  But once you've done that, if you need to add a capability such as a wider range or support conversions, you can often fix that in one spot.  And if you need to find all the places it's used, it's far easier to locate.  Can you make a primitive obsession mistake like using base numeric types for money in a dynamically-typed language? Absolutely.
On the other hand, in my experience, dynamically typed languages make reusing existing types easier and I therefore don't feel the need to create as many custom types as I would in a statically-typed language.  But you should still be considering whether a custom type is warranted and largely for the same reasons that you would in a statically-typed language.

A: Primitive obsession is about failing to design a dedicated type that would abstract a concept and instead trying to force an existing type into the role. If  the language in question has customizable types then the smell applies.
The whole static vs dynamic thing is just about where you declare the type. Has nothing to do with primitive obsession.


text:
Q: Cloud Functions Emulator can't get default credentials I'm trying to test my cloud function locally, and using the Functions emulator has been fine until I tried adding Datastore to my project. Now whenever I start the emulator, deploy, and call the function with my test data via --file=test.json, i get an error from my datastore promise
error: (node:35048) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.
the only problem with this is that i've tried it multiple times, both with beta and normal auth modules, ie:
gcloud beta auth application-default login
and
gcloud auth application-default login
they both say they are successful but my Functions emulator still fails no matter what.
Datastore version ^1.1.0 & Google Cloud SDK 170.0.1, beta 2017.03.24

A: I ran into the same problem. a workaround is to set process.env.GOOGLE_APPLICATION_CREDENTIALS = "path to json file";
However, you cant deploy the function like that, a better solution would be nice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to concatenate a string to all cells of a column (in-place)? I want to simply append some text to all cells of a column, but I would like to do it in-place. i.e. update the same column with the new values.
For example, if I have a column:

A

a

b

I want to get:

A

a new

b new

I know I can do =A1&" new" on the first cell of B and drag (then override column A with the generated values in column B). But as I said, I'm looking for an in-place solution that doesn't use an auxiliary column and simply updates column A.
Preferably looking for a solution without VBA, but that would be accepted as well.

A: The simplest solution would be to create a new column with your
formula =A1&" new" and copy-paste it over the old column.
You may use Paste special of Values to not overwrite formulas.
The complex solution would be to use a VBA macro like this :
Sub AppendToExistingOnLeft()
Dim c As Range
For Each c In Selection
  If c.Value <> "" Then c.Value = c.Value & " new"
Next
End Sub

This VBA can be used like this :

*

*Select the range

*Hold down Alt+F11 to open a
Microsoft Visual Basic window.

*Click Insert > Module and paste the above VBA code in the Module window

*Press F5 key to run this macro.


text:
Q: replaceWith() not working on some mobile phones I'm setting up a Wordpress theme for a client and I'm trying to replace the Logo on smaller screens / mobile phones. This jquery script works on desktop when resized / refreshed as well as some mobile phones (Nokia and LG Optimus) however in iPhones, Samsung Galaxy, Google Nexus and Blackberry phones the logo is not replaced with the smaller version.
Below is the code I'm using, this is added through the theme's "custom code" form and is added in the footer. (Unfortunately I'm not able to enqueue a script in the child theme to add this snippet for some mysterious reason).
I'm at a loss as to how to resolve this problem, any help would be appreciated.
<script>
(function($){
    var width = $(window).width(),
        defaultLogo = $('.default-logo'),
            mobileLogo = $('<img src="/wp-content/uploads/2015/11/small-logo.png" alt="" class="default-logo">');

    if(width <= 530) {
        defaultLogo.replaceWith(mobileLogo);
    }

 })(jQuery);
</script>

A: Try this:
(function ($) {
  /**
   * ===============================================
   * Cross-browser polyfill
   * @returns {Number|number} - Browser width (px)
   * ===============================================
   */
  function getBrowserWidth() {
    return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  }

  function swapLogo() {
    var $logo = $('img.default-logo');
    if ($logo.length) {
      if (getBrowserWidth() < 530) {
        $logo.prop('src', '/wp-content/uploads/2015/11/small-logo.png');
      } else {
        $logo.prop('src', '/wp-content/uploads/2015/11/large-logo.png'); // replace with actual image name
      }
    }
  }

  $(function () {
    swapLogo();
    $(window).resize(swapLogo);
  });
})(jQuery);

A: This problem has been solved, the problem was that the theme was loading a separate logo image on retina screens, so that is why my code didn't work. Once I replaced the retina logo as well everything worked as intended.


text:
Q: Problem performance datawarehouse with lots of indexes Our product takes tests of some 350 candidates at the same time. At the end of the test, results for each candidate are moved to a datawarehouse full of indexes on it. For each test there's some 400 records to be entered in datawarehouse. So 400 x 350 is a lot of records. If there are not much records in the datawarehouse, all goes well. But if there are already lots of records in the datawarehouse, then a lot of inserts fail...
Is there a way to have indexes that are only rebuild at the end of the day or isn't that the real problem? Or how would you solve this?

A: It is common in data-warehousing do drop indexes and constraints before loading, and re-create them after.
If you get rid of constraints (FKs), make sure that your loading process takes care of this. Drop any check constraints too, and move check validations into ETL software,

A: 140K is NOT a lot of rows.
Please post your table design and the error that you get when the inserts fail

A: I've worked with both normalized and Kimball star data warehouses and this doesn't sound like a problem you should be running into.  I would say 140000 rows is not a lot of rows even in a small data warehouse.
Why do the inserts fail?  Typically in a Kimball-style warehouse, no inserts ever fail - for instance in a fact table, inserts always have a unique set of primary keys related to the dimensions and the grain (like a date or time snapshot).  In a dimmension table, changes are detected, new dimensions are inserted, existing ones are re-used.  In a normalized warehouse, you usually have some kind of revision mechanism or archive process or effective date which keeps things unique.
It seems to me that regardless of your DW philosophy or architecture, there should be something keeping these rows unique.
If (as you stated in your comments) you have a single index containing every column, that's probably not a very useful index (in any database design).  Are you sure your index is even being used for any queries?  Is it also marked to be unique and is that constraint being violated?  In any case, that's a pretty large multi-column index, and it's going to be relatively expensive to compare against - this could result in a timeout - you can always fix that in your connection to wait forever, but I would attack the problem from a design perspective.

A: I would suggest the following: Keep all you data, except of today's in the separate table (lets call it History), where indexed are tuned for your reports. Keep today's data in another separate table, (Lets call it Today) and run a job in the midnight to move data from Today table to History table. In the Today table - you should have minimal indexing to improve insert performance.
By implementing this design you will be sure that you reports are not congesting with inserts. In addition - you have two table tuned for their purposes. In general it is hard to tune table for both a fast inserts and a fast selects.


text:
Q: Maximum string length for Java EE security roles names There is a limit in the maximum length of Java EE security roles names ( for example one of the names used in the @DeclareRoles and @RolesAllowed annotations) ?
I would like to have some references to standards or RFC that possibly puts a limit (or not ) in the length security roles names? Is the same for Java EE 5, Java EE 6, Java EE 7 ?

A: There are no constraints in the spec. This is not explicitly said, but the absence of explicit constraint makes it like there are none.

*

*https://docs.oracle.com/javaee/7/tutorial/security-intro005.htm

*https://docs.oracle.com/javaee/7/api/javax/annotation/security/RolesAllowed.html

*https://docs.oracle.com/javaee/7/api/javax/annotation/security/DeclareRoles.html
Note that specific implementations like Wildfly, Weblogic, Glassfish, etc. might have constraints. You should check with your AS.

A: Doing a little research I found that the maximum value of an array in java is determined by Integer.MAX_VALUE - 4 wherein MAX_VALUE is 2 ^ 31-1.
You can take a look at the following response in SO: Do Java arrays Have a maximum size?
Source: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html


text:
Q: Animatable TweenSequence throwing error in Null Safety I just migrated my flutter app in Null Safety. Everything seems to be working well, except the below code:
Animatable<Color> animColorPend = TweenSequence<Color>([
  TweenSequenceItem(
    weight: 1.0,
    tween: ColorTween(
      begin: Colors.purple,
      end: Colors.white,
    ) as Animatable<Color>,
  ),
  TweenSequenceItem(
    weight: 1.0,
    tween: ColorTween(
      begin: Colors.white,
      end: Colors.purple,
    ) as Animatable<Color>,
  ),
]);

The cast (as Animatable) is throwing this error:

type 'ColorTween' is not a subtype of type 'Animatable' in type cast

Previously (and when I run the app with --no-sound-null-safety) I didn't get this error. Could that be a bug coming from something not yet implemented, as it says here (https://flutter.dev/docs/null-safety)

Not all parts of the Flutter SDK support null safety yet, as some parts still need additional work to migrate to null safety.

Or do you think there is something in the code? Everything I tried (removing the cast, initializing a TweenSequence and not the abstract class and so on) will not work. Thanks for the help!

A: For some reason that I do not understand you have to make the color nullable.
Try this:
Animatable<Color> animColorPend = TweenSequence([
  TweenSequenceItem(
    weight: 1.0,
    tween: ColorTween(
      begin: Colors.purple,
      end: Colors.white,
    ) as Animatable<Color?>,
  ),
  TweenSequenceItem(
    weight: 1.0,
    tween: ColorTween(
      begin: Colors.white,
      end: Colors.purple,
    ) as Animatable<Color?>,
  ),
]);

A: This is an issue with null safety replace
Animatable<Color> animColorPend = TweenSequence<Color>([

with
Animatable<Color?> animColorPend = TweenSequence<Color?>([

as of flutter stable 3.0.2


text:
Q: How to insert data into access table from two different Excel files using access vba I have two excel files with the following columns
1st Excel file: Roll No, Student Name, age, gender
2nd Excel file: Roll No, course, grades
From these two tables i need to add Roll No, Student Name, Course and Grades into access table
To import this data i need to load two files add particular column data using access vba.

A: Link the two Excel files and create one or two queries to append the data to your table.


text:
Q: In VBA, how do I read a bookmark that is an array? Information being pulled into MS word via a bookmark is an array and is being placed in a table. I need to replace some text in that array. How can I do that via VBA.
For example:
Incoming is bookmark1 = ("question 1","TRUE",question 2,"False",.......)
And need to change to bookmark1 = ("question 1","Yes",question 2,"No",.......)

A: Use something like this as the basis and add salt and pepper to taste...
Replace ActiveDocument.Bookmarks(1).Range.Text, "True", "Yes"
Replace ActiveDocument.Bookmarks(1).Range.Text, "False", "No"

Based on your comment and your example that is showing the value of Bookmark1 as a string then ...
Bookmark1 = Replace(Bookmark1, "True", "Yes")

A: Your question lacks clarity. For starters, it is not apparent what 'bookmark1' has to do with a table - it's not even a bookmark in any sense that Word would recognise as one.
As for changing the array contents:
Sub Demo()
Dim bookmark1(), i As Long
bookmark1 = Array("question 1", "TRUE", "question 2", "False")
For i = 0 To UBound(bookmark1)
  bookmark1(i) = Replace(bookmark1(i), "True", "Yes", , , vbTextCompare)
  bookmark1(i) = Replace(bookmark1(i), "False", "No", , , vbTextCompare)
Next
MsgBox Join(bookmark1, ", ")
End Sub


text:
Q: Windows script to enable TPM I am looking to write a script that will enable a TPM chip and BitLocker in Windows, with VBScript.  I am new to VBScript and Windows scripting in general.
One part that I seem to be hitting a snag on is having my script start up again after a reboot.
For example, to enable the TPM chip a reboot is required to turn on the chip, and then a second reboot is required to take ownership of the TPM chip.  A third reboot would be required to enable BitLocker.
How do I have the script start up again after each reboot to move to the next step?  And is VBscript the best choice to accomplish this task?

A: Something like this should work:
rem Make sure you applied the appropriate policies before activating!

manage-bde -tpm -TurnOn
manage-bde -tpm -TakeOwnership PASSWORD
manage-bde -on C: -RecoveryPassword -SkipHardwareTest

The TPM must be enabled in the BIOS first, though.

A: Microsoft already provides a VBScript for enabling BitLocker. You can learn more about it here:
Enabling BitLocker by using a WMI script
And the script itself is available from here:
BitLocker Deployment Sample Resources


text:
Q: How to check and uncheck checkbox based on a button click (with text change of button) in Mvc? I have button: Turn Email On and checkbox (which is unchecked) on side of that button.
When I click Turn email on button,it should call action method of controller where I have to write SP to update the email table.
Email_ON_OFF_T table have one field: isemailon_off(int type). I inserted value 0 into it.
So, Turn email on button's text will become turn email off and checkbox becomes checked.
I have tried the following code:

                    <input type="button" value="Turn Email ON" class="btn btn-success" id="btnturnemailonoff" />

                    <input type="checkbox" id="Chkemailonoff" />

Ajax code to call button:
    $(document).ready(function () {
                    $('#btnturnemailonoff').on('click', function () {
                        //var prices = [];
                        //$('#Chkemailonoff').each(function () {

                        //    prices.push($(this).attr("value"));
                        //});
                        var checked = !$(this).data('checked');
                        $("#Chkemailonoff").prop('checked', checked);
                        $(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
                        $(this).data('checked', checked);
                        debugger;
                        var url = '@Url.Action("CheckEmail", "BillingDetails")';
                        $.ajax({
                            url: url,
                            type: "POST",
                            data: { checkemails: checked },
                            dataType: "json",
                           // traditional: true,
                            success: function () {
                                alert("ajax request to server succeed");
                            }
                        });
                    });
                });

From Ajax, I am passing data(view) to the Controllers action Method.
    [HttpPost]
            public ActionResult CheckEmail(string checkemails)
            {

                //how to call Stored Procedure
                return new JsonResult { };
            }

I have written the below SP:
    ALTER procedure [dbo].[Sp_Email_on_off]
    @checkemails varchar(10)
    As
    Begin
    if(@checkemails='false')
    Update Email_ON_OFF_T set isEmailON_OFF=1
    else
    Update Email_ON_OFF_T set isEmailON_OFF=0

    End

The thing where I am stuck is the stored procedure. How to write and execute Sp in Controllers action Method? This is my first task in MVC. How to achieve this using Mvc?

A: You can use FromSql or ExecuteSqlCommand to execute stored procedure.
FromSql can only be used to execute raw SQL queries or stored procedures to get the data. You can't use it for INSERT/UPDATE/DELETE. If you want to execute INSERT, UPDATE, DELETE queries, use the ExecuteSqlCommand. It returns integer value which indicates the count of affected rows.
Here is a sample following your requirement. Hope to help, my friend :))
if(!string.IsNullOrWhiteSpace(checkemails))
{
    dataContext.Database
           .ExecuteSqlCommand("Sp_Email_on_off @checkemails", checkemails);
}


text:
Q: Countable Union of Countable Sets Why can't I use this proof to prove that the countable union of countable sets is countable without the axiom of countable choice?
Take the set of integers; some proper subset of it, call it $A$, can be mapped, with $f$, a 1-1 and onto function, to the set of even integers.
Some proper subset of the set of even integers, call it $B$, can be mapped, with $g$, a 1-1 and onto function, to the integers. Take the subset of $A$, call it $C$, which is mapped, with the use of $f$, to $B$ which is mapped, with the use of $g$, to the set of integers. Then find the subset of $A$ which is mapped, in a similar fashion, to $C$. Continue doing this forever.
Each one of these sets is countable, given that that they map to $A$ in a 1-1 and onto fashion.
We can find a countable amount of them (just keep doing the same thing). They are all subsets of $A$ and so their union is a subset of $A$.
One can therefore easily show, using the Cantor Bernstein Theorem, that they have the same carnality as $A$. We can easily show that every union of countable sets can easily be placed in a 1-1 and onto fashion with this specific union of countable set.
I assume that I never used the Axiom of Countable Choice in this proof, so what is the problem?

A: Suppose $\{A_i\}$ are a countable family of countable sets and $\{B_i\}$ partition the integers into countably many disjoint countably infinite subsets.  You're right that the construction of $B_i$ doesn't necessarily use choice.  But let's talk about the truly important map - the injection from $\cup A_i$ into $\cup B_i$, which will show that $\cup A_i$ is countable.
Assume the $A_i$ are disjoint for simplicity.  How can we create this injection?
Start by injecting $A_1$ into $B_1$, which is possible since both are countable.  Well, there are a bunch of ways of doing this.  We need to pick one.  There's no canonical/best choice.  Call it $f_1$.  Then inject $A_2$ into $B_2$.  We have to pick another injection $f_2$ for this.  Then the union of the maps $f_i$ gives us the injection that we want.  But despite the fact that each $f_i$ is individually guaranteed to exist, we still have to pick a particular injection for each index $i$.  This requires the axiom of countable choice (more precisely, you need an element from the infinite product of the sets $\{g: g$ is an injection from $A_i$ to $B_i$$\}$).

A: Given a partition N into pairwise disjoint infinite subsets $\{S_j:j\in N\}$ and  given a family $\{T_j:j\in N\}$ of countable sets, there exists, for each $j\in N,$ an injective map  $f_j:T_j \to S_j.$ (And if $S_j\ne \phi$ there are many such maps.)But then you want to assert the existence  of  a sequence $(f_j)_{j\in N}$ of such maps. This requires  Countable Choice . Consider, for each $j\in N,$ the set $I_j$ of injections from $T_j$ into $S_j.$ We have $\forall j\in N \;(I_j\ne \phi).$ But you need  a Choice-function $\psi:N\to \cup_{j\in N}I_j$ such that $\forall j\in N\;(\psi (j)\in I_j).$  Then can you obtain a sequence $(f_j)_{j\in N}=(\psi (j))_{j\in N}$. Conversely, given the desired sequence $(f_j)_{j\in N},$ you obtain a Choice-function $\psi$ by defining $\psi (j)=f_j$ for all $j\in N.$


text:
Q: Why won't some unicode characters print to my terminal? I'm running Arch Linux with simple terminal using the Adobe Source Code Pro font. My locale is correctly set to LANG=en_US.UTF-8.
I want to print Unicode characters representing playing cards to my terminal. I'm using Wikipedia for reference.
The Unicode characters for card suits work fine. For example, issuing
$ printf "\u2660"

prints a black heart to the screen.
However, I'm having trouble with specific playing cards. Issuing
$ printf "\u1F0A1"

prints the symbol Ἂ1 instead of the ace of spades . What's going wrong?
This problem persists across several terminals (urxvt, xterm, termite) and every font I've tried (DejaVu, Inconsolata).

A: help printf defers to printf(1) for the escape sequences interpreted, and the docs for GNU printf says:

printf interprets two character syntaxes introduced in ISO C 99:
  \u for 16-bit Unicode (ISO/IEC 10646) characters, specified as four
  hexadecimal digits hhhh, and \U for 32-bit Unicode characters,
  specified as eight hexadecimal digits hhhhhhhh. printf outputs the
  Unicode characters according to the LC_CTYPE locale. Unicode
  characters in the ranges U+0000…U+009F, U+D800…U+DFFF cannot be
  specified by this syntax, except for U+0024 ($), U+0040 (@), and
  U+0060 (`).

Something similar is specified in the Bash manual for ANSI C Quoting and echo:

\uHHHH
  the Unicode (ISO/IEC 10646) character whose value is the hexadecimal
  value HHHH (one to four hex digits)
\UHHHHHHHH
  the Unicode (ISO/IEC 10646) character whose value is the hexadecimal
  value HHHHHHHH (one to eight hex digits)

In short: \u is not for 5 hex digits. It's \U:
# printf "\u2660 \u1F0A1 \U1F0A1\n"
♠ Ἂ1

A: Muru's answer is completely correct, but just to clarify one point:
When you're printing \u1F0A1, that's interpreted as a sixteen-bit Unicode escape \u1F0A, followed by the literal character 1 (since \u takes the following four characters, no more, no less). U+1F0A then gives Ἂ, a Greek alpha with a couple diacritics on it (Greek Capital Letter Alpha with Psili and Varia, to be precise).
If you want more than sixteen bits in your Unicode escape, you need to use \U, which takes eight characters' worth of hex: \U0001F0A1 will give you the playing card.


text:
Q: How to assign multiple elements to single list variable I'm still pretty new to programming and python. Building a project to automate some tedious tasks at my day job. I have a working python script that pulls data from several websites and compares it to ensure our advertising is consistent across several advertising platforms. I'm going to explain the goal of what I'm trying to do then explain how I tried to do it and see if I'm on the right track and just not doing it properly or if there's a better route to go hopefully someone can point me in the right direction.
My work has ALL of our inventory listed on our own personal website (website A) and another website (website B) has ONLY items costing $150 or more. So what I'm trying to do is scrape the name/price of ONLY the items greater than or equal to $150 on website A and then scrape all items on website B and take the list of items and subtract website B from website A and get a remainder of items on website A that are $150 or more that aren't listed on website B. Hopefully that makes sense.
    xtitles = driver.find_elements_by_class_name("product-name")
    xprices = driver.find_elements_by_class_name("content-item price")
    xjoined = {}

    for title in xtitles:
        xtitletext = [title.text]
    for price in ggprices:
        xpricetext = price.text
        xjoined.update({xtitletext:xpricetext})

    print(xjoined)

    driver.quit()

This is some sample code I tried to use. I feel like I'm close but can't quite get it to work properly. Trying to pull the title and price of the item from website A and merge them together so I can pull the same from website B and do the cross-check. There's probably a better way to do this than the way I'm doing it but figured I would ask here and see what people say. Thanks in advance!

A: You seem to be asking about set intersection.
Let's assign some arbitrary identifiers to expensive items on the personal and the other website, and find the difference:
site_a = set('cdeghklm')
site_b = set('cefhijlnop')
print(sorted(site_a - site_b))

['d', 'g', 'k', 'm']


text:
Q: Power Bi - Add Total Average column in Matrix Hi I am trying to add a AVERAGE column in a matrix, but when I put my metric added the average per column, but I need a total AVERAGE and total at the end just once
What I have:

What I need:

Group
Maria
Pedro
average
total

First
4
6
5
10

Second
5
10
7.5
15

Regards

A: Following the example detailed in the sample data table, to get the Total you could add the following measure;
Total By Group = CALCULATE( SUM(AverageExample[Maria]) + SUM(AverageExample[Pedro]))

and to average
Average By Group = [Total By Group] / 2

Based on the first three columns, this will provide

A: You have to build a DAX table (or Power Query) and a designated measure.
Matrix Table =
UNION(
    DATATABLE("Detail", STRING, "Detail Order", INTEGER, "Type", STRING, {{"Average", 1000, "Agregate"}, {"Total", 1001, "Agregate"}}),
    SUMMARIZE('Your Names Table', 'Your Names Table'[Name], 'Your Names Table'[Name Order], "Type", "Names")
)

This should give you a table with the list of people and 2 more lines for the agregations.
After that, you create a measure using variables and a switch function.
Matrix Measure =
var ft = FIRSTNONBLANK('Matrix Table'[Type], 0)
var fd = FIRSTNONBLANK('Matrix Table'[Detail], 0)
return SWITCH(TRUE,
    ft = "Names", CALCULATE([Total], KEEPFILTERS('Your Names Table'[Name] = fd)),
    fd = "Total", [Your Total Measure],
    fd = "Average", [Your Averagex Measure]
)

The rest is up to you to fiddle with orders, add any agregate measures and whatnot.
Note that the Matrix Table should have no relation with any table from your model.
You can also hide it and the Matrix measure.


text:
Q: Slow first load for each browser or after a while I have a low-traffic ASP.NET MVC 4 application that run on Windows Server 2008 / IIS 7.5.
My problem is that:

*

*The first request is slow around 15 sec. (Subsequent requests are fine)

*Another request after about 2 minutes without any requests always gets a slow response (around 15 sec)

*After first request if I make another request from new browser, again it takes 15 sec.

A scenario to address the problem (the document size is 24 KB):

*

*Time: 16:26 - Using Chrome - First Request takes 15 sec. Subsequent requests are fine.

*Time: 16:27 - Using Firefox - First Request takes 15 sec. Subsequent requests are fine.

*Time: 16:30 - Using IE 11 - First Request takes 15 sec. Subsequent requests are fine.

Here is all screenshots of Developer Tools/Network Tab
And also Fiddler time output:
Request Count:  1
Bytes Sent:     380     (headers:380; body:0)
Bytes Received: 7,217       (headers:409; body:6,808)

ACTUAL PERFORMANCE
--------------
ClientConnected:    22:41:26.377
ClientBeginRequest: 22:41:26.378
GotRequestHeaders:  22:41:26.378
ClientDoneRequest:  22:41:26.378
Determine Gateway:  0ms
DNS Lookup:         0ms
TCP/IP Connect: 28ms
HTTPS Handshake:    0ms
ServerConnected:    22:41:26.407
FiddlerBeginRequest:    22:41:26.407
ServerGotRequest:   22:41:26.407
ServerBeginResponse:    22:41:41.496
GotResponseHeaders: 22:41:41.496
ServerDoneResponse: 22:41:41.503
ClientBeginResponse:    22:41:41.503
ClientDoneResponse: 22:41:41.504

Overall Elapsed:    00:00:15.1258651

It shows 15 sec delay between ServerGotRequest and ServerBeginResponse
This issue just occurs at my home. There is no problem at work or my friends computers (means another ISP). Also I have no problem in internet speed, then I tested my website connection:
output for ping neshoonak.ir
Reply from 94.232.172.248: bytes=32 time=67ms TTL=122
Reply from 94.232.172.248: bytes=32 time=56ms TTL=122
Reply from 94.232.172.248: bytes=32 time=63ms TTL=122

output for ping 8.8.8.8
Reply from 8.8.8.8: bytes=32 time=134ms TTL=47
Reply from 8.8.8.8: bytes=32 time=171ms TTL=47
Reply from 8.8.8.8: bytes=32 time=132ms TTL=47

I tested some sites placed in same data-center that my site located
and found that all of them have the same problem (there is no problem at work at all).
My reseller hosting says there is 3 data-center and I have problem with 2 of them (just at home). He proposed to move my website to the third data-center. But it may occurs for my site visitors and I don't want to solve it just for me.
Please help!

A: There are two possibilies that come to mind:

*

*Caching: there are some resources that are not cached and thus they need to be loaded and that takes a while. How do you identify if this is the case? Install Fiddler and open the page. You will see the http response codes. How to fix? Cache :)

*App pool: does not seem to be your issue but want to mention for other readers. This happened to me in an app for a Microsoft portal. They wanted near instant loading and it worked fine... Sometimes. I debugged and profiled the code a few times until it hit me. The problem was that the app pool was recycled and it needed to start and load everything. How did I fix? I set up a cron job every 5 minutes to open one page and this kept the app loaded in memory this getting near instant responses.

Hope this helps!

A: One good test is to set up a monitoring service like www.site24x7.com and have it ping your site from multiple locations and you can see response time there.


text:
Q: Change ReadOnly Input Value on  option change I want to display the value in a "select > option" in an  based on the location selected from my  tag.
Here is the html:
<select name="stateCoord" id="stateCoord" autocomplete="off">
       <option selected="selected">SELECT STATE</option>
       <option value="lg">Lagos</option>
       <option value="abj">Abuja</option>
</select>

<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo"  readonly>

And here is the javascript:
$(document).ready(function() {

$("#stateCoord option").filter(function() {
    return $(this).val() == $("#stateCoordInfo").val();
}).attr('selected', true);

$("#stateCoord").live("change", function() {

    $("#stateCoordInfo").val($(this).find("option:selected").attr("value"));
});
});

I'm still getting the hang on javascript so a detailed explanation won't hurt. Thanks in advance.

A: I am not sure, if this is what you need, but I think it should be: JSfiddle
Here is the JS code:
$(document).ready(function() {

  $("#stateCoord").change(function() {
      var value = $("#stateCoord option:selected").text();
      $("#stateCoordInfo").val(value);
  });
});

A: $(document).ready(function() {

     $("body").on("change","#stateCoord",function() {

     $("#stateCoordInfo").val($(this).find("option:selected").val());

});

   $("#stateCoord").trigger("change");
});

A: From what I understand, you want to update the text shown in the readonly text box with the value attribute of the selected option from the dropdown.
To do this, you just need to update the val of your read-only text box to the val of the drop-down whenever change event is fired.

$(document).ready(function() {
  $('#stateCoord').change(function(e) {
    $('#stateCoordInfo').val($(this).val());
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="stateCoord" id="stateCoord" autocomplete="off">
       <option selected="selected">SELECT STATE</option>
       <option value="lg">Lagos</option>
       <option value="abj">Abuja</option>
</select>

<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo"  readonly>

A: If I assume correctly, you want this:
1) initialization of the select option at document ready, that strange thing the code with filter() was trying to do.
2) Capture the change event on the select and show the value of the current selected option on the input. This is what the live() (deprecated) part was trying to do.

$(document).ready(function()
{
    $("#stateCoord").val("").change();

    $("#stateCoord").change(function()
    {
        $("#stateCoordInfo").val($(this).val());
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="stateCoord" id="stateCoord">
  <option value="" selected>SELECT STATE</option>
  <option value="lg">Lagos</option>
  <option value="abj">Abuja</option>
</select>

<input type="text" name="stateCoordInfo" value="" id="stateCoordInfo">


text:
Q: How to select multiple enum values from mysql table? I have enum field Manufacturer
`manufacturer` ENUM('Manufacturer1','Manufacturer2','Manufacturer3','Manufacturer4') NOT NULL

and I have a array containing multiple manufacturer values. Ho to write query that would select every row that has, lets say for example, manufacturer1 or manufacturer3?
I could write it like this:
SELECT FROM table_name WHERE manufacturer=manufacturer1 OR manufacturer=manufacturer3;

but I am looking for shorter version like:
SELECT FROM table_name WHERE manufacturer=$myArrayOfManufaturers;

I get possible values of manufacturers form checklist so the number of manufacturers can change depending from user choice.
My site is built using CodeIgniter so I tried
    $query = $this->db->get_where('products', array('manufacturer' => $data['manufacturers']));
and using forech loop
foreach ($data['manufaturers'] as $man) {
            $this->db->or_where('manufacturer'=$man)
            }

but can not understand how to set first one as where.

A: You can use IN query like
SELECT FROM table_name WHERE manufacturer IN ('Manufacturer1','Manufacturer2')


text:
Q: C# ANTLR4 right-associative warning Given my simple grammar in the C# build target:
grammar Expr;

prog: stmt+ EOF;
stmt: expr NEWLINE+;

expr:
    expr '^' <assoc=right> expr # Power
|   expr ('*'|'/') expr         # Mult
|   expr ('+'|'-') expr         # Add
|   REAL                        # Real
|   '(' expr ')'                # Paren
;

NEWLINE : '\r\n';
REAL     : [0-9]+'.'[0-9]+ ;

I continue to get a C# compiler warning stating that "Warning   1   rule 'expr' contains an 'assoc' terminal option in an unrecognized location"
Can anyone suggest where I'm supposed to indicate right-associativity for exponentials?  This is the way I've seen it done in numerous examples.

A: The answer is placing the tag hint to the left of the rule, not right after the operator as I've seen in many examples:
expr:
<assoc=right> expr '^'  expr    # Power
|   expr ('*'|'/') expr         # Mult
...
;


text:
Q: How do you center graphics?
Possible Duplicate:
Should I use center or centering for figures and tables?

I am doing an assessment and as part of it have linked some graphics into my Latex report, however they are not centred in the report but the left hand side of the graphics starts on the centre line of the report.
Is there anyway i can centre the graphics so that the middle of the graphics is in the middle of the report(on the centre line)?

A: Use
\begin{figure}
\begin{center}
...
\includegraphics[...]{...}
...
\end{center}
\end{figure}

or
\begin{figure}
...
\centerline{\includegraphics[...]{...}}}
...
\end{figure}

or
\begin{figure}
\centering
...
\includegraphics[...]{...}
...
\end{figure}

The first approach tends to add vertical space padding, the second is undocumented, and so the third approach is often preferred.


text:
Q: svg icons are not aligned to center of a container I am designing a list and there i am using svg icons to show the items of list. Now, my icons and text are aligned properly. It is in corner like this below:

Here is my code:

                <svg-icon v-if="!favEdit" name="building" />
                <svg-icon v-else name="delete" fill="#E30000" />

                {{ item.fav }}

css code
    .fav-list-item {
    display: flex;
    align-items: center;
    margin-left: 30px;
    border: .5px solid rgba(0,0,0,0.1);
    border-radius: 5px;
    width: 65%;
    min-height: 35px;

    > div {
        display: flex;
        &:first-of-type {
            background-color: #e8e8ed;
            min-height: 35px;
            min-width: 20%;
        }
    }
    .pl-2 {
       font-size: 14px;
       font-weight: 500;
    }
}

A: Add a block of css
.del_fav {

display:flex;
justify-content:center;
align-items:center;
flex-direction:row;

}

A: Looks to me like you're only centering .del_fav itself, but not its children (the svg). Maybe try adding something like this:
.del_fav {
  display: flex;
  align-items: center;
  justify-content: center;
}


text:
Q: how to change color of activity indicator in iOS I want to change the color of the activity Indicator in iOS.
However, I do not want to create a custom indicator. There is a color property for the activity Indicator but it's not showing up in xcode.
Please advice.

A: From the docs:

color
  The color of the activity indicator.
If you set a color for an activity indicator, it overrides the color
  provided by the activityIndicatorViewStyle property.

Notice that it is iOS 5.0 and later only.

A: You cannot change the default activity indicator's color.

A: just fyi, another way to do progress view  http://github.com/jdg/MBProgressHUD


text:
Q: Understanding treeifying in Java HashMap I found following code in Java HashMap source code:
/**
 * The bin count threshold for using a tree rather than list for a
 * bin.  Bins are converted to trees when adding an element to a
 * bin with at least this many nodes. The value must be greater
 * than 2 and should be at least 8 to mesh with assumptions in
 * tree removal about conversion back to plain bins upon
 * shrinkage.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 */
static final int UNTREEIFY_THRESHOLD = 6;

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 */
static final int MIN_TREEIFY_CAPACITY = 64;

My doubt is this:

Q0. How these three variables together determine treeifying and untreeifying?

However the question above could be abstract as there might involve a lot of subtle facts that needs to be addressed in the answer to make it complete overall. As these are subtle facts and could possibly be overlooked in the answer, I tried to list them down in three separate questions below. You may answer Q0 or preferably Q1, Q2 and Q3.

I understood as follows:

We start with linked list for collision resolution. Once we insert a key which is to be hashed to the bucket already containing 8 (TREEIFY_THRESHOLD) keys and if there are already 64 (MIN_TREEIFY_CAPACITY) keys in HashMap, linked list of that bucket is converted to balanced tree. If  we delete a key from the bucket containing 6 keys in a balanced tree, then it is converted back to the linked list.

Q1. Is above understanding correct?
Q2. I didnt get why

UNTREEIFY_THRESHOLD should be at most 6 to mesh with shrinkage detection under removal.

Q3. I didnt get why

MIN_TREEIFY_CAPACITY should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts between resizing and treeification thresholds.


text:
Q: How to add and use custom js in admin configuration creating custom module I am creating custom module. I want to add js file in admin configuration. How can i include and use js in magento 2.x.

A: You try following step to add js in admin:
Create file app/code/Vendor/Module/view/adminhtml/layout/adminhtml_system_config_edit.xml
<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Vendor_ModuleName::js/yourjs.js"/>
    </head>
</page>

app/code/Vendor/Module/view/adminhtml/web/js/yourjs.js
require(
    [
        'jquery',
        'mage/translate',
    ],
    function ($) {
     //add your code
    }
);

A: As per magento 2 standards, you will required requirejs-config.js to add custom javascript
Create requirejs-config.js in app/code/vendor/module-name/view/adminhtml/requirejs-config.js
var config = {
    map: {
        '*': {
            customscript:'Vendor_ModuleName::js/custom'
        }
    }
};

then create custom.js :
app/code/Vendor/modulename/view/adminhtml/web/js

A: Load js file using the requirejs-config.js
app/code/BA/BStore/view/adminhtml/requirejs-config.js
requirejs-config.js
   var config = {
    map: {
        '*': {
            loadcatalogs:'BA_BasysStore/js/loadcatalogs'
        }
    }
};

app/code/BA/BStore/view/adminhtml/web/js/loadcatalogs.js
define(['jquery'], function ($) {
    "use strict";
    return function(config) {
        $("#division_id").on('change', function() {
            var divisionId = $("#b_division_id").val();
            $.ajax({
            url: config.ajaxUrlValue,
            type: "POST",
            data: { divisionId:divisionId },
            showLoader: true,
            cache: false,
            success: function(response){
              console.log(response);
            }
        });
    });
}
});

app/code/BA/BStore/view/adminhtml/templates/loadjs.phtml
<?php
    $viewModel = $block->getViewModel();
    $ajaxUrl = $viewModel->getAjaxUrl();
?>
<script type="text/x-magento-init">
{
    "*": {
        "loadcatalogs": {
            "ajaxUrlValue": "<?= __($ajaxUrl)?>"
        }
    }
}
</script>

app/code/BA/BStore/view/adminhtml/layout/adminhtml_system_config_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="footer">
            <container name="basys_load_js" htmlTag="div" htmlClass="basys_load_js">
                <block name="basysloadjs.viewmodel" template="BA_BStore::loadjs.phtml">
                    <arguments>
                        <argument name="view_model" xsi:type="object">BA\BStore\ViewModel\LoadajaxUrl</argument>
                    </arguments>
                </block>
            </container>
        </referenceContainer>
    </body>
</page>

app/code/BA/BStore/ViewModel/LoadajaxUrl.php
<?php
namespace BA\BStore\ViewModel;

use Psr\Log\LoggerInterface;
use Magento\Store\Model\StoreManagerInterface;

class LoadajaxUrl implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    public function __construct(
        StoreManagerInterface $storeManager,
        LoggerInterface $logger
    ) {
        $this->logger = $logger;
        $this->storeManager = $storeManager;
    }
    public function getAjaxUrl()
    {
        return $this->storeManager->getStore()->getBaseUrl().'admin/loadcatalogs/index/index';
    }
}


text:
Q: Нет доступа к хранилищу Я декомпилировал apk файл моего проекта чтобы просмотреть его android manifest. В манифесте есть такие строчки:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Первая строчка это для получения разрешения на использование камеры, и при запуске приложения у меня появляется окно которое спрашивает разрешить ли использовать камеру. Однако не появляется запроса на использование внутренней памяти. Я посмотрел в настройках телефона, разрешения которые есть у данной программы. Там есть разрешения: Камера и Память.

 Флажок у камеры находится в активном состоянии, однако память находится в неактивном, хотя как видно выше у меня есть WRITE_EXTERNAL_STORAGE и  READ_EXTERNAL_STORAGE то есть хотя бы запрос должен появится.Но его нету. Кто сталкивался с таким, как решили проблему? И да я для примера добавлял флаг android.permission.READ_MEDIA_IMAGES и тогда оно у меня запрашивало доступ к изображениям и файлам на устройстве. И после флажок был активен.

A: Народ нашел решение. Так как эта тема еще будет актуальна, то вот мое решение проблемы. Не знаю почему, но когда в настройках unity стоит Write Permission: Internal то оно как то коряво работает с внутренней памятью. То есть запрос на использование внутренней памяти не появляется. После этого я сделал простой скрипт на создание папки. Папка и вложенные в нее не создались. После этого я по новому собрал приложение но, с Write Permission: external(sdcard). После этого я установил приложение, и запрос при запуске на использование памяти появился. После этого моему скрипту удалось создать папку на внимание! внутреннем хранилище. То есть как пишется в доках unity external(sdcard) эта опция позволяет работать с sdcard если есть, а если нет то будет с внутренней памятью. Вот мой тестовый скрипт:
public void BtnClick()
{
    string paths = "/storage/emulated/0/";
        DirectoryInfo dir = new DirectoryInfo(paths);
        dir.CreateSubdirectory("Folder/Videos");
    dir.CreateSubdirectory("Folder/Images");

}

Протестировано на устройствах: Xiaomi Redmi note 6 pro и samsung galaxy s7 edge. Возможно это многие знают, но почему то когда я искал как использовать внутреннее хранилище, я натыкался на статьи, где надо было "Танцевать с бубном".
Такой путь: /storage/emulated/0/ работает вполне безотказно. И не нужно никаких функций для получения внутреннего хранилища.


text:
Q: Advice on DNS good practice for LAN and public queries with DNSDist / recursor / powerdns I am setting up a cluster of DNS that are soon going to reply to both LAN clients and public internet queries. On the internet is a special network (XX.YY.ZZ.AA/26) that I need to reply differently when querying the public zone ext.net
I tried to follow good practices but am still doubting and confused...
I decided to point my LAN clients to the recursor and not to dnsdist to ensure a running LAN DNS system if Dnsdist experiences issue.
Am I using a proper way to resolve names differently between the internet and the specific network XX.YY.ZZ.AA/26 ?
Should the requests from XX.YY.ZZ.AA/26 go from dnsdist to the LAN recursor before hitting the auth servers ? (instead of directly from dnsdist to the auth servers)
This is my priv/pub DNS diagram:

Thanks a lot for your comments


text:
Q: evernote versus confluence I need a solution to keep track of important information (links, reference info) for my family and to try to remove tons of paper that we have around the house with information. I would expect my wife and my kids to use this as well but my guess is that I will do most of the publishing.
Which would be a better solution for this:

*

*Evernote

*Confluence - (I would use the personal starter edition)

A: Of those two choices I would definitely go for Evernote. Evernote solves the problem of a single user's (or a single user's family's) little-evolving asset storage (driver's licenses, passports, etc), as well as some note-keeping on the side. It'll hold a bunch of different document types and will also be available everywhere (Web/Desktop/Mobile).
Confluence solves a similar but actually distinctly different problem: Collaborative efforts to evolve living documentation, with some asset storage / attachment handling (which is often abused and thus actively discouraged) on the side. Confluence doesn't have good options for Desktop/Mobile either, and unlikely to rush there feature wise.

A: Although either could probably be used, they are really focused on two different concepts.
Confluence is more of a team focused multiuser editor to document ideas, build consensus, and generate documentation either internally or in a blog. It does have ability to search for information that has been generated previously.
Evernote is more of an extended brain to keep everything you feel is, or may be, important.  It can clip and record anything from text, webpages, photos, pdf's, graphics, and even sound and video.  You can also generate new notes, either typed or hand written.  It's unique stack/folder/tag structure allows for easy finding material so indexed, as well as fast keyword searching through the whole stored database. It is both web based, as well as on your local PC, and accessible from a multitude of hand held devices.
So, review your needs and choose accordingly.

A: I am having the exact same dilemma and found this article.  Without knowing what sort of technical capabilities you have (I'd assume more than average since you are posting on superuser), or what kind of money you'd like to spend--confluence has a 7-user setup for a 1-time payment of 10$, money goes to charity, where Evernote is ~45$/yr I believe.  Here are a couple of thoughts on it:
1) If you are thinking of loading tons of images (scanned papers), I would probably recommend Confluence since Evernote's free version caps uploads at 60MB/month.  Premium Evernote is ~45$/yr but upgrades the uploads to 1 GB/month at that point.
2) Evernote is widely available on just about every smart-mobile device you and your family may have, as well as most computers.  It's a great place to jot down notes.  I did notice a month ago though that Confluence has a Mini Confluence plug-in which may offer mobile support allowing easy on-the-go note taking.
For collaboration between family members (like a family message board), I would probably swing towards Confluence over Evernote though.  I have tested Evernote on a PC/iPhone/iPad and like it, but haven't completely begun setting up and attempting to use confluence though, so I'll try to pop back and update after I test it.

A: What about Microsoft OneNote?


text:
Q: QML Dynamically Update ListModel I'm confused at some point in QML as I'm new to it. The simplified QML codes define a window that includes one ListView which includes my delegate Items. One button loads and unloads this ListView Element. When I load and unload the ListView Element, all text that I wrote inside the TextInput is reset from listModel as I expected. So I need to dynamically update listModel thus I will not lose the text that I wrote in TextInput. I added a Keys.onPressed in TextInput to achieve that. But it works with some logical error. When I type, let's say "aaaa", then  I unload the ListView and load again via Button, what I get is "aaa" (the last letter is not passed to listModel). This is understandable but how can I update the list model roles dynamically in this example?
main.qml
ApplicationWindow {
    id: applicationWindow

    width: 300
    height: 200
    visible: true
    title: qsTr("01_Change_Model_Data")

    ListModel {
        id: listModel1
        ListElement {labelText: "Text Field 1:"; textInput_text : "This is text 1"}
        ListElement {labelText: "Text Field 2:"; textInput_text : "This is text 2"}
    }

    Button {
        id: loadUnloadBtn
        height: 24
        width: 50
        text: "Load"

        anchors {
            right: parent.right
            rightMargin: 20
            top: parent.top
            topMargin: 10
        }
        onClicked: {
            if(listAreaLoader.source == "") {
                listAreaLoader.source = "ListArea.qml"
            }else {
                listAreaLoader.source = ""
            }

        }
    }

    Loader {
        id: listAreaLoader
        anchors {
            top: parent.top
            topMargin: 10
            bottom: parent.bottom
            bottomMargin: 10
            left: parent.left
            leftMargin: 10
            right: parent.right
            rightMargin: 80
        }
        source: ""
    }
}

ListArea.qml:
Item {
    id: listViewDelegate
    ListView {
        id: listView1
        anchors.fill: parent

        model: listModel1
        delegate: listElementDelegate
        spacing: 6
    }

    Component {
        id: listElementDelegate

        Rectangle {
            color: "#00000000"
            height: 24
            width: 50

            Label {
                id: label1
                text: labelText
            }

            Rectangle {
                color: "grey"
                radius: 4
                width: 100
                height: 20
                anchors {
                    verticalCenter: label1.verticalCenter
                    left: label1.right
                    leftMargin: 10
                }

                TextInput {
                    id: textInput1
                    anchors.fill: parent
                    leftPadding: 5
                    rightPadding: 5
                    clip: true
                    verticalAlignment: Text.AlignVCenter
                    text: textInput_text

                    Keys.onPressed: {
                        listView1.currentIndex = index
                        listModel1.setProperty(index, "textInput_text", textInput1.text)
                    }
                }
            }
        }
    }
}


text:
Q: Locust. Read --host value from python code locust --no-web --client=1 --hatch-rate=1 --num-request=2 --host= http://localhost
I want to read --host value provided in cmd line in my HTTPLocust class. I am aware I can use host attribute for direct assignment but I do not want it. I want to read the value from cmd line with in HTTPLocust class. I am building custom logs and want to pass that value to the logs. I tried HTTPLocust.host but that returns none.
Also I want to read --web-port from python code.

A: New answer
There is a much more straightforward solution than my initial one below. Each TaskSet has a locust property that links back to their parent Locust locustinstance, so something like this will do exactly what you need:
class UserBehaviour(TaskSet):
    def __init__(self, parent):
        super().__init__(parent)
        print(self.locust.host)

Old answer
Looking at the code for HttpSession, it seems base_url is what you want.
So something like this should give you the current host, either default or specified on the command line:
class HostGetter(locust.TaskSet):
    @locust.Task()
    def get_host(self):
        print(self.client.base_url)

A: You can access the host variable by an instance of User()class. See the example below:
from locust import HttpLocust, TaskSet, task
import random, requests, time, os, inspect, json, sys

class UserBehaviour(TaskSet):
    @task(1)
    def test1(self):
        user = User()
        print(user.host)
        self.client.get("/v3/User/ListOfCoupon/")

class User(HttpLocust):
    task_set = UserBehaviour
    min_wait = 1000
    max_wait = 3000

see the log:
~/P/m/p/general (master ⚡↑) locust -f app_couponlist.py --host=http://www.google.com
[2017-09-19 14:33:13,020] Mesuts-MacBook.local/INFO/locust.main: Starting web monitor at *:8089
[2017-09-19 14:33:13,021] Mesuts-MacBook.local/INFO/locust.main: Starting Locust 0.8a3
[2017-09-19 14:33:22,281] Mesuts-MacBook.local/INFO/locust.runners: Hatching and swarming 5 clients at the rate 1 clients/s...
[2017-09-19 14:33:22,282] Mesuts-MacBook.local/INFO/stdout: http://www.google.com
[2017-09-19 14:33:22,282] Mesuts-MacBook.local/INFO/stdout:
[2017-09-19 14:33:23,285] Mesuts-MacBook.local/INFO/stdout: http://www.google.com
[2017-09-19 14:33:23,285] Mesuts-MacBook.local/INFO/stdout:
[2017-09-19 14:33:24,226] Mesuts-MacBook.local/INFO/stdout: http://www.google.com

A: This is my code:
import time,csv,argparse

class MySQLLocust(Locust):
    parser = argparse.ArgumentParser()
    parser.add_argument('--host', '--host')
    args, unknown = parser.parse_known_args()
    print("Host = " + args.host)

Now when I give:
locust -f mysql_locust.py --host=myhost-vm-101 --no-web --clients=2 --hatch-rate=10 --run-time=5m
I get the print statement result as expected:
Host = myhost-vm-101

A: You can access it via sys.argv
Or parse options via argparse
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-H', '--host')
args, unknown = parser.parse_known_args()

print str(args.host)


text:
Q: Input Functions in Snakemake I am building an example Workflow in snakemake, the Game of Life. In this particular example, I am using a starting grid that leads to an empty world after a few iterations. I would like to build a conditional workflow that checks for emptiness after each time step and stops the calculation of new time steps once the world is empty. It should then proceed to render a video from the displays of previous time steps.
To check for emptiness, I am using an input function and a checkpoint. Here is the Snakefile:
configfile: "config_exercise_2.yaml"
workdir: "../"

import numpy as np

Time = 1
def gridEmpty():
    global Time
    with open(checkpoints.CalculateNextTimeStep.get(time=Time).output[0],"rb") as f:
        if np.all(np.load(f) == 0): #grid is empty, no more timesteps required
            return [f"pictures/picture_t-{i}.jpg" for i in range(0,Time+1,1)]
        else: #grid is not empty, more timesteps required
            Time += 1
            checkpoints.CalculateNextTimeStep.get(time=Time)

rule RenderVideo:
    input:
        gridEmpty
    output:
        "video/clip.mp4"
    params:
        framerate = config["FrameRate"]
    shell:
        "cat {input} | ffmpeg -framerate {params.framerate} -f image2pipe -i - {output}"

rule Displaytimestep:
    input:
        "arrays/array_t-{time}.npy"
    output:
        "pictures/picture_t-{time}.jpg"
    conda:
        "../environment/environment.yaml"
    params:
        timeStep = lambda wildcards: wildcards.time
    script:
        "../scripts/DisplayTimeStep.py"

checkpoint CalculateNextTimeStep:
    input:
        lambda wildcards: f"arrays/array_t-{int(wildcards.time)-1}.npy"
    output:
        "arrays/array_t-{time}.npy"
    params:
        GridSize = config["GridSize"]
    conda:
        "../environment/environment.yaml"
    script:
        "../scripts/CalculateNextTimeStep.py"

I remember that this code worked previously, however now I am getting

Error:   TypeError: gridEmpty() takes 0 positional arguments but 1 was
given Wildcards:
Traceback:

Which puzzles me, since I do not see where any arguments are given to the input function. Any ideas? Thank you!

A: When you use a function as input, like:
rule RenderVideo:
    input:
        gridEmpty

snakemake automatically calls the function using the wildcards object as argument to the function. That is, it calls gridEmpty(wildcards). Since your definition of gridEmpty does not take any parameter, you get the error you see.
The easiest solution may be to define gridEmpty so that it takes one argument even if that argument is not used. Alternatively, this should also work and it is equivalent:
rule RenderVideo:
    input:
        lambda wildcards: gridEmpty(),

(NB: I haven't checked whether the rest of your code is correct)


text:
Q: JavaFX Menu (not MenuItem) with ToolTip? is there any possibility to add a Tooltip to a JavaFX (Sub-)Menu?
The usual (but ugly - why can't a menu not just be made of nodes?!) solution for MenuItems is to use a CustomMenuItem and put a Label (which is a Node) in it - the label can be assigned a ToolTip.
But how can I achieve this for a (Sub-)Menu? See the following example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class CustomSubMenu extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        MenuButton menuButton = new MenuButton("Menu");

        Label helloLabel = new Label("Hello...");
        helloLabel.tooltipProperty().setValue(new Tooltip("World!"));
        menuButton.getItems().add(new CustomMenuItem(helloLabel));

        Menu submenu = new Menu("This Submenu needs a ToolTip!");
        //             new CustomMenuItem(new Menu()); // doesn't work, because Menu is not a Node.
        submenu.getItems().add(new MenuItem("Some other Item"));
        menuButton.getItems().add(submenu);

        primaryStage.setScene(new Scene(menuButton));
        primaryStage.show();

    }

}

A: Each menuItem (and naturally also a menu) is associated with a node. That node is accessible after the item has been shown at least once. Then the node is accessible via item.getStyleableNode() (since fx9, for fx8 see below) and a tooltip can be set on that node.
So basically, the way to go is to listen for that instant and then install a tooltip. The example below does so by

*

*create a tooltip for the menu/item and put it into its properties

*register a onShown handler on the parent menu and install the tooltip if available

A basic snippet:
String tooltipKey = "TOOL_TIP";
MenuItem normalItem = new MenuItem("Good .. ");
normalItem.getProperties().put(tooltipKey, new Tooltip("Morning!"));
menuButton.getItems().add(normalItem);
Menu submenu = new Menu("This Submenu needs a ToolTip!");
submenu.getProperties().put(tooltipKey, new Tooltip("It's meee!"));
menuButton.setOnShown(e -> {
    menuButton.getItems().forEach(item -> {
        Node node = item.getStyleableNode();
        if (node != null && item.getProperties().get(tooltipKey) instanceof Tooltip) {
            Tooltip tip = (Tooltip) item.getProperties().get(tooltipKey);
            Tooltip.install(node, tip);
        }
    });

});

For fx8, the basic approach is the same - but access to the node that represents the menuItem is nasty (beware: don't in production! *cough ..):

*

*getStyleableNode is new to fx9, so we have to hack around using internal api and implementation details

*the time at which the node is available is harder to find: the obvious hook would be an eventHandler for SHOWN on the menuButton, but that doesn't seem to be supported (doesn't seem to be supported yet - didn't dig though)

*one way around is to first listen to the showingProperty, grab the contextMenu, listen to its skinProperty and do the install once the skin is set

code snippets:
// not working - what's wrong?
menuButton.addEventHandler(MenuButton.ON_SHOWN, e -> {
    LOG.info("not getting here?");
    // install tooltips here
});

ChangeListener<Skin> skinListener = (src, ov, skin) -> {
    ContextMenuContent content = (ContextMenuContent) skin.getNode();
    VBox menuBox = (VBox) content.getChildrenUnmodifiable().get(0);
    menuBox.getChildren().forEach(node -> {
        // implementation detail: the menuItem is set in the node's properties
        if (node.getProperties().get(MenuItem.class) instanceof MenuItem) {
            MenuItem item = (MenuItem) node.getProperties().get(MenuItem.class);
            if (node != null && item.getProperties().get(tooltipKey) instanceof Tooltip) {
                Tooltip tip = (Tooltip) item.getProperties().get(tooltipKey);
                Tooltip.install(node, tip);
            }

        }

    });
};
menuButton.showingProperty().addListener((src, ov, nv) -> {
    ContextMenu popup = submenu.getParentPopup();
    if (popup != null) {
        if (popup.getSkin() == null) {
            popup.skinProperty().addListener(skinListener);
        } else {
            popup.skinProperty().removeListener(skinListener);
        }
    }
});

A: I figured out a simple way to trick the MenuItem as a Control Label node, use code like below:
    Label lb=new Label("MenuItem Text");
    lb.setStyle("-fx-text-fill:black;");
    MenuItem myMenuItem = new MenuItem(null, lb);
    Tooltip tips = new Tooltip("Your tip text here");
    Tooltip.install(myMenuItem.getGraphic(), tips);

set the tooltip to the label and this works pretty good for me.


text:
Q: How to remove element from HTML string? This doesn't seem to be working, I get an Uncaught Type error on the .remove() line:
JS:
var str = $("a").html();
var $html = $.parseHTML(str);
$("i",$html).remove();

$("div").html($html);

HTML:
Hello Bob

How to get this to work?

A: You can remove the HTML tags by just using the .text() function.
var str = $("a").text();

$("a").text(str);

Which will result in:
Hello Bob

Example: http://jsfiddle.net/3s1c55w2/
How it works:

*

*The $("a").text(); will retrieve only the text of the element, so in your case it will return Hello Bob.

*Once you retrieve Hello Bob, simply set the a tags text value using .text(str) again, where the str is the value with no html tags.

A: You can clone a, change html code of clone and put clone inside div.
Fiddle.
$(document).ready(function()
{
    var clone = $("a").clone();
    clone.find("i").remove();
    $("div").html(clone);
});

A: Maybe he's trying to remove i tags from every anchor.
http://jsfiddle.net/1fytum86/
$("a").each(function(index) {
    var str = $(this).text();
    $(this).html(str);
});

Anyway, it's possible that he was getting a type error because parseHTML() parses a string into an array of DOM nodes. Best of luck!

A: If you are trying to remove the italics and leave the text:
$("a").html($("a").html().replace(/<\/?i>/g, ""));

Otherwise, the other answers using either remove or detach would be appropriate.


text:
Q: При работе в команде, как правильно подтягивать изменения из веток в git? Во время работы в команде над одним продуктом возник вопрос - как правильно и корректно подтягивать изменения других коллег с их веток или с ветки dev (основной, скажем так).
Когда я работаешь один, таких вопросов естественно не возникает и мне между двумя моими машинами было достаточно git pull - подтянуть изменения свои на одной машине - продолжить работать на другой и снова закомитить.
Так как все таки правильно? Я вижу три решения:
1) git pull - подтягиваем все изменения и работаем уже с изененными файлами
из минусов вижу только то что все изменения отображаются как "мои"
2) git merge - мержить свою ветку с чужими и работать дальше
3) git cherry-pick - вносить в свою ветку коммиты коллег, которые в ветке будут отображаться как "мои"
из минусов вижу только долгий и не удобный перебор всех хешей коммитов
Так вот вопрос - как все таки правльно подтягивать изменения из веток других людей?

A: Давно придумали git-flow, которое решает все вопросы. Даже есть шпаргалка.
git pull на самом деле по умолчанию делает git fetch + git merge, поэтому второй  вариант включает как бы первый. git pull умеет ещё ребейзить, но этим пользуются те, кто понимает. И если отбросить мишуру, то ребейз формально делает серию git cherry-pick.
Подсумируем. Как правильно. Когда нужно сделать фичу, делаем ветку от девелопа (или мастера), делаем фичу. Если фича делается долго - поливаем изменения с ветки себе (git checkout develop && git pull && git checkout - && git merge develop) - этим упростим мердж в будущем. Когда фича готова - мержим назад в девелом (мастер). Можно напрямую, можно через pull/merge request.

A: Вопрос субъективный. Когда вам нужно опубликовать код из своей ветки в основную, у вас есть по сути четыере опции:

*

*просто merge вашей ветки в основную;

*rebase вашей ветки на head основной (линеаризация истории);

*комбирированный вариант rebase + merge;

*перенос патчей (cherry-pick).

Все они имеют плюсы и минусы. Выбирают, то что подходит к текущему проекту/нравится команде. Кроме того, они могут использоваться совместно в рамках сложного workflow.
Сами по себе git flow, github flow, gitlab flow и прочие flow не являются серебрянной пулей и на маленьких проектах в небольшой команде могут доставлять больше сложностей, чем удобств.


text:
Q: How do I change the unit of multiple numbers in a Less mixin? I am trying to create a mixin whereby I can change the unit from px to rem.  For now, I have the following code:
@emSize : 16px;
@pxr    : 1 / unit(@emSize, rem);

.padding(@padding) {padding: @padding * @pxr;}

.test {.padding(10px);}

This works fine if I only have one number in the mixin, but it does not work if I have multiple numbers.  For instance, this does NOT work:
.test {.padding(10px 25px);}

What I cannot figure out is how to I could get this to work in Less.

A: Option 1
You can use the comma separated values to achieve the same with your minimal code:
@emSize : 16px;
@pxr    : 1 / unit(@emSize, rem);

.padding(@verticalpad, @horizontalpad) {
      padding: (@verticalpad * @pxr) (@horizontalpad * @pxr);
}

.test {
      .padding(10px, 25px);
}

See it working
Option 2
Did you tried with two functions separated?
@emSize : 16px;
@pxr    : 1 / unit(@emSize, rem);

.paddingver(@paddingver) {
       padding-top: @paddingver * @pxr;
       padding-bottom: @paddingver * @pxr;
}
.paddinghor(@paddinghor) {
       padding-left: @paddinghor * @pxr;
       padding-right: @paddinghor * @pxr;
}

.test {
       .paddingver(10px);
       .paddinghor(25px);
}

See it working


text:
Q: Memory management in numpy arrays,python I get a memory error when processing very large(>50Gb) file (problem: RAM memory gets full).
My solution is: I would like to read only 500 kilo bytes of data once and process( and delete it from memory and go for next 500 kb). Is there any other better solution? or If this solution seems better , how to do it with numpy array?
It is just 1/4th the code(just for an idea)
  import h5py
  import numpy as np
  import sys
  import time
  import os
  hdf5_file_name = r"test.h5"
  dataset_name = 'IMG_Data_2'

  file = h5py.File(hdf5_file_name,'r+')
  dataset = file[dataset_name]
  data = dataset.value
  dec_array = data.flatten()
  ........

I get memory error at this point itsef as it trys to put in all the data to memory.

A: Quick answer

*

*Numpuy.memmap allows presenting a large file on disk as a numpy array. Don't know if it allows mapping files larger than RAM+swap though. Worth a shot.

*[Presentation about out-of-memory work with Python] (http://hilpisch.com/TPQ_Out_of_Memory_Analytics.html)

Longer answer
A key question is how much RAM you have (<10GB, >10GB) and what kind of processing you're doing (need to look at each element in the dataset once or need to look at the whole dataset at once).
If it's <10GB and need to look once, then your approach seems like the most decent one. It's a standard way to deal with datasets which are larger than main memory. What I'd do is increase the size of a chunk from 500kb to something closer to the amount of memory you have - perhaps half of physical RAM, but anyway, something in the GB range, but not large enough to cause swapping to disk and interfere with your algorithm. A nice optimisation would be to hold two chunks in memory at one time. One is being processes, while the other is being loaded in parallel from disk. This works because loading stuff from disk is relatively expensive, but it doesn't require much CPU work - the CPU is basically waiting for data to load. It's harder to do in Python, because of the GIL, but numpy and friends should not be affected by that, since they release the GIL during math operations. The threading package might be useful here.
If you have low RAM AND need to look at the whole dataset at once (perhaps when computing some quadratic-time ML algorithm, or even doing random accesses in the dataset), things get more complicated, and you probably won't be able to use the previous approach. Either upgrade your algorithm to a linear one, or you'll need to implement some logic to make the algorithms in numpy etc work with data on disk directly rather than have it in RAM.
If you have >10GB of RAM, you might let the operating system do the hard work for you and increase swap size enough to capture all the dataset. This way everything is loaded into virtual memory, but only a subset is loaded into physical memory, and the operating system handles the transitions between them, so everything looks like one giant block of RAM. How to increase it is OS specific though.

A: The memmap object can be used anywhere an ndarray is accepted. Given a memmap fp, isinstance(fp, numpy.ndarray) returns True.
Memory-mapped files cannot be larger than 2GB on 32-bit systems.
When a memmap causes a file to be created or extended beyond its current size in the filesystem, the contents of the new part are unspecified. On systems with POSIX filesystem semantics, the extended part will be filled with zero bytes.


text:
Q: Como configurar rotas quando a aplicação não esta na raiz do servidor asp.net mvc? Localmente o meu site tem a seguinte rota padrão é tudo funciona:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Projeto.WEB.Celular
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Home",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

        }
    }
}

Mais o meu site não esta na pasta raiz do servidor, eu tenho uma pasta virtual com o nome website, ficando assim:
http://www.teste.com.br/website
Desta forma quando eu vou fazer um acesso a uma página o redirecionamento fica apontando para a pasta raiz, e deveria vim o nome da pasta antes:
http://www.sistemaguardiao.com.br/" falta a pasta"/RecuperaSenha
Exemplo:
@model Generico.Dominio.TB_USUARIO

@{
    ViewBag.Title = "Index";
}

@Html.Partial("_navbarPrincipal")
@Html.Partial("_PartialMensagens")

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
       @Html.ValidationSummary(true)

                @Html.TextBoxFor(x => x.login, new { placeholder = "endereço de e-mail", @class = "form-control input-lg "})
                @Html.ValidationMessageFor(x => x.login)
                @Html.TextBoxFor(x => x.senha, new { placeholder = "password", @class = "form-control input-lg", type = "password" })
                @Html.ValidationMessageFor(x => x.senha)

                <button class="btn btn-lg btn-block btn-primary glyphicon glyphicon-log-in" type="submit" name="opcao" value="pesquisar" >   Login...</button>

                    Recuperar Senha

}

web confing:
<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <connectionStrings>
    <add name="Conexao"
         connectionString="Server=PC-ESTUDO\SQLEXPRESS;Database=teste;User Id=teste;Password=123;"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <customErrors mode="Off"/>

  </system.web>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

agradeço a ajuda

A: Para fazer sua aplicação funcionar em um subdiretório, altere seu Web.config para o seguinte:
<?xml version="1.0" encoding="utf-8"?>

<configuration>
<location path="." inheritInChildApplications="false">
  <connectionStrings>
    <add name="Conexao"
         connectionString="Server=PC-ESTUDO\SQLEXPRESS;Database=teste;User Id=teste;Password=123;"
         providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <customErrors mode="Off"/>

  </system.web>
  </location>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

Esta declaração:
<location path="." inheritInChildApplications="false">

Faz com que as configurações neste ponto sejam usadas apenas pela aplicação do diretório raiz. Configurações específicas de subdiretórios passam a ser consideradas.
Note que a seção não vale para o arquivo todo. <runtime> não entra na seção.


text:
Q: How do I make another block of text? I understand how to display some text with the user input, but what I'm confused about is how to add a completely new block of text under the one I have right now (I want to put a new block of text because I want the size of the text to be different). Right now, I display "Welcome [user input]!"
In my activity file I have:
public class DisplayMessageActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Get the message from the intent
        Intent intent = getIntent();
        String message = "                Welcome " + intent.getStringExtra(MainActivity.EXTRA_MESSAGE) + "!";

        // Create the text view
        TextView textView = new TextView(this);
        textView.setTextSize(25);
        textView.setText(message);

        // Set the text view as the activity layout
        setContentView(textView);
    }

And in my fragment.xml file, I have:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.myfirstapp.DisplayMessageActivity$PlaceholderFragment"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:text="TEST"
        android:layout_height="wrap_content" />
</LinearLayout>

With some help from the feedback I got from other users, I added android:text="TEST" too the second "TextView". And I also added the android:orientation="vertical" to LinearLayout. But the "TEST" still doesn't show up when I run the app! Thanks in advance.

A: You are not associating your layout to your Activity. Instead, you are adding a TextView on runtime, that is created on runtime. That's why only one TextView appears. You have to use setContentView(R.layout.mylayout); instead of setContentView(textView);, so your Activity fetches your layout.
Edit: In your layout, add ids to your TextViews, so you can access them from your Activity code, like this:
<TextView
    android:id="@+id/myFirstTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="TEST1" />

<TextView
    android:id="@+id/mySecondTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="TEST2" />

Then on your Activity, inside onCreate():
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        // Get the message from the intent
        Intent intent = getIntent();
        String message = "                Welcome " + intent.getStringExtra(MainActivity.EXTRA_MESSAGE) + "!";

        TextView textView1 = (TextView) findViewById(R.id.myFirstTextView);
        TextView textView2 = (TextView) findViewById(R.id.mySecondTextView);

        textView1.setTextSize(25);
        textView1.setText(message);

    }

A: Assuming fragment.xml is in the res/layout folder
setContentView(R.layout.fragment);

instead of
setContentView(textView);


text:
Q: Sonata Admin, split one entity (in db) to more display block switch a discrimatory field I pass all the day reading, testing, re-reading and re-testing, I can't find a proper solution to my problem.
Let say you have a file entity, which switch type, go to a different block. (I mean, in the database i only have 1 file table, but in the display, i have a block "images", another "documents" and another "map"). All 3 are files with a different value for the field "type".
I know that the simplest should be to have 3 tables but i don't want to ruin my architecture because of using sonata.
I totally figure out how to do it in practice with preupdate and prepersist events and the initialisation phase. But even when i try to give the option "admin_code" to my unmapped property $images. It's always saying that it need an admin class. As the admin class is mapped by the annotation @ORM\OneToMany, i can't use it otherwise doctrine generates me another table.
Is there any way to achieve this ?
Is the admin_code option bugged ?
Or should i pass by a front-end solution? (i totally prefer back-end, but i will do with what is possible)

A: Did you try to use Doctrine inheritance
I think you'll be able to create an abstract File class and 3 other classes that extend File :
/**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({"image" = "Image", "document" = "Document", "map" = "Map"})
 */
abstract class File {
    ...
}

Then you'll have to create the 3 classes:
class Image extends File {
    ...
}

class Document extends File {
    ...
}

class Map extends File {
    ...
}

After, you'll be able to create 3 differents admin class to display in Sonata.


text:
Q: list lines ending with a period or semicolon how can I write a command by using grep or egrep to display all the lines in a file that end with a semicolon ";" or a period "." character.

A: This should do it:
$ grep -E '(;|\.)$'

The -E switch enables regular expression mode. The expression simply matches a line ending in either a semicolon or a period.
Note: I haven't tested this.

A: Without -E:
grep '\.\|;$' filename

A: three ways:any of these worked for me.
one:
grep '[\.;]$' your_file

two:
awk '/\.$/ || /;$/' your_file

three:
awk '/[\.;]$/' your_file

A: With sed :
sed -rn '/(\.|;)$/p'

With awk
awk '/(\.|;)$/'

A: With grep (and egrep) a dollar sign ($) matches the end of a line, and a carret (^) matches the beginning of a line. So, for example, if you wanted to match lines containing exactly the word "fish" and no other characters you could use this:
grep '^fish$'

It's important to use single quotes to wrap the search expression so that bash doesn't do anything funny to it.
So, to answer your question, you will need to use the search pattern '[.;]$' to match either a . or ; character followed by an end of line character. I am using this as an example test file:
$ cat testfile
one
two;
three.
four:

And here is the result:
$ grep '[.;]$' testfile
two;
three.

If you also want to allow whitespace at the end of the line, then use this pattern: '[.;][ \t]*$' which will match with any number of spaces or tab characters after the . or ;.


text:
Q: How to make ngx-bootstrap datepicker be able to select and display only month and year? I tried setting the config object 'bsConfig' value to 'MMM-YYYY'. The problem is that when I click on the input it is showing all the three options (day, month, year) to select. I want only month and year to be shown for selecting. When I select one particular date, it is displaying only month and year in the input field. The displaying part is fine but I also want the datepicker to show only month and year to select and not show day for selecting.
Here is my sample code.
In the html file.
<input bsDatepicker [bsConfig]="bsConfig">

In the component.ts file
bsConfig: Partial<BsDatepickerConfig>;

ngOnInit() {
this.bsConfig = Object.assign({}, {dateInputFormat: 'MMM-YYYY', selectDay: false, showWeekNumbers: false});

}
I installed ngx-bootstrap, included "ngx-bootstrap/datepicker/bs-datepicker.css" file, imported it to the component. every thing is good. Except that it is showing day also to select when i want only month and year to be selected.
Someone help me please.

A: For those who still looking, here is the new updated config value.
min-mode
In app.component.ts
export class AppComponent  {
        bsValue: Date = new Date(2017, 7);
        minMode: BsDatepickerViewMode = 'month';
        bsConfig: Partial<BsDatepickerConfig>;

      ngOnInit(): void {
        this.bsConfig = Object.assign({}, {
          minMode : this.minMode
        });
      }
}

app.component.html
<bs-datepicker-inline [bsConfig]="bsConfig" bsDatepicker [(bsValue)]="bsValue"></bs-datepicker-inline>


text:
Q: How to use actions command in GDB tool? Below is the code which i had used to understand actions command in gdb.
#include <stdio.h>
int Use_Action(int CatchedInt, char * CatchedStr)
{
    printf("CatchedInt = %d, CatchedStr = %s\n", CatchedInt, CatchedStr);
    return 0;
}
int main(void)
{
    int PassingInt = 20;
    char PassingStr[10] = "Hello";

    Use_Action(PassingInt, PassingStr);
}

In GDB Tool I have done the following things with the help of https://sourceware.org/gdb/current/onlinedocs/gdb/Tracepoint-Actions.html
(gdb) trace Use_Action
Tracepoint 1 at 0x1169: file action.c, line 5.
(gdb) info tracepoints
Num     Type           Disp Enb Address            What
1       tracepoint     keep y   0x0000000000001169 in Use_Action at action.c:5
    not installed on target
(gdb) actions
Enter actions for tracepoint 1, one per line.
End with a line saying just "end".
>collect CatchedInt
>end
(gdb) info tracepoints
Num     Type           Disp Enb Address            What
1       tracepoint     keep y   0x0000000000001169 in Use_Action at action.c:5
        collect CatchedInt
    not installed on target

If i had collect the value of "Catchedint" by command collect Catchedint, then how to display the value. Is there something I missed? or i understand this actions command in wrong way!!?

A:
Is there something I missed?

Yes: you need to actually run the program while collecting the trace, using tstart, run and tstop commands.
If you tried that, you would likely get this error:
(gdb) tstart
You can't do that when your target is `exec'

That's because only some targets support tracepoints, and local execution doesn't. You'll need to use gdbserver instead.


text:
Q: Generating regular expression using a set of regular expressions I am working on a regular expression that matches the postal codes of a set of countries. Since getting a regex that matches the postal code for any one country is relatively easy, I plan to parse all those regexes each of which matches the postal code for a country and output a regex which strictly matches the union of the input regexes.
I know about the | operator. But is there any such operator for C# regex / regexvalidator class

A: Use the | alternative regexp operator:
regex1|regex2|regex3|...

This matches anything that matches any of the component regexps.
According to the answer in Merge several regexes to a single one the PCRE engine will optimize regular expressions that are merged this way.

A: For example, you have REGEX1, REGEX2, REGEX3 that match to some postal code.
Use REGEX1|REGEX2|REGEX3 than. You don't need to parse contents of regex'es.


text:
Q: Remove holes in polygon I am trying to solve the following problem in R :
I have a polygon object defined by a list l with two components x and y. The order defines the edges of the polygon.
For instance :
l=list(
    x=c(-1.93400738955091,0.511747161547164,1.85047596846401,-1.4963460488281,-1.31613255558929,-0.0803828876660542,1.721752044722,-0.724002506376074,-2.08847609804132,2.13366860069641),
    y=c(-1.02967154136169,1.53216851658359,-1.39564869249673,-1.21266011692921,1.6419616619241,-1.87141898897228,0.946605074767527,1.49557080147009,0.324443917837958,-0.517303529772633)
)
plot(l,type="b",pch=16)
points(l$x[c(10,1)],l$y[c(10,1)],type="b",pch=16)

Now what I am interested in is to keep only the outer boundary (but not the convex hull) of this polygon. The following picture highlights the point I'd like to keep
points(
    x=c(-1.13927707377209,-1.31613255249992,-1.3598262571216,0.511747159281619,0.264900107013767,0.671727215417383,-0.724002505140328,-1.93400738893304,-1.4811931364624,-1.45298543105533,-2.08847609804132,-1.40787406113029,-1.3598262571216,0.278826441754518,1.85047596733123,1.48615105742673,1.48615105742673,2.13366860069641,1.38016944537233,1.38016944537233,1.17232981688283,1.17232981688283,1.72175204307433,0.671727215417383,-1.496346, -0.08038289, -0.2824999),
    y=c(1.13914087952916,1.64196166071069,0.949843643913108,1.53216851597378,1.27360509238768,1.18229006681548,1.49557080106148,-1.02967154055378,-0.972634663817139,-0.525818314106921,0.324443915423533,0.188755761926866,0.949843643913108,-1.30971824545964,-1.3956486896768,-0.59886540309968,-0.59886540309968,-0.517303527559411,-0.367082245352325,-0.367082245352325,0.0874657083966551,0.0874657083966551,0.94660507315481,1.18229006681548,-1.21266,-1.871419,-1.281255),
    pch=16,
    col="red",
    cex=0.75
)

I am really clueless about whether there are tools to easily do that. The closest I have found is the polysimplify function in the polyclip package, which identifies all the points I need, but also outputs some points I do not need (inner points where segments intersect).

I actually found a solution (below). The following function does what I want but I am unsure why it works (and whether it may fail).

Actually the function below correctly identifies the point I want but outputs them in the wrong order, so it is still useless to me...
polygon.clean<-function(poly){
  require(polyclip)
  poly.cleaned=polysimplify(poly)
  x=unlist(sapply(poly.cleaned,function(x)x$x))
  y=unlist(sapply(poly.cleaned,function(x)x$y))
  x.src=x[!x%in%x[duplicated(x)]]
  y.src=y[!y%in%y[duplicated(y)]]
  poly.cleaned=poly.cleaned[sapply(poly.cleaned,function(poly.sub,x,y){
    any(poly.sub$x%in%x&poly.sub$y%in%y)
  },x=x.src,y=y.src)]

  x=unlist(sapply(poly.cleaned,function(x){
    res=x$x
    if(length(res)==4){
      res=vector()
    }
    res
  }))
  y=unlist(sapply(poly.cleaned,function(x){
    res=x$y
    if(length(res)==4){
      res=vector()
    }
    res
  }))
  x=c(x,x.src)
  y=c(y,y.src)
  tester=duplicated(x)&duplicated(y)
  x=x[!tester]
  y=y[!tester]
  list(x=x,y=y)
}

plot(l,type="b",pch=16)
points(l$x[c(10,1)],l$y[c(10,1)],type="b",pch=16)
points(polygon.clean(l),pch=16,cex=0.75,col="red")

A: Using rgeos routines, you first "node" your linestring to create all the intersections, then "polygonize" it, then "union" it to dissolve its insides.
First make a SpatialLines version of your data with duplicated first/last point:
library(sp)
library(rgeos)
coords = cbind(l$x, l$y); coords=rbind(coords,coords[1,])
s = SpatialLines(list(Lines(list(Line(coords)),ID=1)))

Then:
s_outer = gUnaryUnion(gPolygonize(gNode(s)))

Plot it thus:
plot(s,lwd=5)
plot(s_outer, lwd=2,border="red",add=TRUE)

If you want the coordinates of the surrounding polygon they are in the returned object and can be extracted with:
s_outer@polygons[[1]]@Polygons[[1]]@coords

#                x           y
# [1,]  0.27882644 -1.30971825
# [2,] -0.08038289 -1.87141899
# [3,] -0.28886517 -1.27867953

Assuming there's only one polygon, which might not be the case - suppose your line traces a figure-of-eight - then you'll get two polygons touching at a point. We don't know how free your jaggly line is to do things like that...


text:
Q: Counter/Storage Collector + Matlab I'm trying to design a storage system where excess energy goes into it. There is a cap of a maximum storage size for the system. I am struggling to work out how to code this in matlab.
Currently im using a function similar to this
max_storage = no_tanks*tank_size

if cumsum(excess) > 0
   storage = cumsum(excess)
elseif cumsum(excess) < 0

After that I am confused how to continue writing the code. Any help would be greatly appreciated

A: Attempt at mind-reading, while awaiting an update to the question.
To limit the storage size to max_storage, you need to have some code like
storage = calc_storage(excess);      % or whatever
storage = min(storage, max_storage);

Don't forget to finish your statements with ;, and if you need to use cumsum(excess) lots of times it is better to assign it to a variable rather than calculating it over and over again.