text:
Q: Is it necessary to escape a backslash in a config file Say I have the following string:
c:\testmypath

In C#, if I want to use that inside code without a tab appearing inside it, I can do the following:
string t = @"c:\testmypath";

However, if I want to read this from a configuration file; let's say an appsettings.json that looks like this:
{
  "MyPath": "c:\testmypath"
}

The following code results in a tab being displayed in the console:
static void Main(string[] args)
{
    var path = returnString();

    Console.WriteLine(path);
    Console.ReadLine();
}

static string returnString()
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json");

    var configuration = builder.Build();

    return configuration["MyPath"];
}

I can fix this by escaping the path inside the config file; for example:
{
  "MyPath": "c:\\testmypath"
}

By, can I escape the single slash version somehow?  I've tried:
return @configuration["MyPath"];

Which, to my surprise, does compile, but has no effect.  I've also tried .ToString(), although I'm not sure why I thought that would work.

A: In addition to @Joey's excellent answer, for paths you could use forward slashes:
{
  "MyPath": "c:/testmypath"
}

This is usually pretty well supported. Or to be super safe, you could just revert them back to regular backslashes:
return configuration["MyPath"].Replace("/", @"\");

A: C# and JSON are different languages with different syntactic rules (after all, JSON doesn't look much like C#), albeit their rules regarding how strings look are kind of similar.
Since you're dealing with a JSON file, C#'s rules for strings (verbatim strings in particular) don't apply, but JSON's rules do. In those rules you have to escape a backslash as \\ every time. There is no other way. Otherwise the sequence \t actually means Tab, as you noticed.
There is no real way of fixing this after the fact. Depending on the character after \ you'd get something, like the Tab, or get a parsing error when trying to read the JSON file. While you could turn Tab back into \t if you know you're dealing with file paths I wouldn't recommend it. As mentioned, if the character after the backslash isn't a t, you might get an error anyway without a chance to recover.
As for your attempt of "escaping" the wrong version on the C# side: @ has different meaning, depending on where it's used:

*

*@"string" is a verbatim string in which almost anything can be written verbatim without having to worry about escape characters. The only exception is "" for double quotes inside the string. But indeed, it's most commonly-used and handy for things like file paths on Windows and regular expressions, both of which are rather annoying to type when having to escape every single backslash.

*@name makes any keyword or other name a valid identifier. You can prefix every identifier with @ and this would make a valid program slightly longer, but doesn't change anything about its semantics. It's purely something for the compiler, similar to, e.g. using directives.

While both features use the same character and have somewhat comparable ideas, they don't work the same and of course, both have no impact at runtime. They're merely for the compiler.


text:
Q: Why doesn't Margin: auto work in this Flex-box container? Main container didn't stretch full width
Margin-left: auto doesnt work in the Nav > Main's Flex-box container, I can't figure out why. Maybe the display: inherit in the Main's styling causes this problem, but even changing it to flex doesn't work out. I have included a demo down below. I'd appreciate your help and hopefully won't take up too much of your time. Thanks in advance!

*,
::before,
::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0; }

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  font-size: 1em;
  line-height: 1.5;
  color: rgba(0, 0, 0, 0.87); }

main {
  display: inherit;
  margin-right: 3rem;
  margin-left: 3rem; }

section {
  margin-top: 16px;
  margin-bottom: 16px;
  padding-bottom: 2rem;
  border-bottom: 1px solid rgba(192, 192, 192, 0.6); }

nav {
  background-color: #2196f3;
  display: flex;
  padding-top: 16px;
  padding-bottom: 16px; }
  nav ul {
    display: inline-flex; }
    nav ul li {
      display: block; }
      nav ul li:not(:first-child) {
        margin-left: 32px; }
    nav ul a {
      display: block;
      color: rgba(255, 255, 255, 0.6); }
      nav ul a:hover {
        text-decoration: none;
        color: rgba(255, 255, 255, 0.87); }
    nav ul.secondary {
      margin-left: auto !important; }

ul, ol {
  list-style: none; }

h1 {
  font-size: 3.5em; }
  @media (min-width: 37.438em) {
    h1 {
      font-size: calc(3.5em + ((100vw - 37.438em) / (120 - 37.438)) * (5.998 - 3.5)); } }
  @media (min-width: 120em) {
    h1 {
      font-size: 5.998em; } }

h2 {
  font-size: 2.375em; }
  @media (min-width: 37.438em) {
    h2 {
      font-size: calc(2.375em + ((100vw - 37.438em) / (120 - 37.438)) * (3.75 - 2.375)); } }
  @media (min-width: 120em) {
    h2 {
      font-size: 3.75em; } }

h3 {
  font-size: 2em; }
  @media (min-width: 37.438em) {
    h3 {
      font-size: calc(2em + ((100vw - 37.438em) / (120 - 37.438)) * (2.999 - 2)); } }
  @media (min-width: 120em) {
    h3 {
      font-size: 2.999em; } }

h4 {
  font-size: 1.563em; }
  @media (min-width: 37.438em) {
    h4 {
      font-size: calc(1.563em + ((100vw - 37.438em) / (120 - 37.438)) * (2.024 - 1.563)); } }
  @media (min-width: 120em) {
    h4 {
      font-size: 2.024em; } }

h5 {
  font-size: 1.25em; }
  @media (min-width: 37.438em) {
    h5 {
      font-size: calc(1.25em + ((100vw - 37.438em) / (120 - 37.438)) * (1.499 - 1.25)); } }
  @media (min-width: 120em) {
    h5 {
      font-size: 1.499em; } }

h6 {
  font-size: 1.125em; }
  @media (min-width: 37.438em) {
    h6 {
      font-size: calc(1.125em + ((100vw - 37.438em) / (120 - 37.438)) * (1.25 - 1.125)); } }
  @media (min-width: 120em) {
    h6 {
      font-size: 1.25em; } }

h1, h2 {
  font-weight: 300; }

h3, h4, h5 {
  font-weight: 400; }

h6 {
  font-weight: 700; }

p.subtext {
  color: rgba(158, 158, 158, 0.87); }

a {
  color: rgba(30, 144, 255, 0.87);
  text-decoration: none; }
  a:hover {
    text-decoration: underline; }

h1, h2, h3, h4, h5, h6 {
  margin-top: .5em;
  margin-bottom: .5em; }

p {
  padding-top: 8px;
  padding-bottom: 8px; }

span.subheading {
  color: rgba(158, 158, 158, 0.87);
  font-size: calc(1em - 0.375em); }

.textAlign_center {
  text-align: center !important; }

/*# sourceMappingURL=main.css.map */

Home

Documentation

Home

Documentation

Responsive Typography

HeadingSubheading

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam et vitae id, tempora, placeat modi, aliquam, illo dolores aut ad similique esse aliquid dolorum ipsum fugit eum nostrum optio laborum totam. Minus placeat recusandae velit neque officia esse, commodi officiis cumque quibusdam sequi tenetur hic, ullam aut itaque pariatur excepturi maxime ad aperiam quidem? Itaque officia eum a, aliquid necessitatibus similique accusamus aspernatur ipsum soluta esse beatae temporibus ducimus dolorem quasi, ipsam quos. Sint maiores tempore, at adipisci consequuntur illum rerum laborum aliquam commodi mollitia ducimus, harum veniam, laudantium modi provident porro. Quisquam illo nisi sapiente modi officia incidunt molestias.

HeadingSubheading

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam et vitae id, tempora, placeat modi, aliquam, illo dolores aut ad similique esse aliquid dolorum ipsum fugit eum nostrum optio laborum totam. Minus placeat recusandae velit neque officia esse, commodi officiis cumque quibusdam sequi tenetur hic, ullam aut itaque pariatur excepturi maxime ad aperiam quidem? Itaque officia eum a, aliquid necessitatibus similique accusamus aspernatur ipsum soluta esse beatae temporibus ducimus dolorem quasi, ipsam quos. Sint maiores tempore, at adipisci consequuntur illum rerum laborum aliquam commodi mollitia ducimus, harum veniam, laudantium modi provident porro. Quisquam illo nisi sapiente modi officia incidunt molestias.

A: Flexbox has its own layout positioning properties that you can use instead of adding margins for positioning. When you are using flex, it already defines a lot of positioning properties for you. I assume you are trying to push your flexbox to the right with marginLeft: "auto" . With flex properties, and depending on where your flex box main axis is, you would only need to use justify-content: flex-end or align-items: flex-end.
If it is only one item that you need to readjust, try using justify-self for that purpose: https://developer.mozilla.org/en-US/docs/Web/CSS/justify-self

redpajama_set_name: RedPajamaStackExchange


text:
Q: count id, insert, then update by number range in another columns in same table mysql I am trying to update levels in db like this:
"count (id) from users table where referral_id = id As aggref set agg_referral = aggref AND level = 1 if aggref in between 1 to 3"
So far i know but no success :(
Here is my db structure
users table:
  id (AI)      name       Referral id      agg_referral   Level
=========== ========== ================== ============== ======
     1        user A          0                 0          0
     2        user B          3                 0          0
     3        user C          1                 0          0
     4        user D          3                 0          0

Here is my code i am running it using cron job:
  <?php
    include( $_SERVER['DOCUMENT_ROOT'] . '/config.php' );
    mysql_connect(DB_HOST,DB_USER,DB_PASS);
    mysql_select_db(DB_NAME);
    $query="UPDATE users SET agg_referral = (SELECT COUNT(id) from users WHERE users.referral_id = users.id)";
    mysql_query($query);

    ?>

I am expecting results like this

 id (AI)      name       Referral id      agg_referral   Level
=========== ========== ================== ============== ======
     1        user A          0                 0          0
     2        user B          3                 0          0
     3        user C          1                 2          1
     4        user D          3                 0          0

A: In MySQL, you can do this by counting the number of referrals for each id using a subquery.  Then use that information in the update:
UPDATE users u JOIN
       (SELECT referral_id, COUNT(*) as cnt
        FROM users u
        GROUP BY referral_id
       ) ur
       ON u.id = ur.referral_id
    SET u.agg_referral = ur.cnt,
        u.level = (CASE WHEN ur.cnt BETWEEN 1 and 3 THEN 2 ELSE level END);

A: You can use an update join:
update users u1
join (
    select referral_id,
        count(*) cnt
    from users
    group by referral_id
    ) u2 on u1.id = u2.referral_id
set u1.agg_referral = u2.cnt,
    u1.level = case
        when cnt < 1
            then 0
        else ceil((- 5 + sqrt(25 + 8 * cnt)) / 2)
        end;

Demo
It finds times an id is referred and then join it with the table to update the counts and level.
The case statement produces 0 for cnt = 0 or less, 1 for cnt between 1 and 3, 2 for cnt between 4 and 7 and . . so on.
To learn more on how the formula works, see https://math.stackexchange.com/questions/2171745/find-group-number-for-a-given-number-from-groups-of-increasing-size
EDIT:
If your initial group size is value other than 3, use this to get the required equation:
ceil((1 - 2 * g + sqrt(4 * g * g + 1 - 4 * g + 8 * cnt)) / 2)

where g is the intial size of the group.
For g = 3, it solves to:
ceil( -5 + sqrt(25 + 8 * cnt) / 2 )

for g = 10, it solves to:
ceil( -19 + sqrt(361 + 8 * cnt) / 2 )

On how this function is made, see the link provided above.


text:
Q: Tracking and setting goals referral sites using Google Analytics Using Google Analytics is it possible either by using goals or creating a custom chart to track month by month how much traffic a referal network site passes to my website?
I'd like to measure the traffic source from a paid directory service, let's say, Yell - so I want to see how much traffic each month comes to me from their site and ideally set a monthly target so I can monitor this ongoing.
Any help or direction with this would be very helpful.
Thanks

A: Goals are not necessary for this. Simply ask the referring website to add utm parameters to all links on their domain that point to your website. So if your website is www.example.com, any links on their website pointing to your domain would be www.example.com?utm_source=yelp&utm_medium=affiliate&utm_campaign=summer_2017. Once that is done, you would just check the Acquisition > All Traffic > Source/Medium report and you should see a row for "yelp/affiliate". For that row, one of the columns will be sessions, which tells you how much traffic they sent you for the selected time period. More info on campaign tracking can be found here: https://support.google.com/analytics/answer/1033867?hl=en


text:
Q: Why does CHECKSUM_AGG() return same values for totally different input values? I don't really get how CHECKSUM_AGG() works, although I understood that it is somehow built by using XORs. Which explains why it returns 0 when you pass just equal integers.
But why do I get the same aggregated checksum in the following SQL, where the input values are unique?
DECLARE @test1 TABLE (chksum INT)
INSERT INTO @test1 VALUES (2147473855), (2147473343)
SELECT CHECKSUM_AGG(chksum)
FROM @test1

DECLARE @test2 TABLE (chksum INT)
INSERT INTO @test2 VALUES (2147474831), (2147472271)
SELECT CHECKSUM_AGG(chksum)
FROM @test2

An explanation would be much appreciated. Thanks!

A: There are known issues with SQL Server CHECKSUM and CHECKSUM_AGG implementations: CHECKSUM weakness explained
Use HASHBYTES instead: Using HASHBYTES to compare columns
From Microsoft:
If one of the values in the expression list changes, the checksum of the list also generally changes. However, there is a small chance that the checksum will not change. For this reason, we do not recommend using CHECKSUM to detect whether values have changed, unless your application can tolerate occasionally missing a change. Consider using HashBytes instead. When an MD5 hash algorithm is specified, the probability of HashBytes returning the same result for two different inputs is much lower than that of CHECKSUM.
You may not use HASHBYTES across rows directly - there is one workaround here.
Here is comparison for smaller numbers, using HASBYTES workaround:
DECLARE @test1 TABLE (chksum INT)
DECLARE @test2 TABLE (chksum INT)

INSERT INTO @test1 VALUES (50), (3), (26)
INSERT INTO @test2 VALUES (45), (0), (6)

SELECT [Values]    = '50, 3, 26',
       [Checksum]  = CHECKSUM_AGG(chksum),
       -- HashBytes is limited to 8000 bytes only
       [Hashbytes] = HashBytes('md5',convert(varbinary(max),(SELECT * FROM @test1 FOR XML AUTO)))
FROM @test1

UNION ALL
SELECT  [Values]    = '45, 0, 6',
        [Checksum]  = CHECKSUM_AGG(chksum),
        -- HashBytes is limited to 8000 bytes only
        [Hashbytes] = HashBytes('md5',convert(varbinary(max),(SELECT * FROM @test2 FOR XML AUTO)))
FROM @test2


text:
Q: Association of Associations : how to permute level 1 and level 2 keys? I have a ragged Association of Association, say :
assoc = Association[
  "1" -> Association["a" -> "x", "b" -> "y"],
  "2" -> Association[            "b" -> "z", "c" -> "k"]
                   ]

I would like to transform it into a Association where level 1 and level 2 keys are reversed, that is to say :
Association[
      "a" -> Association["1" -> "x"],
      "b" -> Association["1" -> "y", "2" -> "z"],
      "c" -> Association[            "2" -> "k"]
           ]

My solution is :
keysExplodedList = Reap[MapIndexed[Sow[Reverse[#2] -> #1] &, assoc, {2}]][[2, 1]]
groupedLevel1 = GroupBy[#[[1, 1]] &] @ keysExplodedList
groupedLevel2 = GroupBy[#[[1, 2]] &] /@ groupedLevel1
result = Map[#[[1, 2]] &, groupedLevel2, {2}]

<|"a" -> <|"1" -> "x"|>, "b" -> <|"1" -> "y", "2" -> "z"|>,   "c" ->
  <|"2" -> "k"|>|>

Is there something more elegant ?

A: Not as nice as what WReach posted but this is what I came up with:
GroupBy[
  Join @@ Thread /@ Normal //@ assoc,
  {First@*Last, First}
][[All, All, 1, 2, 2]]

<|"a" -> <|"1" -> "x"|>, "b" -> <|"1" -> "y", "2" -> "z"|>, "c" -> <|"2" -> "k"|>|>

A: Here is another version, using KeyValueMap (needs 10.1):
regroup =
  Composition[
    Map[Association],
    GroupBy[First -> Last],
    Flatten,
    Normal,
    KeyValueMap[Function[{k, v}, Map[k -> # &, v]]]
  ];

So that
regroup @ assoc

(* <|"a" -> <|"1" -> "x"|>, "b" -> <|"1" -> "y", "2" -> "z"|>, "c" -> <|"2" -> "k"|>|> *)

A: Mathematica 10.1 almost supports this operation directly:
assoc // Query[Transpose]

(*
<| "a" -> <|"1" -> "x", "2" -> Missing["KeyAbsent", "a"]|>,
   "b" -> <|"1" -> "y", "2" -> "z"|>,
   "c" -> <|"1" -> Missing["KeyAbsent", "c"], "2" -> "k"|>
|>
*)

All that remains is to delete the unwanted Missing elements:
assoc // Query[Transpose] // DeleteMissing[#, 2]&

(*
<| "a" -> <|"1" -> "x"|>,
   "b" -> <|"1" -> "y", "2" -> "z"|>,
   "c" -> <|"2" -> "k"|>
|>
*)

We can see that Query uses the undocumented function GeneralUtilities`AssociationTranspose to do the heavy-lifting:
Query[Transpose] // Normal

(* GeneralUtilities`AssociationTranspose *)

assoc // GeneralUtilities`AssociationTranspose

(*
<| "a" -> <|"1" -> "x", "2" -> Missing["KeyAbsent", "a"]|>,
   "b" -> <|"1" -> "y", "2" -> "z"|>,
   "c" -> <|"1" -> Missing["KeyAbsent", "c"], "2" -> "k"|>
|>
*)

An Imperative Solution
The words "elegant" and "imperative" rarely appear together these days, but an imperative solution can express the transposition directly:
Module[{r = <| |>}
, Do[r = Merge[{r, <| j -> <| i -> assoc[[i, j]] |> |>}, Association]
  , {i, Keys[assoc]}
  , {j, Keys[assoc[[i]]]}
  ]
; r
]

(*
<| "a" -> <|"1" -> "x"|>,
   "b" -> <|"1" -> "y", "2" -> "z"|>,
   "c" -> <|"2" -> "k"|>
|>
*)

A ScanIndexed operator would come in handy here (the undocumented one in GeneralUtilities` is not, well, general enough).

A: DeleteMissing /@ GeneralUtilities`AssociationTranspose[assoc]

<|a-><|1->x|>,b-><|1->y,2->z|>,c-><|2->k|>|>

I have not noted WReach have mentioned this method here.But I think this is a bug behavior in function Transpose when it process Association.And I have report it to Wolfram Research before this.And there is workaround to avoid this bug
DeleteMissing /@ Normal[Transpose[Dataset[assoc]]]

<|a-><|1->x|>,b-><|1->y,2->z|>,c-><|2->k|>|>

A: Just for completeness:
assoc // Query[ Transpose /* Map[ DeleteMissing ] ]

<|"a" -> <|"1" -> "x"|>, "b" -> <|"1" -> "y", "2" -> "z"|>,
   "c" -> <|"2" -> "k"|>|>


text:
Q: onDraw gets called before onMeasure in a custom view I have two method in custom view, onMeasure and onDraw. I have a function that is used to set the data from the source and use invalidate the view function to redraw the view. I use the onMeasure to get the width of the view that is needed for my calculation. But when i use the invalidate function onDraw get called first and then my onMeasure gets called. Hence my view width is always 0px.
I have tried calling requestLayout() and then invalidate() to redraw the view
override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)

    val pointY = 15.px.toFloat()
    var pointX = oneCellWidth.toFloat() / 2f

    totalDays.forEach { day ->
        val isWorkedDay = workedDays.filter { it.date == day.date }.size
        if (isWorkedDay > 0) {
            canvas?.drawCircle(pointX, pointY, 8f, circlePaint)
        }
        pointX += oneCellWidth
    }
}

fun submitData(totalDays: List<Day>, workedDays: List<WorkedDateAndTime>, color: Int) {
    this.totalDays = totalDays
    this.workedDays = workedDays
    circlePaint.color = color
    oneCellWidth = viewWidth / totalDays.size
    invalidate()
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)

    val widthMode = MeasureSpec.getMode(widthMeasureSpec)
    val widthSize = MeasureSpec.getSize(widthMeasureSpec)

    if (widthMode == MeasureSpec.EXACTLY) {
        viewWidth = widthSize

    }
}

Need the viewWidth not to be have the view width value.

A: I guess the problem is happening because you are reading viewWidth before calling View.invalidate(). So, when you read the viewWidth, it still has the old value.
So, I suggest following changes:
override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)

    oneCellWidth = viewWidth / totalDays.size // Add this
    val pointY = 15.px.toFloat()
    var pointX = oneCellWidth.toFloat() / 2f

    totalDays.forEach { day ->
        val isWorkedDay = workedDays.filter { it.date == day.date }.size
        if (isWorkedDay > 0) {
            canvas?.drawCircle(pointX, pointY, 8f, circlePaint)
        }
        pointX += oneCellWidth
    }
}

fun submitData(totalDays: List<Day>, workedDays: List<WorkedDateAndTime>, color: Int) {
    this.totalDays = totalDays
    this.workedDays = workedDays
    circlePaint.color = color
    // oneCellWidth = viewWidth / totalDays.size --> Remove this
    requestLayout() // Add this. invalidate only request re-draw. requestLayout will request to re-measure
    invalidate()
}

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)

    val widthMode = MeasureSpec.getMode(widthMeasureSpec)
    val widthSize = MeasureSpec.getSize(widthMeasureSpec)

    if (widthMode == MeasureSpec.EXACTLY) {
        viewWidth = widthSize
    }
}

This way, you avoid the issue of reading viewWidth before onMeasure is re-executed. After those changes, you read viewWidth during onDraw which is always executed after onMeasure (if you call requestLayout() of course.


text:
Q: Javascript autoselect for dropdown not selecting I'm progamming a website and I would love to select all my dropdowns automatically instead of doing it manually.
The thing is that my JS code brings the values, but it doesn't select any option so the box keeps like "Select an option"
HTML:

 Gender
  Select an Option    <input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-2" id="s2id_autogen2" tabindex="0" autocomplete="Female">
 <select name="_ctl0:ContentPlaceHolder1:personDetails:genderDropDownList" id="ContentPlaceHolder1_personDetails_genderDropDownList" onchange="nzis.UpdateDropdownErrorLabel(this)" errorlabel="mandatory" tabindex="-1" title="" style="display: none;"> <option selected="selected" value=""></option> <option value="M">Male</option> <option value="F">Female</option> </select>

JavaScript:
var index = document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList).selectedIndex; alert("value="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').value); alert("text="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[1].text); s2id_autogen1.value= document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[2].text; s2id_autogen1.checked = true; var index = document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').selectedIndex; alert("value="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').value); alert("text="+document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[1].text); s2id_autogen2.value= document.getElementById('s2id_ContentPlaceHolder1_personDetails_genderDropDownList').options[2].text;

Any suggestion? :)
Thanks a lot!

A: You don't seem to have an element with id ContentPlaceHolder1_personDetails_titleDropDownList so it's failing to get the element using document.getElementById and therefore you're most likely getting the error Uncaught TypeError: Cannot read property 'selectedIndex' of null in your console.
Edit: did you mean to use s2id_ContentPlaceHolder1_personDetails_genderDropDownList as your selector?


text:
Q: Retrieve First Record of Nested Json Array I'm trying to parse the first record in an embedded JSON array and create an object based on a subset of those properties. I have this working, but based on this question, I have to think there is a more elegant/less brittle way of doing this. For a bit more background, this is a result set from a call to the musicbrainz JSON web service, and I am treating the first artists record as the artist I am looking for.
The format of the JSON is like this:
{
    "created": "2014-10-08T23:55:54.343Z",
    "count": 458,
    "offset": 0,
    "artists": [{
        "id": "83b9cbe7-9857-49e2-ab8e-b57b01038103",
        "type": "Group",
        "score": "100",
        "name": "Pearl Jam",
        "sort-name": "Pearl Jam",
        "country": "US",
        "area": {
            "id": "489ce91b-6658-3307-9877-795b68554c98",
            "name": "United States",
            "sort-name": "United States"
        },
        "begin-area": {
            "id": "10adc6b5-63bf-4b4e-993e-ed83b05c22fc",
            "name": "Seattle",
            "sort-name": "Seattle"
        },
        "life-span": {
            "begin": "1990",
            "ended": null
        },
        "aliases": [],
        "tags": []
    },
    ...
}

Here's the code I have so far. I'd like to be able to use my ArtistCollection type to get around some of the interface{} stuff, but I'm stuck as to how. I also don't want to bother with mapping all of the properties of the artist record, I'm only interested in the "name" and "id" values.
package main

import (
    "fmt"
    "encoding/json"
    )

type Artist struct {
    Id string
    Name string
}

type ArtistCollection struct {
    Artists []Artist
}

func main() {
    raw := //json formatted byte array
    var topLevel interface{}
    err := json.Unmarshal(raw, &topLevel)
    if err != nil {
        fmt.Println("Uh oh")
    } else {
        m := topLevel.(map[string]interface{})
        //this seems really hacky/brittle, there has to be a better way?
        result := (m["artists"].([]interface{})[0]).(map[string]interface{})
        artist := new(Artist)
        artist.Id = result["id"].(string)
        artist.Name = result["name"].(string)
        fmt.Println(artist)
    }
}

Requisite go playground link

A: Define a type that matches the structure of the JSON and unmarshal to a value of that type. I use an anonymous type below. Use an array of length one to grab the first artist record:
package main

import (
    "encoding/json"
    "fmt"
)

type Artist struct {
    Id   string
    Name string
}

func main() {
    raw := // JSON formatted byte array
    var result struct {
        Artists artist
    }
    err := json.Unmarshal(raw, &result)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%#v\n", result.Artists[0])
}

playground


text:
Q: Splitting pl/sql substitution variable at whitespace I'm trying to use an anonymous block to have a user enter 'Hello World' and then have the console output Hello then World.
DECLARE
 user_text VARCHAR2(20) := &userInput;
 start_position VARCHAR2(20) := INSTR(user_text, ' ');
 extracted_string VARCHAR2(20) := SUBSTR(user_text, start_position);

BEGIN

DBMS_OUTPUT.PUT_LINE(TRIM(extracted_string));

END;

The above code only outputs 'World'.

A: It only outputs "World" because thats exactly what you coded.
If you also want the first word, you need to add something like this :
DECLARE
   -- rest of your code
   first_word VARCHAR2(20) := SUBSTR(user_text, 0, start_position);
BEGIN
   DBMS_OUTPUT.PUT_LINE(TRIM(first_word));
   -- rest of your code
END;

A: Its not clear what you are trying to achieve but if just want that for input Hello World, World Hello should be displayed, then you also need to get start word of string before space as below.
DECLARE
 user_text VARCHAR2(20) := 'Hello World';
 start_position VARCHAR2(20) := INSTR(user_text, ' ');
 start_word_of_string varchar(20) := SUBSTR(user_text,0,start_position);
 extracted_string VARCHAR2(20) := SUBSTR(user_text, start_position);

BEGIN

DBMS_OUTPUT.PUT_LINE(extracted_string || ' ' || start_word_of_string);

END;

Result:
World Hello

DEMO


text:
Q: Can I use Android Studio emulator to test Google in-app purchase when I publish to Internal test track? I know I nned test the Google in-app purchase of an app in a real mobile phone.
Can I use Android Studio emulator to test Google in-app purchase when I publish the app to Internal test track of Google Play?

A: Yes, it is no different than with a physical device.
Just make sure your emulator is running an Android OS with Play Services. You can then open Play Store on it, log in with your Google Account (the one in the Internal test track) and then you can test the in-app purchase.
You can learn more about how to test this here. Relevant steps for setting up a device (including an emulator) can be found here.


text:
Q: excel-bootstrap-table-filter-bundle.js shows values in filter list from the above tables I'm trying to creare a Excel like Filter in my bootstrap table using excel-bootstrap-table-filter-bundle.js. The filter works but it shows not only the values from the working table but also the values from above tables.
That's my jsp page:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.util.*"%>
<!DOCTYPE html>

<title>Scheda Cliente</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">

<link rel="stylesheet" href="https://www.jqueryscript.net/demo/Excel-like-Bootstrap-Table-Sorting-Filtering-Plugin/excel-bootstrap-table-filter-style.css">

<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5″>>

TABLE 1

                                    1a
                                    1b
                                    1c

                        <c:forEach items="${fornitureList}" var="forniture">

                                ${forniture.nrContratto}
                                ${forniture.commodity}
                                ${forniture.statoContratto}

                        </c:forEach>

TABLE 2

                2a
                2b
                2c

            <c:forEach items="${listfattureClientePagate}" var="fattureClienteP">

                    ${fattureClienteP.nrContratto}
                    ${fattureClienteP.nrFattura}
                    ${fattureClienteP.dataFattura}

                </c:forEach>

As you can see from the immage below filter in table 2 column b shows the last value from table 1 column b.
thanks

A: You have to change:
$('table').excelTableFilter({

to
$('#divTable').excelTableFilter({

Setup a id and name for the div as divTable!


text:
Q: SQL replace all row values in view column by value from column of another table I'm new to SQL, so it might be an easy question, but I couldn't find the solution by myself.
I need to replace or update all values in a new column Startdate of a view (view1) by the values in column Startdate in a table (table1). The values in table1 are always the same (it is a date, e.g. 01.01.2001 00:00:00).
What I've done so far is to create an empty column with the right format in the view1:
CREATE VIEW view1
AS SELECT [fields],
          [other fields],
          cast(NULL as datetime2(7)) AS [Startdate]
FROM ...

Now I've tried to update the column by:
UPDATE [dbo].[view1]
   SET [dbo].[view1].[Startdate] = [EGDB].[dbo].[table1].[Startdate]

But I get the error "Update or insert of view or function 'view1' failed because it contains a derived or constant field."
Where is my fault?

A: Per the comments and in the question 'the values in table1 are always the same', you can
CROSS JOIN (SELECT TOP (1) [Startdate] FROM [EGDB].[dbo].[table1]) as startdate,
and use startdate.[Startdate] instead of cast(NULL as datetime2(7)) AS [Startdate].
However I consider it strange that all rows have the same value - if it wasn't the case or in the future it won't be, you can change TOP (1) to MIN or MAX to get the earliest/latest startdate, respectively.


text:
Q: PySpark - drop rows with duplicate values with no column order I have a PySpark DataFrame with two columns like so:
+-------------------+--------------------------+
|       right       |            left          |
+-------------------+--------------------------+
|          1        |             2            |
|          2        |             3            |
|          2        |             1            |
|          3        |             2            |
|          1        |             1            |
+-------------------+--------------------------+

I want to drop duplicates but with no respect to the order of the columns.
For example, a row that contains (1,2) and a row that contains (2,1) are duplicates.
The resultant Dataframe would look like this:
+-------------------+--------------------------+
|       right       |            left          |
+-------------------+--------------------------+
|          1        |             2            |
|          2        |             3            |
|          1        |             1            |
+-------------------+--------------------------+

The regular drop_duplicates method doesn't work in this case, anyone has any ideas how to do this cleanly and efficiently?

A: (df1.withColumn('x',array_sort(array(col('left'), col('right'))))#create sorted array column of columns left and right
 .dropDuplicates(['x'])#Use column created to drop duplicates
 .drop('x')#drop unwanted column
).show()


text:
Q: UINavigationBar cut off font I'm using custom font in my application. I've used the code below in AppDelegate to change the UINavigationBar appearance.
let navigationBarAppearance = UINavigationBar.appearance()
navigationBarAppearance.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Pacifico", size: 20)!]

However, the font is getting cut off at the end of the string. The text is "Tell", but you can see that the last character is getting cut off. It works fine if I'm using the default font. Is this a problem with the font itself or it's a bug in Xcode?


text:
Q: Creating a copy of an NSMutableArray with custom objects I've been searching around for the solution to this for quite a while, and none of the other threads have helped. Basically, what I want to accomplish is creating an array of custom objects as a singleton, load them into my level, then create a copy of them since variables assigned to these objects will be manipulated. When the level is complete (or failed) though, I want these objects to remain the same so I can reload them.
Below are some things I've tried.
- (void)spawnStartTiles {
    //where _puzzleGridTilesArray and curLevel.gridTiles are NSMutableArrays
    [_puzzleGridTilesArray removeAllObjects];
    _puzzleGridTilesArray = [curLevel.gridTiles mutableCopy];
    CCLOG(@"tile in curlevel %@", curLevel.gridTiles[0]); //want these to log DIFFERENT objects
    CCLOG(@"tile in puzzle array %@", _puzzleGridTilesArray[0]);//want these to log DIFFERENT objects
}

The above logs the same object ID.
- (void)spawnStartTiles {
    //where _puzzleGridTilesArray and curLevel.gridTiles are NSMutableArrays
    _puzzleGridTilesArray = [self cloneArray:curLevel.gridTiles];
    CCLOG(@"tile in curlevel %@", curLevel.gridTiles[0]); //want these to log DIFFERENT objects
    CCLOG(@"tile in puzzle array %@", _puzzleGridTilesArray[0]);//want these to log DIFFERENT objects
}

-(NSMutableArray*)cloneArray:(NSMutableArray *)myArray {
    return [[NSMutableArray alloc] initWithArray: myArray];
}

Still logs same object ID.
- (void)spawnStartTiles {
    //where _puzzleGridTilesArray and curLevel.gridTiles are NSMutableArrays
    _puzzleGridTilesArray = [[NSMutableArray alloc] initWithArray:curLevel.gridTiles copyItems:YES];
    CCLOG(@"tile in curlevel %@", curLevel.gridTiles[0]); //want these to log DIFFERENT objects
    CCLOG(@"tile in puzzle array %@", _puzzleGridTilesArray[0]);//want these to log DIFFERENT objects
}

The above gives a runtime error. I think this is because the objects I am copying are a custom class named Tile. The class is a CCNode, and the .h file is below.
#import "CCNode.h"

@interface Tile : CCNode

@property (nonatomic, assign) NSInteger value;
@property (nonatomic, assign) NSInteger gemLevel;
@property (nonatomic, assign) BOOL mergedThisRound;
- (void)updateValueDisplay:(BOOL)bannerTiles difficultyMode:(int)difficultyMode;
- (void)updateOpacity:(NSInteger)opacityVariable;
- (void)tileHasBeenSelected:(BOOL)tileHasBeenTouched;

@end

Is there a way to somehow transform this class so that is can be copied? I've looked at http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C and Implementing NSCopying and I'm still confused, so further help would be greatly appreciated. Thank you!

A: You get an error because [[NSMutableArray alloc] initWithArray:curLevel.gridTiles copyItems:YES] calls copyWithZone: on each item in the array. Your items must conform to NSCopying for you to use this method, but this is the correct approach.
To implement NSCopying:

*

*Update your Tile class to add the protocol, i.e. @interface Tile : CCNode <NSCopying>

*Implement the method - (id)copyWithZone:(NSZone *)zone in your Tile implementation.

*In that method, allocate a new instance of Tile and assign all of it's properties to that of your current instance.


text:
Q: vb6 does not recognize the error when there is a result set
I have a stored procedure which
  returns a result set with the error
  message, when an error occurs. If it
  executes without any error, the result
  set is empty (Command(s) completed
  successfully)
On the vb6 side, I execute the sp and
  check whether there is an error by
If Err <> 0 Then
 ' do sth
End If

But, when there is a result set, the
  Err is always 0.
How should I handle this situation?

Sorry for inadequate explanation.
Here are my scripts:
--my sample table
create table #InvoiceDocument (InvoiceID int, ItemID int, Price float, DocStatus bit)

--my test values
insert into #InvoiceDocument (InvoiceID, ItemID, Price)
values (1, 1, 2.5), (1, 2, 5.0), (1,5, null)

--my sample procedure
create procedure sp_ApproveInvoice @InvoiceID int
as
begin

    set nocount on

    select * into #temp
    from #InvoiceDocument
    where Price is null and InvoiceID = @InvoiceID

    if exists (select 1 from #temp)
    begin
        select InvoiceID, ItemID, Price from #temp
        RAISERROR ('There are non priced items. Invoice can not be approved!',16, 1)
        return
    end

    update #InvoiceDocument
    set DocStatus = 1
    where InvoiceID = @InvoiceID

end

when I execute this:
sp_ApproveInvoice 1

It both generates a resultset (Results),  and an error message (Messages).
On the vb6 side, vb6 can not catch the error here.

A: You need to RAISERROR in the stored proc to set the error.
Or use output parameters. Or the RETURN statement
Or add logic to distinguish "success" and "fail" recordsets in the client code.
Currently, Err has no meaning because there is no error state
Personally, I use RAISERROR as per my question here with this template

A: Your particular case cannot be caught with Err since your stored procedure is not generating any error in the traditional sense---it's either giving an empty result set or a normal result set. How can VB know the semantics of a non-empty result set?
For this to work, you either need to change your stored procedure to raise error OR you need to check the result set returned by the stored procedure directly in your code (nothing to do with Err).


text:
Q: float() argument must be a string or a number, not 'tuple' i need some help i am starting in odoo and i have this
@api.depends('clave_factura')
def set_totales(self):

    self.env.cr.execute('select sum(total_detalle) as total from caratulas_detalle where factura_id = %s', (self.clave_factura,))
    # fetchone() will return the first element found as dictionary
    registros = self.env.cr.fetchall()
    totaldtotales = registros[0] if registros else 0
    for rec in self:
        rec.total_kllevo = totaldtotales
        rec.total_resto = rec.total_fac - rec.total_kllevo

and these are my fields
total_kllevo = fields.Float('Lo Agregado', readonly=True, help='Total', compute='set_totales', store=True)
total_resto = fields.Float('Lo Restante', readonly=True, help='Total', compute='set_totales', store=True)

and this is the error
File "c:\program files (x86)\odoo 12.0\server\odoo\addons\prossesa_proyectos\models\prossesa_proyectos.py", line 147, in set_totales
    rec.total_kllevo = totaldtotales
  File "C:\Program Files (x86)\Odoo 12.0\server\odoo\fields.py", line 1003, in __set__
    value = self.convert_to_cache(value, record)
  File "C:\Program Files (x86)\Odoo 12.0\server\odoo\fields.py", line 1263, in convert_to_cache
    value = float(value or 0.0)
TypeError: float() argument must be a string or a number, not 'tuple'

I know that maybe it is something really easy but my mind crash.

A: You got that error because the first element of registros is a tuple.
Example:
>>> registros = self.env.cr.fetchall()
>>> registros[0]
(4610.0,)

You can fixt it using the first element of totaldtotales.


text:
Q: Tuples or Objects Today, talking with some colleagues of mine, we were discussing the usage of tuples. The specific problem was: we have an API returning a list of some kind of objects (let's say POJO instances)
public List<Pojo> getPojos()

we decided to use pagination in order to prevent enormous responses
public List<Pojo> getPojos(int page, int pageSize)

the next step was: can we return both the list and a boolean saying if more results are available preventing useless calls?
My approach was to consider the results as a pair of values
public Pair<List<Pojo>, Boolean> getPojos(int page, int pageSize)

Some colleagues say that this approach can hide the meaning of the returned variables because it is not explicit what the boolean means, their proposal was to introduce an "ad hoc" object to handle the response
class PojoResponse{
    List<Pojo> result;
    Boolean hasMore;
}
public PojoResponse getPojos(int page, int pageSize)

In my opinion, this solution breaks the uniformity of the APIs, introduces new classes that should be maintained and, in my opinion, hides the real objective of the method, in this case, return a list of POJOs.
What is your opinion on that problem? Find articles on these "style problems" on the internet is not always so easy.

A: In my opinion, neither is correct. A better solution would be to have a PojoRetriever class which implements Paginator, which handles the pagination and keeps track of the state (i.e. page size, current page) so that the client code can simply call a method to determine if there is more data.
A lot of the time when you feel the need to return multiple values, you could (should, imo) use an object to store/handle them.

A: Your query for information will need to return both count of matching items as well as the current payload of information.  Typically what I do for this scenario is to create a generic object that handles the pagination logic:
public class Page<T>
{
    public int Total {get;}
    public int PageSize {get;set;}
    public int PageNum {get;set;}
    public bool HasNext {get;}
    public bool HasPrevious {get;}
    public List<T> Records {get;}
}

Given the current page size and page, and the total number of records that apply to the query, everything else could be calculated.  The container class Page<T> handled all the pagination logic, and it could be reused for any type we needed.

A: I think using Tuples in API boundaries is troublesome. If you just have one, it's easy enough to remember what Item1 is, but when you have 20, it gets harder to remember.
The question is is it worth it having names for my parameters?
Making little classes is somewhat annoying, but it's a small price to pay to gain the ability to name the items. Now, your IDE can remind you which is what. The maintenance cost of the class is minimal, the up front cost of defining it is low, but the mental cost is remembering what's what becomes 0.

A: If the only two options you have are the ones you listed, then I have to agree with @whatsisname and suggest that you go with the class.
However, in this case, I believe that you might have a better solution:
int numberOfRemainingItems getPojos(int page, int pageSize, out List<Pojo> retrievedPojos)

You redesign your getPojos method to return the list of pojos as an out parameter, and the return value of the method is the number of remaining Pojos in whatever repository you are getting them from. Of course, there are variations to this solution:

*

*You could return a bool if you just know whether the repository is empty or not, but do not know how many pojos are left there

*The List retrievedPojos parameter does not have to be an out parameter, in which case you would have to instantiate and initialize the list before the method is called - I would not suggest this for multiple reasons

Generally, whenever you have a method that returns more than one value, either refactor it to use two methods, or return the values using out parameters.

A: class PojoResponse{
    List<Pojo> result;
    Boolean hasMore;
}

is a glorified version of
Pair<List<Pojo>, Boolean>

As long as your team agrees to one approach and sticks with it, I don't see it as an issue to debate too much.
However, I would recommend a strategy that uses neither.
Add another function
Boolean hasMorePages(int page, int pageSize);

Then use that function call instead of using the hasMore member variable of PojoResponse.
Caveat If hasMorePages is compute intensive, this might not be the better option.


text:
Q: It's broken or it has been broken What is the difference between it is broken and it has been broken please?
Thanks.

A: First of all, the sentence "it is broken" is in the "Present passive voice" and the second one is in the "Present perfect passive voice". And the main difference is that you may use the first sentence if the action is happening at the moment or not a long time ago. Whereas when you use the second one, the range of  time in which the action may have happened seems longer.
e.g.:
"-Oh, you dropped the glass!
 -Oh, no. It's broken." (It is broken)
"-We've not lived here for ages.
 - Look at this glass. It's been broken." (You have no idea when the glass has been broken) (It has been broken)
BTW, as usual, there are many ways to say a single sentence in English, so sometimes you can use either of the sentences interchangeably.

A: When I say something is broken, broken is used as an adjective. I'm describing the state of the thing and I'm not interested in the action that led to this state. For all I know it could have got broken without human intervention through decomposition, old age, etc. And it does not say how long it's been in that state, it could be minutes, hours, years, etc.

My CD player is broken.

It's a plain statement.
If I say something "has been broken" (present perfect, passive), I focus on the action and not on the object. It helps me specify one or several aspects of this action.

My CD player has been broken for a week now.

This last sentence focuses on how long it has been in that state.

I love this vase, unfortunately it has been broken twice and next time I don't know if I'll be able to mend it.

This last sentence focuses on the repetition of the action.

I can't listen to my CDs now that my CD player has been broken.

When I say this last sentence, although I do not name anyone I imply that the CD player got broken through human intervention. I could even be more specific and add who caused this to happen.

I can't listen to my CDs now that my CD player has been broken by my brother.

So your choice of one or the other will entirely depend on context, on what you want to say.

A: You can use both. But "it has been broken" especially refers to the recent time period i.e. a finished action with a result in the present (focus on result)  (it is a present perfect tense)


text:
Q: printing character with double variable in c #include<stdio.h>
#include<math.h>
int main()
{
    char sign1='-',sign2='-' ;

    double x=-1,y=4,radius=9;

        if(x<0.0)
        {
            sign1='+';
            x=x*-1;
        }
        if(y<0.0) {
            sign2='+';
            y=y*-1;
        }

        printf("(x %c %.3lf)^2 + (y %c %.3lf)^2=%.3lf^2\n",x,sign1,y,sign2,radius);//here doesn't print the values of sign1 and sign2

        printf("%c %c\n",sign1,sign2);//here prints properly;

    return 0;
}

In my code, the first printf function doesn't work properly. It should print (x + 1.000)^2 + (y - 4.000)^2 = 9.000^2 but the output I get is
(x   0.000)^2 + (y   0.000)^2 = 9.000^2

Why?

A: printf is not type safe!
Any mismatch in the actual type passed to printf and the format specifier specified for it results in Undefined Behavior.
sign1 and sign2 are declared as char so using %f results in Undefined Behavior.

You messed up the ordering of parameters to printf,
printf("(x %c %.3lf)^2 + (y %c %.3lf)^2=%.3lf^2\n",x,sign1,y,sign2,radius);

should be:
printf("(x %c %.3lf)^2 + (y %c %.3lf)^2=%.3lf^2\n",sign1,x,sign2,y,radius);

A: Correct this line as
printf("(x %c %.3lf)^2 + (y %c %.3lf)^2=%.3lf^2\n",sign1,x,sign2,y,radius);


text:
Q: Inheritance not working From my code I want my bedroom class to inherit length and breadth from the superclass - room. I have filled the errors in the respective lines within comments.
I am getting errors and I can't find my way out. Help me please?
package index;

public class Room {
int length;
int breadth;

Room(int x,int y)
{
    length = x;
    breadth = y;
}
int area(){
    return (length*breadth);
}
}

class BedRoom extends Room{      //Implicit super constructor Room() is undefined for default constructor. Must define an explicit constructor
    int height;
    public void Bedroom(int x,int y,int z)
    {
        super(x,y);    //Constructor call must be the first statement in a constructor
        height=z;
    }

int volume(){
    return (length*breadth*height);
    }
}
class InherTest
{
    public static void main(String args[])
    {
        BedRoom room1 = new BedRoom(14,12,10); //The constructor BedRoom(int, int, int) is undefined
        int area1 = room1.area();
        int volume1 = room1.volume();
        System.out.println("Area1 = "+area1);
        System.out.println("Volume1 = "+volume1);
    }

}

A: You have simply misspelled BedRoom as Bedroom in the constructor declaration. (Correcting this would give you a more simple-to-understand error message about the problem that @HovercraftFullOfEels mentions: constructors do not have a return type.)

A: Your BedRoom class has a pseudo-constructor not a real constructor. Constructors don't return anything, not void not anything.  Get rid of that void statement.
Change
public void Bedroom(int x,int y,int z)

to
public BedRoom(int x,int y,int z) // also capitalize correctly

A: *

*Constructors' name must match class name, but since Java is case-sensitive Bedroom is not valid name for constructor in BedRoom class.

*Also constructors doesn't have return type so remove void from it.

In other words replace
public void Bedroom(int x, int y, int z) {
//     ^^^^    ^

with
public BedRoom(int x, int y, int z) {

A: Change to
 public void BedRoom(int x,int y,int z)

As for java Bedroom is not same as BedRoom


text:
Q: doubts in derivatives If s is distance and v is velocity, then:   $$v=\frac{ds}{dt}$$and$$a=\frac{dv}{dt}$$
$$\frac{a}{v}=\frac{\frac{dv}{dt}}{\frac{ds}{dt}}$$
$$\frac{a}{v}=\frac{\frac{d}{dt}(\frac{ds}{dt})}{\frac{ds}{dt}}=\frac{dv}{ds}$$
I don't understand the last step .Is it possible? Numerator is first derivative whereas denominator is second derivative. Please explain it . Thanks.

A: Acceleration is rate of change of velocity.
Velocity is rate of change of displacement.
Acceleration by velocity would be rate of change of velocity by rate of change of displacement.
Let velocity in some small time period t, change by v.
And in the same time period displacement changes by d.
Then a/v = v/d, since the time period is the same.
This is essentially what the last step is trying to convey.


text:
Q: MySQL dynamically display distinct values from a column with count of occurrences? Using MySQL 5.5.34 on MAMP.
How do I display distinct values with count of occurrences ?
my_table looks like this:
id fruit
01 apple
02 orange
03 grape
04 apple
05 banana
06 orange

What i'm trying to display is something like:
apple 2
banana 1
grape 1
orange 2
fruits 6

I could hard code the values and use count with distinct but I'm sure there is a dynamic way. I've found some examples on here using group by and with rollup, but I can't seem to get the syntax right or find a example.
The non-dynamic way I'm doing right now:
SELECT fruit,COUNT(*) as count
FROM my_table
GROUP BY fruit
ORDER BY fruit ASC
WITH ROLLUP;

I hope somebody has some a clear example. I've been trying for many hours now. thanks!

A: You need to make the rollup row say fruits instead of NULL using the IFNULL() function
You also don't need ORDER BY
PROPOSED QUERY
SELECT IFNULL(fruit,'fruits') fruit,COUNT(*) as count
FROM my_table
GROUP BY fruit
WITH ROLLUP;

SAMPLE DATA
mysql> drop database if exists fruitdb;
Query OK, 0 rows affected (0.00 sec)

mysql> create database fruitdb;
Query OK, 1 row affected (0.00 sec)

mysql> use fruitdb
Database changed
mysql> create table my_table
    -> (id int not null auto_increment,
    -> fruit varchar(20) not null,
    -> primary key (id));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into my_table (fruit) values
    -> ('apple'),('orange'),('grape'),
    -> ('apple'),('banana'),('orange');
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from my_table;
+----+--------+
| id | fruit  |
+----+--------+
|  1 | apple  |
|  2 | orange |
|  3 | grape  |
|  4 | apple  |
|  5 | banana |
|  6 | orange |
+----+--------+
6 rows in set (0.00 sec)

mysql>

PROPOSED QUERY EXECUTED
mysql> SELECT IFNULL(fruit,'fruits') fruit,COUNT(*) as count
    -> FROM my_table
    -> GROUP BY fruit
    -> WITH ROLLUP;
+--------+-------+
| fruit  | count |
+--------+-------+
| apple  |     2 |
| banana |     1 |
| grape  |     1 |
| orange |     2 |
| fruits |     6 |
+--------+-------+
5 rows in set, 1 warning (0.00 sec)

mysql>

GIVE IT A TRY !!!


text:
Q: Borderless table react-bootstrap-table I am trying to make my react-bootstrap-table table fully borderless and have checked out all their docs and GitHub issues but haven't been able to get a fully borderless table. Here's what I have:
In my CSS:
.react-bs-container-header tr {
  border-bottom-style: hidden !important;
}
.react-bs-container-header {
  border-bottom-style: hidden !important;
  border-left-style: hidden !important;
  border-right-style: hidden !important;
}

.columnClassNameFormat1 {
  color: #4F58EA;
  border: none;

}

In my React Component:
<BootstrapTable data={this.state.data} version='4' options={ this.getOptions() }
              tableHeaderClass='columnClassNameFormat1'
              tableBodyClass='columnClassNameFormat1'
              containerClass='columnClassNameFormat1'
              tableContainerClass='columnClassNameFormat1'
              headerContainerClass='columnClassNameFormat1'
              bodyContainerClass='columnClassNameFormat1'
              trStyle = { this.rowClassNameFormat }
              >
              <TableHeaderColumn isKey dataField='name' dataFormat={formattedTextH3} columnClassName='columnClassNameFormat1' isKey > Name</TableHeaderColumn>
              <TableHeaderColumn dataField='img' dataFormat={imageFormatter} >Images</TableHeaderColumn>
              <TableHeaderColumn dataField='category1' dataFormat={formattedTextH3} columnClassName='columnClassNameFormat1'>Category</TableHeaderColumn>
              <TableHeaderColumn dataField='category2' dataFormat={formattedTextH3} columnClassName='columnClassNameFormat1'>Category</TableHeaderColumn>
              <TableHeaderColumn dataField='category3' dataFormat={formattedTextH3} columnClassName='columnClassNameFormat1'>Category</TableHeaderColumn>
              <TableHeaderColumn dataField='category4' dataFormat={formattedTextH3} columnClassName='columnClassNameFormat1' >Category</TableHeaderColumn>

            </BootstrapTable>

 ...

  rowClassNameFormat(row, rowIdx) {
     return 'border: none';
  }

Right now, it the only borders to remain standing are the inside column borders and the border at the bottom of the table. Even so, this just seems like a really verbose way to do this. How should this be done?

A: react-bootstrap-table has a property bordered={ false }.
Add it to <BootstrapTable data={this.state.data} bordered={ false } ... />. It will remove part of the inside borders.
Accroding to your goals you need to remove all other borders as you overwrite the css classes.

A: There are other properties that might help you...
For example -
<BootstrapTable bootstrap4 keyField='id' data={data} columns={columns}  bordered={true} striped={true} hover={true} />


text:
Q: stepwise regression: Undefined function ' stepwiselm' for input arguments of type 'cell' I have one .txt file and I have converted it to first a table Ta(Ta=readtable('xxx.txt')) then an array Aa(Aa=table2array(Ta)), the .txt file contains 220 rows and 12 cols, but the table and the array only have 219 rows and 1 col. Where did I do wrong?
Then when I tried to do stepwise regression I got error message: Undefined function ' stepwiselm' for input arguments of type 'cell'.
My coad was: mdl=stepwiselm(Aa)
In the .txt file, the first raw are texts e.g. elevation, hight, yields etc. I though I could use these names to define Predictor variables and Response variable. But since these names are lost in Aa, how should I write code for stepwise regression?Thanks!

A: Try the following
delim = ' ';
nrhdr = 1;
A = importdata('A-100spreg2-raa06a.txt', delim, nrhdr);

A.data will be your data, A.textdata your header. A ".txt" does not contain columns, so you need to specify a delimiter (I assumed a space). You can then use your A.data in your stepwise function.
As you indicated you wanted column 10 as y, and I assume others as X, use
stepwise(A.data(:,1:9),A.data(:,10))

I wouldn't use the headers for anything other than creating labels in figures.


text:
Q: Google web font renders differently on mobile Safari vs. desktop Chrome? A Google web font (Signika) renders differently on desktop versus mobile. As illustrated by these screenshots, the kerning (space between letters) is larger on mobile than desktop, and the stroke is thinner. The letters on desktop also seem crisper, though this is more subjective.
Desktop (Chrome):

Mobile (Safari, iOS 12):

Codepen:
https://codepen.io/Crashalot/pen/3ff682e5aa123e1ac293ab19b06f1285

#pageBox h1 {
  margin: 30px auto;
  text-align: center;
}

h1 {
  font-size: 2em;
  font-weight: bold;
  line-height: 1.2em;
}

h1,
h2,
h3,
h4 {
  font-family: "Signika", Verdana, Tahoma, Arial, Sans-Serif;
  color: #7C7A7D;
}

  <link href="https://fonts.googleapis.com/css?family=Lato|Roboto|Signika|Source+Sans+Pro:400,700" rel="stylesheet">

 Icon Editor

Signika portion of self-hosted font stylesheet:
@font-face {
  font-family: 'Signika';
  font-style: normal;
  font-weight: 400;
  src: url(https://fonts.gstatic.com/s/signika/v10/vEFR2_JTCgwQ5ejvG18mBlprZ0gk0w.woff2) format('woff2');
  unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
  font-family: 'Signika';
  font-style: normal;
  font-weight: 400;
  src: url(https://fonts.gstatic.com/s/signika/v10/vEFR2_JTCgwQ5ejvG1EmBlprZ0g.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

A: It turns out Safari alters the font if you use a font-weight not supported by a font (e.g., the font file only offers weights of 400 and 600, but you choose 700). Specifying a supported weight or using normal removed this issue.
Extremely frustrating, but hopefully our misery helps someone.

A: @crashalot the reason why the font looks different on Safari as to Chrome is that the webkits are ever so slightly different. The only way to avoid this problem really is to download the font files and then link them:
body {
...
font-family: Signika;
...
}

@font-face {
font-family: Signika;
src: url(signika.ttf);
}

A: I wasn't sure from your question whether you were more interested in the why or the how to fix aspects. Assuming how to fix:
Since you used the word kerning, you are probably already aware of this, but I was able to match up the appearances by adjusting the following:
body {
     letter-spacing: -0.1px;
     transform: scale(1.05, 0.95);
}

If that doesn't look quite right to you, those values are of course adjustable.
font-kerning: none; is a little more severe, but does help normalize between engines a little bit.
For reference,
So, you could if you wish, detect mobile and/or safari via numerous other checks (which have already been answered in other questions, so I will omit here), and then apply the CSS above.
If, in fact you were asking about why there is a difference, that comes down to the rendering engine - but I will assume for now you are asking about normalizing appearances.


text:
Q: Component ID can be found by $find in Chrome console but not in external injection code It has a web page using MircrosoftAjax to create the confirmation dialog that ComponentID could be found by $find (or Sys.Application.findComponent) in Chrome console and Sys.Application.getComponents got the ID Component list as well,but when I moved the code injecting into Content Script of Chrome extension,The result always returned 'NULL' except for DOM operation . I just want to change the Component's property to achieve automatical confirmation without manual clicking,but it seems hard to do.
  This is my code:
 $(document).ready(function(){

    Sys.Application.getComponents() //return 'NULL'
    Sys.Application.findComponent('sth')._ConfirmOnFormSubmit=true  //return 'Cannot set property '_ConfirmOnFormSubmit' of null '
    })

    function pageLoad(sender,args) {
//Sys.Application.initialize()
console.log($find('sth'))  //return 'NULL'
function confirm() {return true} //seems to approach the fact working well that bypassed the dialog in chrome console  but still not working in Content Script
}

Why has the different result between Content and Console? How should I do the right way?
I appreciate so much if someone can give me a solution.
Best Regards.

A: The reason you see this behavior is that content scripts live in an isolated context.
They don't have access to page's JavaScript and its state.
To test, you can open the console and at the top switch context from <top frame> to your extension's context. You'll see different console results.
To fix this situation, you need to inject yet another time, this time from the content script into the page's context; you can then communicate data between the two using custom events or window.postMessage().
Here's a canonical question for that.


text:
Q: How to get the month argument from permalink in wordpress? I am working on a custom Wordpress template for the archive. I have the archive set up by category but now I want to organize by category and month but I can't figure out how to access the month argument from the permalink. How would I get access to that argument.

A: the standard WP function for that is:
the_date();

(source)


text:
Q: Emacs how to show only the lines on or before the cursor in a file I am a high school computer science teacher and would like to use emacs to present programs to my students.  I would like to be able to present the programs, even short ones, one line at a time and not have the whole program show in the emacs buffer from the start.
Thus I would like emacs to hide all the lines below the current line and reveal each line when I move the cursor down to that line.

A: Try this:
(defun narrow-next-line ()
  (interactive)
  (widen)
  (call-interactively 'move-end-of-line)
  (forward-char)
  (call-interactively 'move-end-of-line)
  (narrow-to-region 1 (point)))

(global-set-key (kbd "C-x n i") 'narrow-next-line)

Choose your own hotkey for this command. See also http://www.gnu.org/software/emacs/manual/html_node/emacs/Narrowing.html

A: Inspired by your question, I added library reveal-next.el to EmacsWiki.  I think it does what you want.


text:
Q: How to keep NSWindow.FrameAutosaveName out of scope of tabbed windows? I have a NSWindowControllerclass in an app that can be used to show a standalone window or to show a tabbed window attached to a main window, which has a different window controller. If the user opens the window as standalone, then I want to use the same window position and size as the last standalone window session. It's comparable to opening a code view in Xcode in a new window.
So I have a self.windowFrameAutosaveName = NSWindow.FrameAutosaveName("Detail App Window") line in windowDidLoad. This works, but the problem is that it also works when the window is shown as a tab in the main window. Next time the user opens the same window as standalone, the size of the main window is being used.
Question: how can I keep self.windowFrameAutosaveName outside a tabbed window scenario?
I create the window controller like this:
let storyboard = NSStoryboard(name: "Detail", bundle: nil)

if let controller = storyboard.instantiateInitialController() as? DetailController {
    document.addWindowController(controller)

    if tabbed,
        let mainWindow = document.windowControllers.first?.window,
        let detailWindow = controller.window {
        mainWindow.addTabbedWindow(detailWindow, ordered: .above)
    }
    else {
        controller.showWindow(nil)
    }
}

The code in windowDidLoad of the DetailController above is:
override func windowDidLoad() {
    super.windowDidLoad()
    self.shouldCascadeWindows = true
    self.windowFrameAutosaveName = NSWindow.FrameAutosaveName("Detail App Window")
}

As you see, I use self.shouldCascadeWindows = true, and this must also keep working. I have experimented with detecting being in a tab scenario, but without any complete success. Also, moving the windowFrameAutosaveName before the controller.showWindow(nil) works in itself, but the windows are no longer loaded with shouldCascadeWindows = true.
Interesting, even Xcode doesn't do that, so maybe it's a limitation of AppKit.


text:
Q: How to select from the database within a option that is filled with JavaScript I'm new to razor page
I have an edit page - that it has 2 selection tags

*

*1 - "MissionTime" and the other - "MissionDay".
The choices in MissionDay vary according to the choice of MissionTime.
In terms of JavaScript it works great! On the Create page it works really well.

Also on the edit page it works well on the part of the JavaScript.
The problem is when the database has information () but it does not select according to the value in the database.

             <select id = "MissionTime" asp-for = "Mission.MissionTime">
                <option value = "0">
                    with no
                </option>
                <option value = "1">
                    Every day
                </option>
                <option value = "7">
                    once a week
                </option>
                <option value = "30">
                    once a month
                </option>
                <option value = "365">
                    Once a year
                </option>
            </select>

            <select id = "MissionDay" asp-for = "Mission.MissionDay">
                <option value = "0">
                    with no
                </option>
            </select>

Code JavaScript -

The code works great!
The problem is that I can not get the data in the "MissionDay"
I  guess this is because first the page takes data from the database and only then does it run the script. Anyone have any tips on how to solve this problem?
Best regards

A:
The problem is when the database has information () but it does not select according to the value in the database.

Please note that the option(s) that you generate on JavaScript client could not be available when the Select Tag Helper is rendered. Therefore it does not set default selected option based on the data passed through Mission.MissionDay.
To achieve your requirement of setting the default selected option based on the stored MissionDay, you can try to store the data in a hidden field, then set the selected option in JavaScript code, like below.
Add a hidden field with id="hf_missionDay"

<input type="hidden" id="hf_missionDay" value="Mission.MissionDay" />
<select id="MissionDay" asp-for="Mission.MissionDay">
    <option value="0">
        with no
    </option>
</select>

Set selected option based on the data store in hidden field
$(document).ready(function() {

    missionTime();

    SetSelectionOfMissionDay();

    //...
    //your code logic here
    //...

SetSelectionOfMissionDay function
function SetSelectionOfMissionDay() {
    var mday = $("#hf_missionDay").val();

    $("select#MissionDay option[value='" + mday + "']").attr("selected", true);
    //or
    //$("select#MissionDay").val(mday);
}


text:
Q: Why does the last bit of an Elixir bitstring default to 1? Create a bitstring of 3 bits:
b = <<1 :: 3>>

Use bitstring comprehension to show the value of each bit:
for <<x :: 1 <- b>>, do: inspect x

Output:
["0", "0", "1"]

Notice that the last bit is 1, not 0.
How come all bits are not 0 by default, and can that be achieved somehow?

A: The code
b = <<1 :: 3>>

effectively sets a bitstring of length 3 bits to the value 1 (≡ 001). To initialize the bitstring to have all bits set to zero, use:
b = <<0 :: 3>>

Check:
b = <<0 :: 3>>
for <<x :: 1 <- b>>, do: inspect x
#⇒ ["0", "0", "0"]

Sidenote: e. g. b = <<3 :: 3>> will result in bitwise representation of 3 ≡ 011 etc.


text:
Q: jquery .html is reloading the page only in Chrome I have this function that's re-writing html in a div. It's to make an image gallery with rollover effects on the displayed image. Only in Chrome, the page fully reloads and brings you back to the top of the page. How can I stop this? It works fine in FF and IE.
$(document).ready(function(){
 $(".imagegrid").click(function(e){
  var newIMG = $(this).attr("id");
  $("#show").html("");
    })
});

The original link looks like this:

I've tried to add a

to try and get it to force the refresh to that section of the page as a workaround and that doesn't work at either.
This is the effect I'm looking for:
    http://www.retouche.com/site/Portfolio.aspx?id=svc102

A: changing the CSS instead of the image itself worked out the issue.
$(document).ready(function(){
 $(".imagegrid").click(function(e){
  var newIMG = $(this).attr("id");
  $("#galleryshow").css("background-image", "url(Images/"+newIMG+"after.jpg)");
  $("#galleryshow").hover(function(){
    $("#galleryshow").css("background-image", "url(Images/"+newIMG+"before.jpg)");
  },function(){
    $("#galleryshow").css("background-image", "url(Images/"+newIMG+"after.jpg)");
    });
  })
});


text:
Q: Clojure Function Error "Key must be integer" I have a problem in this function although it compiles without errors!
The function gets two vectors with the same length n, another vector with length 2^n, and an index. The function does a simple calculation and then returns a vector.
The problem appears when trying to call the function. For example:
(check [1 2 3] [1 2 3] [1 2 3 4 5 6 7 8] 1)
java.lang.IllegalArgumentException: Key must be integer (NO_SOURCE_FILE:0)

Function definition:
(defn check [row1 row2 arr j]
  (
   (def x1 (nth arr (nth row1 j)))
   (def x2 (nth arr (nth row2 (- j 1))))
   (def x3 (nth arr (nth row1 (- j 1))))
   (if (<= x1 x2)
     (
      (def row1 (assoc row1 j x3))
      row1
      )
     ((def row1 (assoc row1 (- j 1) x2))
      row1)
     )
   )
  )

A: I cleaned up your code to this:
(defn check [row1 row2 arr j]
  (let [x1 (nth arr (nth row1 j))
        x2 (nth arr (nth row2 (- j 1)))
        x3 (nth arr (nth row1 (- j 1)))]
    (if (<= x1 x2)
        (assoc row1 j x3)
        (assoc row1 (- j 1) x2))))

I have no idea if that does what you want it to do, but the function evaluates, and returns sensible values, e.g.
user=> (check [1 2 3] [1 2 3] [1 2 3 4 5 6 7 8] 1)
[2 2 3]

A: You should probably try to fix the following problems before anything else:

*

*Don't use def inside a function, you should use (let [name1 value1 name2 value2] ...) instead. def is really for defining something in a namespace, not for local values.

*Your lets have a syntax problem, it should be (let [row1 (assoc row1 j x3)] ...) for example

*The parenthesis on line 2 mean that you are calling the result of (def x1 (nth arr (nth row1 j))) as a function. This almost certainly isn't what you want. Turning the defs into a let should help solve this.


text:
Q: Why does Entity Framework 4.0 require using DTM? Is it possible to do not use it? I use EF almost one year ago. I just try to use TransactionScope deal with quite complex query like the following code.
using (var tran = new TransactionScope())
{
    // Clear all data in some table
    DataContext.SomeTables
        .ForEach(x => DataContext.SomeTables.DeleteObject(x));

    DataContext.SaveChanges();

    // Import data from excel as DataSet object.
    var ds = ImportDataFromExcel(file.FullName);

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        DataContext.SomeTables.AddObject(new SomeTable
        {
            // fill object with data from current row.
        });
    }

    DataContext.SaveChanges();

    // Commit Transaction
    tran.Complete();
}

After that, I got some error about DTM is not enabled or accessible. I know it cause by this service at database server is not start or blocked by firewall. But it is not my point.
I want to know why EF uses this service to create transaction while plain SQL script can use only some statement like "BEGIN TRAN", "SAVE TRAN" or "ROLLBACK TRAN" does that.
Is there any other way to avoid calling DTM service for my quite simple transaction statement?
PS. Current working database is so small and I think it should not be affect from different transaction technic.
Thanks,

A: After I search a lot of websites, I just found I can manually create transaction using Entity transaction like the following source code.
using (var tran = DataContext.BeginTransaction())
{
    // Clear all data in some table
    DataContext.SomeTables
        .ForEach(x => DataContext.SomeTables.DeleteObject(x));

    DataContext.SaveChanges();

    // Import data from excel as DataSet object.
    var ds = ImportDataFromExcel(file.FullName);

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        DataContext.SomeTables.AddObject(new SomeTable
        {
            // fill object with data from current row.
        });
    }

    DataContext.SaveChanges();

    // Commit Transaction
    tran.Commit();
}

Helper class
public static DbTransaction BeginTransaction(this ObjectContext context, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
{
    if (context.Connection.State != ConnectionState.Open)
    {
        context.Connection.Open();
    }

    return context.Connection.BeginTransaction(isolationLevel);
}

Thank to Kim Major for answering the following question. I cannot found any other pages that clearly suggest me to use Entity transaction including main MSDN website (How to: Manage Transactions in the Entity Framework).
How to use transactions with the Entity Framework?


text:
Q: Is there any method for fix manually an Alloy Analyzer graph? I need to fix my Alloy graph, for example I have this output:

I can't move "node2" rectangle over the row of "node0" and "node1", and I can't move "node1" under "node2" whitout also move "node0". Is there any solution? Thank you.
PS: I am using Alloy Analyzer 4.2 under Windows.
PPS:  This is only an example, i get a big graph with 5 or 6 rows of 20-25 rectangles, and if I can't fix it manually, it's only a mess.

A: To answer the direct question:  I for one have never found a way to make the visualizer change its mind about which nodes should be on the same horizontal level.  (That doesn't quite mean it's not possible, but it does mean that if it's possible it's not immediately obvious how to do it.  But I guess you knew that already.)
If your goal is to make the auto-generated diagrams easier to read, the simplest approach is to experiment with adjustments to the visualizer theme.  The "Magic Layout" button can be helpful; manual adjustments to hide some nodes or display some relations as labels rather than arcs can help with diagrams which are otherwise too cluttered.
If your goal is to make a 'good' version of a diagram for inclusion on a slide for a talk or a figure for a paper, you may want to export to Dot and import into a graph-drawing tool that gives you the kind of manual control you want (or edit the .dot file yourself, if you are familiar with graphviz and can make it do what you want), or export to XML and generate the graph description language of your choice from the XML.
I hope this helps.

A: The Lightning tool is an Ecplise plugin relying on Alloy4.2 to formally define Domain Specific Languages and might be a solution to your problem.
It's still under development, but if you are only interested in being able to freely reorganize each atom and label of generated instances, there shouldn't be any problems, as it uses Ecplise draw2D to render those latter.
If now you're really interested in providing an intuitive visualization to your generated instance (by intuitive I mean a visualization that is closer to its domain rather than the structure of your model), then you can define your own language (with your model as abstract syntax ) and define a concrete syntax for it.
The update site to be used for the installation of the tool is : http://lightning.gforge.uni.lu/update-site
Don't hesitate to contact me if you plan to give it a shot and get any issues.
(I'm eager of constructive feedbacks ;-) )
The steps to follow to generate a graphical instance in which any components can be moved are :

*

*Install Lightning

*Create a new Lightning Project

*Create a new Language in this project

*Put your model in the ASM folder

*generate instances of the language by "running the project"


text:
Q: Doubt in proof that given a commutative ring $(I_p, +, \cdot)$ is a field iff p is prime $I_p$ is a commutative ring of residue classes ie. $I_p = \{\bar{0}, \bar{1}, \ldots, \overline{p-1}\}$. I have a doubt in proving the necessary condition that when p is prime => $I_p$ is a field.
We basically try to prove that there are no zero divisors in $I_p$. So the proof starts with let $\bar{a}, \bar{b} \in I_p$ then
$\bar{a}\bar{b} = 0$ => $\bar{ab} = 0$
=> p is divisor of ab i.e. p | ab
=> p | a or p | b (This is the step that is not clear)
=> $\bar{a}$ = 0 or $\bar{b}$ = 0
=> there are no zero divisor in $I_p$
And since $I_p$ is a finite commutative ring with no zero divisor it is a field.
If p|ab how can we say p|a or p|b. According to Euclid's lemma isnt it that p divides atleast one of a or b. That mean that there is a possibility where p | a and p |b.
In that case the proof is still valid. since both $\bar{a} = 0$ and $\bar{b} = 0$ and there are no zero divisors.
But isn't the step incorrect?
I also found this definition of Prime element in Ring. The definition says the same what was used in the proof. In the article it states

With this definition, Euclid's lemma is the assertion that prime numbers are prime elements in the ring of integers.

but that is not the definition of prime numbers in integer, again there is a case where p|a and p|b.


text:
Q: OpenGL + Mesa 3D + MinGW I program C++ applications on (Ubuntu) Linux and compile them to 2 operating systems: natively to Linux by using "g++" (GNU C++ compiler) and cross-compile them to Windows by using "i386-mingw32-g++" (MinGW C++ cross-compiler).
Now, I am trying to cross-compile "OpenGL" applications (from Linux to Windows) - for that I need some OpenGL library files.
As an implementation of OpenGL, I use "Mesa 3D" open source library. Fortunately, Ubuntu offers "precompiled" mesa3d libraries (libgl1-mesa-dev and libglu1-mesa-dev) for Linux, but unfortunately, there are not any precompiled libraries for using with MinGW cross-compiler (thus Windows versions of them) - so I "MUST" manually compile them "from source" (which can be downloaded from http://www.mesa3d.org homepage).
But I have no idea to do that. Within the mesa3d source code, there are some documents how to build the libraries for some specific platforms - specifically there is "README.MINGW32" readme file.
But just on the first lines there is some command
mingw32-make -f Makefile.mgw [OPTIONS...]

which I cannot run because I don't have any "mingw32-make" program installed. By other softwares, I used to build them with the "classic"
./configure -> make -> make install

procedure, but this is not working on mesa3d libraries.
For example, I have also tried
./configure --host=i386-mingw32

and it has been configured ok but after typing
make

it threw some error
error: #error No PIPE_SUBSYSTEM_WINDOWS_xxx subsystem defined.

and now I am LOST :-( .
So does anybody know how to build the mesa3d libraries for using them with mingw32?
P.S.: And of course, I DON'T WANT to use Microsoft Visual Studio NEVER MORE :-) . And also I would like to do all the required things to build up OpenGL environment from Linux and using mingw32 for cross-compiling. I hope it is possible.
P.S.2: On http://www.mesa3d.org/systems.html page there is written that using MinGW with Mesa 3D is "deprecated". I am on the right way to use it just that way?

A: There is no need to compile Mesa3D for MinGW. MinGW includes the GL library; it's just not called libGL.a nor libGLU.a; the libraries are instead called libopengl32.a and libglu32.a. Sadly, this is what Microsoft decided to call them under Windows on Visual Studio, so both Windows and GNU/Linux release of MinGW decided to include the libraries named as above.
So, when cross compiling for Windows, just change:
-lGL -lGLU

into
-lopengl32 -lglu32

Mesa3D on GNU/Linux is actually a name for a libre implementation of OpenGL. This is because OpenGL is a trademark, and SGI's policy did not allow for anyone to use the name without paying a hefty sum of money. Despite this, SGI provided the author, Brian Paul, a copy of the testing suite.
Mesa3D is on most platforms with native OpenGL implementation known as a software "sanity check" library with emulation of numerous high-end-hardware-only features. But on GNU/Linux, much more important is something called DRI or direct rendering interface. This is the real deal, the hardware acceleration and all. This library is also called Mesa3D; in fact, provisioning for DRI is a part of Mesa3D as well as of X11 and the kernel.
Mesa3D provides libre OpenGL-compatible headers on GNU/Linux and other free platforms.
Summary: Mesa3D is the name for the GNU/Linux implementation of OpenGL since that name is trademarked. This library includes an excellent, featureful, correct and relatively fast software implementation. It also includes direct rendering interface for hardware acceleration.


text:
Q: Shape modified by AffineTransform is rendering reverse from expectations I have a few geometric shapes which are in different co-ordinates that I want to be brought to the center of the panel.  I have written a function called "Set Scale," which is bringing it in to center, but the shape is reversed.
My Code:
private void SetScale1(Graphics2D gr, int gr_width , int gr_height, double left_x , double right_x , double top_y , double bottom_y ){

    Rectangle2D drawing_rect = new Rectangle2D.Double(left_x, top_y, right_x - left_x, bottom_y - top_y);
 double drawing_cx=( left_x+ right_x) / 2;
 double drawing_cy =(top_y + bottom_y) / 2;

AffineTransform at = AffineTransform.getTranslateInstance(-1 * drawing_cx, -1 * drawing_cy);
//gr.translate(-1 * drawing_cx, -1 * drawing_cy);
//gr.TranslateTransform(0, 0)
double scale_x=gr_width / drawing_rect.getWidth();
double scale_y=gr_height / Math.abs(drawing_rect.getHeight());

scale_x = Math.min(scale_x, scale_y);
scale_y = scale_x;
scale_x = Math.abs(scale_x);
// at = AffineTransform.getScaleInstance(scale_x, -1 * scale_y);
//gr.transform(tt);
gr.transform(at);

//' Translate to center over the drawing area.
double graphics_cx =gr_width / 2;
double graphics_cy = gr_height / 2;
gr.translate(graphics_cx, graphics_cy);
}

A: From the description given, I would recommend you take a look at your transformation matrix:
AffineTransform at = AffineTransform.getTranslateInstance(-1 * drawing_cx, -1 * drawing_cy);

Are you certain that your tx and ty parameters are correct?  Here is the matrix returned by getTranslationInstance:
[   1    0    tx  ]
[   0    1    ty  ]
[   0    0    1   ]

The -1 values you have set in the parameters for getTranslationInstance seem suspect to me... unless I've missed something, I don't see any reason why they should be negative.  Negative values should mirror the result, so that may very well be why you're seeing the reversal. Try changing those (they will change the tx and ty fields in the matrix above, respectively) and let us know if it helps.

A: i Tried this... it Works:-)
Thanks for the help:-)
Rectangle2D drawing_rect = new Rectangle2D.Double(left_x, top_y, right_x - left_x, bottom_y - top_y);
      drawing_cx=(left_x+ right_x) / 2;
      drawing_cy =(top_y + bottom_y) / 2;
 at= AffineTransform.getTranslateInstance( -1* drawing_cx,  -1*drawing_cy);
//gr.translate(-1 * drawing_cx, -1 * drawing_cy);
//gr.TranslateTransform(0, 0)
double scale_x=gr_width / drawing_rect.getWidth();
double scale_y=gr_height / Math.abs(drawing_rect.getHeight());

scale_x = Math.min(scale_x, scale_y);
scale_y = scale_x;
scale_x = Math.abs(scale_x);
// at = AffineTransform.getScaleInstance(scale_x, -1 * scale_y);

gr.scale(Math.round(scale_x), Math.round( scale_y));
//gr.scale(1.2, 1.2);
//gr.transform(tt);
gr.transform(at);

//' Translate to center over the drawing area.
 graphics_cx =gr_width / 2;
 graphics_cy = gr_height / 2;
gr.translate(graphics_cx, graphics_cy);


text:
Q: PHP file in www dir can't access images in user dir I have a PHP file in my var/www directory and I want it to read images from the /user/folder/folder directory. I have tried creating a soft link to the user folder, however, nothing seems to be working. Any help would be greatly appreciated. To note, my permissions for dir and all files is set to 755 and the user and group are set to my username (pass required for access).

$files = glob("~user/downloads/other/*.*");

A: Seems to work fine when you include the full file path.  Not sure what OS you're on, but should be similar to glob("/Users/yourusername/downloads/*.*");


text:
Q: How to connect to MySQL server from Visual Studio Code I recently downloaded the MySQL server and want to connect to it using VSCode, after i installed the VSCode extension, i still have little idea on how to connect to the server/database. All the guides online seem to cover Visual Studio C++.

A: When you install the plugin vscode-database you have some buttons in the footer menu bar to connect to your database. When you open the plugin there is a short tutorial how to connect.
https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-database

A: Use this extension. I tried many of them but they didn't seem to connect.

*

*Make sure you first have downloaded MySQL Community Server on your machine.

*Then go ahead and temporarily download Workbench just to easily get the credentials for your connection.

*Then use this cweijan.vscode-mysql-client2 extension!

Hope this helps


text:
Q: Distinguished name of Configuration in AD is tampered? A user of our product came out with a problem which was caused by the DN of Configuration object in AD. We had a rather static lookup method to find Configuration object, thus it failed.
Let's say the domain name of AD is foo.bar.example.com. Therefore, the expected DN of configuration should be CN=Configuration,DC=foo,DC=bar,DC=example,DC=com, right?
But somehow, this user's DN of configuration has one value missing:
CN=Configuration,DC=bar,DC=example,DC=com.
Do you know how can we reproduce this issue (or is it commonly implemented?)?

A: It seems that the root configuration is associated with the bar.example.com domain and foo is just a subdomain.  To be sure you can get the configuration distinguished name programatically:
// you may need to specify username/password here as well with another
// constructor overload.  Try any of the following:
// DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE", user, pwd);
// DirectoryEntry root = new DirectoryEntry("LDAP://ADServer/RootDSE");
// DirectoryEntry root = new DirectoryEntry("LDAP://ADServer/RootDSE", user, pwd);
DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");

string configDN = root.Properties["configurationNamingContext"].Value.ToString();


text:
Q: Changing button style from .bordered to .borderedProminent when pressed I'm trying to create a button that changes its appearance from .bordered to .borderedProminent to make some kind of illusion of a button that stays pressed when clicked.
Button {}
label: {Text("Xyz").frame(minWidth: 0, maxWidth: .infinity)}
      .controlSize(.regular)
      .buttonStyle(.bordered)
      .buttonBorderShape(.automatic)

I tried using action function to do it but with no success. Is it even possible?

A: In order to achieve your use case, You should create custom button style.
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
        . background(configuration.isPressed ? Color.green : Color.yellow)
 }
}

& apply customButtonStyle to your button.
You can when button is pressed it will be green otherwise yellow. You can change this code to match requirement. Let me know if its useful.


text:
Q: Let $A$ be a matrix with echelon form $U_n=E_n\cdots E_1A$ produced without row interchanges. Show $E_j$ is lower triangular.
Let $A$ be a matrix with echelon form $U_n=E_n\cdots E_1A$ produced without row interchanges. Show $E_j$ is lower triangular.

More specifically,  $U_j$ is the intermediate form between $A$ and $U_n$ that has $j$-many pivot columns. Then $E_j$ is clearly a matrix that zeroes all entries below the $j$th pivot, and $E_j$ is clearly lower triangular (recall the corresponding elementary matrix for adding a multiple of a row to another). But I'm having a hard time making a rigorous proof for this.
I'm seeing that this is probably some sort of induction proof, so I've been working on the $E_1A = U_1$ case. But I'm having trouble even with this first case, so I've decided to prove a single simple case, where $E_1A$ is a $4 \times 4$ matrix with entries of only either 1 or 0. Then, the possible values of $U_1$ are:

This at least seems to suggest a vague angle of attack, since there clearly seems to be an algorithmic way to define $U_j$. For the simplified $U_1$ case above, we clearly see that $E_1$ has to be lower triangular. But, how can we start making an abstract proof on the basis of what we've done?
Would anyone have tips on how to move forward from here?


text:
Q: Using git svn with some awkward permissions Due to some funky permissions on our client's side that we can't change, we have a project whose hierarchy looks something like:

*

*projectname/trunk: foo/, bar/, baz/

*projectname/branches: branch1/, branch2/

*

*(where branch1 and branch2 each contain foo, bar, and baz.)
The thing is, I have no permission to access trunk, so I can't just do a clone of project/trunk. I do have permission to access branches.
What I am currently doing is checking out each subdirectory individually via git svn clone, so that each one has their own git repo. I use a script to update/commit them all, but what I would prefer to do is to check them all out under a single repo, and be able to commit changes with a single call to git svn dcommit. Is this possible?
I mentioned the branches hierarchy because if possible, I'd also like to be able to track the branches the way I could if the permissions were more sane.
I've tried permuting a lot of options that sounded useful, but I haven't found one that gives me exactly what I want. I sense that the solution may have something to do with --no-minimize-url, but I'm not even sure about that, as it didn't help me when I tried it.

A: After a quick check it seems a standard way works flawlessly.
git svn clone --branches /projectname/branches SVN_URL

You can then do dcommits on these branches normally.
Update: it does not work without permissions to read (list) folder /projectname and /
unfortunately.
Update2: it seems that --no-minimize-url would allow to do such import with restricted read permissions.


text:
Q: Displaying Dataset Query and Report Expressions in SSRS Report I am switching from Crystal Reports to SSRS Reporting. In Crystal Reports, there was a way to display the Selection Criteria at the end of each report. This displayed all of the data manipulations made by the developer to the report data.
Example:(this would be displayed at the end of each report in Crystal)
Selection Criteria:
    usp.Members.MemberID <>2 and
    usp.Members.Active = "Y" and
    if(usp.Members.Location = "M1" then "Admission Location" else " ")
In SSRS I am able to manipulate the data in a number of places; Query Builder in the Dataset Properties, Textbox/Field Expressions, and via Filters.
Is there any any that I can display all the report expressions I have made, or display the query used to generate the dataset, at the end of the report to show the user the logic behind the data?
I understand what I am asking could be difficult to understand. Any help is appreciated.

A: You can view the Dataset query using an expression like:
=DataSets!DataSet1.CommandText

Where DataSet1 is the name of your Dataset.
To give an example, say I have a report with the query:

I have a simple report based on this:

You can see the textbox expression is the same as above:

The expression is showing an error but this works anyway:

See What DataSet Query Text Is Executed for more information.
Not sure on extracting all expressions from the report, but hopefully this will be enough.
Edit after comment
OP mentions that it is only working for him in the report header, but in my example this is working in the body.
From Using Built-in Collections in Expressions it seems like there are some further restrictions here:

Represents the collection of datasets referenced from the body of a
  report definition. Does not include data sources used only in page
  headers or page footers. Not available in local preview.

Which explains why it was working for me - it was also being used in a table.
As a simple workaround you could simply add a hidden textbox somewhere on the report body that references the required Dataset; this should allow .CommandText to work in the body.


text:
Q: SQL Server - Table just 1 Identity Column - sys.dm_db_index_usage_stats says user_scans : 100% I have one table made of just one identity column with is a PK clustered constraint on.
CREATE TABLE [Commodity].[tblUniqueIDIndex](
    [UniqueIDIndex] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_tblUniqueIDIndex] PRIMARY KEY CLUSTERED
(
    [UniqueIDIndex] ASC
) ON [Commodity_FG]
) ON [Commodity_FG]

When I look at the index usage using select * from sys.dm_db_index_usage_stats, SQL Server reports the following:

*

*user_seeks : 5 K

*user_scans: 34 Mln!

There are only 10 K records in the table.
This table is linked to other tables obviously where it is referenced as a Foreign Key. The other 'foreign tables' have several hundreds Mlns records in them each.
The software logic which performs statistical calculations treats each UniqueID as unique - there is no batch or grouping.
I am trying to understand why SQL is scanning rather than seeking that table?. Given the way this table is defined that makes no sense to me. Would anyone have an idea how this may happen or perhaps how to find why SQL server is not using the index?
Many thanks,
M


text:
Q: ng-include using scope variables not working So I am trying to add an ng-include for my side bar content but it is not working.
app.js
...
gvhsApp.controller('MainController', function($scope) {
    $scope.template = 'views/mainSidebar.html';
});

index.html
...

I am not seeing any errors in my chrome console. Could it be I am not pointing to the file location properly?
Edit:
Directory Structure
app/
   js/
      app.js
   views/
      index.html
      templates/
          mainSidebar.html
build/
   js/
      app.js
   views/
      index.html
      mainSidebar.html

The build directory is where my server is looking at

A: ng-include doesn't automatically resolve the src value to an expression - it just expects text. Use mustaches inside the value:

This of course assumes that the
 is inside an Angular-enabled view and bound to the controller correctly.