text:
Q: how to put every
* in a new line? I am making a review section for an item on my website, so to put the reviews and comment section, I used

 Comment code

 Comment code

inside the li items, there are divs inside divs. I made all the comments section as I like and everything is good.
The only problem I have is the comments ( li items) is in line with each other. I tried using
.review_bottom li{
    list-style: none;
    display: block;
}

but it did not change anything. I can fix it with br tags, but I can't because the br will either work on PC or Phones, it can't work perfectly with both.
Any recommendations?

A: The solution is to insert a line break after each item of the list.

.review_bottom li {
  list-style: none;
}
.review_bottom li:after {
  content: "\A";
  white-space: pre;
}

    Comment code

    Comment code

A: You need to apply your class to your list:

.review_bottom {
margin: 0;
padding :0;
    list-style: none;
}

.review_bottom li {
float: left;
display: inline-block;
}

 Comment code

 Comment code

A:

 Comment code

 Comment code

This is all you need for the Html code


text:
Q: How to pack properly in this Tkinter script? I'm learning about Tkinter and trying to create a normal looking chat style window. However, when resizing the window there are some unexpected results, such as a gray frame appearing between the items, despite setting expand=1.
Also how can I set it so the space is shared when resizing the window to be smaller than the original?
Here is my code:
from Tkinter import *

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        frame = Frame(self, relief=RAISED, borderwidth=1)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.msgfield = Text(self, wrap=WORD, yscrollcommand=scrollbar.set)

        self.msgfield.pack(side=TOP, fill=BOTH, expand=1)
        self.msgfield.config(state=DISABLED)

        self.inputbox = Text(self, height=2, width=30)
        self.inputbox.pack(fill=BOTH, side=BOTTOM, expand=0)
        self.inputbox.bind('<Return>', self.retrieve_input)

        frame.pack(fill=BOTH, expand=1, side=BOTTOM)
        self.pack(fill=BOTH, expand=1, side=TOP)

    def retrieve_input(self, event):
        msg = self.inputbox.get(1.0, END)[:-1]

        self.msgfield.config(state=NORMAL)
        self.msgfield.insert(END, msg)
        self.msgfield.see(END)             # Scroll if necessary
        self.msgfield.config(state=DISABLED)
        self.inputbox.delete(0.0, END)

def main():
    root = Tk()
    root.geometry("300x400+300+300")
    app = Example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

A: The issue is that you are packing both your msgfield and inputbox into self instead of frame, and self is the Tk instance which acts a bit different than a Frame. Try packing into your frame and I think you'll get the behaviour you want (note I added a black border to the Text widget so I could see it):
from Tkinter import *

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        frame = Frame(self, relief=RAISED, borderwidth=1)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.msgfield = Text(frame, wrap=WORD, yscrollcommand=scrollbar.set)

        self.msgfield.pack(side=TOP, fill=BOTH, expand=1)
        self.msgfield.config(state=DISABLED)

        self.inputbox = Text(frame, height=2, width=30, borderwidth=2)
        self.inputbox.config(highlightbackground="Black")
        self.inputbox.pack(fill=BOTH, side=BOTTOM, expand=0)
        self.inputbox.bind('<Return>', self.retrieve_input)

        frame.pack(fill=BOTH, expand=1, side=BOTTOM)
        self.pack(fill=BOTH, expand=1)

    def retrieve_input(self, event):
        msg = self.inputbox.get(1.0, END)[:-1]

        self.msgfield.config(state=NORMAL)
        self.msgfield.insert(END, msg)
        self.msgfield.see(END)             # Scroll if necessary
        self.msgfield.config(state=DISABLED)
        self.inputbox.delete(0.0, END)

def main():
    root = Tk()
    root.geometry("300x400+300+300")
    app = Example(root)
    app.mainloop()

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wired character in zsh I have problem with zsh at command line for non English language
but after enter key the language show the right word, try on OSX have same issue too.
~
❯ สว<0e31>สด<0e35>
สวัสดี
zsh: command not found: สวัสดี

i was check the locale everything is utf8
locale
LANG=en_US.UTF-8
LANGUAGE=en_US
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

and check if any fonts, it's have same problem.
i use zsh version 5.0.2 and oh-my-zh

A: You could do setopt combiningchars.

COMBINING_CHARS
Assume that the terminal displays combining characters correctly. Specifically, if a base alphanumeric character is followed by one or more zero-width punctuation characters, assume that the zero-width characters will be displayed as modifications to the base character within the same width. Not all terminals handle this. If this option is not set, zero-width characters are displayed separately with special mark-up.
-- zshoptions(1) COMBINING_CHARS


text:
Q: How to compute unpolarized cross section for $e^−+\gamma \to e^−+\pi$ I need some help with this calculation. I have already made a few attempts but, even applying Feynman's rules for QED on the first vertex and for Yukawa interaction on the second one, I cannot figure out the various indexes.
The full calculation is not needed. I just need to have the correct setting of the reduce matrix amplitude.
Thank you so much!
Lagrangian:
$\mathscr{L} = -\frac{1}{2}\partial_\mu\phi\partial^\mu\phi -\frac{1}{2}m_\pi^2\phi^2 + \bar{\psi}(i\gamma^\mu \mathscr{D}_\mu - m_e + \lambda\phi)\psi - \frac{1}{4}F_{\mu\nu}F^{\mu\nu} + \mathscr{L}_{gauge-fixing}$
Feynman rules found:
$\mathscr{L}_{Yukawa} = \lambda\phi\bar{\psi}\psi$
from 3-point correlation function
$G^{(3)}(x_1,x_2,x_3) = \frac{1}{Z[0,0,0]}{\displaystyle \int}\mathcal{D}\phi\mathcal{D}\bar{\psi}\mathcal{D}\psi \ e^{iS_0[\phi,\bar{\psi},\psi]} \ \phi(x_1)\bar{\psi}(x_2)\psi(x_3) \ \left[1 + i\lambda{\displaystyle \int}dy \ \phi(y)\bar{\psi}(y)\phi(y) \right]$
using Wick and LSZ, the rules are:

*

*$i\lambda$ for each vertex;

*$\frac{i}{p^2 - m_\pi^2}$ for each $\pi$ propagator;

*$\frac{i}{\gamma^\mu p_\mu - m}$ for each $e$ propagator;

*$u_s$ for each incoming electron;

*$\bar{v_s}$ for each incoming positron;

*$\bar{u_s}$ for each outgoing electron;

*$v_s$ for each outgoing positron.

$\mathscr{L}_{QED} = -ie\bar{\psi}\gamma^\mu\mathcal{A}_\mu\psi$
after similar steps:

*

*$-ie\gamma^\mu$ for each vertex;

*$\frac{-i\eta_{\mu\nu}}{p^2}$ for each e.m. propagator;

*$\frac{i}{\gamma^\mu p_\mu - m}$ for each $e$ propagator;

*$u_s$ for each incoming electron;

*$\bar{v_s}$ for each incoming positron;

*$\epsilon_\mu^*$ for each incoming photon;

*$\bar{u_s}$ for each outgoing electron;

*$v_s$ for each outgoing positron;

*$\epsilon_\mu$ for each outgoing photon.

The question is:
How can I put all this together to correctly calculate the amplitude for the scattering $e^−+\gamma \to e^−+\pi$?


text:
Q: PHP: RegEx fails to match on HTML page retrieved using file_get_contents         $url = "http://steamcommunity.com/profiles/7656119XXXXXXXXX/";
        $content = file_get_contents($url);
        $regExd = '/
\n\s+.?<a href=\"(steam.+?)\"[\s]class=\".+\"/i';
        $a = preg_match($regExd, $content, $matches);

        var_dump($a);

I am trying to retrieve a html from page using get_file_contents and then find specific URL from page using RegEx that I built here: https://regex101.com
I tried copying whole HTML source code from file_get_contents return and paste it into tester on that website and it worked perfectly but using my code - it fails to find any matches even though URL searched for is 100% on page.
HTML contents of return from get_file_contents:

                        Join Game

That's how it comes back, messed up with white spaces etc.. but if I test my regex rule on tester - it still works fine.
I know the URL is empty but that doesn't matter, its supposed to return steam:// in this case.

A: Okay nevermind, apparently I am an idiot, I went over documentation for regex and found issue.
I am not supposed to store preg_match in a variable, it generates array instead $matches.


text:
Q: What is the best way to make the output of one stream the input to another I'm wondering if there is a better/inbuilt way, other than using a byte buffer and looping, to read from one stream and write it to another (in .NET). Generally this is done to apply a transform to a stream and move it on.
In this instance, what I am loading a file, putting it through a deflate stream and writing it out to a file (Error handling removed for simplicity):
byte[] buffer = new byte[10000000];
using (FileStream fsin = new FileStream(filename, FileMode.Open))
{
    using (FileStream fsout = new FileStream(zipfilename, FileMode.CreateNew))
    {
        using (DeflateStream ds = new DeflateStream(fsout, CompressionMode.Compress))
        {
            int read = 0;
            do
            {
                read = fsin.Read(buffer, 0, buffer.Length);
                ds.Write(buffer, 0, read);
            }
            while (read > 0);
        }
    }
}
buffer = null;

Edit:
.NET 4.0 now has a Stream.CopyTo function, Hallelujah

A: There's not really a better way than that, though I tend to put the looping part into a CopyTo extension method, e.g.
public static void CopyTo(this Stream source, Stream destination)
{
    var buffer = new byte[0x1000];
    int bytesInBuffer;
    while ((bytesInBuffer = source.Read(buffer, 0, buffer.Length)) > 0)
    {
        destination.Write(buffer, 0, bytesInBuffer);
    }
}

Which you could then call as:
fsin.CopyTo(ds);

A: .NET 4.0 now has a Stream.CopyTo function

A: Now that I think about it, I haven't ever seen any built-in support for piping the results of an input stream directly into an output stream as you're describing. This article on MSDN has some code for a "StreamPipeline" class that does the sort of thing you're describing.


text:
Q: Emitter Resistor Why is there a voltage drop of 2v across the C/E in the following circuit (XMM2)? I thought that a transistor behaves like a variable resistor, in that when you apply 0.7v across the base, it's like the resistance across the C/E goes to zero.
So I was expecting the 6v to be mostly dropped across R1 and R2.
Note : This is an amplifier circuit that I took from one of the books I am trying to learn electronics from. I was just seeing if I could explain the values I was seeing in the simulation.

A: The voltage across R2 rises when the collector current increases so it counteracts the base current.
Transistor dude (as seen in Win Hill & Horowitz's Art of Electronics) only sees the base current resulting from the voltage at the base relative to the emitter.

As an approximation (and if the divider on the base is low enough resistance, the transistor is high gain and is in the active region), the base current is close to zero, so Vb = 6V* R4/(R3+R4) or about 1.72V.
The base will load this (Ib= Ic/hFE), so it will actually be less. The emitter voltage will be about 0.7V less than the base (about 1V), so the emitter (and thus collector) currents will be around 1mA. Which means the collector voltage will be about 6V - 3V = 3V. Checking, the Vce is thus about 2V which is far from saturation. And, in this case, the numbers match the simulation quite well.
If you increased the base divider values by (say) 10:1 the estimate would not be as accurate because the base current would load the divider much more heavily.

A: Although the variable resistance analogy is not really valid in this case (it is a BJT and that transistor is in the active region), the overarching issue would still remain. You have the transistor in a negative feedback configuration.
The current through the transistor circulates through R2, which reduces the transistor's Vbe, which reduces the current through the transistor.

A: Vbe is about 0.62V for this device model under these conditions as we can see from the base voltage (1.63V - 1.009V dropped across R2).
It is best to think of a bipolar junction transistor as a part which adjusts its emitter current to try to maintain ~0.6-0.7V (give or take) across the base/emitter junction (Actually this is very much 'lies to children', but don't worry about it yet). The base current is generally small compared to the collector current when operating in the linear region.
R2 provides negative feedback by developing a voltage across itself proportional to the current flowing in it, this voltage is clearly subtracted from the base voltage to give the difference Vbe which is what the transistor is trying to maintain.
We have 1.63V on the base, so the emitter will be at about 1V, which given R2 is 1k (This resistor is referred to as the emitter degeneration resistor in some of the literature) will give an emitter current of ~1mA. Beta is large so Ic ~= Ie, giving a collector current of about 1mA, which will develop ~3V across the 3k of R1, which leaves ~2V across the transistor itself.
Look mum, no Spice!
One of the nice things about this circuit is that its performance is substantially independent of device beta and also of small changes in Vbe (which is NOT stable with temperature), the feedback means that these things have little effect on either the bias point or circuit gain.

A: You need to think about this diagram.

Noice how the bipolar becomes a (poor) constant current source, that current SET BY THE EMITTER RESISTOR in you circuit, once the Vce is 2 volts or more.
By the way, these lines are drawn with constant slope, and these lines intercept at some (imaginary negative ) voltage we call the EARLY voltage, or Vearly.

A: Perhaps the shown diagram can help to explain the role of the emitter resistor.
As one can see, the (unwanted) variation of the collector current caused by temperature changes can be kept much smaller (if compared with the case RE=0, vertical stabilization line).
Regarding uncertainties in the DC current gain B a similar effect can be observed (second figure: Variation in B causes only little changes in Ic if the slope of the line is small).
However, it is worth mentioning that in both cases it is the Voltage Vbe which determines the value of Ic - in accordance with Shockleys famous exponential reöationship Ic=f(Vbe).


text:
Q: redirect to route protected with middleware laravel I have dashboard protected with guest middleware and I want to display a dashboard for every employer with the ID but I don't know how to get the ID in guest middleware I tried some solutions from stackoverflow but the ID returned is null
public function handle($request, Closure $next, $guard = null,$id)
{

    $employer=Employer::find($id);
    if (Auth::guard($guard)->check())
        return redirect('/home');
      if(Auth::guard('job_seeker')->check())
      return redirect('job_seeker/profile');

      if(Auth::guard('employer')->check())
      return redirect('employer/dashboard',$employer);

    return $next($request);
}

    //web.php
    Route::get('/dashboard/{id}','Employer\Dashboard_Controller@show_dashboard')->name('employer/dashboard');

class Dashboard_Controller extends Controller
{
    public function __construct(){

        $this->middleware('auth:employer');

    }

    public function show_dashboard($id){
        // $locations=Location::all();
        // $categories=Category::all();
        $employer=Employer::find($id);
        return view('employer.dashboard',compact('employer'));
    }

}


text:
Q: Apache Strom upgrade from 1.0.3 to 2.2.0 and not all workers are used I am upgrading from Apache Storm 1.0.3 to 2.2.0 and facing a peculiar issue where the topology tasks are not running on all the workers and is only running on the same worker as the Spout.
I am using shuffleGrouping and have configured 6 workers and a total of 51 executors among 2 bolts and 1 spout. When I start the topology all 6 the workers are started as expected but only the one worker with the spout is doing all the work.
Do I need any special configuration for 2.2.0, all my topologies are working fine with version 1.0.3
As a test I am also running the ExclamationTopology from Strom-starter but seeing the same issue of only one worker doing all the work.
Thanks in advance for any help.
Regards,

A: When upgrading to storm 2.0.0 I was baffled by the behavior you have observed as well. The reason lies within the shuffleGrouping which you are using. According to the storm performance guide:

*Load Aware messaging

When load aware messaging is enabled (default), shuffle grouping takes additional factors into consideration for message routing. Impact of this on performance is dependent on the topology and its deployment footprint (i.e. distribution over process and machines). Consequently it is useful to assess the impact of setting topology.disable.loadaware.messaging to true or false for your specific case.

This leads to the spout delegating all tuples to the same worker it finds itself on. To fix it and to go back to the old behavior, in your topology, set topology.disable.loadaware.messaging to true, e.g. with
conf.put("topology.disable.loadaware.messaging", true);


text:
Q: Where did the 1920s slang word "grungy" (meaning "envious") originate, if the modern word "grungy" (meaning "dingy") doesn't appear until 1965? I've heard grungy used to mean envious in old motion pictures and books. Here is one reference, and there are several more on the internet.
However, when I researched the etymology of the word grungy online, I only found this:

grungy (adj.)
  "sloppy, shabby," 1965, American English slang, perhaps a blend of grubby and dingy.
  grunge (n.)
  "sloppiness," also "untidy person," 1965, American English teen slang, probably a back-formation from grungy. The music and fashion style that originated in Seattle is attested from the early 1990s.

The dates given are considerably later than the 1920s. I'm curious to know if anyone has any idea where the word grungy from the 1920s could have originated to mean envious.

A: I found this in The English Dialect Dictionary: Being the Complete Vocabulary of All Dialect Words Still in Use, or Known to Have Been in use During the Last Two Hundred Years, published in London in 1900, and which I am totally bookmarking:
GRUNGY, sb. [apparently "subject," or noun] Sc. [Scottish?] A deep revengeful feeling; a grudge.
The supplied example sentence:
Abd. [Aberdeen?] An' he aye had a grungy efter 't at Bruce.
This suggests to me that grungy evolved directly from grudge, probably due to its similar sound, and later took on the clearly related "envious" meaning as an adjective.

A: I've divided my answer into three parts, addressing three epochs in the real or imagined life of the words grunge and grungy. In brief, the nineteenth-century usage of grunge seems to have evolved naturally from other, similar dialect words; but it appears to have no obvious connection to or influence on the later manifestations of grunge and grungy. The 1920s usage of grungy is difficult to nail down, since—as far as I can tell—no one on the Internet has yet provided a citation to an instance of that usage in action. And the modern usage of grunge seems to have started a few years earlier than the mid-1960s (the starting time that most references attribute to it), but with no evident connection to the nineteenth-century British usage or to the widely claimed but mysteriously ghostly 1920s-era usage.

Nineteenth-Century Scottish Grunge
The example from Joseph Wright's English Dialect Dictionary that phenry reproduces in his answer can be found rendered at greater length as item 24 on page 775 of Alexander J. Ellis, "The Lowland Division of English Dialect Districts, Being Chiefly Those Lying in Scotland: The Mid North Lowland; Third Example. The Fight," in On Early English Pronunciation with Especial Reference to Shakspere and Chaucer (1889), where the author translates the relevant excerpt as follows:

She [Miss Elizabeth Gray] promised first to one, and then to another, to allow them to accompany her home, and when away-going time came, [Jock] Shanks had her at the door setting out, but [James] Bruce was sitting there, and the sly (faithless) coquette took a nip of his whiskers on the going past, and he got up to his feet, and the loving little girl swung herself out of Shanks' plaid, and clutched Bruce by the arm, and went off with him, and fairly gave the slip to Shanks, and he always had a deep revengeful feeling after it at Bruce.

The last clause of the translation deals with (approximately) this original wording:

en hii a'i ha'd y gruuqsi efter't) at :bris.

Ellis's footnote to the translation then observes:

—deep revengeful feeling, the nearest word to grungy in Jamieson is "grunye, promontory, mouth ludicrously, a grunt." After this Mr. Innes [who provided the examples and translated them] adds, "The narrative here enters on another subject, and I believe you have had more of it than can be of interest to you. I shall there fore not follow it further."

I get the impression that the version of the sentence in Wright's dictionary (the one quoted by phenry) is simply another translation of Innes's original example.
In any event, several nineteenth-century Scottish dictionaries provide interesting coverage of grunge and its possible antecedents. First, from John Jamieson, An Etymological Dictionary of the Scottish Language (1818), we have these entries:

To GROUNCH, GRUNTSCH, v. n. 1. To grunt. Ruddiman. 2. To grumble, S.B. Douglas.
To GRUCH, v. n. To grudge. Wyntown.
To GRUMPH, v. n. To grunt, S.
GRUMPH, s. A grunt, S.
GRUMPHIE, s. A vulgar name for a sow, S. Ramsay.
GRUNYE, s. Promontory.
GRUNYIE, s. The mouth, ludicrously, S.
To GRUNTSCH. V[ariant]. GROUNCH.

A more elaborate description of "grounch, gruntsch" appears in the glossary to J. Sibbald, Chronicle of Scottish Poetry (1805):

Grounch, Gruntsch, to grudge, to murmur, to grumble, to express displeasure by protruding the mouth like the snout of a pig. [A]lso, to dig like a swine.

Jameson, A Dictionary of the Scottish Language (1846) retains most of it predecessor's entries and definitions, but it also adds these new entries:

To GROUNGE, GRUNGE, v. a. 1. To look sullen or sulky, Roxb. 2. To grumble, to murmur ; as, "He's aye groungin' about something," ibid. This seems nothing more than a provincial variety of Grounch, Gruntsch.
To GRUNGE, v. n. To look sullen. V[ariant of] Grounge.

And finally, in Johnstone, Jamieson's Dictionary of the Scottish Language (1896), all of the entries remain the same as they were 50 years earlier.
Grunge also shows up in a nineteenth-century publication of the English Dialect Society. From F.M.T. Palgrave, "A List of Words and Phrases in Every-day Use by the Natives of Hetton-Le-Hole, in the County of Durham" (1896):

Grunge. To grunt. 'Grunt' unknown. "they will shew their teeth at you and grunge at you."—Boy's essay.

From these sources, it appears that the nineteenth-century Scottish and English term grunge was closely connected to the grunting and grumbling of pigs, whether by extension from the earlier term grounch, or independently.

Roaring '20s Grunge
I couldn't find any any mention of grunge or grungy in the sense of "enviousness" or "envious" in my Google Books search results. Perhaps more significantly, I couldn't find any mention at all of grunge or grungy in a Google Books search for the years between 1900 and 1958 (aside from a couple of dictionary entries referring to the older Scottish and English dialect meanings discussed above), suggesting that if grunge or grungy existed as a slang term in the 1920s, the term wasn't especially common in published work of the period.
Reinforcing that impression is the fact that more-recent compendiums of slang—most notably Chapman & Kipfer, Dictionary of American Slang, Fourth Edition (2007), which is generally conscientious about reporting earlier senses of slang words—begin and end their coverage of grunge and grungy with the modern senses of the terms. Mr. L. Venier of the Dufferin-Peel Catholic District School Board of Mississauga, Ontario, is the source for "grungy" = "envious" in the OP's citation of 1920s slang, though Mr. Venier seems to have drawn his list verbatim from the 1920s Slang Terms and Definitions page of the Shot in the Dark Mysteries website) or from The Internet Guide to Jazz Age Slang or from one of a number of other echo-chamber pages that dot the Internet.
Unfortunately, each of these sources for 1920s slang usage (except a couple of brave pages that offer "Grungy: jealous") supplies the brief notation "Grungy: envious" and lets it go at that—no citation, no example from a contemporaneous book, nothing else. I did find a December 8, 1996, article by Howard Goodman of the Philadelphia Inquirer titled "That Groovy Lingo Ain't So Happenin' After All," which interviews an "avid logophile" named Tom Dalzell. Dalzell notes that many supposedly new slang terms actually have had earlier incarnations as slang terms, sometimes with very different meanings. The following text appears about two-thirds of the way through the article:

"The real birth of American youth slang was in the '20s, with the flapper," Dalzell says, recalling the gin-guzzling, bob-haired, corsetless free spirit of F. Scott Fitzgerald memory.
"In retrospect, it was kind of dopey and very white," Dalzell says, "but it was a great generation, the first real generation of youth." It's when grungy meant "envious," a holaholy was someone who objected to necking, and when things were good, they were hotsy-totsy.

But Goodman doesn't attribute the "grungy = envious" factoid that he includes in his story to Dalzell, so we don't know whether Dalzell endorses that equivalence or not. And in any event, we  don't have any hard evidence of when and where that usage has been recorded.
I don't find it especially hard to believe that certain hipsters of the 1920s might have used grungy to mean "envious," but I'd like to see some documentation that they did so before I accept the assertion as true. The unattributed, identically worded, skeletal coverage of the subject at other online sites does not inspire confidence in the rigor and authoritativeness of that coverage.

Modern Grunge
The newer meaning of grunge surely antedates 1965. In a Google Books search, I discovered that the term grunge-jumper appears (twice) in Jack Kerouac, The Dharma Bums (1958). Here's the first instance:

Meanwhile, suddenly Japhy's sister Rhoda appeared on the scene with her fiancé. She was going to be married in Japhy's father's house in Mill Valley, big reception and all. Japhy and I were sitting around in the shack in a drowsy afternoon and suddenly she was in the door, slim and blond and pretty, with her well-dressed Chicago fiancé, a very handsome man. "Hoo!" yelled Japhy, jumping up and kissing her in a big passionate embrace, which she returned whole-heartedly. And the way they talked!
"Well, is your husband gonna be a good bang?"
"He damn well is, I picked him out real careful, ya grunge-jumper!"
"He'd better be or you'll have to call on me!"

A note in Gregory Stephenson, "Explanatory Notes to Jack Kerouac's The Dharma Bums*" in Polarity Magazine runs as follows:

grunge-jumper: the word grunge means any nasty substance or a dirty and distasteful person; whereas a jumper is a copulator. Hence, a grunge-jumper is one who is so indiscriminately or so desperately lascivious as to copulate with persons who are unclean or otherwise repellent.

Many instances of grunge and grungy in the sense of something grimy, grubby, dingy, and/or sludgy appear in a Google Books search for matches from the middle to late 1960s and the early 1970s, as you'd expect.
Also of potential interest is this very different sense of grunge cited in John Jones Design Methods (1970) [combined snippets]:

[Robert W.] Mann [in "Engineering Specifications for a Man-Computer System"] (1963) describes the long periods of systematic thinking that are often necessary in designing as 'crank-turning or grunge' and the shorter imaginative periods as 'creative peaks'. The creative peaks of a traditional designer may well be the occasions when he resorts to 'back-of-an-envelope' sketching; his grunge consists mainly of the making of scale drawings and detailed calculations. We may suppose that the skill of knowing when to switch from one to the other is something that a traditional designer develops for himself.

And similarly, we have this snippet from University of Michigan, Engineering Summer Conferences, Applications of Computers to Automated Design (1965):

Much but by no means all, of the methodology and techniques involved in the analytical, lower level, longer duration "grunge" or "crank turning" is very properly relegated to the machine. ... If you will we want our computer-aided design system to change our fanciful "CRO display" of a design process from occasional decision peaks inserted into long periods of noisy "grunge" into a time sequence where the "grunge" period is reduced toward zero and the opportunities for new decisions and judgements based upon analysis occurs again and again with far more possible reiterations, and the consideration of far more alternatives of concept, configuration, parameter values, etc. than is now permitted by limitations of schedule and budget

Here grunge sounds as though it might have different root words—perhaps grind and plunge—from those that underlie the word as it is usually used today.
And finally, in a search of the Elephind newspaper database, I found an early instance of grungy in use in a university setting in a party announcement by "the men of Alpha Chi Rho fraternity in the [University Park, Pennsylvania] Daily Collegian (February 8, 1964):

The Crow swung out to Bellafonte/ to produce some "Milk" and Cheese—/ Brought it back to our abode,/ to welcome our Rushees./ If you should be a Freshman/ Woe to you, dear Friend—/ But don't fret too much, son,/ The world's not at an end.../ (we have sexy Pepsi for you)/ So put on some grungy clothes/ just about anything will go—/ pick up your date and swing on out/ to meet the jolly Crow.


text:
Q: Manually position legend in Patchwork I want to position a legend (common to all plots) in a blank space in a patchwork layout.  From what I can find online I cannot manually position a legend using legend.position if I also use guides="collect" (but can use left, right etc.).
I have tried to use l <- get.legend and then + inset_element(l, 0.6, 0.6, 1, 1) however it doesn't understand l.  I also tried mixing in + inset_element(gridExtra::tableGrob(l)) without luck.
My goal is to place the legend in the blank space.  My actual patchwork plot is more complicated but has two blank spaces I want the legend to sit in.
MWE
library(patchwork)
library(ggplot2)
p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp, color = mpg)) +
  ggtitle('Plot 1')

p2 <- ggplot(mtcars) +
  geom_boxplot(aes(gear, disp, group = gear)) +
  ggtitle('Plot 2')

p3 <- ggplot(mtcars) +
  geom_point(aes(hp, wt, colour = mpg)) +
  ggtitle('Plot 3')

design <- "
1111
223#
"
p1 + p2 + p3  + plot_layout(guides = 'collect') + plot_layout(design=design, guides = "collect")  &
  theme(legend.position = 'right',
        legend.direction = 'vertical')

A: Alter your design object to include a fourth element and use guide_area() to place the guide.
library(patchwork)
library(ggplot2)

design <- "
1111
2234
"
p1 + p2 + p3 + guide_area() + plot_layout(design=design, guides = "collect")


text:
Q: VB.Net Simple Json Edit (Sorry my bad english.)

I installed JSON.Net(Newtonsoft) yesterday.
so i read documents.. examples.. but i cant do anything.
first, here is my json code.
{
    "profiles": {
        "164o": {
            "name": "164o",
            "lastVersionId": "1.6.4-Forge9.11.1.965",
            "launcherVisibilityOnGameClose": "keep the launcher open"
        },
        "BellCraft5": {
            "name": "BellCraft5",
            "gameDir": "C:\\Users\\HideHideHide\\AppData\\Roaming\\.custompacks\\BellCraft5",
            "lastVersionId": "1.6.4-Forge9.11.1.965",
            "javaArgs": "-Xmx2G -XX:PermSize\u003d128m -XX:MaxPermSize\u003d256m",
            "launcherVisibilityOnGameClose": "keep the launcher open"
        },
        "HideHideHide": {
            "name": "HideHideHide",
            "lastVersionId": "1.7.9_kr"
        },
        "TFC": {
            "name": "TFC",
            "gameDir": "C:\\Users\\HideHideHide\\AppData\\Roaming\\.minecraft\\crazy",
            "lastVersionId": "1.6.4-Forge9.11.1.965",
            "launcherVisibilityOnGameClose": "hide launcher and re-open when game closes"
        },
        "Nooby": {
            "name": "Nooby",
            "gameDir": "C:\\Users\\HideHideHide\\AppData\\Roaming\\.custompacks\\172wepsv",
            "lastVersionId": "1.7.2-Forge10.12.2.1121",
            "launcherVisibilityOnGameClose": "keep the launcher open"
        },
        "OswinCraft": {
            "name": "OswinCraft",
            "gameDir": "C:\\Users\\HideHideHide\\AppData\\Roaming\\.custompacks\\OswinCraft",
            "lastVersionId": "1.6.4-Forge9.11.1.965",
            "launcherVisibilityOnGameClose": "keep the launcher open"
        }
    },
    "selectedProfile": "OswinCraft",
    "clientToken": "HideHideHide-18ef-4b3a-a421-HideHideHide",
    "authenticationDatabase": {
        "HideHideHide": {
            "username": "dbcc@abcd.com",
            "accessToken": "HideHideHide",
            "userid": "HideHideHide",
            "uuid": "HideHideHide",
            "displayName": "HideHideHide"
        },
        "HideHideHide2": {
            "username": "abcd@dbcc.com",
            "accessToken": "HideHideHide",
            "userid": "HideHideHide",
            "uuid": "HideHideHide",
            "displayName": "HideHideHide"
        }
    },
    "selectedUser": "HideHideHide",
    "launcherVersion": {
        "name": "1.5",
        "format": 16
    }
}

Yeah, just one of game settings.
i want just make one profiles.
like,
"Test Profile": {
    "name": "Test Profile",
    "gameDir": "C:\\Test",
    "lastVersionId": "Test"
}

Yeah, i tried
Public Class Form
    Private Sub AnySub()
        Dim sJsonObj As JSON_Object = JsonConvert.DeserializeObject(Of JSON_Object)(File.ReadAllText("C:\example.json"))
    End Sub
End Class

Public Class JSON_Object
    Public profiles As Object
    Public selectedProfile As String
    Public clientToken As String
    Public authenticationDatabase As Object
    Public selectedUser As String
    Public launcherVersion As Object
End Class

but i cant.
anyone can help me?
(If you know about serialize it as a file, please teach me.)

A: Deserialize profiles as a Dictionary, and add a new profile to it.
Imports Newtonsoft.Json
Imports System.IO

Public Class Profile
    Public name As String
    Public gameDir As String
    Public lastVersionId As String
    Public javaArgs As String
    Public launcherVisibilityOnGameClose As String
End Class

Public Class JSON_Object
    Public profiles As Dictionary(Of String, Profile) '' Object -> Dictionary
    Public selectedProfile As String
    Public clientToken As String
    Public authenticationDatabase As Object
    Public selectedUser As String
    Public launcherVersion As Object
End Class

Module Module1

    Sub Main()
        Dim sJsonObj As JSON_Object =
            JsonConvert.DeserializeObject(Of JSON_Object)(File.ReadAllText("C:\example.json"))

        ' Add a new profile.
        sJsonObj.profiles.Add("Test Profile", New Profile With {
                              .name = "Test Profile",
                              .gameDir = "C:\Test",
                              .lastVersionId = "Test"
                          })

        ' Serialize to JSON string.
        Dim settings As New JsonSerializerSettings
        settings.NullValueHandling = NullValueHandling.Ignore
        settings.Formatting = Formatting.Indented
        Dim strJson As String = JsonConvert.SerializeObject(sJsonObj, settings)

        ' Write to file.
        File.WriteAllText("C:\your\writable\path\exampleNew.json", strJson)
    End Sub

End Module


text:
Q: How do simulate a class of 100 students? An exam with 20 multiple choice question with P=0.25 how do I simulate a class of 100 students and what is the average of the class of students. If the class is increased to 1000 what happens to the average?
I'm not sure where to begin. Other than just try to solving this manually.
n_experiments<-100
n_samples<-c(1:20)
means_of_sample_n<-c()

hist(rbinom( n = 100, size = 20, prob = 0.25 ))

I'm not sure what to do after this?

A: Well you just have to find a way to set the probability of answering correctly to 0.25, you can do that easily with the generation of a uniform distribution
n_experiments<-100
n_samples<-c(1:20)
means_of_sample_n<-c()

hist(rbinom( n = 100000, size = 20, prob = 0.25 ))

Nstu=100000
Nquest=20

Results=matrix(as.numeric(runif(100000*20)<0.25),ncol=20)

hist(apply(Results,1,sum))
mean(apply(Results,1,sum))

A: from the definition of the binomial distribution:

*

*the mean is defined to be n*p, so mu = 20*0.25, giving a mean of 5.  this is independent of the class size

*the variance is defined to be n*p*(1-p), and the standard deviation is the usual sqrt of this, so sigma = sqrt(20*0.25*0.75), i.e. ~1.94.

*the standard error of the mean is sigma / sqrt(k), where k would be your class size.  so we get SEMs of 0.19 and 0.061 for class sizes of 100 and 1000 respectively

it's often useful to check things via simulation, and we can simulate a single class as you were doing.
x <- rbinom(100, 20, 0.25)
plot(table(x))

I'm using plot(table(x)) above instead of using hist, because this is a discrete distribution.  hist is more suited to continuous distributions, while table is better for discrete distributions with a small number of distinct values.
next, we can simulate things many times using replicate. in this case you're after the mean of the binomial draw:
y <- replicate(1000, mean(rbinom(100, 20, 0.25)))
c(mu=mean(y), se=sd(y))

which happened to give me mu=5.002 and se=0.201, but will change every run.  increasing the class size to 1000, I get mu=5.002 again, and se=0.060.  because these are random samples from the distribution they are subject to "monte-carlo error" but given enough replicates they should approach the analytical answers above.  that said, they're close enough to the analytical results to give me confidence I've not made any silly typos


text:
Q: Is there a class (similar to contentProvider) to interact with jdbc or other databases? I am currently using a contentProvider to work with my SQLite database in Android. At the same time, I am using an online Postgresql database.
I was wondering if there is a similar approach that I can use for interacting with my online database as I do with my local database.
My current approach to make it generic is to pass in a table name, so the code can work with different tables in my database and take specific actions, based on the table:
public static LinkedList<Value> sendToServer(String tableName, LinkedList<Value> values) {
    LinkedList<Values> successfullySentValues = new LinkedList<>();
    switch (tableName) {
        case "tableOne":
            //Do whatever needs to be done in case of tableOne
            //Add the Values that are successfully sent to the database to successfullySentValues
            break;
        case "tableTwo":
            //Do whatever needs to be done in case of tableTwo
            //Add the Values that are successfully sent to the database to successfullySentValues
            break;
        default:
            throw new IllegalArgumentException("UnsupportedTable: " + tableName);
    }
    return successfullySentValues;
}


text:
Q: Basic question on ODEs I may be asking something very basic, but consider the two ODEs
$$
\begin{align}
1.\,\,f'(x)&=af(x)\\
2.\,\,f'(x)&=af(x)+b(f(x))^2
\end{align}
$$
Naturally, if $b=0$, the two ODEs are identical. However, that does not happen with the solution of each. For the first one, we have (computed in Mathematica 13)
$$
f_1(x)=C_1e^{ax}
$$
and for the second
$$
f_2(x)=\frac{ae^{a(x+C_2)}}{1-be^{a(x+C_2)}}
$$
However, when $b=0$,
$$
f_2(x)=ae^{a(x+C_2)}
$$
which does not equal $f_1(x)$. Why is that? Since these work for any constants $C_1,C_2$, do I need to rewrite the solution by solving
$$
f_1(x)=f_2(x)\Leftrightarrow C_1=ae^{aC_2}
$$
What am I missing?

A: There is no contradiction. When in ODE's we use constants these can be arbitrary constants and so we get a family of curves for all values of the constant. If you set
$C=ae^{c_{1}}$ then you again obtain the same family of curves. Constants are NOT fixed. They can take any value in $\mathbb{R}$.


text:
Q: Connect to LDAP with C# I'm trying to figure out how to connect to LDAP via C#.
The only address that I've got is the following:
LDAP://CDS.mycompany.com/o=mycompany.com

I have tried to follow the following guide:
https://msdn.microsoft.com/en-us/library/ms257181(v=vs.90).aspx
But they are using a <user> <pwd> <domain> for the credentials. Which is the domain?
I have also tried this:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://CDS.mycompany.com/o=mycompany.com");

But when I run that, I only get the following:
base {System.Runtime.InteropServices.ExternalException} = {System.Runtime.InteropServices.COMException (0x8007052E): The user name or password is incorrect.

       at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
       at System.DirectoryServices.DirectoryEntry.Bind()
       at System.DirectoryServic...

What username and password is it asking for? I only want to connect to LDAP, and then just specify a username to get data about that user. No password.


text:
Q: How to refresh a list with an ons-carousel when ons-lazy-repeat detects a change I have an ons-list which ons-list-item has the ons-lazy-repeat delegate.
Every ons-list-item has also an ons-carousel element with two indexes (0 and 1).
If I use a for loop to splice the array that is bound to the ons-lazy-repeat delegate the list will be changed to remove the items that were removed from the array but the ons-carousel index stays the same
Example:
<ons-list>
   <ons-list-item id="myList" modifier="chevron" class="item" ons-lazy-repeat="myDelegate">
      <ons-carousel swipeable auto-refresh style="height: 72px; width: 100%;" initial-index="0" auto-scroll>
         <ons-carousel-item class="list-action-item" ng-click="doThis()">
           Some random text
         </ons-carousel-item>
         <ons-carousel-item class="list-action-menu" ng-click="delete(elementId)">
           Remove all items like this one
         </ons-carousel-item>
      </ons-carousel>
   </ons-list-item>
</ons-list>

The delete function is a javascript for loop that will go through the array associated with myDelegate and remove items that don't match the elementId
Example:
for (var i = $scope.myArray.length - 1; i >= 0; i--) {
        var currenElement = $scope.myArray[i];
        if(currenElement.elementId === elementId){
            $scope.myArray.splice(i,1);
        }
};

Which works absolutely fine, the  gets updated and the items are visually removed from the list.
The ons-carousel index however stays 1 for element i of the array, which means that if the element i gets removed the element i+1 in the list that becomes element i will change the index to 1.
an example is available at http://codepen.io/anon/pen/XJOgoa
Try to drag to the left any of the elements and press on delete: you will see that the element gets removed but element i+i is now showing delete (the ons-carousel index="1" instead of 0)
Any help is appreciated.

A: The view is fixed with prev({animation: 'none'}) before removing the element:
$scope.remove = function(index) {
  $scope.carousel[index].prev({animation: 'none'});
  $scope.myArray.splice(index, 1);
};

And well, in your Codepen the delete function is triggered twice. That was a bug but it's now fixed in the latest build of Onsen UI. Working here: http://codepen.io/frankdiox/pen/ByMmwE
Edit:
Created an issue on Github about this.


text:
Q: Correlate days & number of year on Python I need to itinerate the days of the week on the following tuple and assign it to a day of the year (from 1 to 365). I have to do it without transforming the tuple in a list. Of course, my first attempt was to transform the tuple on a list, extend it and use zip() function. Any ideas of how to do it without transforming the tuple with loops?
Thanks a lot!
days = ("lunes","martes","miércoles","jueves","viernes","sábado","domingo")
list_days = list(days)
number = list(range(1,366))
list_compl = list_days*53
list_compl

for j,i in zip(list_compl,number):
    print(i,j)

A: To cycle over the list of days, you can use the cycle function from the itertools package.
import itertools

days = ("lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo")
number = range(1, 366)

for j, i in zip(itertools.cycle(days), number):
    print(i, j)
``

A: An even simpler answer than the one from @thomas_bssnt could be to do this
days = ("lunes", "martes", "miércoles", "jueves", "viernes", "sábado", "domingo")

for i in range(1, 366):
    print(i, days[i%7-1])


text:
Q: SQL Server : columns leaving blank spaces in it I have a problem with a database hosted by Microsoft SQL Server 2008 R2.
I made a table with some varchar(length) columns.
The problem is, when I insert anything in it, it leaves "blank spaces" in the end of the column, messing everything up.
So the columns practically looks like this =
some_value _________

(__ = blanks)
Sometimes the blank spaces are even longer...
And I cannot delete them, cause even when deleting them, they get back in place.
What is it the issue?
Is the varchar(length) too high?
The fact is I cannot set it shorter, cause the value I'm going to insert in the table isn't fixed in length..
Any fix?


text:
Q: How to convert SQL with CAST function to Eloquent I have a problem with this sql.
SELECT wp_posts.*
FROM wp_posts
JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_date > '2017-04-20 23:59:59'
  AND wp_postmeta.meta_key = 'views'
ORDER BY wp_postmeta.meta_value+0 DESC
LIMIT 0, 10

This query return most viewed posts. I want to convert it to Eloquent.

A: Assuming you have set up wp_posts and wp_postmeta modal as said in this tutorial then below query will do the thing for you.
$dp = DB::getTablePrefix();
$order_by = "CAST(" . $dp . "postmeta.meta_value AS unsigned) DESC";
BlogPost::with('postmetas')
    ->where('posts.post_date', '>', '2017-04-20 23:59:59')
    ->where('postmeta.meta_key', 'views')
    ->orderByRaw($order_by)
    ->limit(10)
    ->get();

Hope this helps!


text:
Q: Windows 10 - keyboard settings (properties) reset after restart I have Windows 10 64-bit and usually everything is working fine.
Lately, I have noticed that after restart (for any reason, of course), the keyboard repeat rate resets to its default and I have to go to the keyboard properties window and set it again to what I need.
I have seen the question here about this issue exactly, but the solution there doesn't help me, as it points to a key in the registry that I simply don't have on my PC.
So how do I "force" Windows to keep these settings like it always did, up until a few days ago??...


text:
Q: Automapper "flattening" I am trying to "flatten out" the contents of a source List to fields on the Dest object, as follows:
class Source
{
    public IList<TypeX> TypeXs {get; set;}
}

class Dest
{
    public int IdentifierXValue { get; set;}
    public int IdentifierYValue { get; set;}
    public int IdentifierZValue { get; set;}
}

class TypeX
{
   Identifier Identifier {get; set;}
   float Value {get; set;}
}

enum Identifier
{
    X,
    Y,
    Z
}

Mapping from source to dest works fine using the below mapping:
Mapper.CreateMap<Source, Dest>.ForMember( dest => dest.IdentifierXValue, opt =>     opt.MapForm(src => src.TypeXs.First(f => f.Identifier == Identifier.X).Value));

How do I achieve the reverse mapping? The "Source" reference will already exist and it will have prepopulated references to TypeXs. I just need to search for a TypeX object whose Identifier matches (say X) and for that object I need to replace the value with the IdentifierXValue in the Dest object.

A: This worked for me
Mapper.CreateMap<Dest, Source>()
      .ForMember(d => d.TypeXs, opt => opt.Ignore())
      .AfterMap((s, d) =>
                         {
                          d.TypeXs.First(tx => tx.Identifier == Identifier.X).Value = s.IdentifierXValue;
                          d.TypeXs.First(tx => tx.Identifier == Identifier.Y).Value = s.IdentifierYValue;
                          d.TypeXs.First(tx => tx.Identifier == Identifier.Z).Value = s.IdentifierZValue;
                         }
                );

A: I think you'll need a custom type converter.  That would probably be the easiest way.


text:
Q: Agregar color a una celda de un dataframe si cumplen varias condiciones Tengo el siguiente problema:
Requiero agregar color a unas celdas especificas de los registros que cumplan varias condiciones. Tengo el siguiente dataframe
      Departamento      Municipio       Zona de dificil Acceso
   0            CAUCA    ARGELIA                     NO
   1  VALLE DEL CAUCA       CALI                     NO
   2            CAUCA    POPAYAN                     NO
   3            CAUCA     BALBOA                     NO

Encontré este ejemplo y con esto me estoy basando para resolver mi problema: https://es.stackoverflow.com/questions/193521/agregar-background-a-una-celda-en-funci%c3%b3n-de-una-condici%c3%b3n[1]
En resumidas cuentas, el ejemplo me pide usar pandas.style.apply y crear una pequeña funcion que no me queda del todo clara pero ahí asigna el color:
import pandas as pd
import numpy as np
datos=[["CAUCA","ARGELIA","NO"],["VALLE DEL CAUCA","CALI","NO"],["CAUCA","POPAYAN","NO"],
["CAUCA","BALBOA","NO"]]
df = pd.DataFrame(datos, columns=["Departamento","Municipio","Zona de dificil Acceso"])
listaMunicipios=["ARGELIA","PALOQUEMADO","PAMPLONA"]
color=["red"]

Arriba creo el df de prueba y creo la lista color. Luego copie y pegue la funcion que aparece en el ejemplo:
def funciomAgregarColores(column, bool_masks, color_list, default="white"):
 cond_bg_style = [f'background-color: {color}' for color in color_list]
 default_bg_style = f'background-color:{default}'
 a =  np.select(bool_masks, cond_bg_style, default=default_bg_style)
 print(a)
 return a

Aquí principalmente piden una mascara boolena que es masks y es aquí donde tengo el problema en cara a mi situación ¿Por qué? Bueno, para señalar con color algunas casillas estos registros deben cumplir con dos condiciones:
1.Sí los registros en la columna Municipio estan en la lista listaMunicipios Y además en la columna Zona de dificil Acceso Debe ser NO y el problema esta cuando hago la cimprobacion si el registro tiene municipios que estan en listaMunicipios
masks=[(df.iloc[x,2]=="NO") and (df.iloc[x,1] in listaMunicipios) for x in range(len(df))]

Tengo que usar un for para hacer la comprobación de que registros cumplen con estar en listaMunicipios y la otra condicion no me pone problema. Ya cuando ejecuto la linea me sale todo ok pero cuando ejecuto:
styled=df.style.apply(funciomAgregarColores,subset=["Zona de dificil Acceso"],bool_masks=masks,color_list=color)

Me sale este error cuando imprimo styled:
File ~\anaconda3\lib\site-packages\numpy\lib\function_base.py:666, in select(condlist, choicelist, default)
664 # Check the size of condlist and choicelist are the same, or abort.
665 if len(condlist) != len(choicelist):
666     raise ValueError(
667         'list of cases must be same length as list of conditions')
669 # Now that the dtype is known, handle the deprecated select([], []) case
670 if len(condlist) == 0:

ValueError: list of cases must be same length as list of conditions

Si la mascara fuera más sencilla como
masks2=[df.Municipio=="ARGELIA"]

Me devuelve un objeto de tamaño 1 pero me dice que es una lista pero si con la mascara que utilice me dice que el tamaño es 4 pero es una lista
type(masks)
len(masks)
type(masks2)
len(masks2)

No se que hacer y no veo como cumplir mi tarea ¿Que me recomiendan leer o revisar? Gracias

A: Buen día,
Casi lo logras, el problema es sencillo. Si te das cuenta, en la respuesta original masks es una lista de máscaras o filtros
masks = [data.A >= 0,
        (data.A >= -1) & (data.A < 0),
         data.A < -1
        ]

En este caso tenemos tres filtros o máscaras.
Lo que tu haces aquí:
masks=[(df.iloc[x,2]=="NO") and (df.iloc[x,1] in listaMunicipios) for x in range(len(df))]

Devuelve una sola lista, así:
[True, False, False, False]

Pero lo que necesitas en máscaras es una lista de listas (Filtros/Máscaras) por lo que necesitarías esto:
[[True, False, False, False]]

Si agregas los corchetes externos a tus máscaras de esta forma:
masks = [[(df.iloc[x,2]=="NO") and (df.iloc[x,1] in listaMunicipios) for x in range(len(df))]]

El código ya funciona.
Nota: Al utilizar pandas es recomendable no utilizar ciclos (Por ejemplo for) para iterar en los elementos, hay métodos optimizados que trabajan con el dataset rápida y eficientemente. En la mayoría de los casos, si lo que quieres hacer crees que se puede hacer con un for entonces es el camino incorrecto (O el que va a tardar más y tener mayor impacto al procesador). En esos casos, si no hay un método directo que realice la tarea entonces apply podría ser una buena opción, como último recurso sería utilizar ciclos.
En este caso tu comprensión de listas te devuelve la lista de booleanos que requiere la función pero hay una mejor forma de hacerlo ya que los ciclos van a consumir mucho tiempo si el dataset incrementa el tamaño
La forma óptima para obtener las máscaras sería así:
masks = [df['Municipio'].isin(listaMunicipios) & df['Zona de dificil Acceso'].eq('NO')]

Ejemplo completo:
import pandas as pd
import numpy as np

datos=[["CAUCA","ARGELIA","NO"],["VALLE DEL CAUCA","CALI","NO"],["CAUCA","POPAYAN","NO"],
["CAUCA","BALBOA","NO"]]

df = pd.DataFrame(datos, columns=["Departamento","Municipio","Zona de dificil Acceso"])

listaMunicipios=["ARGELIA","PALOQUEMADO","PAMPLONA"]
color=["red"]

def funciomAgregarColores(column, bool_masks, color_list, default="white"):
    cond_bg_style = [f'background-color: {color}' for color in color_list]
    default_bg_style = f'background-color:{default}'
    return np.select(bool_masks, cond_bg_style, default=default_bg_style)

masks = [df['Municipio'].isin(listaMunicipios) & df['Zona de dificil Acceso'].eq('NO')]
styled = df.style.apply(funciomAgregarColores,subset=["Zona de dificil Acceso"],bool_masks=masks,color_list=color)

Al imprimir styled obtenemos el siguiente dataframe:

A: Cordial saludo
Agrego aquí la función sombrear, con style.applymap que les podría servir
#ver
#https://towardsdatascience.com/a-quick-and-easy-guide-to-conditional-formatting-in-pandas-8783035071ee
import pandas as pd
import seaborn as sns

iris = sns.load_dataset('iris')
df = iris.sample(n=10, random_state=1)

def sombrear(val,ini,fin,colorFondo):
    condition = (val >= ini) & (val <= fin)
    color = 'red' if condition else 'black'
    background_color= colorFondo if condition else 'normal'
    font_size = '15px' if condition else '1em'
    font_family = 'cursive' if condition else 'serif'
    font_weight = 'bold' if condition else 'normal'
    return 'color: {}; background-color: {}; font-size: {}; font-family: {}; font-weight: {}'.format(color,background_color,font_size,font_family,font_weight)

df.style.applymap(sombrear,ini=1,fin=3,colorFondo='blue', subset=['sepal_length',   'sepal_width',  'petal_length', 'petal_width'])\
.applymap(sombrear,ini=3.1,fin=5,colorFondo='yellow', subset=['sepal_length',   'sepal_width',  'petal_length', 'petal_width'])\
.applymap(sombrear,ini=5.6,fin=8,colorFondo='green', subset=['sepal_length',    'sepal_width',  'petal_length', 'petal_width'])

A: Cordial saludo
Tal vez una solución mas simple sea emplear style.highlight_between
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.io.formats.style.Styler.highlight_between.html
import pandas as pd
import seaborn as sns

iris = sns.load_dataset('iris')
df = iris.sample(n=10, random_state=1)

df.style.highlight_between(left=1, right = 3, inclusive ='both', color= 'blue',subset=['sepal_length',  'sepal_width',  'petal_length', 'petal_width'])\
.highlight_between(left=3.1, right = 5, inclusive ='both', color= 'yellow',subset=['sepal_length',  'sepal_width',  'petal_length', 'petal_width'])\
.highlight_between(left=5.6, right = 8, inclusive ='both', color= 'green',subset=['sepal_length',   'sepal_width',  'petal_length', 'petal_width'])\
.highlight_between(left='versicolor',right = 'versicolor',  color= 'pink',subset=['species'])\
.highlight_between(left='setosa',right = 'setosa',  color= 'purple',subset=['species'])


text:
Q: Docker container is not running on given port in dockerfile I am trying to run my application on docker (Linux container).
In my Dockerfile i'm exposing the port 80
Dockerfile
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["project/project.csproj", "project/"]
COPY ["project.Data/project.Data.csproj", "project.Data/"]
RUN dotnet restore "project/project.csproj"
COPY . .
WORKDIR "/src/project"
RUN dotnet build "project.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "project.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "project.dll"]

but the application is not starting on the same port instead and i'm getting KestrelServer error for development https certificate even i don't want to enable ssl for my application and also as in log it showing that application is starting on port 5000
Logfile
2020-08-11 15:00:53.3929|1|DEBUG|Microsoft.Extensions.Hosting.Internal.Host|Hosting starting
2020-08-11 15:00:53.4224|60|WARN|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
2020-08-11 15:00:53.4312||INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
2020-08-11 15:00:53.4650|53|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver|Repository contains no viable default key. Caller should generate a key with immediate activation.
2020-08-11 15:00:53.4694|57|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider|Policy resolution states that a new key should be added to the key ring.
2020-08-11 15:00:53.4800|58|INFO|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Creating key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} with creation date 2020-08-11 15:00:53Z, activation date 2020-08-11 15:00:53Z, and expiration date 2020-11-09 15:00:53Z.
2020-08-11 15:00:53.4918|32|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Descriptor deserializer type for key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} is 'Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=3.1.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
2020-08-11 15:00:53.5035|34|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|No key escrow sink found. Not writing key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} to escrow.
2020-08-11 15:00:53.5070|35|WARN|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|No XML encryptor configured. Key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} may be persisted to storage in unencrypted form.
2020-08-11 15:00:53.5293|39|INFO|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Writing data to file '/root/.aspnet/DataProtection-Keys/key-7c98d268-e4df-4a6b-8ed3-d8689029c5e8.xml'.
2020-08-11 15:00:53.5362|23|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Key cache expiration token triggered by 'CreateNewKey' operation.
2020-08-11 15:00:53.5433|37|DEBUG|Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository|Reading data from file '/root/.aspnet/DataProtection-Keys/key-7c98d268-e4df-4a6b-8ed3-d8689029c5e8.xml'.
2020-08-11 15:00:53.5502|18|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager|Found key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8}.
2020-08-11 15:00:53.5631|13|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.DefaultKeyResolver|Considering key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} with expiration date 2020-11-09 15:00:53Z as default key.
2020-08-11 15:00:53.6033||DEBUG|Microsoft.AspNetCore.DataProtection.TypeForwardingActivator|Forwarded activator type request from Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=3.1.6.0, Culture=neutral, PublicKeyToken=adb9793829ddae60 to Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Culture=neutral, PublicKeyToken=adb9793829ddae60
2020-08-11 15:00:53.6122|11|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ManagedAuthenticatedEncryptorFactory|Using managed symmetric algorithm 'System.Security.Cryptography.Aes'.
2020-08-11 15:00:53.6163|10|DEBUG|Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ManagedAuthenticatedEncryptorFactory|Using managed keyed hash algorithm 'System.Security.Cryptography.HMACSHA256'.
2020-08-11 15:00:53.6415|2|DEBUG|Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider|Using key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} as the default key.
2020-08-11 15:00:53.6466||DEBUG|Microsoft.AspNetCore.DataProtection.Internal.DataProtectionHostedService|Key ring with default key {7c98d268-e4df-4a6b-8ed3-d8689029c5e8} was loaded during application startup.
2020-08-11 15:00:54.2074|2|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer|Failed to locate the development https certificate at '(null)'.
2020-08-11 15:00:54.2318||WARN|Microsoft.AspNetCore.Server.Kestrel|Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'.
2020-08-11 15:00:54.2486|1|DEBUG|Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer|Unable to locate an appropriate development https certificate.
2020-08-11 15:00:54.2525||DEBUG|Microsoft.AspNetCore.Server.Kestrel|No listening endpoints were configured. Binding to http://localhost:5000 by default.
2020-08-11 15:00:54.2569||INFO|Microsoft.Hosting.Lifetime|Now listening on: http://localhost:5000
2020-08-11 15:00:54.2612||DEBUG|Microsoft.AspNetCore.Hosting.Diagnostics|Loaded hosting startup assembly SwiftX
2020-08-11 15:00:54.2677||INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down.
2020-08-11 15:00:54.2715||INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development
2020-08-11 15:00:54.2764||INFO|Microsoft.Hosting.Lifetime|Content root path: /app
2020-08-11 15:00:54.2816|2|DEBUG|Microsoft.Extensions.Hosting.Internal.Host|Hosting started

docker-compose.yaml
version: "3"
services:
    app:
        hostname: app
        container_name: app-container-dev
        image: server.azurecr.io/project-app:dev-local
        volumes:
            - ./data/app/Settings/appsettings.json:/app/Settings/appsettings.json
            - ./data/app/Settings/nlog.config:/app/Settings/nlog.config
            - ./data/app/Log:/app/Log
            - ./data/app/Files:/app/Files
            - ./data/app/Images:/app/Images
        ports:
            - 8001:80
        networks:
            - project-net-dev
networks:
    project-net-dev: {}

and even if trying to bind 5000 port to docker's 8001
ports:
    - 8001:5000

then also i'm getting the below error
Unable to bind to http://localhost:5000 on the IPv6 loopback interface: 'Cannot assign requested address'

my question is how can i disable development https certificate checking (disable ssl) and can start the application on port 80.

A: You need to tell ASP.Net core to listen on the port you exposed.
So the end of your docker file should look like this:
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# Expose the port in the container
EXPOSE 80/tcp
# Expose the port in ASP.Net Core
ENV ASPNETCORE_URLS=http://*:80
ENTRYPOINT ["dotnet", "project.dll"]

Basically your Expose should match your ASPNETCORE_URLS.
In your docker compose try using:
- 80:80

Basically the mappings need to match what the container is exposing.
Later on you can experiment changing the port mapping to different ports.


text:
Q: Display an image contained in a byte[] with ASP.Net MVC3 I've a view with a strong type. This strong type has a field consisting of a byte[], this array contains a picture.
Is it possible to display this image with something like @Html.Image(Model.myImage) ?
Thank you very much

A: It depends on how big the image is. If it is small, you could write something to base-64 encode it and embed it in the html, like any of these.
For a concrete example from here:

If the image is of any appreciable size, you may want instead to write a route that allows lookup via some key to the image, i.e. a route like /images/{id} - in that route you fetch the image binary and use return File(bytes, contentType), additionally setting caching headers (and remember to re-check any necessary security). In your html you would just have an

(using razor syntax, but similar for aspx).
The separate route approach requires an additional hop to the server, but allows caching at the client (the inline base-64 approach puts the data on every request).

A: If you already happen to have the image loaded in your model as a byte[] array you can do this as @Marc Gravell mentions in his answer:

This greatly simplifies the whole process and you won't need to have a specific FileContentResult action method and hit the database again (see @Dmitry S's answer) just to fetch that byte[] array with your image/photo since you already have it loaded in your model.

A: Sounds like you'd need a new action that gets the byte array (from a database?) and returns the image via the File method....
Then generate an anchor that points to that action, that way the image can be loaded while the page is loading, speeding up the display.

A: You can create a controller action method that returns an image as a FileContentResult:
public FileContentResult Display(string id) {
   byte[] byteArray = GetImageFromDB(id);
   return new FileContentResult(byteArray, "image/jpeg");
}

Then you can create an ActionLink to the action method in the view using the image id from the model.

A: Look at WebImage class.
http://msdn.microsoft.com/en-us/library/system.web.helpers.webimage(v=vs.99).aspx

A: I would design a simple generic handler for serving your images. This handler could, given some parameter, load images from the database, and write them to the http output stream.
public class UserImage : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";

        // Get the stream from the database
        var image = System.Drawing.Image.FromStream(stream);

        image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }
}


text:
Q: XML Config file for SharePoint Designer 2013 Good Morning,
I need help with configuring an xml config file for Sharepoint Designer 2013. specifically, I'm looking for a way to disable the start options screen (regarding updates) so end users do not have to see it. This is an SCCM2012 install to a citrix environment. We've tried the following reg hacks, but it does not work for all users:
User Configuration – HKCU\Software\Microsoft\Office\15.0\FirstRun   Value Name: BootedRTM   Value Type: REG_DWORD   Value Data: 1
User Configuration – HKCU\Software\Microsoft\Office\15.0\Common\General   Value Name: ShownFirstRunOptin   Value Type: REG_DWORD   Value Data: 1
I'm hoping to incorporate the above lines into my xml file (once we get them working) for my deployment. XML file below:

A: Answering my own question here:
We simply went through GPO instead of arguing with the XML file:
User Configuration > Policies > Administrative Templates > Microsoft Office 2013 > Miscellaneous
Disable the Office Start Screen for all Office applications - Enable
User Configuration > Policies > Administrative Templates > Microsoft Office 2013 > First Run
Disable First Run Movie - Enable
Disable Office First Run on application boot - Enable
User Configuration > Policies > Administrative Templates > Microsoft Office 2013 > Privacy > Trust Center
Automatically receive small updates to improve reliability - Disable
Disable Opt-in Wizard on first run - Enable
Enable Customer Experience Improvement Program - Disable


text:
Q: Get "Encountered unsupported property KeyName" error when start a stack to launch a ec2 instance I use cloudformation to launch a ec2 instance. Below is the cloudformation template:
Parameters:
  KeyName:
    Description: The EC2 Key Pair to allow SSH access to the instance
    Type: 'AWS::EC2::KeyPair::KeyName'
Resources:
  Ec2Instance:
    Type: 'AWS::EC2::SpotFleet'
    Properties:
      SecurityGroups:
        - !Ref InstanceSecurityGroup
        - MyExistingSecurityGroup
      KeyName: !Ref KeyName
      ImageId: ami-07d0cf3af28718ef8
      InstanceType: p2.8xlarge
      AllocationStrategy: lowestPrice
      SpotPrice: 1
  InstanceSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: Enable SSH access via port 22
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp: 0.0.0.0/0

I created a stack in cloudformation and specify the Key Name from a drop list of key pair. After than the stack rolled back and I see this error message Encountered unsupported property KeyName. I wonder what wrong with my configuration?

A: Check documentation on AWS::EC2::SpotFleet. It only supports SpotFleetRequestConfigData as property.
You will probably need to specify something like:
  Ec2Instance:
    Type: 'AWS::EC2::SpotFleet'
    Properties:
      SpotFleetRequestConfigData:
        SpotPrice: 1
        AllocationStrategy: lowestPrice
        LaunchSpecifications:
        - InstanceType: p2.8xlarge
          SecurityGroups:
          - !Ref InstanceSecurityGroup
          - MyExistingSecurityGroup
          KeyName: !Ref KeyName
          ImageId: ami-07d0cf3af28718ef8

Check the AWS::EC2::SpotFleet documentation, it has a quite elaborate example.


text:
Q: iperf bandwidth less than interface speed I used linux bonding driver to bond 2 NICs in mode 6 in client PC.
ethtool ethX shows speed =1000
ethtool bond0 shows speed =2000
but when i use iperf
bandwidth of eth0 = 934Mbps
bandwidth of eth1 = 637Mbps
bandwidth of bond0 = 934Mbps
Shouldnt the bandwidth of bond0 be around 2000Mbps?

A: In short: no, bonding does not work in this manner.
Long story: the linux bonding, with its various bonding scheme, is very configurable. It has no less than 7 different bonding types, each with its strong and weak points. I strongly suggest you to read the documentation you can found here. However, the take away is the (except for the round-robin mode, which I detail below) no bonding scheme is capable of increase the throughput of a single session, rather they speedup multiple concurrent session. So your iperf output is perfectly normal, as it open a single session which can not be accelerated by the bonding driver.
The only expcetion to this rule is the round-robin mode, which transmits packet in a, well, round-robin fashion: the first one goes out from the first inteface, the second one from the second interface, and so on. This bonding mode can accelerate a single session by the virtue of concurrent sent packets. However it has many pitfalls, ranging from incompatible switches, out-of-order packet delivery (with relative retransmission), bad scaling over 2 interfaces, etc.
This is only a very concise summary. If you are interesting in how bonding works, you should really give a serious look at the documentation I provided above.

A: I am currently experimenting with round robin - I noticed that when bonding 2 NICs it does provide a 1.6-1.7 Gb/s when using iperf (keep in mind that two machines I use to test the speed have 2 NICs each in mode 0). I did a test today with 3 NICs and got ¬900 Mb/s - the reason for this is that round robin works best with an even number of NICs. I would only use it as a backbone for server backup (on the cheap) with an NFS share...


text:
Q: Increase the time for console report in Gatling I am running the gatling simulations and the gatling console report is printed every 5 seconds.
---- user-workflow ---------------------------------------------------------
[##########################################################################]100%
          waiting: 0      / active: 0      / done:10
---- Requests ------------------------------------------------------------------
> Global                                                   (OK=1495   KO=0     )
> login-request                                            (OK=104    KO=0     )
> edit-request                                             (OK=255    KO=0     )
> update-request                                           (OK=257    KO=0     )
> delete-request                                           (OK=257    KO=0     )
> list-request                                             (OK=311    KO=0     )
> logout-request                                           (OK=311    KO=0     )
================================================================================

Is there a way to increase this time or better to print at the end of simulation?
I was looking at the gatling.conf default configurations on the github repo, but couldn't find anything relevant.

A: Its possible. See https://github.com/gatling/gatling/blob/master/gatling-core/src/main/resources/gatling-defaults.conf#L109
In gatling.conf, set data.console.writePeriod to 0.


text:
Q: Finding the Coordinates (2D Array) of Lowest Value I feel like I'm missing something terribly obvious, but I cannot seem to find the array pair with the lowest value.
I have an int[,] worldMapXY where a 2D map is stored, say worldMapXY[0,0] through worldMapXY[120,120].  All values of map's array are 1 (wall\invalid) or 0 (path/valid).
I'm writing a method that will find coordinates in one of the eight cardinal directions to create a spawn point.  So I also have int[,] validSpotArr which has a subset of bounds of the map closest to the direction I'm setting the spawn.  The values for wall/invalid locations are set to 9999, the values for path/valid locations are set to (x + y).  This is all specific to the bottom left corner, nearest to [0,0], hence "BL" or "Bottom Left"
        case "BL":

        for (int x = (int)border + 1; x < worldX + (int)border / 4; x++)
        {
            for (int y = (int)border + 1; y < worldY + (int)border / 4; y++)
            {
                if (worldMapXY[x,y] = 0)
                {
                    validSpotArr[x,y] = x + y;
                }

                else
                {
                    validSpotArr[x,y] = 9999;
                }
            }
        }

What I can't quite wrap my head around is how to determine the coordinates/index of validSpotArr with the lowest value in such a way that I could pass those as separate x and y coordinates to another function (to set the spawn point).  I suspect there's a lambda operator that may help, but I literally don't understand lambdas.  Clearly that needs to be my next point of study.
E.g. - if validSpotArr[23, 45] = 68, and 68 is the lowest value, how do I set x=23 and y=45?
Edit:  I tried messing around with something like this, but it isn't right:
    Array.IndexOf(validSpotArr, validSpotArr.Min());

A: While not precisely an answer to your question, in a strictly given situation I'd probably go for finding those from within the cycles, i.e.
int minValidSpot = int.MaxValue, minX, minY;
for (int x = (int)border + 1; x < worldX + int(border) / 4; x++)
    {
        for (int y = (int)border + 1; y < worldY + int(border) / 4; y++)
        {
            if (worldMapXY[x,y] = 0)
            {
                validSpotArr[x,y] = x + y;
            }
            else
            {
                validSpotArr[x,y] = 9999;
            }
            if ( minValidSpot > validSpotArr[x,y] )
            {
                minValidSpot = validSpotArr[x,y];
                minX = x;
                minY = y;
            }
        }
    }

Other than that, if looking for some kind of more universal solution, I'd probably just flatten that array, the maths for index conversion (nD<=>1D) are pretty simple.


text:
Q: Separate properties for a shared spring library contained inside a spring boot application I created a shared library in spring that I deploy as an artifact in an artifactory. I use this shared library artifact in another spring boot application as a pom dependency. Shared library has it's own properties files under src/main/resources
I am having problems with the following:
When I try to load the spring boot application, it is not able to load the properties for the shared library and expects all the properties shared library needs in the outer spring boot application. How can fix this and have shared library always read its own properties file ?

A: Use @PropertySource annotation to provide the two sources for your app:
@PropertySources({
        @PropertySource("classpath:yourSharedLib.properties"),
        @PropertySource("classpath:youApp.properties")
    })


text:
Q: Dropdown submenu do not stay open on hover I have a dropdown menu with submenu that does fadeIn/Out on hover.  The dropdown does fadeIn and out like I want, and the dropdown submenu does fadeIn / Out like I want.  However, when I go from dropdown to submenu-link it fadeOut and disappears.
I can't really figure out how to solve this issue and keep the submenu open.
HTML:

                    Trigger 1

                        Trigger in sub

2 Columns

3 Columns

4 Columns

                       Trigger in sub 2

2.2 Columns

3.3 Columns

4.4 Columns

jQuery
$('.dropdown').hover(function() {

      $(this).find('.has-sub').next('ul').stop(true, true).fadeIn("fast");

      },
      function() {
        $(this).find('.has-sub').next('ul').stop(true, true).delay(300).fadeOut("fast");

     });

      $('.sub-has-sub').hover(function() {
      $(this).next('ul').stop(true, true).fadeIn("fast");
      $(this).addClass('open');
      },
      function() {
        $(this).next('ul').stop(true, true).delay(300).fadeOut("fast");

     });


text:
Q: Retorno de um List Da View para o Controller - Asp.Net Core Possuo uma viewmodel chamada Perfil, nesta viewmodel há uma propriedade List de ItensPerfil e uma string - título.
public class PerfilViewModel
{
    [Key]
    [DisplayName("Código")]
    public int Id { get; set; }

    [Required(ErrorMessage = "O campo {0} é obrigatório")]
    [StringLength(50, ErrorMessage = "O campo {0} deve ter no mímino {1} caracteres")]
    [DisplayName("Título")]
    public string Titulo { get; set; }

    public IEnumerable<PerfilItens> ItensPerfil { get; set; }
}

Os atributos da classe ItensPerfil são boleanos: visualizar, criar, editar e excluir e mais um, inteiro (id) que indica o Perfil deste ItensPerfil.
Crio minha view desta forma:
var viewModel = new PerfilViewModel();
var itens = Bootstrap._listaPerfil;

viewModel.ItensPerfil = itens.Select(x => new PerfilItensViewModel
{
    ItemMenu = x.ItemMenu,
    Criar = x.Criar,
    Visualizar = x.Visualizar,
    Excluir = x.Excluir,
    Editar = x.Editar
});

return View(viewModel);

A função Bootstrap._listaPerfil() apenas carrega os itens de perfil que devem ser criados.
A view aparece perfeitamente, através de um for ou foreach consigo gerar para o usuário dos os itens do perfil, ele só precisa inserir um título e marcar ou não, via checkbox, os itens.
    <form asp-action="Create">

            <input asp-for="Descricao" class="form-control" />

        @foreach (var item in Model.ItensPerfil)
        {

                @item.ItemMenu

                <input type="checkbox" asp-for="@item.Visualizar" checked="@item.Visualizar" />

                <input type="checkbox" asp-for="@item.Editar" checked="@item.Editar" />

                <input type="checkbox" asp-for="@item.Criar" checked="@item.Criar" />

                <input type="checkbox" asp-for="@item.Excluir" checked="@item.Excluir" />

        }

            <input type="submit" value="Create" class="btn btn-default" />

    </form>

Agora vamos ao problema, quando retorna para a função Create por Post o Perfil vem corretamente, o título aparece certinho, mas os itensPerfil retorna como null.
Alguma solução para isto?

A: Barbetta, seria isso que vc queria ver?
public class Bootstrap
{
    public static List<PerfilGenerico> _listaPerfil { get; private set; }

    public static void Configuracao(IServiceCollection services)
    {
        SetListaPerfil();

        services.AddScoped<IAmbiente, AmbienteRepositorio>();
        services.AddScoped<IAmbienteApp, AmbienteApp>();

        services.AddScoped<ICidade, CidadeRepositorio>();
        services.AddScoped<ICidadeApp, CidadeApp>();

        services.AddScoped<IEstado, EstadoRepositorio>();
        services.AddScoped<IEstadoApp, EstadoApp>();

        services.AddScoped<IPerfil, PerfilRepositorio>();
        services.AddScoped<IPerfilApp, PerfilApp>();

        services.AddScoped<IPerfilItens, PerfilItensRepositorio>();
        services.AddScoped<IPerfilItensApp, PerfilItensApp>();
    }

    private static void SetListaPerfil()
    {
        _listaPerfil = new List<PerfilGenerico>
        {
            new PerfilGenerico { Classe = "Ambiente" },
            new PerfilGenerico { Classe = "Cidade" }
        };
    }
}

 public class PerfilGenerico
{
    public string Classe { get; set; }
    public bool Visualizar { get; set; }
    public bool Criar { get; set; }
    public bool Editar { get; set; }
    public bool Excluir { get; set; }
}

A: Resolvido. Neste caso não se pode utilizar List porque no HTML os IDs nos inputs dentro do loop se repetem e causam o problema, deve-se utilizar vetor.


text:
Q: What's the ground state wave-functional of a fermion? The vacuum state, free field wave-functional of a scalar field $\hat\phi(x)$ in the Schrödinger representation of quantum field theory is
$$\begin{array}{cl}
\Psi_0[\phi] &= C\prod_k e^{-\omega(k)\frac{\tilde\phi(\vec k)^2}{2}\epsilon^3} \\
&\to C e^{-\frac{1}{2}\int\frac{d^3k}{(2\pi)^3} \omega_k|\tilde\phi(\vec k)|^2} \\
 &= \operatorname{det}^{\frac{1}{4}}\left(\frac{K}{\pi}\right)\; e^{-\frac{1}{2}\int d\vec{x} \int d\vec{y}\, \phi(\vec{x}) K(\vec{x},\vec{y}) \phi(\vec{y}) } = \operatorname{det}^{\frac{1}{4}}\left(\frac{K}{\pi}\right)\; e^{-\frac{1}{2}\phi\cdot K\cdot\phi}.\\
\end{array}$$
What is the ground state wave-functional of a fermionic field $\hat\psi(x)$?
Clearly it shouldn't resemble the harmonic oscillator as $\hat\phi$'s did, but rather an $SU(2)$ state, as the wavefunctional $|\Psi(u)\rangle$ is now a functional of anti-commuting Grassmann fields $u(x)$.  Jackiw gives some discussion but not an explicit form.  Assume $\hat\psi$ is a massless Majorana fermion if necessary.

A: To keep the math simple, we can treat space as a very-fine-but-discrete lattice of very-large-but-finite dimensions, say of size $10^{1000}\times 10^{1000}\times 10^{1000}$ with a lattice spacing of $10^{-500}$ meters.
Let $\hat\psi_a(\vec x)$ denote the components of the fermion field operator, where $a$ is a spinor index, and let $\hat\psi_a^\dagger(\vec x)$ denote its adjoint. For a free field, the Hamiltonian has the form
$$
 H\sim\sum_{\vec x} \sum_{a,b}\hat\psi_a^\dagger(\vec x)
  D_{ab}\hat\psi_b(\vec x)
\tag{1}
$$
for some differential operator $D_{ab}$ whose details don't affect the essence of the answer. Since we've discretized space, we can streamline the notation by using a single index $n$ for both $a$ and $\vec x$. Then the Hamiltonian is
$$
 H\sim\sum_{n,k}\hat\psi_n^\dagger
  M_{nk}\hat\psi_k
\tag{2}
$$
where $M$ is an ordinary (but extremely large) matrix.
The goal is to find a representation of these operators as things that operate on a Hilbert space of "functionals" $\Psi[u]$, where $u$ are Grassmann variables, and then to derive an explicit expression for the functional that minimizes the energy defined by $H$.
 The Hilbert-space representation
For each value of the index $n$, let $u_n$ be a Grassmann variable. Let $\Psi[u]$ denote a function of all of these variables, with complex coefficients. The Grassmann variables satisfy $u_n^2=0$, and we've replaced continuous space with a finite lattice, so the function $\Psi[u]$ is actually a polynomial with a finite (but very large) number of possible terms. We can think of $\Psi[u]$ as an ordinary many-component vector whose components are the coefficients of the polynomial. We can then define the inner product $\langle\Psi_1|\Psi_2\rangle$ in the obvious way, as the "dot product" of the vector of $\Psi_2$'s coefficients with the complex conjugate of the vector of $\Psi_1$'s coefficients.
The same inner product can also be written as
$$
 \langle \Psi_1|\Psi_2\rangle
 \sim
 \int [dw][du]\
 \exp\left(-\sum_n w_n u_n\right)
 \Psi_1^*[w] \Psi_2[u]
\tag{3}
$$
using a second set of Grassmann variables $w_n$ that anti-commute with the original variables as well as with each other. (I"m writing "$\sim$" so I don't have to keep track of minus signs.) Here's the intuition behind equation (3): Grassmann integration is defined so that the result is simply the coefficient of the term in the integrand that involves exactly one factor of every integration variable. The exponential factor expands to a sum over all possible products of the factors $w_n u_n$. So, if we think of a polynomial $\Psi[u]$ as a vector of coefficients, then the integral over $[dw][du]$ is equivalent the usual "dot product" of two complex vectors $\Psi_1$ and $\Psi_2$. The exponential factor in (3) is what makes this work.
The field operators are represented by
$$
 \hat\psi_n\Psi[u] = u_n\Psi[u]
\hskip2cm
 \hat\psi_n^\dagger\Psi[u] \sim \frac{\partial}{\partial u_n}\Psi[u].
\tag{4}
$$
(Again, I'm writing "$\sim$" so that I don't have to keep track of minus signs.) Inside the inner product (3), taking the derivative of $\Psi_2[u]$ with respect to $u_n$ has the same effect as multplying the other wavefunction $\Psi_1[w]$ by $w_n$, so the second operator in (4) really does represent the adjoint of the first operator in (4).
For a more detailed treatment that pays closer attention to minus signs, see chapter 4 in Montvay and Münster's book Quantum Fields on a Lattice.
 The ground state
Regardless of what Hilbert-space representation we use, we can choose a basis for the set of field operators $\hat\psi_n$ that diagonalizes the matrix $M$. This is standard textbook material, so suppose that this has already been done. Then the Hamiltonian has the form
$$
 H\sim\sum_{n}\omega_n\hat\psi_n^\dagger\hat\psi_n.
\tag{5}
$$
(For example, such a basis exists in which each value of the index $n$ represents some combination of a spinor index $a$ and a momentum $\vec p$.) Then the ground state of the Hamiltonian (2) is annihilated by $\hat\psi_n$ if $\omega_n>0$ and is annihilated by $\hat\psi_n^\dagger$ if $\omega_n<0$.
Finally, in the representation described above, the wavefunction $\Psi[u]$ that satisfies these conditions is just a monomial, namely the product of the $u_n$ for which $\omega_n>0$. Here's why: the vacuum state is the eigenstate of $H$ with minimum eigenvalue. That condition is satisfied by the state that's annihilated by $\hat\psi_n$ whenever $\omega_n>0$ and by $\hat\psi_n^\dagger$ whenever $\omega_n<0$. In the basis that diagonalizes $H$, this implies that the state is just the product of $u_n$s for which $\omega_n>0$.
This monomial is the "wavefunction" of the ground state. Its spatial structure is encoded through the indices $n$, which refer to a basis that diagonalizes the Hamiltonian as in (5). Note that this is a different basis than the one used in (1) where $D$ is the usual Dirac operator. Equations (2)-(4) apply in any basis. Equation (1) corresponds to equation (3.84) in Peskin and Schroeder's An Introduction to Quantum Field Theory, and equation (5) corresponds to (3.90) in the same book. Going from (1) to (5) involves a change of basis, so the $\psi_n$ in equation (5) is a linear combination of the $\psi_n$s in equation (1); I recycled the notation. The details of this basis-change are shown in Peskin and Schroeder.
All of the information about the spatial struction of the "wavefunction" is buried in the relationship between the basis used in (1) and the basis used in (5). I omitted those details because that part is textbook material.


text:
Q: Code Modification of Existing Access 2007 Macro - Aim to Create & Open (from Access) a New Excel Work-Sheet in Existing Excel 2007 Work-book? Here's the code that makes the new Excel work book, but I need the code to create a new work SHEET in the same Excel 2007 workbook each time I click the Access 2007 control button.
Clicking the control button needs to open the Access query and create the Excel work sheet and open the Excel book/sheet.
The Excel work book must be a macro enabled work book .xlsm format
' Command104ContrDonatWeekly_Click
'
'------------------------------------------------------------
Private Sub Command104ContrDonatWeekly_Click()
On Error GoTo Command104ContrDonatWeekly_Click_Err

    DoCmd.OpenQuery "Contributors Who Donated in Past Week", acViewNormal, acEdit
    DoCmd.OutputTo acOutputQuery, "Contributors Who Donated in Past Week", "ExcelWorkbook(*.xlsx)", "C:\Users\Michael1\Desktop\KSN\DistributionListWeekly.xlsx", True, "", 0, acExportQualityScreen

Command104ContrDonatWeekly_Click_Exit:
    Exit Sub

Command104ContrDonatWeekly_Click_Err:
    MsgBox Error$
    Resume Command104ContrDonatWeekly_Click_Exit

End Sub

A: You can use Transferspreadsheet:
XLFile = "C:\Docs\MyXLFile.xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
    "MyTableOrQuery", XLFile, True, "Sheet2"

FollowHyperlink XLFile

''OR

Shell "Excel.exe " & xlfile, vbNormalFocus


text:
Q: prove that $\int_{a}^{b}(|f-{\frac{1}{b-a}} \int_{a}^{b}f|)~dx \le {(b-a)}\int_b^{a}|f'| ~dx$ where $f$ is differentiable on $[a,b]$ and $f'$ is integrable on $[a,b]$. Apparently it has something to with the fundamental theorem of calculus although I'm not entirely sure how you would apply it to this example. How would I proceed? Any ideas?

A: By the mean value theorem for integrals, there is a point $c\in (a,b)$ such that $$f(c) = \frac{1}{b - a}\int_a^b f\, dx.$$ Thus
\begin{align*}
\int_a^b |f(x) - \frac{1}{b - a}\int_a^b f|\, dx &= \int_a^b |f(x) - f(c)|\, dx\\
& = \int_a^c |f(x) - f(c)|\, dx + \int_c^b |f(x) - f(c)|\, dx\\
&= \int_a^c |\int_x^c f'(t)\, dt|\, dx + \int_c^b |\int_c^x f'(t)\, dt|\, dx\\
&\le \int_a^c \int_x^c |f'(t)|\, dt\, dx + \int_c^b \int_c^x |f'(t)|\, dt\, dx\\
&=\int_a^c \int_a^t |f'(t)|\, dx\, dt + \int_c^b \int_t^b |f'(t)|\, dx\, dt\\
&= \int_a^c (t - a)|f'(t)|\, dt + \int_c^b (b - t)|f'(t)|\, dt\\
&\le (c - a) \int_a^c |f'(t)|\, dt + (b - c) \int_c^b |f'(t)|\, dt\\
&\le (c - a) \int_a^b |f'(t)|\, dt + (b - c) \int_a^b |f'(t)|\, dt\\
&= (b - a) \int_a^b |f'(t)|\, dt.
\end{align*}


text:
Q: unbalanced dataset, anomalies have same distribution as normal data I worked with a dataset which contains 2 classes (95%, 5%).
And the features of these 2 classes have almost the same distribution.
Question is: How can I classify these 2 classes and explain which principal the model uses to classify the test set?

A: Actually the distribution of features makes sense, but you have to make more detailed exploratory analysis than simple distribution of features. I suggest to have a look some 3D plots. You can have a look at some links about EDA:
https://www.kaggle.com/dejavu23/titanic-eda-to-ml-beginner
https://www.kaggle.com/dejavu23/house-prices-eda-to-ml-beginner
Regarding to classification models, I would suggest to have use Decision Tree based models, such as Random Forest or Gradient Tree Boosting.
The idea behind Decision Tree is partition of feature space and making the same prediction for each part of it. You can plot Decision Trees, using some packages and it will help to understand principles behind the model. You can read more about all these models in the nice book:
http://www-bcf.usc.edu/~gareth/ISL/
Links to packages:
https://lightgbm.readthedocs.io/en/latest/
https://scikit-learn.org/stable/modules/tree.html
https://scikit-learn.org/stable/modules/ensemble.html
You can read about decision tree visualization:
https://medium.com/@rnbrown/creating-and-visualizing-decision-trees-with-python-f8e8fa394176
https://www.kaggle.com/willkoehrsen/visualize-a-decision-tree-w-python-scikit-learn


text:
Q: Tell StormCrawler to delete pages from ES-index after they have been deleted on the server I have the following scenario:

*

*An existing page gets crawled by StormCrawler

*StormCrawler adds a corresponding document to an Elasticsearch index

*The page is deleted on the server

=> The crawler "detects" the removal of the page by updating the status-index: The document gets status "FETCH_ERROR" (and after reaching the "max.fetch.errors" the status "ERROR").
Problem:
The Elasticsearch-Index still keeps the document, but since the page was deleted that doesn't make sense.
Looking at the configuration, I haven't found a way to tell StormCrawler to remove documents from the ES-index which have status "ERROR" (e. g. have been deleted).
Is there a way to accomplish this using StormCrawler or is there a reason why this is not possible?
Thank you very much for your help!

A: We're planning to add a GONE status but this is not yet implemented, see #253. In the meantime we could delete the ERROR status (even if most of them would not have been added to ES), the difficulty being that the indexing is done on the default stream i.e. docs which have been fetched and parsed whereas the status info gets sent to the status stream by the various bolts. We could have a bespoke bolt for deletions - it would just need the URL and nothing else: to use it we could modify AbstractStatusUpdaterBolt so that it emits the URLs to delete onto a special stream e.g. 'deletion' and connect our bespoke ES delete bolt to it. Does this make sense? Please feel free to contribute to the discussion on the link above. Thanks!


text:
Q: EntityFramework Deleting Objects while Observing Collections and Property Changes I have an EntityService class which wraps around entity operations and also provides the WPF application ObservableCollections of materialized entities.
When I come to delete a Book from my collection of Books:
<Class EntityService>

public void DeleteBook(Book book)
{
    context.DeleteObject(book)
    observableCollectionOfBooks.Remove(book)
}

EntityFramework then proceeds to null all the navigation properties of the to-be-deleted Book which fires off PropertyChanged events. One of my ViewModels is an observer of this event:
<Class LibraryViewModel>

private void BookPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    //Get all materialized books
    var books = entityService.Books.Where(x => x.Author.Name == "Dan");
}

Here I get a NullReferenceException because the deleted Book hasn't been removed from the ObservableCollection yet and the Author for the to-be-deleted Book is null.
I've tried changing the order of operations in DeleteBook(Book book) but it produces a different but related inconsistency.
The problem is that the operation is not atomic.
What I'm looking for is BookPropertyChanged to be called only when the model is in a consistent state: The Book is in deleted and the ObservableCollection doesn't contain the deleted object.
I realise there may be some hack to fix this such as checking for nulls but I was wondering if there was a better way?
I was thinking of somehow suppressing the events until both operations were completed. I'm not sure how this would work even in theory but I think I need to achieve something equivalent to the following:
using (new EventSuppressor(book, observableCollectionOfBooks))
{
    context.DeleteObject(book)
    observableCollectionOfBooks.Remove(book)
}

So here, any objects passed into the EventSuppressor constructor will have their event notifications suppressed and cached up. The operations inside the using block can take place. When the suppressor is disposed, all events that would have been fired due to the operations executed in the using block are now fired.

A: I may be way off, but,  what if you try the below?
public void DeleteBook(Book book)
{
    context.DeleteObject(book);
    context.SaveChanges();
    observableCollectionOfBooks.Remove(book);
}