text:
Q: InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List to System.Collections.Generic.IEnumerable I am trying to implementation clean architecture in netcore and I have Runtime Error
InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List to System.Collections.Generic.IEnumerable
In the WebUI I have Match controller and ViewAllMatch Action like this
public async Task<IActionResult> ViewAllMatch()
        {
            var matches = await _mediator.Send(new GetMatchesDetail());
            return View(matches);
        }

In the application Layer I have A queries like this:
public class GetMatchesDetail : IRequest<IEnumerable<MatchesDetail>>
    {
    }
    public class MatchesDetail
    {
        public string MatchId { get; set; }
        public int MatchNumer { get; set; }
        public DateTime DateMatch { get; set; }
        public TimeSpan TimeMatch { get; set; }
        public int MatchYear { get; set; }
        public string SeasonId { get; set; }
        public string Round { get; set; }
        /// <summary>
        /// Set value to Qualified for Qualified and Final for Final Round
        /// </summary>
        public string Stage { get; set; }
        public string SubStage { get; set; }
        public string HTeam { get; set; }
        public string HTeamCode { get; set; } //For Flag get from Table Team from Foreign Key TeamName
        public int HGoal { get; set; }
        public int GGoal { get; set; }
        public string GTeam { get; set; }
        public string GTeamCode { get; set; }
        public string WinNote { get; set; }
        public string Stadium { get; set; }
        public string Referee { get; set; }
        public long Visistors { get; set; }
        public string Status { get; set; }
    }

    public class GetMatchesHandler : IRequestHandler<GetMatchesDetail, IEnumerable<MatchesDetail>>
    {
        private readonly IMatchRepository _matchRepository;

        public GetMatchesHandler(IMatchRepository matchRepository)
        {
            _matchRepository = matchRepository;
        }

        public async Task<IEnumerable<MatchesDetail>> Handle(GetMatchesDetail request, CancellationToken cancellationToken)
        {
            var matchlistview = await _matchRepository.GetMatchDetailAsync();

            return matchlistview;
        }
    }

And the code for matchRepository to get all the match in Infastructure like this.
public async Task<IEnumerable<MatchesDetail>> GetMatchDetailAsync()
        {
            var matchDetailList = (from match in _context.Matches
                                   join team1 in _context.Teams on match.HTeam equals team1.TeamName
                                   join team2 in _context.Teams on match.GTeam equals team2.TeamName
                                   join season in _context.Seasons on match.SeasonId equals season.SeasonId
                                   select new
                                   {
                                       match.MatchId,
                                       match.MatchNumber,
                                       match.DateMatch,
                                       match.TimeMatch,
                                       match.MatchYear,
                                       match.SeasonId,
                                       season.SeasonName,
                                       match.Round,
                                       match.Stage,
                                       match.SubStage,
                                       match.HTeam,
                                       HTeamCode = team1.TeamCode,
                                       match.HGoal,
                                       match.GGoal,
                                       match.GTeam,
                                       GTeamCode = team2.TeamCode,
                                       match.WinNote,
                                       match.Stadium,
                                       match.Referee,
                                       match.Visistors

                                   });

            return (IEnumerable<MatchesDetail>)await matchDetailList.ToListAsync();
        }

Full code have been upload to Github at https://github.com/nguyentuananh921/Betting.git.
for more detail.
Thanks for your help.
I am so confuse about model in clean architech when i have more entities and the model I want to view in the WebUI contain many entities in domain.

A: Thanks for your help.
I have Modify public IEnumerable GetMatchDetailAsync() like that.
public IEnumerable<MatchesDetail> GetMatchDetailAsync()
    {

        #region TryOther way
        var matchQuery = (from match in _context.Matches
                               join team1 in _context.Teams on match.HTeam equals team1.TeamName
                               join team2 in _context.Teams on match.GTeam equals team2.TeamName
                               join season in _context.Seasons on match.SeasonId equals season.SeasonId
                               select new
                               {
                                   #region selectResult
                                   //Remove to clear Select what I want to get.
                                   #endregion

                               });
        MatchesDetail matchesDetail = new MatchesDetail();
        List<MatchesDetail> retList = new List<MatchesDetail>();
        //IEnumerable<MatchesDetail> retList;
        foreach (var item in matchQuery)
        {
            #region ManualMapping
                matchesDetail.MatchId = item.MatchId;
                //other field mapping

            #endregion
            retList.Add(matchesDetail);
        }
        #endregion
        return retList;

    }

And it work


text:
Q: How to hide an element for a certain user forever if clicked I am trying to figure out how to hide an element to not show again if a user clicks the dismiss button. Basically it is just a drop down with promotional information. If the user clicks dismiss, I do not want this element to show to that user ever again.
I would like it to function like the banner seen here http://codecanyon.net/
Is there a way to do this? I tried Googling this answer but could not really find this example. I am assuming this needs to be achieved with cookies. Also, if that is the case, would that cause any issues with SSL Encrypted pages?
Update: What about just setting a cookie that would expire after so many days?
Here is my code:

<img src="<?php echo Mage::getStoreConfig(Mage_Core_Model_Store::XML_PATH_SECURE_BASE_URL); ?>media/wysiwyg/infortis/fortis/custom/rewards.png" alt="Earn Rewards" title="Earn Rewards" /> Earn reward points every time you shop at WeePumpkin.com

X Dismiss

A: If you mean "forever forever", like when they leave the page and come back, you will need to incorporate a server side technology.
If you have users who aren't registered, you could use PHP (or similar) to capture their IP and mark that IP with a flag. The flags initial state would be 'show' or similar. Once they have clicked dismiss, do a quick jQuery ajax request to your server marking the flag as 'hide'.
Obviously if they changed their IP you're info would be out of date.
You could also use cookies as a solution, but if they cleared their cookies it would be lost.

A: you could achieve this using a combination of backend and front end solutions. Basically when a user is registered, his username is registered against a backend flag (in database) like isPromotionsAllowed.
When the user is initially registered, this flag has to be set to true. When he accesses the application by logging again, the promotional content like banners will be displayed to him, if this flag in the db is set to true. When he clicks "dismiss", the backend database field will be updated to false and hence, he will not see the content any longer.
To improve the user experience,this flag can be extended to cookies as well.When he clicks dismiss, a cookie can be saved consisting the flag so that we can save the extra round trips to the server and back to check if the promotional matters are to be displayed or not. This is a conditional enhancement that we can implement on top of the basic solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing various values for a textarea as array but only detects the original textareas and NOT the loaded via AJAX I've a backend website where the user can add textareas in a section and later I save all the $_POST["array[]"] in the database.
My actual HTML code is:
<textarea class="context" name="context[]"></textarea>
<textarea class="context" name="context[]"></textarea>
<textarea class="context" name="context[]"></textarea>

If I post this I get 3 results for context. My problem is when I load via AJAX. The exact view that my PHP loads is:
<textarea class="context" name="context[]"></textarea>

And I see how in firebug is loaded and is exactly like the above. My loader code is:
$("a#add-conx").live("click", function(){
    $("#ajax-loader").fadeIn('normal');

    $.ajax({
        url: BASE_URL + 'projects/ajax/get_textarea',
        type: "POST",
        success: function(data) {
            $("textarea.context:last").after(data);
        }
    });

    $("#ajax-loader").fadeOut("normal");

    return false;
});

And it works fine because it adds exactly next to the last context. But when I post it, i only get results for the first and not for the ajax-loaded ones.
Anyone knows why?
Thank you in advance!
UPDATE:
When the page is load:

After adding some content dynamically:

Code that actually I'm using:
$("a#add-conx").click(function(){
    $("#ajax-loader").fadeIn('normal');

    $("textarea.context:last").after('<textarea class="context" name="context[]"></textarea>');

    $("#ajax-loader").fadeOut("normal");

    return false;
});

And when I get the $_POST["context"] I ONLY get the first 4 textareas, the ones that I've not created. Why???
Thank you!

A: I can't read your full code since ooeramini sort of cuts out the rest of it.
Anyway, are you certain the loaded fields are being loaded inside the form tags? They could be outside leading to their data not being passed. Try a dom source view by highlighting and reading selection source.

A: Just for adding a textarea to dom you should not use ajax...Its a waste of valuable bandwith and time.. There is no need to contact server since you do no need any data fromn there....... just use document.createElement("textarea") or a jquery shortcut for the same for creating textarea....

A: The form was not closed... Closing the various forms with </form> solved the problem.


text:
Q: How to filter list of custom post type with 2 custom taxonomy with ajax in wordpress i've a custom post type that i called it app with 2 custom taxonomy that i called them app_platform and app_category
and now in taxonomy-app_platform.php page i wanna show whole of apps with specifed app platform along with a drop-down list that shows list of app_category like this .

so in the end . i able to filer list app with specifed app_platform and app_category
Note That: in the first time that page is loaded i just wanna show whole of apps in specifed app platform . for exmaple whole of android application
how can i do it with ajax and good performance?

A: Since this is a wordpress issue (I believe) you are likely using MySQL to store your data which means you can't use CTEs. What you will have to do is something like this:
In $(document).ready return your result set in JSON write a query something like this:
"SELECT DISTINCT FROM table where AppCategory = 'iPhone 7` LIMIT 0, 50"

This would return 50 records of that category.
Inside the AJAX call you would then populate the select list based on these results.
I will need more info to take you any further.


text:
Q: Compile ANTLR4 runtime with GCC/MinGW I am trying to compile the ANTLR4 runtime sources
with GCC compiler and MinGW libraries. Is that
possible.
My development environment :
Windows 10, CodeBlocks, GCC, MinGW libraries
Compilation stops with the following error :

error: 'mutex' in namespace 'std' does not name a type

Kind regards
Pier Tilma

A: The MinGW version that comes with Code::Blocks us much too old.
Use a more up to date version of MinGW-w64.
For example the one from: https://winlibs.com/ (instructions for Code::Blocks are on the site).

A: Thanks Sanders,
Using an up-to-date MingW version doesn't give me anymore the
error: 'mutex' in namespace 'std' does not name a type.
But now I ran into another problem :
When crosscompiling the ANTLR4 runtime sources for windows on Linux I
get the following error :
/src/atn/ATNSimulator.cpp:17:21: error: definition of static data member 'antlr4::atn::ATNSimulator::ERROR' of dllimport'd class
My configuration :
os : Ubuntu (Linux 5.15.0-52-generic x86_64),
compiler : x86_64-w64-mingw32-gcc (9.3 posix),
antlr4 : runtime sources 4.11.1
Regards pstilma


text:
Q: remove the array strings in the given string? String fullname="Mr Vivek N Nandakumar Sr";
String [] strst={"Sr.", "sr.", "Jr.", "jr.","Jr ","jr ","Sr ","sr "," Jr"," jr"," Sr"," sr",",I",".I","I.","II","III"," IV","IV ",".IV",",IV", "V.","V ",".V",",V","VI", "VII", "VIII", "IX", "X" ,"M.D","MBA","PhD","M.A","Mr.","Mr ","Mrs.","Miss","MISS","miss","MR ","MRS ","mr ","mrs "," mr"," mrs","Dr ","DR ","Dr.","DR.",")","("};

I just want to remove the this given array strings from the fullname..
I want a output be like ...."Vivek N Nandakumar"

A: I don't know what version of Java you are using, but in Java 8 i would use streams like so:
Arrays.stream(fullname.split(" ")).filter(namePart -> Arrays.stream(strst).noneMatch(str -> str.trim().equals(namePart))).collect(Collectors.joining(" "));

for me the output came as you wanted.
EDIT
This would be the case for JAVA 7. Before that you have to implement your own search.
    String fullname="Mr Vivek N Nandakumar Sr";
    String [] strst={"Sr.", "sr.", "Jr.", "jr.","Jr ","jr ","Sr ","sr "," Jr"," jr"," Sr"," sr",",I",".I","I.","II","III"," IV","IV ",".IV",",IV", "V.","V ",".V",",V","VI", "VII", "VIII", "IX", "X" ,"M.D","MBA","PhD","M.A","Mr.","Mr ","Mrs.","Miss","MISS","miss","MR ","MRS ","mr ","mrs "," mr"," mrs","Dr ","DR ","Dr.","DR.",")","("};
    Arrays.sort(strst);
    StringBuilder sb = new StringBuilder();

    for (String namePart :
            fullname.split(" ")) {
        if (Arrays.binarySearch(strst, namePart, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.trim().compareTo(o2.trim());
            }
        }) < 0 ) {
            sb.append(namePart).append(" ");
        }
    }
    return sb.toString();

A: If you don't have constrain over space complexity, than try to split the main string using space(if space separated) in an array, and check every value with the given array if found remove that one from the main string array and at the end concatenate the main string array. I will say use set to store the second list, it will help you to increase the time performance. it will reduce the time from O(n^2) to O(n).


text:
Q: Why Vue animate differently in case replacing or creating and removing an array item? I encounter with transition issue when animation when clicked on 'stream' button is different from animation after click on 'stream random' button from jsfiddle bellow.
Maybe I'm wrong with styling but could not realize why still getting the stream behaviour.
I need behaviour as on 'stream random' for array of div's.
Thank you

new Vue({
  el: '#list-complete-demo',
  data: {
    items: [1,2,3,4,5,6,7,8,9],
    nextNum: 10
  },
  methods: {
    add: function (item) {
      this.items.splice(this.items.length, 0, item)
    },
    remove: function () {
      return this.items.splice(0, 1)[0]
    },
    stream: function () {
     this.add(this.remove())
    },
    streamrnd: function () {
     this.add(this.nextNum++)
      this.remove()
    }
  }
})
.list-complete-item {
  transition: all 1s;
  display: inline-block;
  margin-right: 10px;
  border: 1px solid green;
  padding: 10px 10px 10px 10px;
}
.innerDiv {
  border: 1px solid red;
}
.list-complete-enter {
  opacity: 0;
  transform: translateX(40px);
}
.list-complete-leave-to {
  opacity: 0;
  transform: translateX(-40px);
}
.list-complete-leave-active {
  position: absolute;
}

  <button v-on:click="stream">Stream</button>
  <button v-on:click="streamrnd">Stream Random</button>

  <transition-group
    name="list-complete"
    tag="div"
    style="margin-top: 50px">

{{ item }}

  </transition-group>

A: In the stream function, you are adding the element that was removed back into the array.  So the animation moves it from the end to the start.
In the streamrnd function you are just removing it entirely, and adding a new one.  So it animates accordingly.

A: You have keyed the transition elements by the item itself, which is a number.
When you click the stream button, you're removing the last item from the array and inserting it at the beginning of the array. Since the key is the same for that item, Vue has detected that the item was moved in the array and transitions it as such.
When you click the stream random button, you are removing the last item from the array and inserting a new unique item with a different key than the existing items in the DOM. Vue will perform a leave transition for the removed item and an enter transition for the new item.
You need to use key to control how Vue reuses DOM elements for your items.
You can associate a unique numerical key for each item in your array to prevent Vue from reusing the spans:
{{ item.value }}

data: {
  items: [
    { key: 1, value: 1 },
    { key: 2, value: 2 },
    { key: 3, value: 3 },
    { key: 4, value: 4 },
    { key: 5, value: 5 },
    { key: 6, value: 6 },
    { key: 7, value: 7 },
    { key: 8, value: 8 },
    { key: 9, value: 9 },
  ],
  nextNum: 10,
  nextKey: 10
},

methods: {
  add(item) {
    this.items.splice(0, 0, {
      key: this.nextKey++,
      value: isNaN(item) ? this.nextNum++ : item,
    })
  },

  remove() {
    return this.items.splice(this.items.length - 1, 1)[0].value
  },

  stream() {
    this.add(this.remove())
  },

  streamrnd() {
    this.add(this.nextNum++)
    this.remove()
  }
}

Obviously you can simplify that code, but you get the idea.
Updated fiddle.


text:
Q: Compare the chances of throwing 4 with one dice, 8 with two dice and 12 with three dice Compare the chances of throwing 4 with one dice, 8 with two dice and 12 with three dice.
My try:
$\begin{aligned}\\
\text{The chance of throwing 4 with one dice is} &=\frac 16\\
\end{aligned}\\$
There are 6 ways to get 8 if we throw two dice i.e. $(2,6)$, $(6,2)$, $(3,5)$, $(5,3)$, $(4,4)$, $(4,4)$.
So, the chance of throwing 8 with two dice is = $\frac{6}{36} = \frac 16$
There are 36 ways to get 12 if we throw three dice i.e. $(1,5,6)\times 3!$
$(2,5,5)\times 3!$
$(2,4,6)\times 3!$
$(3,5,4)\times 3!$
$(3,3,6)\times 3!$
$(4,4,4)\times 3!$
So, the total probability to get 12 by throwing three dice is =$\left(\frac 16\times \frac 16\times \frac 16\right)\times 3!\times 6$ =$\frac 16$
Thus comparing the chances = $1:1:1$
$\begin{aligned}\\
\text{But, in my book the answer is} = 36&:30:25\\
\end{aligned}\\$
Though I am not sure if i am correct or not, but please anyone confirm it.

A: The chance of throwing an $8$ with $2$ dice is $\frac{5}{36}$ since there are a total of $36$ possibilities and we can have $(2,6) , (6,2), (3,5), (5,3)$ and $(4,4),$ since you don't count the event $(4,4)$ twice.
Consider the following table:

For $3$ dice there are $6^{3}=216$ total possibilities.
Next we can consider the cases:

*

*$(1,5,6)$ : these numbers can be arranged in $3!=6$ ways (which are $(1,5,6),(1,6,5),(5,1,6),(5,6,1),(6,5,1)$ and $(6,1,5)$).

*$(2,5,5)$ : these can be arranged in $\frac{3!}{2!}= 3$ ways (i.e $(2,5,5),(5,2,5)$ and $(5,5,2))$

*$(2,4,6)$ :  $3!=6$ ways

*$(3,5,4)$ :  $3!=6$ ways

*$(3,3,6)$ :  $3$ ways

*$(4,4,4)$ : $1$ way.

Total number of ways: $6+3+6+6+3+1=25$ ways.
So comparing we have $\frac{1}{6}:\frac{5}{36}:\frac{25}{216}$ or $36:30:25$ as required.


text:
Q: Copy and paste stops working For several months now i've had an issue where after using my laptop for a couple of weeks without restarting, i'll slowly lose my ability to copy and paste. First it's only between different apps such as Terminal and Sublime Text, but eventually it's system wide and stops working everywhere.
As I type this, nothing seems to be copying to clipboard. Not in textedit, chrome, safari, terminal or otherwise.
Going in to Finder > Clipboard shows only one small piece of text which is the last thing I successfully copied before it completely stopped working.
Should I dump a process list here to show what i've got running or is there a common issue that could be the cause?
I'm on a 13" retina macbook pro running 10.9.
Thanks
Edit 1: It's drag and drop too.
Edit 2: After trying a million fixes found on the internet (changing file permissions, /private/var fixes, disabling hidden files from showing etc, killing third-party processes one by one), none of it worked. I did find however that killing the WindowServer process, which esentially closes all windows and resets the GUI, does provide a bandaid "fix" to the problem and bring copy&paste/drag&drop back. However, this is not particularly surprising. It's almost as inconvenient as simply restarting, which was my old fix. Still would like to figure out the underlying cause. My main suspect is the Windows apps I run via Crossover are messing with something in the system, even after killing Crossover and their processors.
Edit 22/6: I will post a process list and result from kextstat | grep -v com.apple once the issue arrises again.

A: This may happen when some system service crashed/was restarted. The applications started before can't exchange their copy buffer with applications started later. If you quit an earlier started application and start it new, it works again properly.

A: Please check whether the pbcopy command works correctly.
If it fails, then the advice from here may help by restarting the pasteboard service, e.g.:
launchctl stop com.apple.pboard
launchctl start com.apple.pboard

If this won't help, and you'd like to avoid restart, you may try remapping your Copy&Paste shortcuts by Karabiner app. See: Remap Ctrl+C, Ctrl+V, and Ctrl-X.

A: Whenever I have this problem it's because I've accidentally turned mouse keys on. (Option + 5) This is only the case if you have a keyboard without a numpad though.

A: This sounds like an extreme answer, but it's not.
If you are on OSX 10.8+ press alt as the computer boots, go into disk utility and verify/repair everything. Then go to reinstall OSX. I've done this at least a dozen times when I've messed up,OS files. It doesn't touch your files, just OSX files. It will take several hours and a good internet connection, but it has fixed every OS level problem I've ever had.

A: First sorry for the length of this post and for the spelling I am dyslexic....
People are giving answers without having the info needed to give a good answer.
The info that Martin needs to give is:
1) How he is trying to do the cut and paste (only with the mouse or using the keyboard ("command+c" for copy and "command+v" for paste) or both or using the menu items?
2) Is highlight the object to C+P the problem?
3) What software is installed and running?  (because the problem get's worse over time it sounds like a "memory leak" from a program with a bug in it)
He tells use what he has done and why (looked at answers on the internet) but applying answers you find on the internet without knowing the cause can make matters worse.
Now for a answer based on the information given: As his problem is something that gets worse over time it must be down to something that is happing over time or something that is triggered at certain times it must be software.
Why not hardware?  The time frame is weeks not second, minutes or hours then it is unlikely to be hardware.
It is very unlikely to be the OS, Why? because we don't see this problem on all other systems running the same version of the OS X that he is running.
It is very unlikely to be a "permissions" problem because it happens after a time frame of a week.  If it was "permissions" then it would happen straight (right away)  off and all the time.
So what is left:  Installed Software.
Martin says killing the "WindowServer" sort of fixes the problem: Why? All software that uses cut and past uses the "WindowServer" and if any software is overwhelming the "WindowServer's cut&past services" maybe by a memory leak due to a bug then this symptom is to be expected. Also as OS X uses cache systems, both memory and disk killing the buggy process will not clear the cache or fix the symptom.  So tracking down the software is not going to be easy or quick.
So knowing the above; even though he kills the Crossover programs and that douse not work we can say that it still might be the programs used with Crossover or Crossover itself that is leading to the problem especially if Martin is cutting and pasting between programs running in Crossover and OS X programs.  Without knowing what other programs he uses including what ones he using with Crossover it is hard to move forward.
What can Martin do?
1) Shut the computer down more frequently.
2) Note how long it takes before the first error happens and keep a running log of what programs he has had running in that time.
3) Take note of if the problem starts right after a particular program is used.
4) Find a way of working without Crossover programs find MAC OS X alternatives
5) If you can't move from windows programs and have an intel mac then think about using VMware and bootcamp install of Crossover
6) If you must use Crossover then you need to find the program causing the problem and that is going to take a long time as you say it thats weeks for the problem to start. the points below are for this process.
7) Work with only Mac programs for a while (just over the time it takes for the problem to start and if the problem has not started then the problem must be with programs running under Crossover or Crossover itself.
8) Only work with mac programs and one other program under Crossover if the problem happens the :-) you found it.
9) Only work with mac programs and another program under Crossover if the problem happens the :-) you found it.
10) repeat 8 to 9 until the problem happens :-) you found it.
11) backup your data files
12) re-format/erase your disk
13) reinstall OS X

A: This is perhaps a mistaken sudo command that deleted a file or a virus.
From your description it seems that it is most likely a virus.
In which case you need to reinstall mavericks somehow. Yep viruses really suck.
But first there are a few other things you can try.
Solution to the problem:

*

*Try and look through your permissions using Disk Utility, see if anything looks funky.

*If your are using the apple mighty mouse, it has been prone to have problems with copy and paste functions.

*Check and see if you have any Logitech application installed, they also have been prone to causing problems with copy and paste.

*Many printer applications can cause similar problems, especially Lexmark.

*Oh and make sure your mouse has the secondary button function turned on in system preferences.

*If none of these things are working and you don't want to buy a new computer or somehow reinstall your entire OS, try this. (Warning you have to be a little bit of a hacker (not much of a hacker really though)). Reinstall your important system files."WHAT?!" You might be thinking. "HOW?!!". Well I'll tell you.  Get out your old install Mavericks disk or application and find the system files. Then right click on the application (or the application on the disk) and select "Show Package Contents". Then it will bring up a folder of the application contents. Go into the contents folder and select MacOS folder. Inside is the file "Install Mac OS X Mavericks". Double click then go through the package install steps and your good to go!

*And yet even if that doesn't work then call apple to ask if you can re-install in an even more manual way.

A: I faced the same issue.
I was not able to copy from TextEdit to Mail using cmd+C cmd+V.
Then I realized that I had enabled "Paste and Match Style" for all applications in System Preferences->KeyBoard->Shortcuts->App Shortcuts.
I changed "Paste and Match Style" only for Textedit app in system preferences and then I was able to copy paste from TextEdit to Mail.


text:
Q: Duplication Formula for the Gamma function by trigonometric identities There are many books with a proof of Legendre's duplication formula:
$$2^{1-2z}\sqrt{\pi}\Gamma(2z)=\Gamma(z)\Gamma\left(z+\frac{1}{2}\right).$$
which start with the Beta function in the form:
$$B(z_1,z_2)=\int_{0}^{1}u^{z_1-1}(1-u)^{z_2-1}\text{d}u$$
Is there, however, a way to prove it from the trigonometric definition of the Beta function:
$$B(z_1,z_2)=2\int_0^{\frac {\pi}{2}}\sin ^{2z_1-1}\theta\cos^{2z_2-1}\theta\text{d}\theta$$
without going back to the non-trig version of the function?
My attempt so far:
Let $z_1=z_2=z$
$$B(z,z)=2\int_0^{\frac {\pi}{2}}\sin ^{2z-1}\theta\cos^{2z-1}\theta\text{d}\theta$$
$$=2\int_0^{\frac {\pi}{2}}\sin ^{2z_1-1}\theta\cos^{2z_2-1}\theta\text{d}\theta$$
$$=2\int_0^{\frac {\pi}{2}}\left(\frac {\sin 2\theta}{2}\right)^{2z-1}\text{d}\theta$$
$$=2^{-2z}\int_0^{\frac {\pi}{2}}\left(\sin 2\theta\right)^{2z-1}\text{d}\theta$$
and I'm not sure where to go from here.


text:
Q: Adding an eventListener to each checkbox I'm looking for a clean and concise way to add event listeners to each of my checkboxes without having to repeat my Javascript code, I'm still wet behind the ears when it comes to JS, so any assistance would be  greatly appreciated.
Here's what I have so far

   function exFunction() {};

// on-click
var x = document.getElementById("checkboxopt");
x.addEventListener("click", function(){
    console.log("Opt");
  });

var y = document.getElementById("checkboxopt1");
y.addEventListener("click", function(){
    console.log("Opt 1");
  });
var z = document.getElementById("checkboxopt2");
z.addEventListener("click", function(){
    console.log("Opt 2");
  });

<input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">

<input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">

<input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">

A: Either select all and loop over the collection and add the events to each element in the collection.

var cbs = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function (cb) {
    cb.addEventListener("click", function(){
        console.log(this.id);
    });
});

    <input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">

    <input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">

    <input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">

or event delegation and use the event object to figure out what element was clicked.

var wrapper = document.getElementById('wrap');
wrapper.addEventListener("click", function (evt) {
    var elem = evt.target;
    if (elem.name==="checkboxopt") {
        console.log(elem.id);
    }
});

    <input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">

    <input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">

    <input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">

A: Well you can iterate in each checkbox:
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
for(var i = 0; i < checkboxes.length; i++){
     var checkbox = checkboxes[i];
     checkbox.addEventListener('click', function(){
         console.log(this);
     });
}

Hope that helps.
Cheers

A: You can use for loop and create function outside of loop.

var c = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < c.length; i++) {
  clickFunction(i)
}

function clickFunction(num) {
  c[num].addEventListener('click', function() {
    console.log('Opt ' + (num + 1));
  })
}

<input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">

<input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">

<input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">

Or with ES6 you can use let instead of var which have block scope so in each iteration of loop new i will be created.

var c = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < c.length; i++) {
  c[i].addEventListener('click', function() {
    console.log('Opt ' + (i + 1));
  })
}

<input name="checkboxopt" id="checkboxopt" value="true" type="checkbox">

<input name="checkboxopt" id="checkboxopt1" value="true" type="checkbox">

<input name="checkboxopt" id="checkboxopt2" value="true" type="checkbox">


text:
Q: Python Looping with etree I'm sure many of you have seen the inundation of minidom questions I've had as of late. This weekend, I finally gave up and moved to etree, and have one simple question: How should I be looping this to give the output in the following format:
Name Class_Name members color #field y #field z
XML example (there are many different types of Class_Name):
<network_objects>
<network_object>
<Name>Test_Group_A</Name>
<Class_Name>network_object_group</Class_Name>
<members>
  <reference>
    <Name>Host1</Name>

network_objects

  </reference>
  <reference>
    <Name>Host2</Name>

network_objects

  </reference>
  <reference>
    <Name>Host3</Name>

network_objects

  </reference>
  <reference>
    <Name>Host4</Name>

network_objects

  </reference>
  <reference>
    <Name>Host5</Name>

network_objects

  </reference>
  <reference>
    <Name>Host6</Name>

network_objects

  </reference>
  <reference>
    <Name>Host7</Name>

network_objects

  </reference>
</members>
<color><![CDATA[deep pink]]></color>
<comments><![CDATA[no comment]]></comments>
<group_convention_query><![CDATA[]]></group_convention_query>
<group_sort_type>3</group_sort_type>
<is_convention_on>false</is_convention_on>
<member_class><![CDATA[network_object]]></member_class>
<members_query><![CDATA[]]></members_query>
<type><![CDATA[group]]></type>
  </network_object>
 </network_objects>

The following code gives me one iteration of each name (what I want):
for Name in tree.iterfind('network_object/Name'):
    print (Name.text)

However, if I do a for loop within the for loop, I get an output of all names, with all variations of Class_Name (versus what it is in reality). For instance:
for Name in tree.iterfind('network_object/Name'):
    for Class_name in tree.iterfind('network_object/Class_Name'):
          print (Name.text,Class_name.text)

DB_Servers host_plain
DB_Servers network_object_group
DB_Servers dynamic_object

etc etc, I'm sure you get the idea.
How would I go about collecting all of the data I need, and then placing each object with it's relevant details, on it's own line?
Thank you!

A: Both the <Name> and the <Class_Name> are children of the <network_object>. So you could use iterfind to find all the <network_objects>, and then use find to find the single <Name> and <Class_Name> child elements:

For example, with this setup:
import xml.etree.ElementTree as ET

content='''<network_objects>
<network_object>
<Name>Test_Group_A</Name>
<Class_Name>network_object_group</Class_Name>
<members>
  <reference>
    <Name>Host1</Name>

network_objects

  </reference>
  <reference>
    <Name>Host2</Name>

network_objects

  </reference>
  <reference>
    <Name>Host3</Name>

network_objects

  </reference>
  <reference>
    <Name>Host4</Name>

network_objects

  </reference>
  <reference>
    <Name>Host5</Name>

network_objects

  </reference>
  <reference>
    <Name>Host6</Name>

network_objects

  </reference>
</members>
</network_object>
</network_objects>
'''

The code
root = ET.fromstring(content)
for network in root.iterfind('network_object'):
    name = network.find('Name')
    class_name = network.find('Class_Name')
    print (name.text,class_name.text)
    for subname in network.iterfind('members/reference/Name'):
        print(subname.text)

yields
('Test_Group_A', 'network_object_group')
Host1
Host2
Host3
Host4
Host5
Host6


text:
Q: How do I implement configurations and settings? I'm writing a system that is deployed in several places and each site needs its own configurations and settings.  A "configuration" is a named value that is necessary to a particular site (e.g., the database URL, S3 bucket name); every configuration is necessary, there is not usually a default, and it's typically string-valued.  A setting is a named value but it just tweaks the behavior of the system; it's often numeric or Boolean, and there's usually some default.
So far, I've been using property files or thing like them, but it's a terrible solution.  Several times, a developer has added a requirement for a configuration but not added the value to file for the live configuration, so the new release passed all the tests, then failed when released to live.
Better, of course, for every file to be compiled — so if there's a missing configuration, or one of the wrong type, it won't get past the compiler — and inject the site-specific class into the build for each site.  As a bones, a Scala file can easy model more complex values, especially lists, but also maps and tuples.
The downside is, the files are sometimes maintained by people who aren't developers, so it has to be pretty self-explanatory, which was the advantage of property files.  (Someone explain XML configurations to me: all the complexity of a compilable file but the run-time risk of a property file.)
What I'm looking for is an easy pattern for defining a group required names and allowable values.  Any suggestions?

A: How about using Mixin composition? Since traits are applied from right to left we can:
Define traits:
default property:
trait PropertyA {
   val userName = "default"
   def useUserName() : Unit = {
     println(userName)
   }
}

some other property:
trait SomePropertyA extends PropertyA {
   val userName = "non-default"
   def useUserName() : Unit = {
     println(userName)
   }
}

Define an abstract class with default property:
trait HasPropertyA {
   val prop : PropertyA = new PropertyA
}
Define an abstract class with non - default property:
trait HasSomeOtherPropertyA extends HasPropertyA {
       override val prop:PropertyA   = new SomePropertyA {}
}
In your class use default one:
trait MyClass extends PropertyA {
   doSomethingWith(prop.userName)
}
or in the other situation mix it with some other property:
if(env.isSome) {
   val otherProps = MyClass with HasSomeOtherPropertyA
   doSomethingWith(prop.userName)// userName == non-default!
}

Read in more detail in the paper Scalable Component Abstractions

A: Although Lift is a web framework in its essence, it has some utilities as well. One of them is Dependency Injection, see : http://simply.liftweb.net/index-8.2.html#toc-Section-8.2. So you can for example create a base trait with default values and then subclass the Runtime, Development, Test... environment values. And I think that it's easy for someone without knowledge of scala to put some override def defaultValue = "new value" in a file.


text:
Q: Move Li between
* Sorry again but here is my last code and everthing works great except that when i make the jquery the li from 4 to the end moves after the "ul" that i want but i want that li from 4 to the end to move BETWEEN the ul that i want. here is my code:

Forums

Members

Calendar

Chat

Pages

Blogs

Gallery

Downloads

                        More

                                 Dropdown

Extra Link

Extra Link

Extra Link

Separated link

if( $('#nav li').length > 5 )
    {
        $('#nav li:gt(3)').insertAfter('
');
    }

i need form you the best code that i have to replace the jquery part or "insert after"
so it the li form 4 to the end would go between the desired ul thanks

A: Use .appendTo() instead of .insertAfter().
Append puts it inside of the open/closing tags, insert puts it outside the tags.
$('#nav li:gt(3)').appendTo('#more');

JS Fiddle

A: Try this jsfiddle using .wrapInner
$('#nav li:gt(3)').wrapInner('
');


text:
Q: Why is Schouten-Nijnhuis bracket trivial on Poisson cohomology? For a commutative algebra $A$, let a biderivation $P$ be called a Poisson structure if $[[P,P]]=0$ (the bracket is Schouten-Nijenhuis). Then one obtains a complex of multiderivations with $[[P,{}]]$ being the differential, and so one gets Poisson cohomology. Due to graded Jacobi identity for Schouten-Nijenhuis bracket, Poisson cohomology inherits this bracket.
Let $P$ be called nondegenerate if $da \mapsto P(a,{})$ defines an isomorphism between 1-forms and 1-derivations. (Here one also needs to assume that the module of 1-forms is projective and finitely generated.)
How can one see that for a nondegenerate Poisson structure Schouten-Nijenhuis bracket on cohomology is trivial?
I highly suspect that for X and Y from cohomology we have $[[X,Y]]=[[P,i_\Omega(X\wedge Y)]]$ where $\Omega$ is the symplectic 2-form corresponding to $P$ and $i$ is insertion, but I only managed to show that for $|X|=1$ and $|Y|=0$ which is a little bit not enough.

A: I've done it myself but the full proof is a little bit long so here is the pdf file: https://www.dropbox.com/s/d368qulnyzn82v4/Poisson.pdf?dl=0.
The idea is that there exists a bracket on differential forms that is trivial on de Rham cohomology for any Poisson structure and that coincides with Schouten-Nijenhuis bracket if Poisson structure is nondegenerate.


text:
Q: Normalizing ASCII characters I need to normalize a string such as "quée" and I can't seem to convert the extended ASCII characters such as é, á, í, etc into roman/english versions. I've tried several different methods but nothing works so far. There is a fair amount of material on this general subject but I can't seem to find a working answer to this problem.
Here's my code:
#transliteration solution (works great with standard chars but doesn't find the
#special ones) - I've tried looking for both \x{130} and é with the same result.
$mystring =~ tr/\\x{130}/e/;

#converting into array, then iterating through and replacing the specific char
#( same result as the above solution )
my @breakdown = split( "",$mystring );

foreach ( @breakdown ) {
    if ( $_ eq "\x{130}" ) {
        $_ = "e";
        print "\nArray Output: @breakdown\n";
    }
    $lowercase = join( "",@breakdown );
}

A: 1) This article should provide a fairly good (if complicated) way.
It provides a solution to converting all accented Unicode characters into the base character + accent; once that is done you can simply remove the accent characters separately.

2) Another option is CPAN: Text::Unaccent::PurePerl (An improved Pure Perl version of Text::Unaccent)

3) Also, this SO answer proposes Text::Unidecode:

$ perl -Mutf8 -MText::Unidecode -E 'say unidecode("été")'
  ete

A: The reason your original code doesn't work is that \x{130} is not é.  It's  LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130 or İ).  You meant \x{E9} or just \xE9 (the braces are optional for two-digit numbers), LATIN SMALL LETTER E WITH ACUTE (U+00E9).
Also, you have an extra backslash in your tr; it should look like tr/\xE9/e/.
With those changes, your code will work, although I'd still recommend using one of the modules on CPAN for this sort of thing.  I prefer Text::Unidecode for this myself, as it handles much more than just accented characters.

A: After working and re-working, here's what I have now. It's doing everything I want except I would like to keep spaces in the middle of input strings to differentiate between words.
open FILE, "funnywords.txt";

# Iterate through funnywords.txt
while ( <FILE> ) {
    chomp;

    # Show initial text from file
    print "In: '$_' -> ";

    my $inputString = $_;

    # $inputString is scoped within a for each loop which dissects
    # unicode characters ( example: "é" splits into "e" and "´" )
    # and throws away accent marks. Also replaces all
    # non-alphanumeric characters with spaces and removes
    # extraneous periods and spaces.
    for ( $inputString ) {
        $inputString = NFD( $inputString ); # decompose/dissect
        s/^\s//; s/\s$//;                   # strip begin/end spaces
        s/\pM//g;                           # strip odd pieces
        s/\W+//g;                           # strip non-word chars
    }

    # Convert to lowercase
    my $outputString = "\L$inputString";

    # Output final result
    print "$outputString\n";
}

Not entirely sure why it's coloring some of the regex and comments red...
Here are a few examples of lines from "funnywords.txt":
quée
22.
?éÉíóñúÑ¿¡
[ .this? ]
aquí, aLLí

A: For your second question about getting rid of any remaining symbols but keeping letters and numbers change your last regex from s/\W+//g to s/[^a-zA-Z0-9 ]+//g.  Since you've already normalized the rest of the input, using that regex will remove anything that is not a-z, A-Z, 0-9, or whitespace.  Using the [] and a ^ at the beginning will indicate that you want to look for everything that is NOT in the rest of the bracket.


text:
Q: Excel VBA script filters header unexpectedly Introduction
I have some spreadsheets like the following.

Here the header is on rows 16 and 17. There is a "header" to the left (not shown) among the earlier rows and columns that includes a picture, some non-tabular data, a legend, etc., that is unimportant here. Header text on row 16 is obfuscated because reasons. Data marked in bold red indicates that that sample point has undergone some process. Here is the code snippet from the script that highlights those data points in bold red.
' Traverse columns applying redding until hitting the row end, Comment, or SpGr: whichever comes first
For currIndex = abcDateCol + 1 To lastCol
  ' Check for exit conditions:
  If Cells(abcDateRowDesc, currIndex).Value() = "Comments" Then Exit For

  If Cells(abcDateRowDesc, currIndex).Value() <> "" Then
    If Cells(abcDateRowDesc, currIndex + 1).Value() = "process" Then
      ' Looks like we have a column of something Red-able
      Columns(ColumnLetter(currIndex) & ":" & ColumnLetter(currIndex + 1)).Select
      Selection.AutoFilter ' Turn on autofiltering (hopefully)
      Selection.AutoFilter Field:=2, Criteria1:="=1", Operator:=xlOr, Criteria2:="=e"
      Selection.Font.ColorIndex = 3
      Selection.Font.Bold = True
      Selection.AutoFilter ' Turn off autofiltering
      Columns(ColumnLetter(currIndex + 1) & ":" & ColumnLetter(currIndex + 1)).EntireColumn.Delete Shift:=xlToLeft
    End If
  End If
Next currIndex

Context
Here, abcDateCol refers to column AE, lastCol refers to column AQ, abcDateRow (not shown, but available) and abcDateRowDesc refer to the header rows 16 and 17 respectively, and the ColumnLetter function is a user-defined function that returns the human-readable column letter(s) given a column number; this is common functionality you may have seen elsewhere, or even made yourself.
Let's Continue
Never mind that the condition in If Cells(abcDateRowDesc, currIndex).Value() = "Comments" is never satisfied because of an oversight (I'm assuming) -- two different rows, guaranteed.
Let's take a look at what the spreadsheet looks like before this script is executed.

So, the script takes pairs of columns, and for each pair of columns it marks data cells bold red if a data cell's right-adjacent cell has a 1 (or an "e"?) (as a boolean; answers the question, "Has this sample point undergone whatever process?") and then trashes the "process" column.
The Problem
A client wants the gratuitous header gone, so they may more easily import the spreadsheet into whatever solution they have. Delete rows 1 through 15, and this is what I get.

What in the bleepity-bleep happened to the header? I don't understand how this first row gets highlighted. It seems too perfectly weird. Now, let's revisit the very first spreadsheet.

I've filled the "header" with some dummy text after the script executed. Wow, there's the first row reddened again, this time ad infinitum! So, this problem has always existed. Oh, and the first column, too! And, it magically stops right above the proper header so we would never see it.
The Questions
Why is this script unexpectedly reddening the first row and column? Can this be easily solved, or am I looking at some sort of a rewrite? If so, please point me in the general direction.
It helps to mention that these spreadsheets are generated from a Windows application and their scripts executed before a user has a copy of their spreadsheet. Also, regarding the second picture (the spreadsheet with the "process" columns shown), this spreadsheet is not something that normally exists. I generated it for the sake of this post by skipping the script's for loop. The application uses a chosen spreadsheet template, that looks the same minus the data, fills in the sample data, and then executes several scripts over the data.
I considered using conditional formatting, but there are a few dozen spreadsheet templates. Even if I just change the one I need, I can't change the fact that these common scripts run over it. I feel my best option is to correct the script. And, I wouldn't change the script to account for my edge case. The whole ecosystem feels flaky, but that's just subjective.
Note
I am not the author of this script (or any of my company's VBA!). I'm considering this an inheritance tax levied upon me.
*Update
I was asked if I traced through this code. I apologize that I didn't include that information in my original post. Here is what I know. Selection.Font.ColorIndex = 3 turns the cells in the selection that satisfy the autofilter plus the first row (two cells as only two columns are selected at a given time), and Selection.Font.Bold = True makes the same cells bold in the same manner. I suspect it has something to do with the autofilter, so I'm going to take a look at the answers now.

A: This edit should fix your problems, hopefully (they did for my remake of your spreadsheet, but we won't know til you try on the real thing)
' Traverse columns applying redding until hitting the row end, Comment, or SpGr: whichever comes first
For currIndex = abcDateCol + 1 To lastCol
    ' Check for exit conditions:
    If Cells(abcDateRowDesc, currIndex).Value() = "Comments" Then Exit For

    If Cells(abcDateRowDesc, currIndex).Value() <> "" Then
        If Cells(abcDateRowDesc, currIndex + 1).Value() = "process" Then
            ' Looks like we have a column of something Red-able
            'Columns(ColumnLetter(currIndex) & ":" & ColumnLetter(currIndex + 1)).Select
            With Range(Cells(abcDateRowDesc, currIndex), Cells(abcDateRowDesc, currIndex + 1).End(xlDown))
                .AutoFilter 2, "=1", xlOr, "=e"
                ' Don't format header
                With .Offset(1, 0).Resize(.Rows.Count - 1, .Columns.Count)                         .Font.ColorIndex = 3
                    .Font.Bold = True
                    .AutoFilter ' Turn off autofiltering
                End With
            End With
            Columns(currIndex + 1).Delete xlShiftLeft
        End If
    End If
Next currIndex

This all starts with a quirk of how the code is choosing its range to autofilter. The selected area is the full column, instead of the area you actually want to format (row 18 to the last entry). It seems that autofiltering on a full column with empty top rows automatically sets the first nonempty row as the header row. So the header is left unfiltered/unhidden by the statement, and it gets colored in as part of the full column selection. So that's why your headers are getting colored.
Now, if you tried to test this by putting data in the above empty rows like "a", those values would become the first ones in the column and would be selected as the headers - meaning those values get colored. Whatever is in the first nonempty row of your columns will be the autofilter header and will get colored.
But that should only affect the columns you explicitly colored, not the entirety of the first row, right? The problem here is that Excel likes to make assumptions about data in order to save time. So if you have a whole row full of red, bold "a"'s and right next to them you put in another "a" to test whether that cell is formatted or not... well, it automatically gives you a red, bold "a" despite the cell being previously unformatted! And if you keep going down the row in this way, it'll appear like your whole row got formatted. But, if you were to jump over a few columns (say, 5-ish) and enter in another "a", voila, it's unformatted, and any "a"s you put in near it will be too. You can also check what Excel by deleting an unformatted "a" in a far off column, then continuing to enter "a"'s all the way down until you reach that same cell - this time, the "a" will be red and bold because all of the others in the row were, too, even though we just checked that this was an unformatted cell!
Basically, having the wrong range for your autofilter made things act very unexpectedly, then trying to test the formatting issue by entering in values just made everything less clear. The code I've provided just autofilters the relevant area (row 17 to the last contiguous row), fixing the core issue.

A: here's a (commented) refactoring of your code that should do:
Option Explicit

Sub main()
    Dim abcDateCol As Long, lastCol As Long, abcDateRow As Long, abcDateRowDesc As Long, currIndex As Long

    abcDateCol = 31
    lastCol = 43
    abcDateRow = 16 '<--| you can change it to 1 for the last "scenario"
    abcDateRowDesc = 17 '<--| you can change it to 2 for the last "scenario"

    For currIndex = abcDateCol + 1 To lastCol '<--| loop through columns
        With Cells(abcDateRow, currIndex) '<--| refer to cell in current column on row abcDateRow
            If .Value = "Comments" Then Exit For '<--| Check for exit conditions on row 'abcDateRow'

            If .Offset(1).Value <> "" And .Offset(1, 1).Value = "process" Then '<--| Check for processing conditions on row 'abcDateRowDesc'
                With .Resize(.Offset(, 1).End(xlDown).Row - .Row + 1, 2) '<-- consider the range from current referenced cell 1 column to the right and down to last 'process' number/letter
                    .AutoFilter Field:=2, Criteria1:="=1", Operator:=xlOr, Criteria2:="=e" '<--| filter on "process" field with "1" or "e"
                    If Application.WorksheetFunction.Subtotal(103, .Cells.Resize(, 1)) > 1 Then '<--| if any values match...
                        With .Offset(2).Resize(.Rows.Count - 2, 1).SpecialCells(xlCellTypeVisible).Font '<--|... consider only filtered values skipping headers (2 rows), and apply formatting
                            .ColorIndex = 3
                            .Bold = True
                        End With
                    End If
                    .AutoFilter '<-- reset autofilter
                    .Resize(, 1).Offset(, 1).EntireColumn.Delete Shift:=xlToLeft '<-- delete the "2nd" column (i.e. one column offsetted to the right)
                End With
            End If
        End With
    Next currIndex
End Sub

there were two faults in your "inherited" code:

*

*If Cells(abcDateRowDesc, currIndex).Value() = "Comments" Then Exit For was to be referred to abcDateRow index row instead

*the formatting would be applied to all cells, were they filtered (matching) or not


text:
Q: Find a row that has passed different steps in the same table Hi to all here it is my problem:
I have an history table where a record register different steps:

Id
Step
Item Code

1
Created
112345

2
Approved
112345

3
Completed
112345

4
Closed
112345

5
Created
112346

6
Approved
112346

8
Closed
112346

What i want to find inside this table is:
All the item codes that have done one step (for example the Approved one) and where the next one is not the "natural one" (for expample the Completed one). In the example table the time code 112346 item has done the Approved step but has skipped the Completed step).
Is there anyway to do a query like this? I've used the PARTITION BY to make a cluster of Item ,for each step, but i am unable to continue the query.
Thanks in advance for any help or suggestion

A: You can use the LEAD analytic function to check if the next step is not the expected one:
SELECT id, step, item_code
FROM   (
  SELECT t.*,
         LEAD(step) OVER (PARTITION BY item_code ORDER BY id) AS next_step
  FROM   table_name t
)
WHERE step = 'Approved'
AND   (next_step IS NULL OR next_step != 'Completed')

Or, from Oracle 12, you can use MATCH_RECOGNIZE to perform row-by-row processing:
SELECT id, step, item_code
FROM   table_name
MATCH_RECOGNIZE(
  PARTITION BY item_code
  ORDER     BY id
  ALL ROWS PER MATCH
  PATTERN ( approved {- (not_completed|$) -} )
  DEFINE
    approved      AS step = 'Approved',
    not_completed AS step <> 'Completed'
)

Which, for the sample data:
CREATE TABLE table_name (Id, Step, Item_Code) AS
SELECT 1, 'Created',   112345 FROM DUAL UNION ALL
SELECT 2, 'Approved',  112345 FROM DUAL UNION ALL
SELECT 3, 'Completed', 112345 FROM DUAL UNION ALL
SELECT 4, 'Closed',    112345 FROM DUAL UNION ALL
SELECT 5, 'Created',   112346 FROM DUAL UNION ALL
SELECT 6, 'Approved',  112346 FROM DUAL UNION ALL
SELECT 8, 'Closed',    112346 FROM DUAL;

Both output:

ID
STEP
ITEM_CODE

6
Approved
112346

db<>fiddle here

A: Provided you have a table of step names with a proper ordering int column (seqno)
with
/* Sample data */
steps(seqno, Step) as (
   select 1, 'Created'   from dual union all
   select 2, 'Approved'  from dual union all
   select 3, 'Completed' from dual union all
   select 4, 'Closed'    from dual
),
tbl(Id, Step, ItemCode) as (
   select 1, 'Created'  , 112345 from dual union all
   select 2, 'Approved' , 112345 from dual union all
   select 3, 'Completed', 112345 from dual union all
   select 4, 'Closed'   , 112345 from dual union all
   select 5, 'Created'  , 112346 from dual union all
   select 6, 'Approved' , 112346 from dual union all
   select 8, 'Closed'   , 112346 from dual
),
/* Find steps with the next step being out of order */
m as (
  select max(seqno)+1 term
  from steps
)
select Id, Step, ItemCode
from (
  SELECT t.*, s.seqno, lead(s.seqno, 1, (select term from m)) over(partition by ItemCode order by Id) nextSeqno
  FROM tbl t
  JOIN steps s on s.Step = t.Step
) q
cross join m
where nextseqno != Seqno + 1 and nextseqno < m.term


text:
Q: How big is the equilateral triangle inscribed in a triangle? Given a scalene triangle $ABC$ and an inscribed equilateral triangle whose vertices lie on different sides of $\triangle ABC$, what is the maximal ratio of the area of the equilateral triangle to that of the original triangle?
I would expect an answer as a ratio of polynomials in sines and cosines of the angles of $\triangle ABC$. I got such an expression via a clunky unsymmetrical method, but it but it was so messy that I gave up trying to simplify it. However, a more intelligent method might well yield a formula of reasonable length.

A: We start with the process of solving the problem of "inserting" an equilateral triangle in the given triangle. We select the side of the triangle in front the largest angle to create the locus the smaller angles of the equilateral triangle.

When you have (the drawing on the right) the two circles with centers $U$ (radius $r_1$) and $S$ (radius $r_2$), you select the side of the equilateral triangle $GH$, in the larger circle (center $S$ in the drawing), you stretch it to intersect the smaller circle (not shown) and then you draw the line through this intersection and the third vertex of the equilateral triangle intersecting the other circle.
The triangle you created is the smallest triangle subscribing the equilateral triangle and is similar to the original triangle. You scale up the equilateral triangle by the similarity factor to get the largest equilateral triangle.
Note that the largest equilateral triangle is sharing a side with the triangle in which it is inscribed and that the $60^\circ$ angle of the equilateral triangle is included in the largest angle of the original triangle.
This means that to draw the largest equilateral triangle you do not need to go through the lengthy process; you draw a $60^\circ$ angle on the larger side of the largest angle of the triangle and from that vertex to the intersection with the opposite side is the largest equilateral triangle.
Let me know if you have a question.

A: There isn't a single inscribed equilateral triangle: by choosing a point on a side, rotating another side by $60^\circ$ around that point and marking the intersection point with the third side, we always get an inscribed equilateral triangle.

If you mean what is the maximum ratio $\frac{[ABC]}{[DEF]}$, the answer is given by a rescaled Napoleon triangle. We may notice that such ratio is also the ratio between the areas of the largest circumscribed equilateral triangle and the original triangle. On the ther hand, it is quite simple to describe the set of the circumscribed equilateral triangles: let we consider the Napoleon/Torricelli/Fermat configuration:

We have $O_B O_C\perp AV_A$ and so on. If we take a point $P$ on $\Gamma_A$ (the circumcircle of $BCV_A$), draw a line through $B$ till meeting $\Gamma_C$ at a new point $Q$, then draw a line through $A$ till meeting $\Gamma_B$ at a third point, the (grey) triangle defined this way is equilateral. It follows that we simply need the greatest $PQ$ segment among the segments built through the previous procedure. This segment has to be perpendicular to the radical axis of $\Gamma_A$ and $\Gamma_C$, so the Napoleon triangle of $ABC$ is the smallest inscribed equilateral triangle in $A'B'C'$. By rescaling, we get the solution. It is interesting to point out that the side length of $O_A O_B O_C$ is $\frac{1}{\sqrt{3}}AV_A$, and $AV_A=BV_B=CV_C$ is the length of the Steiner net of $ABC$, i.e. $FA+FB+FC$, with $F\in\Gamma_A\cap\Gamma_B\cap\Gamma_C$ being the Fermat point of $ABC$.

A: This is intended as a different view, but doesn't constitute a complete answer.
We are going to work on the following figure, which has a classical aspect (first part of Miquel's theorem, see (https://en.wikipedia.org/wiki/Miquel%27s_theorem))

Instead of having a fixed triangle with given angles $\alpha, \beta, \gamma$, and equilateral triangles inscribed in it, let us completely reverse the problem into: being given a fixed equilateral triangle $UVW$ with unit side, consider a circumscribed triangle $ABC$ with these angles.
This makes sense as the issue is size and rotation invariant.
Being given these angles $\alpha, \beta, \gamma$, where can $A,B,C$ be situated?
Evidently, $A,B,C$ are restricted to be on circles (or more precisely their external arcs) from which one can see resp. line segments $VW$,$WU$ and $UV$ under angles $\alpha$, $\beta$ and $\gamma$ resp..
Taking an arbitrary point $A$ on the $\alpha$ circle; line AW intersects circle $\beta$ in $B$; then, line $BU$ intersects circle $\gamma$ in $C$; at last, points $C,V,A$ are aligned, as can be established by angle chasing in triangles $AWV$, $BUW$ and $CVU$. This is our manner to prove the existence of an infinite number of ways to inscribe an equilateral triangle in a given triangle.
Remark: We have also a global view of the areas ratio $R=[UVW]/[ABC]$ whose maximum is looked for (this ratio has not been modified by the transformation); it is equivalent to look for the
$$\text{Minimization of } \ \ 1/R=[ABC]/[UVW]=1+\frac12(h_A+h_B+h_C)$$
where $h_A,h_B,h_C$ are the altitudes issued from $A,B,C$ onto $VW$, $WU$, $UV$, resp.
As the figure of this text is very similar to the figure given by @Jack d'Aurizio (though obtained in a different spirit), I do not complete (at least for the moment) my proof because it would paraphrase his proof. I am indebted to Jack d'Aurizio because a first draft of this text was on bad tracks : I hadn't perceived that there is a - continuous - infinity of inscribed equilateral triangles in a given triangle.)
See as well Johnson's triangles.


text:
Q: Automated cross-account DB backup using AWS Lambda,RDS,SNS I have a Lambda function that shares an RDS manual snapshot with another AWS account.
I am trying to create a 'chain reaction' where the lambda is executed in the 1st account , then the snapshot is visible to the 2nd account, and another lambda is triggered that copies the visible snapshot in another region (inside the 2nd account) .
I tried using RDS event subscriptions and SNS topics, but I noticed that there is no RDS event subscription for sharing and/or modifying a RDS snapshot.
Then, I tried to setup cross-account permissions so the lambda from the first account will publish to an SNS topic which will trigger the lambda in the second account, but it seems that the topic and the target lambda must be in the same region (however the code that copies the db snapshot must be in the target region) . I followed this guide and I end up with this error:
A client error (InvalidParameter) occurred when calling the Subscribe operation: Invalid parameter: TopicArn
Has anyone tried something like this?
Is cross-region communication eventually feasible?
Could I trigger something in one region from something in another (any AWS service is welcome)?
My next attempts will be:

*

*cross-region lambda invocation

*Make use of API Gateway


text:
Q: Help with problem with AS3 ive been looking and i cant find anything that solves my issue.
Im new in AS3 and i used to do this really easy in AS2.
Im building a website and i want that every time they click in a different menu link the menu box closes and opens and at the same time it loads a different swf inside.
Please if someone can help me i used to this this with variable and on enter frame but now in AS3 i have no idea.
Thanks and any advice will help

A: I'm not 100% sure what you mean by closes and opens at the same time, anyways:
Here is the code you would use to load an SWF:
function loadSWF(url:String):void
{
    var req:URLRequest = new URLRequest(url);
    var loader:Loader = new Loader();

    loader.load(req);

    addChild(loader);
}

loadSWF("http://projectavian.com/projects/swf/what_in_space.swf"); //example

Just put loadSWF("your_file_here") into your button click code. If you want to add the SWF to a certain container, just specify that in front of addChild(loader). eg myMovieClip.addChild(loader);
Hope this helps.


text:
Q: interrupted vs isinterrupted implementation I wonder if anyone can please clear my confusion about the implementation issue that I am having; if Thread.interrupted() clears a flag of the current thread and also tells you if current thread was interrupted, my lack of understanding is the static scope.  How does a static function knows my current thread instance ?
Thanks, just trying to understand the internals.

A: The current thread is looked up using Thread.currentThread() inside the method Thread.interrupted(). Thread.currentThread() returns a reference to the calling thread.


text:
Q: How to move a box (stroked selection) in GIMP? One can create a rectangular box in GIMP by applying a stroke (Edit > Stroke Selection) to a rectangular selection (as discussed in a previous post). How can one select and move the box once it has been created? The box appears to not be amenable to selection by clicking on its border or within its interior. Likewise, the selection does not appear along with other items in e.g., the layer listing.

A: Once you apply a stroke to your selection, it is printed on the underlying layer. If you want to move the created box, you should put it on its own layer.


text:
Q: Unity 5 two-sided cloth plane I'm trying to make some curtains for a game with the cloth component in Unity 5, with the new Standard shader. If I make them with a plane I can only see one side of it (obviously), and if I try to make the curtains with a thin cube it looks really buggy and it doesn't behave like a plane would.
Any help would be appreciated.

A: There's a few ways you can approach this.
1, You can create a two sided plane in any of the 3D graphic programs (Maya, Blender... etc.) then import that into your scene.
2, You can use a two sided shader.
3, You can use two different plane objects parented together and work on the parent object later. [I don't really recommend this but it can certainly work as well...]
Some of the particle shaders are rendering both sides like the "Particles/Alpha Blended" but if that's not good for you then you can also make two-sided versions of other shaders by duplicating your selected shader into your assets and setting it's culling value to Off.
Note: Setting the culling to off may not work for lit shaders and you may have to invert the normals too however that's heavy on performance. It's better to use another method in that case.


text:
Q: How to run a pipeline only on changes in a specific branch? I am looking through the documentation back and forth and cannot find how to configure my .gitlab-ci.yml so that the content is executed only on a change in the branch mqtt_based and not in the default master.
I was hoping that adding an only entry for each section would be enough (I was hoping for a global setting), but this did not help (the pipeline was not started when the mqtt_based branch was changed)
variables:
  BRANCH: "mqtt_based"

stages:
  - build
  - deploy

job:build-back:
  stage: build
  script:
    - cd back
    - docker build --build-arg COMMIT=${CI_COMMIT_SHORT_SHA} --build-arg DATE=$(date --iso-8601=seconds) -t registry.XXX/homemonitor-back:latest -t registry.XXX/homemonitor-back:${CI_COMMIT_SHORT_SHA} -f Dockerfile .
  only:
    - $BRANCH
(...)

A: You need to use 'refs' after 'only'. Something like this
only:
  refs:
    - mqtt_based

Documentation: https://docs.gitlab.com/ce/ci/yaml/#onlyexcept-advanced


text:
Q: Spring boot test, @WithMockUser produce NPE in Controller method i have an issue with my controller test
So my base test class configured like so
@SpringBootTest
@WithMockUser(username = "test_user",authorities = "Configured_allacess_authority")
public abstract class BaseControllerTest extends DatabaseIT {

protected static long counter;

protected MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
protected ObjectMapper objectMapper;
protected MockRestServiceServer restServiceServer;
@Autowired
RestTemplate restTemplate;

@BeforeEach
protected void setup() {
    mockMvc = MockMvcBuilders
            .webAppContextSetup(webApplicationContext)
            .build();
    restServiceServer = MockRestServiceServer.createServer(restTemplate);
}

and test code
        mockMvc.perform(request)
           .andExpect(status().isOk())
           .andExpect(content().contentType(MediaType.APPLICATION_JSON))
           .andExpect(content().json(s));

When i debugging my controller method which is
        public ResponseEntity<?> getSomething (
    @Parameter(description = "ID") final String id,
    @ApiIgnore @AuthenticationPrincipal Authentication user){
        ////
    }

user value is null, though when i invoke         SecurityContextHolder.getContext().getAuthentication() here in controller i'm getting Authentication object that's refers to one i mocked in
@WithMockUser(username = "test_user",authorities = "Configured_allacess_authority")

So recently i've updated my project to Java 17 , that also forced me to update spring boot to
version: '2.5.5'
and spring cloud to
"org.springframework.cloud:spring-cloud-dependencies:2020.0.5"


text:
Q: Vim quickfix double path to file with Ghc-mod I use Ghc-mod Vim for Haskell source file check. I run it on Windows with gvim. Run :GhcModCheck it passes file for Ghc-mod utility and outputs in a quickfix error like:
G:\Haskell\G:\Haskell\huffman.hs|5 col 1 warning| The import of foldl' from module `Data.List' is redundant

As you can see, it includes path to file two times. Of course I can't jump in that location.
It looks like Ghc-mod itself doesn't output any paths at all, then it ether vim's errorformat or Ghc-mod for Vim plugin. Strangely enough, I haven't found such cases anywhere, so it maybe my _vimrc
Could anyone kindly point me out where to search for clues?

A: I've checked standard quickfix window after :vimgrep and it appeared allright. It left me only ghcmod-vim as main suspect. I've carefully traced all paths manipulation and have found that utils use some function, which  reads a path and searches [a-z] regexp in it.
The problem was that my drive letters were uppercase, so plugin treated it like a usual filename.
I've commited a pull request to ghcmod-vim repo. Hope it'll help.
Thanks you for a concearn.


text:
Q: Trying to get a list of a single field from all the documents in my Mongo database I'm using the last driver.  My documents are of the form
{
    "ItemID": 292823,
    ....
}

First problem: I'm attempting to get a list of all the ItemIDs, and then sort them.  However, my search is just pulling back all the _id, and none of the ItemIDs.  What am I doing wrong?
  var f = Builders<BsonDocument>.Filter.Empty;
  var p = Builders<BsonDocument>.Projection.Include(x => x["ItemID"]);
  var found= collection.Find(f).Project<BsonDocument>(p).ToList().ToArray();

When I attempt to query the output, I get the following.
found[0].ToJson()
"{ \"_id\" : ObjectId(\"56fc4bd9ea834d0e2c23a4f7\") }"

It's missing ItemID, and just has the mongo id.
Solution: I messed up the case.  It's itemID, not ItemID.  I'm still having trouble with the sorting.
Second problem: I tried changing the second line to have x["ItemID"].AsInt32, but then I got an InvalidOperationException with the error

Rewriting child expression from type 'System.Int32' to type
  'MongoDB.Bson.BsonValue' is not allowed, because it would change the
  meaning of the operation. If this is intentional, override
  'VisitUnary' and change it to allow this rewrite.

I want them as ints so that I can add a sort to the query.  My sort was the following:
    var s = Builders<BsonDocument>.Sort.Ascending(x => x);
    var found= collection.Find(f).Project<BsonDocument>(p).Sort(s).ToList().ToArray();

Would this be the correct way to sort it?

A: Found the solution.
//Get all documents
var f = Builders<BsonDocument>.Filter.Empty;

//Just pull itemID
var p = Builders<BsonDocument>.Projection.Include(x => x["itemID"]);

//Sort ascending by itemID
var s = Builders<BsonDocument>.Sort.Ascending("itemID");

//Apply the builders, and then use the Select method to pull up the itemID's as ints
var found = collection.Find(f)
        .Project<BsonDocument>(p)
        .Sort(s)
        .ToList()
        .Select(x=>x["itemID"].AsInt32)
        .ToArray();


text:
Q: Can EntryElement be multiline on MonoTouch.Dialog? I subclassed EntryElement and have set the UILineBreakMode in the GetCell method as such:
public class EntryElementEnhanced : EntryElement, IElementSizing
{
    public EntryElementEnhanced(string caption, string placeholder, string value) : base (caption, placeholder, value) {}

    public float GetHeight(UITableView view, NSIndexPath indexPath)
    {
        return 100.0f; //arbitrary number just for testing
    }

    public override UITableViewCell GetCell (UITableView tv)
    {
        var cell = base.GetCell (tv);
        cell.TextLabel.LineBreakMode = UILineBreakMode.WordWrap;
        cell.TextLabel.Lines = 0;

        return cell;
    }
}

This does not seem to make the text that gets entered into the cell word-wrapped. Should I be setting this somewhere else?
If someone knows a better approach, what I'm trying to accomplish at a higher level is I want to create the equivalent of an UITextArea in MonoTouch.Dialog.

A: EntryElement creates an UITextField which is a one line only control.
If you need multiple lines then I suggest you to create your own Element, e.g. MultilineEntryElement, and have it use a UITextView internally.
You could do this by copy-pasting code from EntryElement or by inheriting from the UIViewElement (or a bit of both).

A: there is a multilineEntryElement code piece at https://gist.github.com/315408
in my app it looks a bit funky but it works.

A: I created a MultilineEntryElement by subclassing UIViewElement at https://gist.github.com/4080025
Works pretty well and handles a placeholder. You will need to update it for your specific width.

A: I'll throw my hat into the ring. I looked at a couple of the multiline entry element gists out there, and they all had layout issues. I wrote this one https://gist.github.com/akcoder/5723722 to address the layout issues and to also handle orientation changes. This should work on all versions of the iPhone and iPad.


text:
Q: Export articles in recent changes to an xml dump i am looking for a solution to dump (xml format, incl. templates) each article how was edited in the last hour.
i started with imacro for firefox. Getting the list of articles are now fine. Currently i have troube with article name, which includes spaces or german umlaut.
e.g.Eidgen%C3%B6ssische_Konstruktionswerkst%C3%A4tte_K%2BW_C-35
How can i convert i to "real" article names?

A: The title you are seeing is encoded for use in a URL. Your programming language should provide a standard method for decoding these, e.g. "urldecode" in PHP, "decodeURIComponent" in JavaScript, "urllib2.quote" in Python, etc.
But you shouldn't need to do this at all if you fetch the titles of the changed pages via the MediaWiki API. See this query for Wikipedia, for example: https://de.wikipedia.org/w/api.php?action=query&list=recentchanges&format=xml


text:
Q: PHP E_WARNING Input variables exceeded not displayed I have a problem with my PHP 5.3.24.
My PHP not display E_WARNING message in my script.
I want to appear the following error:

Warning: Unknown: Input variables exceeded 1000

In my setup this error does not appear when it should appear.
Here my php.ini file: http://pastebin.com/iC7yQ2bm
Follows the following discussion : Cannot post hidden input after update PHP 5.3.8 to PHP 5.3.24
Thanks for your help

A: http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-startup-errors
in your php.ini / htaccess
display_startup_errors = On

or you may need more...
error_reporting = -1
display_errors = On
display_startup_errors = On

sadly you can't do nothing more than print or not to print it

A: Put this in the very first line of your php file
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if it doesn't show errors it means there are none.
moreover, check -> http://php.net/manual/en/errorfunc.configuration.php
http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting


text:
Q: What are the roles of physical constants in a relation expression? To describe the properties of a system for which we have designed mathematical symbols and in  relating these properties in an expression, we often introduce some proportionality constant. What is the origin of this constant? Are there any things we missed earlier(some other property that we don't know about)?

A: Consider you have a copper wire with a certain diameter and length, an adjustable power supply and an ammeter. You do a set of experiments and find that as you increase the voltage the current increases. Then, you conclude that voltage is proportional to current and write
$$
V \propto I
$$
But how are you going to convert this proportionality sign to an equal sign?
In this case, yes, there is a property which is missing, namely, resistance R, that is, the constant of proportionality. At this point, with the available data from your experiment, you do not even know what is the nature of this constant; whether it depends on the material or the length or diameter of the wire you used, etc.
Same logic is applicable for the proportionality between the force and the spring constant or the gravitational force and gravitational constant.
Also keep in mind that the values of these constants depend on the system of units one uses.

A: This isn't really all that sophisticated. Take, for example, Newton's law of universal gravitation:

The gravitational force between two objects is proportional to the mass of each of the bodies and inversely proportional to the square of their distance.

That is, if you have two bodies of mass $M$ and $m$, separated by a distance $r$ then the force $F$ between them obeys
$$F\propto\frac{Mm}{r^2}.$$
Put another way, if you have two pairs of bodies, 1 and 2 and 3 and 4, with masses $m_1$, $m_2$, $m_3$ and $m_4$ and separated by distances $r_{12}$ and $r_{34}$ then the mutual forces inside each pair, $F_{12}$ and $F_{34}$, will obey
$$
F_{12} \frac{r_{12}^2}{m_1m_2}=F_{34} \frac{r_{34}^2}{m_3m_4}
$$
You can then choose some representative bodies and set $G=F_{12} \frac{r_{12}^2}{m_1m_2}$, and you'll get the same value regardless of which bodies you chose. In other words,
$$
F \frac{r^2}{Mm}=G
$$
for any two bodies, or
$$F=G\frac{Mm}{r^2}.$$


text:
Q: How to open zip file without additional Nuget packages? I have the following code:
    public static class PracticeFunction
    {
        [FunctionName("LearningAboutFunctions")]
        public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            using (var client = new WebClient())
            {
                client.DownloadFile("https://examplesite.co.uk/file.zip", "myfile.zip");
            }
        }
    }
}

Is there a way of opening the Zip file and extracting the contents without needing to install any additional nuget packages?

A: Try something like this
using System.IO.Compression;

string startPath = @"C:\Users\host\Desktop\Folder";
            string zipPath = startPath + @"\Zipfile.zip";
            string extractPath = @"C:\Users\host\Desktop\Final Folder\";
            ZipFile.ExtractToDirectory(zipPath, extractPath);


text:
Q: Add sequential number to new field based on a sorted ascending list (SQL in QGIS) I have a line (segmented road) dataset where each road has a unique code but that road maybe segmented. I want to add the unique code (Location) and sequential number (based on the start chainage of the segment) to a new field (segment_id).
I need it in the QGIS flavour of SQL that only allows these commands -https://sqlite.org/lang.html?
The example below has the field I want to end up with in the last (Segment_ID) column
fid RoadMntnc   Location    Segments    Start_Chainage  Segment_ID
640 Albatross_Cl    3   1   0   3.1
606 Allamanda_St    4   1   0   4.1
620 Barrbal_Dr  25  5   0   25.1
624 Barrbal_Dr  25  5   50  25.2
628 Barrbal_Dr  25  5   130 25.3
1092    Barrbal_Dr  25  5   180 25.4
1093    Barrbal_Dr  25  5   250 25.5
600 Bayil_Dr    27  2   120 27.2
601 Bayil_Dr    27  2   0   27.1

We would need to group by location and then for each group get an ascending list of the Start_Chainage and then insert 1-x to the location value to get Location.Segment#
Is this possible purely in SQL or do I need to use Python?
==== UPDATED code example based on QuestionGuyBob's suggestions
select ROW_NUMBER () OVER (
    PARTITION BY Location
    ORDER BY Start_Chainage
    ) RowNum, Location, RoadMntnc, Segments,
 CAST(Location as VARCHAR(30))+ '.'+Cast(RowNum as VARCHAR(30))  AS Segment_ID
    from test_simple_roads

Gives an error
Query preparation error on PRAGMA table_info(_tview): no such column: RowNum

If I change RowNum to another field it doesn't concatenate but is adding the two integers

If I change it to concat it works but I still can't use RowNum or Row_Number as i get the same error (no such column).
concat(Location, '.',RowNum)  AS Segment_ID

A: It looks like you will want to use ROW_NUMBER() windowing function.  I looked at the documentation and it does support it.
https://www.sqlite.org/windowfunctions.html#built_in_window_functions
What you will most likely want to do is to "ROW_NUMBER() OVER (PARTITION BY LOCATION ORDER BY FID) AS RN" in a sub-select.  Then cast the RN to a varchar and concat it to location.  Something like "CAST(Location as VARCHAR(30)) + '.' + CAST(RN AS VARCHAR(30)) AS Segment_ID
    SELECT
    *
    ,CAST(Location as VARCHAR(30))+ '.'+Cast(RowNum as VARCHAR(30))  AS Segment_ID
FROM
    (
    SELECT
    ROW_NUMBER () OVER (
    PARTITION BY Location
    ORDER BY Start_Chainage
    ) RowNum, Location, RoadMntnc, Segments

    from test_simple_roads) AS TEST


text:
Q: lualatex: change font for specific characters (IPA) [U+0250 , U+02AF] globally Im using lualatex.
My tex file contains the character ɛ as well as:
\newfontfamily\ipafont{Doulos SIL}
\DeclareTextFontCommand{\textipafont}{\ipafont}

Now I can do s.t. like:
\textipafont{ɛ}

to render that char correctly.
But: How can I define globally that all chars within [ U+0250 , U+02AF ] are surrounded by \textipafont?
The best case would be: I type ɛ and latex changes automatically the font to Doulos SIL for that character.

A: You can make the chars active and give them a definition:
\documentclass[12pt]{book}
\usepackage{fontspec}
\newfontfamily\ipafont{Doulos SIL}
\DeclareTextFontCommand{\textipafont}{\ipafont}

\usepackage{newunicodechar}
\newunicodechar{ɛ}{\textipafont{ɛ}}
\begin{document}
abc ɛ
\end{document}

You can also define the font as a fallback (the color is only there for the demo). It is a bit experimental, see the luaotfload documentation for details
\documentclass[12pt]{book}
\usepackage{fontspec}

\directlua
{luaotfload.add_fallback
 ("ipafallback",
  {
   "DoulosSIL:mode=node;color=FF0000;"
  }
 )
}

\directlua
{luaotfload.add_fallback
 ("ipafallbackslanted",
  {
   "DoulosSIL:mode=node;slant=0.2;color=FF0000;"
  }
 )
}

\setmainfont{LatinModernRoman}[%
 RawFeature={fallback=ipafallback},
 ItalicFeatures={RawFeature={fallback=ipafallbackslanted}}
 ]

\begin{document}

blub hɛˈləʊ wɜːld

\large blub hɛˈləʊ wɜːld

\itshape blub hɛˈləʊ wɜːld

\end{document}


text:
Q: LaTeX equation/align formating issue This doesn't seem to work
\begin {align}
f(x^2-3x+2}+2f(x^2+x)&=9x^2-3x-6 \\
-f{2x^2-2x)-4f(x^2-3x+2)&=-18x^2+30x \\
-3f(x^2-3x+2)&=-9x^2+27x-6 \\
f(x^2-3x+2)&=3x^2-9x+2
\end {align}

Can anyone help? Thanks!

A: You twice put braces where you meant brackets: line 1 has } and line 2 has {.  This works:
\begin {align}
f(x^2-3x+2)+2f(x^2+x)&=9x^2-3x-6 \\
-f(2x^2-2x)-4f(x^2-3x+2)&=-18x^2+30x \\
-3f(x^2-3x+2)&=-9x^2+27x-6 \\
f(x^2-3x+2)&=3x^2-9x+2
\end {align}


text:
Q: Button click event not working in Titanium I am new to Titanium appcelerator programming.My doubt is button click is event is working well in first screen after that when I click that button go to second screen.Second screen consisting of one button ,when I click that button it navigates to third screen .But button click event is not working in second screen.
I wrote the same code in two screens as follows:
Please tell where I did mistake.
First Screen:
Ti.include("Files/MainScreen.js");
var win = Titanium.UI.createWindow({
  title:'My Window',
  backgroundColor:'#cccccc'
});
win.open();

var itemView = Titanium.UI.createView({
    title:'',
    backgroundImage:'splash.png',
    height:'768',
    width:'1024'
});

// Eventlistener
itemView.addEventListener('click',function(e) {

   var newWindow = Ti.UI.createWindow({
        background : "#000",
        title : "Image View",
        url:"Files/MainScreen.js"
    });
    newWindow.open(win,{animated:true});
});
win.add(itemView);
win.orientationModes=[Titanium.UI.LANDSCAPE_LEFT];
win.open();

MainScreen.js:

Ti.include("CustomerScreen.js");
var win = Titanium.UI.createWindow({
  title:'My Window',
  backgroundColor:'#cccccc',
  leftNavButton:btnCancel
  });

  var btnCancel = Titanium.UI.createButton({
    title:'Cancel'
});
var image = Ti.UI.createImageView({
  image:'main_screen.png'
});
win.add(image);
win.open();

var custbutton=Titanium.UI.createButton({
    title:'customer',
    top:200,
    bottom:300,
    left:90,
    height:'235',
    width:'235',
    backgroundColor:"#000"
});
custbutton.addEventListener('click',function alertingcustomer () {
var newWindow1 = Ti.UI.createWindow({
        background : "#000",
        title : "",
        url:"Files/CustomerScreen.js"
    });
   newWindow1.open(win,{animated:true});
});

win.add(custbutton);
win.open();

CustomerScreen.js
var win = Titanium.UI.createWindow({
  title:'Window',
  backgroundColor:'#cccccc',
  modal:true
});
win.open();

A: Try the following code. I have created a sample application from your code. Try it out
app.js
var win = Titanium.UI.createWindow({
  title:'My Window',
  backgroundColor:'#cccccc'
});

var itemView = Titanium.UI.createView({
    title:'Splash screen',
    backgroundColor:'yellow',
    height:'768',
    width:'1024'
});

// Eventlistener
itemView.addEventListener('click',function(e) {
   var newWindow = Ti.UI.createWindow({
        background : "#000",
        title : "Image View",
        url:"MainScreen.js",
        backgroundColor:'#cccccc',
        leftNavButton:btnCancel
    });
    newWindow.open(win,{animated:true});
});
var btnCancel = Titanium.UI.createButton({
    title:'Cancel'
});
win.add(itemView);
win.orientationModes=[Titanium.UI.LANDSCAPE_LEFT];
win.open();

MainScreen.js
var win = Ti.UI.currentWindow;
win.title = 'My Window';

var image = Ti.UI.createImageView({
  backgroundColor:'red'
});

win.add(image);

var custbutton=Titanium.UI.createButton({
    title:'customer',
    top:200,
    bottom:300,
    left:90,
    height:'235',
    width:'235',
    backgroundColor:"#000"
});
custbutton.addEventListener('click',function alertingcustomer () {
    var newWindow1 = Ti.UI.createWindow({
        title : "Customer screen",
        url:"CustomerScreen.js",
        title:'Window',
        backgroundColor:'#cccccc',
        modal:true
    });
   newWindow1.open(win,{animated:true});
});

win.add(custbutton);

CustomerScreen.js
var win = Ti.UI.currentWindow;
//Do stuff here

There are a lot of things you have to notice.

*

*It is wrong approach include a file in another file and opening a window which has property url set to included file.

*Opening a window multiple time is a wrong approach[You have written win.open() twice in the firts file, it is trying to open same window]

*You're opening a window using url property, it'll be better to use Ti.UI.currentWindow property than creating a new window inside that.


text:
Q: scheduling a cron job to run a script that pings an IP address and save it to a log file I wrote a shell script that ping once an IP address and echoes the results of the ping with the addition of the date command.
If I run the script by my self it works just fine and I can also save the script's results to a file with the >> operator like this:
script.sh >> log_file.
The problem starts when I scheduling it in the crontab editor then only the date command result is saved to a file without the ping result.
my script is:
#!/bin/zsh
echo $(date +"%T %D")
ping -c1 google.com | while read replay
do
 echo $replay
done

and the corn job is:
* * * * * ~/new_scrip.sh >> /tmp/plog

A: Since you use -c1, thus do only 1 ping anyway, you do not need the while part. So you could modify new_script.sh like this:
#!/bin/zsh
echo $(date +"%T %D")
ping -c1 google.com

Then in crontab:
* * * * * /home/YOURUSER/new_scrip.sh >> /tmp/plog

Since cron runs under the root user, ~ expansion will not expand to your user, it will expand to root's home directory.  Therefore in crontab entries, you should put the complete path.
Another "trick" with crontab entries is to capture errors.
* * * * * /home/YOURUSER/new_scrip.sh >>/tmp/plog 2>>/tmp/errors

Any failure will be easy to pinpoint, if ever.


text:
Q: Merge two different dataframes I want to merge two different dataframe which the second one has some rows to complete in the first one.
df4 = pd.DataFrame({'a':['red','green','yellow','blue'],'b':[1,5,6,7],'c':[1,7,8,9]})
df5 = pd.DataFrame({'a':'red','b':44, 'c':55}, index=[0])
print(pd.merge(df4,df5, how='left', on='a'))

Output

     a    b_x   c_x  b_y    c_y
0   red     1   1   44.0    55.0
1   green   5   7   NaN NaN
2   yellow  6   8   NaN NaN
3   blue    7   9   NaN NaN

Expected Output

    a      b    c
0   red    44   55
1   green   5   7
2   yellow  6   8
3   blue    7   9

A: Replace - with np.nan and use combine_first:
df4.replace('-',np.nan,inplace=True)
df4.combine_first(df5)

prints:
        a     b     c
0     red  44.0  55.0
1   green   5.0   7.0
2  yellow   6.0   8.0
3    blue   7.0   9.0

A: Concatenate and drop duplicates by column 'a'.
print(pd.concat([df5, df4]).drop_duplicates(['a'], keep='first'))

A: You can use DataFrame.update:
df4.update(df5)

Output:
>>> df4
        a     b     c
0     red  44.0  55.0
1   green     5     7
2  yellow     6     8
3    blue     7     9


text:
Q: Entity Framework - Can't seem to load related entities I'm a bit of an EF newb and I'm using .net core and I just can't seem to load the related entities of an entity unless I do a full-fledged "from..in..join" linq statement.
My entities have Guid primary keys and I'm using SQL Server as a DB.
Let's look at one entity that I'm having trouble with.
[Table("User")]
public class User : AuditableEntity
{
  public Group CurrentlySelectedGroup { get; set; }
}

[Table("Group")]
public class Group : AuditableEntity
{
  public string Name { get; set; }
}

A user can pick one group as their "selected" group. I ran the migration statement and sure enough it created exactly what I wanted on the DB - a brand new column called CurrentlySelectedGroupId that was a FK to the Group table's PK column.
So this looks great.
I then ran some code that added a valid Guid for a valid group into the table.
Now when I execute this line of code:
 var user = _dbContext.Users.Where(u => u.Id == userId).FirstOrDefault();

It returns my user perfectly, but all the related entities are null.
I've even tried things like .Include(), including 'virtual', but no luck.
Any idea what I'm doing wrong?
Thanks!

A: After much trial and error, it seems the following works:
  var user = _dbContext.Users.Single(u => u.Id == userId);
  _dbContext.Entry(user).Reference(u => u.CurrentlySelectedGroup).Load();

Any ideas why this would work yet not anything else?
Thanks

A: Lazy loading is not enabled, this feature was included in EF Core 2.1. In your case Explicit Loading is happening so you need to explicitly load the related entities. So If you are using EF Core 2.1, you can just enable the Lazy Loading and use related entities without explicitly adding them.

A: try
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class User
{
  [ForeignKey("CurrentlySelectedGroupId")]
  public Group myGroup { get; set; }
}

=================
var user = _dbContext.Users.Where(u => u.Id == userId).Include(u => u.myGroup).FirstOrDefault();


text:
Q: Concatenating an int to a string in Objective-c How do I concatenate the int length to the string I'm trying to slap into that array so it is "C10" given length == 10, of course. I see @"%d", intVarName way of doing it used else where. In Java I would of done "C" + length;. I am using the replaceObjectAtIndex method to replace the empty string, "", that I have previously populated the MSMutableArray "board" with. I am getting an error though when I add the @"C%d", length part at the end of that method (second to last line, above i++).
As part of my homework I have to randomly place "Chutes" (represented by a string of format, "C'length_of_chute'", in this first assignment they will always be of length 10 so it will simply be "C10") onto a game board represented by an array.
   -(void)makeChutes: (int) length {// ??Change input to Negative number, Nvm.
    //??Make argument number of Chutes ??randomly?? across the board.
    for(int i = 0; i < length;){
        int random = arc4random_uniform(101);
        if ([[board objectAtIndex:random] isEqual:@""]) {
            //[board insertObject:@"C%d",length atIndex:random];
            [board replaceObjectAtIndex:random withObject:@"C%d",length];
            i++;
        }
    }
}

Please ignore the extra and junk code in there, I left it in for context.

A: In Objective-C the stringWithFormat method is used for formatting strings:
NSString *formattedString = [NSString stringWithFormat:@"C%d", length];
[someArray insertObject:formattedString];

It's often easier to create your formatted string on a line of its own in Objective-C, since as you can see the call can be fairly verbose!


text:
Q: Join two tables with no link - i.e. primary key in SQL Server Management Studio I would like to know how to query two tables with no primary key link. The tables are from the same database and I need to match treenotediscription to employeeid so the results come back true at the moment I'm getting a lot of duplicate and untrue values, I think this is because of no link. Any help would be appreciated.
SELECT DISTINCT
    EMPLOYEE.EMPLOYEECODE,
    TREENODEDESCRIPTION.TREENODEDESCRIPTION2
FROM
    EMPLOYEE
CROSS JOIN
    TREENODEDESCRIPTION
ORDER BY
    EMPLOYEE.EMPLOYEECODE

A: What you are getting is a Cartesian join returning all rows. Regardless of primary or foreign keys, you need to specify which columns to join on.
Check out this article for more information about joins:
http://www.codeproject.com/KB/database/Visual_SQL_Joins.aspx

A: In a CROSS JOIN every single record in one table is joined ot every single record in the other table.  If each table has 10 records, this gives 100 resulting matches.
A more common join is an INNER JOIN...
SELECT DISTINCT
  employee.EmployeeCode,
  TreeNodeDescription.TreeNodeDescription2
FROM
  Employee
INNER JOIN
  TreeNodeDescription
    ON Employee.EmployeeID = TreeNodeDescription.TreeNodeDescription2

You specify how you want to relate the tables yourself, the existance of Foreign or Primary Keys doesn't automate this for you.  They merely serve to enforce certain rules on the database, to keep it in a consistent state.

A: First, there's no requirement to have a relational link on columns to perform a join.  Joins are based on boolean conditions.  If the boolean condition is true, then the join happens.
That said, I suspect your real problem here is the type of join you are using.  A CROSS JOIN will join every match on both sides against every other match.  Depending on what you're after, you are more likely to need an INNER or LEFT join.

A: Just JOIN on the common field - no FK or other relationship needed!!
SELECT DISTINCT
     e.EmployeeCode,
     t.TreeNodeDescription2
FROM
    dbo.Employee e
INNER JOIN
    dbo.TreeNodeDescription t ON e.EmployeeID = t.TreeNodeScription
ORDER BY
    e.EmployeeCode