dataGridView1_CellContentClick randomly doesn't fire

Question: This is just bizarre. It's almost as if there are certain cells in the grid that are turned off. The whole thing was generated using "drag & drop", e.g. the grid is bound to a datasource and it works almost all the time.
I can click around time after time and it works perfectly but there are cells in the grid that don't fire the event. It is completely repeatable, the dataset is fixed.
What could possibly cause this behavior? No exceptions are being thrown, debugger is set to break on all...
Thanks for any advice.
Comment: I've posted an answer which is really just a best guess - can't think of anything else causing this behaviour, but if the answer is wrong update your question (you don't have the reputation to comment I believe) with some code showing how you reproduce the issue - if it is completely repeatable then you should be able to give a good repro. As it stands the question is to open to be sure what you issue is.
Answer: The CellContentClick event is only fired when the contents (the hosted control) of the cell is clicked. This means that the white space around the control does not cause the event to fire.
This is most obvious with a CheckBox cell - the only thing that fires the event is clicking on the CheckBox - however it occurs for all cell types. With a TextBoxColumn for example the event only fires when the text is clicked on.
If you want to know when anywhere in the cell is clicked, use the CellClick or possibly CellMouseDown events instead.
The CellContextClick event is generally for columns like the checkbox, button or link, where the mouse interaction with the actual content, not the whitespace, is what you are after.
Comment: It's just a text field, the whole grid is just text, nothing else. It works time after time, I get an event for every other cell. What am I going to post, the click handler code? Your response is appreciated, but provides no insight into this problem.
Comment: I will try CellClick. Maybe I'm foolish to think that CellContentClick is reliable. It's not an empty cell. Thanks.
Comment: @user1210111 But are you clicking on the actual text or on the whitespace that surrounds it? If for example you have a text field that is 30 pixels wide but your cell is 35 pixels there will be five pixels where the event is not raised. The cell context click event is reliable - it is isn't working then you have done something to break it.
Comment: @user1210111 when you say "it's not an empty cell" I'm not sure what difference you think this would make? The behaviour of CellContentClick has nothing to do with empty cells or not, but with the size of the control embedded within the cell - there this control is smaller than the total size of the cell you will not get a content click when you click on some parts of the cell.
Comment: David, the cell contains a string, the size of the cell is the same as all the others, in this case it contains two characters. You are suggesting that if I click on the white space in the cell rather than the characters in it, the contents of the cell are not relevant. Really? Thank you again for your replies.
Comment: David, you are correct. If I click directly on the text it works. So I guess I need to use CellClick rather than CellContentClick. This is my first time using a DataGridView, so please pardon my ignorance.
Comment: @user1210111 no problems - this behaviour catchs lots of people, so not an issue of ignorance! Please mark this as the answer to your problem and upvote it, it gives you a little reputation as well as giving me some.
Comment: I tried to upvote, I cannot without a reputation of 15. How do I mark it as anwered?
Comment: There should be a little tick beside my answer. Click and that and it will go green :)


Do I have to staple romex to the studs behind the wall?

Question:
Possible Duplicate:
Do I really have to fasten interior-wall electrical wire to a stud to keep it from moving?

I have some plaster walls in my house and I am attempting to add an outlet to one of the rooms.  Basically I plan to fish some romex from the attic into one of the rooms (behind a plaster wall) and add a box / outlet from there.  My only concern is making sure that the job is up to code.  Do I have to staple the romex to the studs behind the wall, etc. or is it OK to just let it hang down.
Obviously I want to avoid having to knock holes in the wall, but overall safety is my primary concern so I'd be happy to do it if it means not burning down my house because i was being lazy.
Comment: Is it safe?  Probably, I have run electrical between walls without attaching to wall joists, just making sure that the outlet box is secure.  Is it to code for your area?  I wouldn't know.  Some older buildings were framed with a 2x4 between the joists with holes drilled for electrical and plumbing to pass through so the whole thing may be a moot point.  Get a good flashlight and see if you can see all the way down to the bottom before you cut a hole in the wall :)
Comment: This [Answer](http://diy.stackexchange.com/a/11636/33) might help.
Comment: yeah, I've dropped a weighted string from top to bottom in several places with zero obstruction so I am pretty sure that the wall is completely empty.
Answer: It's not up to code to leave the wire free. Stapling it to the center of the stud ensures that a nail for something like a picture won't hit the wire (as long as you know this code and don't try to drive a long nail right next to a stud). No one but yourself is likely to ever know this is wrong, and given the age of the home, it's sure to have a lot of other code violations under today's codes since they change over time.
So to answer your question, my recommendation is to install the staples near the top plate, the J-box, and every 3 feet or so in the middle. But I wouldn't lose much sleep if I heard that someone didn't do this in your situation. Just make sure you don't have any hidden junction boxes or connections made outside of a box since that would be a much bigger issue. And also, don't overload any circuits by adding too many outlets.
Comment: NEC 334.30(B)(1) allows Nonmetallic-sheathed cable to be unsupported when fished though "finished buildings or structures and supporting is impracticable."
Comment: I learn something new every day. +1 to your answer in the dup post. Thanks @Tester101.
Comment: @Tester101 This should be an answer.


Hotpoint Dish Washer Not Draining

Question: The model is AQUARIUS FDW60. For about a month it was leaving bits of food all over the dishes and then one day, it just wouldn't drain and now it won't work at all...
Any suggestions?
Answer: first, remove the drain hose. it's usually a flexible hose connected to he drain pipe under your sink. be careful, because when you remove it, it may spill a bunch of nasty water from both the hose and the bottom of the dishwasher.
clean out the hose, or replace it if it looks crushed or damaged at all.
every dishwasher has a one-way valve to prevent the water it pumps out from returning to the dish washer. sometimes the valve is built in to the hose, and sometimes it's built in to the dishwasher. find your valve and make sure it's clean and not jammed. if it looks broken, you can get it replaced.
if the valve looks ok, put everything back together and test it out.
if it still doesn't work, you may need to replace the pump, which should also be fairly easy to replace and available online.

Hotpoint Dish Washer Not Draining


users assigned a sql azure role

Question: I am trying to make sure that all users have been assigned a particular role. Is there any view or SQL query for getting this information?
Answer: The views have changed names but the following should work against SQL Azure
select m.name as Member, r.name as Role
from sys.database_role_members
inner join sys.database_principals m on sys.database_role_members.member_principal_id = m.principal_id
inner join sys.database_principals r on sys.database_role_members.role_principal_id = r.principal_id

Comment: This answer is exactly what is required in SQL Azure (for which the question is tagged).
Answer: I believe the query listed below should list the users and roles of a single database
select b.name as USERName, c.name as RoleName  from dbo.sysmembers a   join dbo.sysusers b   on a.memberuid = b.uid join dbo.sysusers c  on a.groupuid = c.uid

Or for all DBs on a SQL instance you can use sp_MSForEachDB
Exec dbo.sp_MSForEachDB 'select ''?'' as DB, b.name as USERName, c.name as RoleName  from dbo.sysmembers a   join dbo.sysusers b   on a.memberuid = b.uid join dbo.sysusers c  on a.groupuid = c.uid'

users assigned a sql azure role


Empty functions are not injective?

Question: Many sources say that empty functions such as $f:\emptyset \rightarrow S$ are injective because it is a vacuous truth. But currently I am reading a book on axiomatic set by Patrick Suppes, and he gives a definition of an injective(one-to-to) function that prevents any empty function from being a injective. The definition Suppes gives is
$f$ is one-to-one $\leftrightarrow f$ and $\breve{f}$ are functions
For those that don't know what $\breve{f}$ is, here is the definition
$\breve{f}=\{\langle x,y \rangle: \langle y,x \rangle \in f \}$
According to this definition, any empty function is not injective because $\breve{f}:S \rightarrow \emptyset$ is not a function.
Is Suppes definition correct either though it doesn't allow empty functions to be injective or I'm I missing something?
Comment: Yes, $f:X\to Y$ does not mean that $\breve{f}:Y\to X$. Rather, $\breve{f}:\textrm{im}(f)\to X$.
Comment: Isn't it true that $f = \breve{f} = \emptyset$?
Comment: Yup! Just like it's vacuously injective, it's vacuously a relation and vacuously the converse of that relation.
Comment: @ThomasAndrews Wow! You are absolutely right, I did not notice at all.
Answer: That's a good question, but you're not correct.
The reason is that if $f\colon\varnothing\to S$, then $f=\varnothing$. Therefore $\breve f=\varnothing$. Therefore $f=\breve f$ and both satisfy the condition for being a function.
It is true, however, that $\breve f$ is not a function whose domain is $S$ (unless $S$ is empty). And note that we shouldn't require it is a function from $S$, because then the function $f(n)=n+1$ as a function from $\Bbb N$ to itself is not injective anymore, which is plain preposterous.
Also, there is but one unique empty function. The empty set.
Answer: If $f$ is the empty function, then so is $\breve f$.  Its domain, however, is not $S$ but the empty set. So, unless Suppes said that the domain of $\breve f$ is $S$, his definition is correct.  (If he had required $\breve f$ to have domain $S$, then the definition would be wrong not only for the empty function but for any injective function that isn't surjective.)
Comment: Seven and a half seconds! :-)
Comment: @AsafKaragila That's what I get for proofreading (too slowly) before posting.
Comment: Hey, my post is longer! (Also, I diagonalized the process and proofread it while writing...)
Answer: We agree that a function $f:A\to B$ is a subset, $f\subset A\times B$ that satisfies conditions (that we need not repeat). Now let us suppose that $A=\emptyset$. Then the set, $\emptyset\times B$ is itself the empty set since their is no way to make a pair if we cannot put something in the first slot. So $f=\emptyset$. But then we also have $\breve{f}$ must be a subset of $B\times\emptyset$, which must be the empty set. But the empty set is indeed a function from the empty set to any other set.

Empty functions are not injective?


Settings and Livepatch option not working under Software & Updates after upgrading from 20.04 to 22.04

Question: I upgraded 2 days ago from Ubuntu 20.04 to Ubuntu 22.04. After that when I open Software & Updates, either from GUI or cli (using update-manager command) it runs fine and at the end it says: The software on this computer is up to date. I have then the option for "Settings and Livepatch...". When I click on it nothing appears, but in the terminal I receive the following error message.
Traceback (most recent call last):
File "/usr/bin/software-properties-gtk", line 100, in <module> app = SoftwarePropertiesGtk(datadir=options.data_dir, options=options, file=file)
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 254, in __init__self.init_ubuntu_pro()
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py", line 1661, in init_ubuntu_pro self.ubuntu_pro_page = UbuntuProPage(self)
File "/usr/lib/python3/dist-packages/softwareproperties/gtk/UbuntuProPage.py", line 83, in __init__ubuntu_pro_logo = GdkPixbuf.Pixbuf.new_from_file_at_scale(os.path.join(parent.datadir, 'ubuntu-pro-logo.svg'), -1, 50, True)
gi.repository.GLib.GError:
    gdk-pixbuf-error-quark: Couldn't recognize the image file format
    for file "/usr/share/software-properties/ubuntu-pro-logo.svg" (3)

The file is present and file type seems correct.
$ ls -l /usr/share/software-properties/ubuntu-pro-logo.svg
-rw-r--r-- 1 root root 4989 gen 20 11:58 /usr/share/software-properties/ubuntu-pro-logo.svg

$ file /usr/share/software-properties/ubuntu-pro-logo.svg
/usr/share/software-properties/ubuntu-pro-logo.svg: SVG Scalable Vector Graphics image

Do you have any suggestion about what to check?
Comment: Is it possible there's a package missing. Try `sudo apt install ubuntu-desktop^` (the caret is important) - which will put back anything that went astray in the upgrade.
Comment: Run the command, but no positive effect, same error. Furthermore libreoffice was reinstalled, but it's a minor issue. Any further suggestion?
Comment: Sorry, no. I clean installed Ubuntu 20.04 and upgraded to 22.04. It all works fine. I wonder if there's a mime problem. Can you try `sudo update-mime-database /usr/share/mime` and `sudo /usr/lib/x86_64-linux-gnu/gdk-pixbuf/gdk-pixbuf-query-loaders --update-cache`. Then try again?
Comment: I found no /usr/lib/x86_64-linux-gnu/gdk-pixbuf directory. How can I check and install it?
Comment: Apologies, I got the folder name wrong. it's `sudo /usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/gdk-pixbuf-query-loaders --update-cache`
Comment: Solved, window opened. Many thanks
Comment: Is there a way to set the discussion as Solved?
Comment: Excellent! I've turned my comment into an answer, you can mark that as useful.
Answer: When this happens, you can often resolve it by regenerating mime caches with these two commands:
sudo update-mime-database /usr/share/mime
and
sudo /usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/gdk-pixbuf-query-loaders --update-cache


Trying to Create An Object in ZF but gives Application Error

Question: I am New To Zend Framework. However while go through several tutorials I created a model file user.php where I created a class user extends Zend_Db_Table_Abstract and when i create an object of that class in my controller file it gives the application error as follows:

Fatal error: Class 'User' not found in /opt/lampp/htdocs/hello_zend/application/controllers/ShowketController.php on line 17
Comment: in what folder did you create the model file?
Comment: If you're using the latest Zend Framework version. The class should be called `Application_Model_User` and the file path should be `application/models/Users.php`. Mind that if you're extending the table abstract you should use plural Users, User would be the row class for Users.
Comment: First you have to rename file user.php to User.php.
if that class is in the folder Model, give the class name like this: class Model_User { ... } [ or Application_Model_User as markus says]
Answer: You have to load file where the class User is, or autoload all model class.
How to do that, You will find answer here:
How mvc works in Zend framework
Comment: Its not working I tried those things but it gives some errors as    Application error
Exception information:

Message: No adapter found for Model_User
Comment: can you copy/paste your model class pls ?
Comment: Zend_Db_Table::setDefaultAdapter($dbAdapter); // $dbAdapter = your Zend_DB instance


Hyperlink with hashtag do not open in new tab

Question: i am using this code to open all the URLs in new tab.
but i want the url with # do not open in new tab. for example:

jQuery("a").attr("target", "_blank");

content
Contact

Thanks
Answer: You can check working fiddle jsfiddle.net/bharatsing/t0fkzL5p/
$("a").click(function(){
    var href=$(this).attr("href");
  if(href!="" && href!="#"){
    $(this).attr("target", "_blank");
  }
  else{
    return false;
  }
});

Answer: You can check the href attribute value before appending _blank.
jQuery("a").attr("target", function() {
  if ($(this).attr('href') != '#') {
    $(this).attr('target', '_blank');
  }
});

In the above code, we check for the href value, if it's # then ignore it, else append _blank value to the elements target.
Demo

If you are looking to ignore all a tags where href starts from #, you can do something like
jQuery("a").attr("target", function() {
  if ($(this).attr('href')[0] != '#') { //checks for the first char, if #, ignore
    return '_blank';
  }
});

Demo
Comment: Also checked #contact?
Comment: @vusan Aah, I thought he wants to ignore blank hash urls, will modify
Comment: @Mr.Alien the second demo is exactly what i am looking for. Thanks
Comment: Yea, I thought you wanted to ignore the ones with `#` only.. @SajjadAhmad


Double neutral wiring

Question: I'm replacing an outlet and came across this wiring, which I had not seen so far in any other outlet in my house. It's not pigtailed, both neutral are just shoved into the same terminal. Should I mimic this in my replacement or do something different?
Answer: It doesn't look like they shoved 2 ends under the screw - that would be very shoddy indeed.  It looks like they stripped insulation off about 1" of the wire mid-run, and looped it around the screw.  That's legit.
If you need to cut that for some reason, either pigtail or cut it dead in the middle and get a "screw-and-clamp" type recep, which allows 2 wires per screw. Easy peasy.
Comment: ...How engineers (or fussy technicians) reduce the resistance of the connection to the next device ever-so-slightly by cutting only the insulation, so the conductor is unbroken. I resemble this remark when it makes sense. Few electricians will bother, in my limited experience.

Double neutral wiring


How to update ngx-webstorage key value?

Question: I have a component that calls webstorage and retrieves an instance of key-value store. On update, the stored item is not being changed.
<code>@Component({
  templateUrl: 'accomodation.component.html',
 providers: [ItemService]
})
export class AccomodationComponent implements OnInit {
  selectedItem = new Item();
  constructor(private warehouse: Warehouse) {
  }

  ngOnInit() {

  }

  storeData(selectedItem: Item) {
    this.warehouse.set('item',selectedItem);
  }

  updateData(updatedItem: Item) {
    this.warehouse.set('item',updatedItem);
  }

}
</code>
Answer: The ngx-warehouse api is working well, It was the problem with Google Chrome which was not refreshing indexedDB storage, After hours of debugging i tried mozilla and saw that it was working like charm.

How to update ngx-webstorage key value?


How to get the level of each node from a tree demonstrated in a dictionary?

Question: I have a tree data structure demonstrated in a List as the following:
Dictionary<int, List<int>> // Key, list of children

Data(1) = { 2 } // root
Data(2) = { 3 }
Data(3) = { 4, 5 }
Data(4) = { 5 }
Data(5) = {   } // leaf

I wonder if you could help me with creating a dictionary of Items and levels:
Dictioanry<ItemID, Level>
Comment: List only supports a single generic parameter (and you have 2). Can you post some real c#?  I don't understand your pseudocode.
Comment: That's better.  Now, do you mean level=depth? So do you want a dictionary like this? {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 4}, }?  The 3 has 2 children (4 and 5).  4 also has a child of 5?  So what level would 5 have?  4 /and/ 5?
Comment: @agent-j: Sorry, it's a dictionary of (Key, Children)
Comment: @ agent-j : You're right, yes the depth. Actually the max value.
Comment: I think a `Dictionary` and the tree hasn't max value every node/leaf in the tree has its depth,parent,and children nodes except root node hasn't parent
Answer: Not sure that it is the best solution, but should work:
        var data = new Dictionary<int, List<int>>();
        data[1] = new List<int> { 2 };
        data[2] = new List<int> { 3 };
        data[3] = new List<int> { 4, 5 };
        data[4] = null;
        data[5] = new List<int> { 6, 7 };
        data[6] = new List<int> { 8 };
        data[7] = null;
        data[8] = null;

        var allparents = new Dictionary<int, int>(data.Count);

        foreach (var node in data) {
            if (node.Value != null) {
                foreach (var child in node.Value) {
                    allparents[child] = node.Key;
                }
            }
        }

        int root = data.Keys.Except(allparents.Keys).First();
        int maxdepth = 1;
        foreach (int child in allparents.Keys) {
            int depth = 1;
            int parent = child;
            while (parent != root) {
                ++depth;
                parent = allparents[parent];
            }
            if (depth > maxdepth) {
                maxdepth = depth;
            }
        }
        Console.WriteLine(maxdepth);

Answer: If you used this node class, you can simply do this:
nodes.All.ToDictionary(n => n.Value, n => n.Level);

You need to fill the tree a little different (see the info in the link)


Hibernate Criteria Restrictions AND / OR combination

Question: How would I achieve this using Hibernate Restrictions?
(((A='X') and (B in('X',Y))) or ((A='Y') and (B='Z')))

Answer: think works
Criteria criteria = getSession().createCriteria(clazz);
Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"),
           Restrictions.in("B", Arrays.asList("X",Y)));
Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"),
           Restrictions.eq(B, "Z"));
criteria.add(Restrictions.or(rest1, rest2));

Answer: For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();


Issue while using the jQuery function .load()

Question: I am having an issue on my site where I am attempting to load the contents of a PHP file into a
.  I have ruled out the possibility that it is a server-side issue, so this leads me to my question.  Can you find anything wrong with the following code?

I am aware that for security reasons, browsers do not allow .load() to load content from external domains; however, would using window.location.host be an issue as it is the same domain?
Comment: what happens? Does it give you an error? Is it just blank? Did you try removing the `window.location.host`? You don't really need it.
Comment: Shouldn't all of that code be in a document.ready function?
Comment: @Connor: Not if it's after the elements in question.
Answer: window.location.host only includes the host name, not the protocol, which is necessary. Include that too:
$(".content").load(window.location.protocol + '//' + window.location.host + "/index.php?url=" + toLoad);

Of course, you probably don't even need that; a leading / will get you an absolute URL:
$(".content").load("/index.php?url=" + toLoad);

Comment: You can also use `window.location.origin`, but only on WebKit-based browsers.
Answer: Try using window.location.hostname as window.location.host also includes port number and sometimes other characters


Hybrid intel nvidia laptop with two 4k monitors

Question: I was hoping someone here could help me. I have a laptop (hp spectre 360 15"). It has intel gpu on board the motherboard, and a geforce mx150 card. I am running ubuntu 19.04. I have a laptop dock (cable matters thunderbolt 3 dock) that attaches via thunderbolt and has 1 hdmi out and 1 usb-c out ( for monitor ). Each of my monitors work separately but I can't get the system to use both of them. When I run xrandr I see both monitors and they both say connected.
I don't know where the problem is. I'd be happy to provide any diagnostic material. I just don't know many commands.
Thank you
Raif
Comment: Thunderbolt docks are notorious for having problems. I use a direct USB-C thunderbolt to HDMI adapter and only problem was 24Hz at 4K. I bought the new model and got 54 Hz which was much easier on eyes.
Comment: I use the USB-C thunderbolt to HDMI cable as well.  My one 4k ( which ever one runs ) is at 30Hz I'm a developer so I'm not watching videos or playing games.  So I don't notice much difference. I just want my other monitor to work.
Answer: Turns out the cable matters thunderbolt 3 dock will only display one monitor for the hp spectre 360.  Found that gem buried in the knowledge base.


How to add wallpaper with CSS on a Hugo theme?

Question: For the main discussion, see here: https://discourse.gohugo.io/t/how-do-i-add-a-wallpaper-to-my-site-page-cannot-figure-it-out/49084/1
I was told to ask here. Am using the JuiceBar theme on my Hugo-made site. The theme I'm using makes this tricky. My _background.scss code is:
@import "_variables";

    .background-container {
      position: fixed;
      top: 0;
      left: 0;
      height: 100vh;
      width: 100vw;
      background: linear-gradient(
        90deg,
        var($tertiary3hover) 100%,
        var($tertiary2) 100%
      );
      clip-path: ellipse(148% 70% at 91% -14%);
    }

My baseof.html code is:

        {{- partial "header.html" . -}}

        {{- block "main" . }}{{- end }}

        {{- partial "footer.html" . -}}

My _variables.scss imports for bodyof.html are:
$tertiary2: #313131;
$tertiary3hover: #099dd7;

And then I've added
@import "background";

to my styles.scss file.
This all semi-works. For example, this is how it's coming out currently:
https://i.imgur.com/RYAr56x.png
I want the blue/grey, but my results are grey/white, even though my variables and whatnot are for the blue and grey. I have with also tried messing with the "0%" and "100%" parts too.
But here is the entire big issues with this:
With the

added to my baseof.html file, it wipes out the bottom half of my entire site/page. This is how it looks WITHOUT that code added (normal): https://i.imgur.com/IeHhiss.png
When the code is then added, it wipes out the entire blog post section. How can I achieve the blue/grey background design I want without destroying the site?
I have tried just about everything at this point. I'm stuck.
Answer: This would best be accomplished in the following manner:

Set the background-color of the body to what you want the bottom half to be.

Set the background-color of the element and give it the clip-path.

This will ensure you always have the nice separation.

html {
  height: 100%;
  box-sizing: border-box;
}
*, *::before, *::after {
  box-sizing: inherit;
}
body {
  margin: 0;
  min-height: 100%;
  background: #313131;
}
.bg {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: fixed;
  background: #099dd7;
  clip-path: ellipse(148% 70% at 91% -14%);
}

The reason that the linear-gradient doesn't work is that the clip-path that is being applied hides the bottom half of it.
Comment: Hi, @Dan-Mullin! So, I put the CSS in my _background.scss file and the  HTML stuff in my baseof.html file. Your CSS is getting the colors correct for the background, but depending where I place the HTML, it still wipes out some of the site. Here is baseof.html file: https://i.imgur.com/HWFU0Y5.png - If I put it under the body tag and  before  I get: https://i.imgur.com/c49xpqM.png - If placing code and  right under  I get: https://i.imgur.com/Mowkwmo.png - As you can see, it seems to do everything except what I need it, haha. Please help.


How do I install StarCraft 1.18 on Wine with 64-bit Linux?

Question: I'm trying to install the free StarCraft 1.8 on Linux using Wine.
When I try to run the installer I receive a message:

".../StarCraft-Setup.exe" not supported on this system

Do I need to install the 32-bit version of Wine for it to run?

Update, after installing Wine 32 bit I can run it, but now I have this error message:
<code>00e1:err:module:LdrInitializeThunk "ClientSdk.dll" failed to initialize, aborting
</code>
Answer: Installed Wine-staging 6.6 and the game is running fine.
Answer: I've struggled with this a lot, but ultimately it worked for me out-of-the-box when I tried installing it using https://lutris.net/.
I've installed both the Battle.net launcher and StarCraft Remastered (they exist in the Lutris database already) and it prompted me to install a bunch of "vulkan" things and other related drivers and addons, but it did all by itself and then the launcher just worked.
Answer: When in doubt, visit WineHQ's AppDB.  It's got all sorts of useful information about running programs under Wine.  Support for Starcraft 1.18+ is currently listed as "garbage" (doesn't run), but the rating history suggests that if you can get a copy of Wine 3.15, it should work without trouble.
Comment: I'm using Wine 5.


How do i store the output of AWK as a variable to use in a SED command in a BASH script?

Question: I have used this to create a character string:
awk -F "|" 'NR==1 {print $2$4}' file

I now want to use this string to replace another string using SED, using this code, which i know works:
sed -i.bak 's/\(<remote>\).*\(<\/remote>\)/<remote> http:\/\/blabla\/'$var' <\/remote>/g' file2.xml

But what i can't figure out is how to save the output of the awk as $var first to use as an input for SED. can anyone help? thanks.
Comment: The above sed command will fail cryptically for various settings of `var`.
Answer: Don't do that, just use awk, e.g.:
awk -F'|' '
NR==FNR { if (NR==1) var = $2$4; next }
{ gsub(/<remote>.*<\/remote>/,"<remote> http://blabla/" var " </remote>"); print }
' file file2.xml > tmp && mv tmp file2.xml

With GNU awk you could make it more efficient but it won't make a noticeable difference unless your first file is huge:
awk -F'|' '
NR==FNR { var = $2$4; nextfile }
{ gsub(/<remote>.*<\/remote>/,"<remote> http://blabla/" var " </remote>"); print }
' file file2.xml > tmp && mv tmp file2.xml

wrt a comment I made in someone else's post, here's why you should us -v var=val instead of populating variables in the awk args list unless you need to do that to change initial values between files (not necessary with GNU awk courtesy of BEGINFILE):
Here's a script to add the values stored in 3 files to some initial seed value and print the result for each file and across all files (the seed is just added once to the total). file2 is empty:
$ cat file1
3
6
$ cat file2
$ cat file3
2
5
$ cat tst.awk
BEGIN {
    print "seed value =", seed

    for (i=1; i<ARGC; i++)
        subtotal[ARGV[i]] = seed

    total = seed
}

{
    subtotal[FILENAME] += $0
    total += $0
}

END {
    for (filename in subtotal)
        print "File", filename, "subtotal =", subtotal[filename]

    print "total =", total
}
$
$ awk -v seed=7 -f tst.awk file1 file2 file3
seed value = 7
File file1 subtotal = 16
File file2 subtotal = 7
File file3 subtotal = 14
total = 23

All makes sense right? Now lets move the setting of "seed" into the argument list:
$ awk -f tst.awk seed=7 file1 file2 file3
seed value =
File file1 subtotal = 9
File file2 subtotal =
File file3 subtotal = 7
File seed=7 subtotal =
total = 16

Note that the seed value is missing from the first print, the subtotals and total are wrong, and there's an output trying to print a value for a file named "seed=7".
It's all explicable and predictable once you know exactly what you're doing with awk but I bet it's pretty baffling to a newcomer so IMHO populating variables in the arg list should not be how we advise people to initialize their variables by default since it's got far less intuitive semantics than -v variable=value.
Comment: The first and second awk statements both do exactly what i asked. Thank you! I now need to do a bit more though; I want to read the lines of `file` and for each line do this action on their own unique `file.xml` which already exists and it's location is given by `$6` in `file`. Is this possible?
Comment: Yes, any text processing is possible. Post a new question with your new requirements, sample input and expected output.
Answer: var=$(awk -F "|" 'NR==1 {print $2$4}' file)

But its better you give us data and what to do with it.  This way we can make an awk or sed that does it all.
Edit:
var="test"
echo "https://blabla/bla/bla </remote>" | awk '{$NF="</"v">"}1' v="$var"
https://blabla/bla/bla </test>

This will replace the something with value of $var
Comment: That didn't quite work.... the SED no longer accepts the variable, when i had var=string before it had no problem. So what i need to do is replace the contents of this element: ` https://blabla/bla/bla ` with the combination of 2 fields delimited by a "|". I am new to stack so doing my best, also can't go into too much detail due to the content of the data. Thanks
Comment: IMHO you should only set variables in the awk arg list if they need to change between files and if you're going to set variables in the awk argument list, you should at least make sure the person you're replying to understands the negative impacts of doing it that way vs using `-v variable=value`.


Add data into php mysql with single quotes

Question: This is my code:
$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");

      while($e=mysql_fetch_assoc($q))

              //$output[]=$e;
              //echo $e['NAME'];
              {
              $name = $e['NAME'];
              $brand = $e['BRAND'];
              $category = $e['CATEGORY'];
              $query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
              $result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
              }

Since in "BRAND", there may be some data like "First's Choice".
In this case, I cannot insert to database due to error.
How can I insert data that contain single quotes?
Thx
Comment: try reading here  http://php.net/manual/en/function.mysql-real-escape-string.php
Answer: you need to use mysql_real_escape_string on the value, which you should be doing anyway. That should properly escape your value for insertion.
$name = mysql_real_escape_string($e['NAME']);
$brand = mysql_real_escape_string($e['BRAND']);
$category = mysql_real_escape_string($e['CATEGORY']);
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";

Answer: Use mysql_real_escape_string
Answer: You must use :

$brand = mysql_real_escape_string($brand)

See PHP Documentation.

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Escapes special characters in
  the unescaped_string, taking into account the current character set of
  the connection so that it is safe to place it in a mysql_query(). If
  binary data is to be inserted, this function must be used. (..)
Answer: Try below code

$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");

      while($e=mysql_fetch_assoc($q))

              //$output[]=$e;
              //echo $e['NAME'];
              {
              $name = $e['NAME'];
              $brand = mysql_real_escape_string($e['BRAND']);
              $category = $e['CATEGORY'];
              $query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
              $result = mysql_query($query) or die("Unable to insert because : " . mysql_error());
              }

Answer: There are two ways of accomplishing that. You can first run an escape string on it:
$newbrand = mysql_real_escape_string($brand);

and insert $newbrand. When you call it, you have to do strpslashes($newbrand);
OR you could do:
$search = array("'");
$newbrand = str_replace($search,'',$brand);

Answer: I was pulling my hair to solve this, finally i am ok with this solution. Try this


How to save Note item modification

Question: I am creating my Notes app using Core Data.
I am successfully creating New Notes using the following code:
let note = CoreDataHelper.newNote()
        note.noteTitle = noteTitleTextField.text ?? ""
        note.noteContent = noteContentTextView.text ?? ""
        note.noteDate = Date() as NSDate
        CoreDataHelper.saveNote()

However, how do I let the user save modifications on an existing note (vs. creating another new note)?
Hope someone can help. Thanks!
Comment: Can you post your `Note` model class? You need a unique id for every object so that you would know if one instance of `Note` is new or not.
Comment: You have to fetch a note from coredata by uniquely identifying it via some property. And then make changes and save again.
Answer: If you're working with existing notes, you would first fetch those notes from your managed object context. You're probably already doing this, if you're displaying existing notes in the app. Take whichever Note object you want to update and assign a new value to note.noteContent. Then save changes. Don't create a new note (as you do in the first line above)-- use one of the notes that you find in your fetch request results.
Answer: I think you have a sperate model for note (not managedObject type), What you can do is set the model and when user tries to save the modified data find and fetch the item (note) from coredata in required managedObjectContext with the help of id and then set the properties as modification on the fetched managedObject . Finally  managedObjectContext.save() will save all data as per modification. This approach will actually be helpful in the scenerios where user will cancel all the modification.

How to save Note item modification


Is it safe to assume memory won't get destroyed before Application's onCreate is triggered again?

Question: I want to fetch some important data in onCreate of my Application, and store them in the memory.
Can I assume the data I store in memory will be there? If the app get destroyed, can I assume onCreate will always get triggered again?
Comment: What is the "global object" concept?  Java doesn't have globals.  Do you mean `static`?
Comment: How would you access these objects?  If you don't have a way to access them, it is moot whether they are technically still in memory.
Comment: It's in a global object. I remembered Android can destroy the stack and restore the top of the stack when user enters the app.

If only the topmost activity get created, does it mean my global object is gone and application onCreate won't get called?
Comment: Yes they are store in a static object
Answer: From the documentation for onCreate

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

If your application is killed in the background by the system, then it would have to call onCreate again next time it is launched. As long as you re-initialize your static value in onCreate each time it should be safe - assuming your application class would hold a reference to it to prevent it from being garbage collected.
You may also find this question useful regarding garbage collecting of static variables.
Answer: I don't think that you can depend on that.
If you really need to recover the information, you'll need to store it somewhere that survives the destruction of the application, like local storage, or a database.
Comment: I am fine with fetching it again. If the app get recreated, is Application onCreate guaranteed to be called?


Fit to height of browser's window

Question: I want to achieve the following layout with 100% height to browser.

Only the content area should be scrollable, when required and footer should be display at the bottom of browser.
But after tried many times i got this one

by using following code.
html { height:100%; }
body { position:absolute; height: 100%; overflow: hidden; top:0; bottom:0; right:0; left:0; padding: 0px; margin: 0px;}

#header, #footer {
    float: left;
    width: 100%;
    /*height: 100px;*/
    background-color: #808080;
}

#wrapper {
    overflow: scroll;
    height: 100%;
    width: 999px;
    margin: auto;
}

//HTML code
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Satkar Travels</title>
        <meta name="keywords" content="ltc, travel, Satkar Travels, lfc, Satkar Parivar, Satkar Holidays, Satkar Travels Gurgaon">
        <meta name="description" content="A Leader in LTC Travel.">
        <meta name="author" content="Satkar Travels">

        <link rel="stylesheet" href="StyleSheet.css" type="text/css">

please help
Thank you.
Comment: Make header and footer to position : fixed and then give them height. For header make top:0 and for footer make your bottom:0
Comment: @PatsyIssa look in his taskbar he has 4 different browsers right there, with chrome and opera even being active.
Comment: Try removing the `height` for the `html` tag. And make the `wrapper` height equal to the `body` minus the height of `header` and `footer`. Or remove the `header` and `footer`
Comment: Totally unrelated but do consider using something other than IE.
Answer: Try this example:
.header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color:red;
}

.container {
  position: absolute;
  top: 51px;
  bottom: 51px;
  left: 50%;
  width: 900px;
  margin-left: -450px;
  overflow: auto;
  background-color: blue;
}

.footer {
  position: absolute;
  bottom: 50px;
  left: 0;
  right: 0;
  height: 50px;
  background-color:red;
}

And then this:

Here is a fiddle: http://jsfiddle.net/dxL7s/
Is this what you need?
Answer: Just need to change in CSS.
Example: demo
or
Apply this css:
html { height:100%; }
body { position:absolute; height: 100%; overflow-x: hidden; top:0; bottom:0; right:0; left:0; padding: 0px; margin: 0px;}

#header{
    float: left;
    width: 100%;
    /*height: 100px;*/
    background-color: #808080;

}
#footer {
    width:100%;
    position:fixed;
    bottom:0;
    left:0;
    background:#808080;
}

#wrapper {
    overflow: scroll;
    height: 100%;
    width: 999px;
    margin: auto;
}

Answer: I would use fixed position, to align the header and footer at the top and bottom. Then just leave the content with a margin-top to keep it below the header.
HTML:

    Lorem ipsum

CSS:
header {
    height: 50px;
    width: 100%;
    background-color: #f00;
    position: fixed;
    top: 0;
}

footer {
    height: 50px;
    width: 100%;
    background-color: #ff0;
    position: fixed;
    bottom: 0;
}

div#mainContent {
    margin-top: 60px;
}

Fiddle demo: http://jsfiddle.net/w22dr/1/

Fit to height of browser's window


remove all anchors except it's contents?

Question: I found that sometimes this code returns NotFoundError: An attempt was made to reference a Node in a context where it does not exist.
$('a').replaceWith(function() {
    return $.text([this]);
});

Is it complaining about a case when the anchor does not have any text node? perhaps a child HTML element?
Comment: What parts are you trying to keep? href="this" or this?
Comment: what is your target markup and the desired output
Comment: I think you should use return $.text(this);
Comment: @LJ-C I am trying to remove the anchor tag entirely
Comment: @C-link still returns the error
Comment: @ArunPJohny I am targetting all anchors so anything like `anything here text or html` and return `anything here text or html`
Comment: what is the desired output you are looking for
Answer: Try this:
$('a').contents().unwrap()

DEMO
Comment: then please update demo with some real world html for comparison. It's not entirely clear what the issue is
Comment: @charlietfl I've provided the real world html which your code and my code brings about different results. http://jsfiddle.net/KLq5w/3/
Comment: there's script in your html that  throws errors, please remove. What are you wanting, text only? No images? Would help to scale your demo html down to just a few links...and show what output you want as well
Comment: basically with my code it seems to remove the empty spacings beside the title of costumes. with your code it seems to retain the empty spacings. I don't know what is causing this.
Comment: mine just unwraps what's inside which is what the subject title of your posts suggested. If you get `text()` of element that has many text nodes in different children, children can be separated by css...no gurantee that `text()` won't cause some merging. Still not clear what output you wnt...and it's been asked numerous times


SQL Server Hekaton Reclaim Memory Used by Dropped Memory-Optimized Tables

Question: I'm using

Microsoft SQL Server Enterprise: Core-based Licensing (64-bit) Version
  12.0.4100.1

I have a code which creates many non-durable memory-optimized tables, uses them for some things, and drops them when it doesn't need them anymore.
However, it seems as though the dropped tables are still consuming RAM, since if I run
SELECT pool_id, Name, min_memory_percent, max_memory_percent, max_memory_kb/1024 AS max_memory_mb,
    used_memory_kb/1024 AS used_memory_mb, target_memory_kb/1024 AS target_memory_mb
FROM sys.dm_resource_governor_resource_pools
WHERE Name='InMemoryObjects'

I get the following:
pool_id  Name                min_memory_percent max_memory_percent  max_memory_mb   used_memory_mb  target_memory_mb
256      InMemoryObjects     50                 50                  380003          233239          380003

Notice how high the "used_memory_mb" column is.  There are no memory-optimized tables in the server at the time I ran this, so I figure it must be data from the dropped memory-optimized tables still somehow taking up RAM.
Similarly, when I run
SELECT type, name, memory_node_id, pages_kb/1024 AS pages_MB
FROM sys.dm_os_memory_clerks WHERE type LIKE '%xtp%'

I get the following output:
type            name        memory_node_id  pages_MB
MEMORYCLERK_XTP Default     0               1055
MEMORYCLERK_XTP DB_ID_19    0               6
MEMORYCLERK_XTP DB_ID_33    0               6
MEMORYCLERK_XTP DB_ID_41    0               56
MEMORYCLERK_XTP DB_ID_47    0               0
MEMORYCLERK_XTP DB_ID_32    0               233240
MEMORYCLERK_XTP Default     1               0
MEMORYCLERK_XTP Default     64              0

See how DB_ID_32 is taking up the same ~240gb of RAM?
I need some way to clear this out.  When I run more than one instance of the code, I get the error
"There is insufficient system memory in resource pool 'InMemoryObjects' to run this query".  So I think this memory has to actually be tied up, and doesn't release itself when it gets full.  The resource pool 'InMemoryObjects' was made just for this one code, and there are no other memory-optimized objects in the entire server besides the ones this code creates (and subsequently drops).  The memory-optimized tables it creates are all reasonably small (a few gb apiece).
I know the garbage collector is supposed to run every minute, but it has been over a day since any memory-optimized tables have existed in the database, and the memory used hasn't decreased at all.  I've tried forcing garbage collection, checkpoints, resetting statistics, etc., and haven't been able to get this memory back.
The only thing I've found that works is taking the entire database offline and bringing it back online.  But I really can't do that each time I run the code, so I need a better solution.
Any ideas would be immensely appreciated.  Thank you!
Comment: Are you taking regular log backups?
Comment: I'm not manually taking any log backups.
Answer: I think this might be a reason. But I'm surprised the forced garbage collection doesn't pick it up. From the MSDN documentation on the in-memory garbage collection:

After a user transaction commits, it identifies all queued items
  associated with the scheduler it ran on and then releases the memory.
  If the garbage collection queue on the scheduler is empty, it searches
  for any non-empty queue in the current NUMA node. If there is low
  transactional activity and there is memory pressure, the main
  garbage-collection thread can access garbage collect rows from any
  queue. If there is no transactional activity after (for example)
  deleting a large number of rows and there is no memory pressure, the
  deleted rows will not be garbage collected until the transactional
  activity resumes or there is memory pressure.

https://msdn.microsoft.com/en-us/library/dn643768.aspx
Might try the filestream garbage collection? I think I read somewhere that the in-memory optimized filegroup that a db must have uses the filestream technology. Don't quote me on that.
Comment: I appreciate the input.  I've read that same documentation, but A) there is clearly memory pressure, since I can sometimes get the "There is insufficient system memory in resource pool 'InMemoryObjects' to run this query" error, and B) There is still plenty of transactional activity (since the code goes on to create and delete many other tables).  I have also already tried the force filestream collection with no luck.
Comment: When I look at sys.dm_xtp_gc_queue_stats, 22 of the 64 queue_id's have a nonzero "current_queue_depth", indicating they're still in garbage collection queue (I think).  Most of these 22 current_queue_depths are 59136 or 59137 (but I'm honestly not sure what these numbers mean).
Comment: A current queue depth means there is GC work to do, but it has not yet been done. Multiply that number by 16 to get the number of rows queued for GC. I am currently working on a similar issue where the XTP clerks grow and start starving the buffer pool, even though we only use memory optimized table variables. What are the stats on this box? If I had to guess I would say its a 16 core/768gb of memory?


Self Service Checkouts

Question: I have, in the last few months, had to endure these hideous devices. I dislike them because I find them intensely patronising "Invalid item in bagging area" - no it isn't, it is the item you have just scanned. There are others as annoying. And they are normally quite loud too. It strikes me that the UX is really poor - all of the issues that we thought we had progressed beyond years ago.
So my question is, why is the UX so poor, so far behind, for devices that are new and leading edge? Why do they not interact in a 2012 way, rather than a 1999 way?
Comment: I think the question is how do the things make it to installation without seemingly being tested propertly ? This is expensive physical kit, which you can't just fix with a software upgrade...
Comment: I feel your pain, but don't see an a constructive and useful question here.
Comment: The question is, why do new products like this not have substantially better UXs?
Comment: @PhilipW - yes, and especially with this type of product wich is a new product, not hamstrung with historical requirements. It seems like a good opportunity to do it right.
Comment: @SchroedingersCat Could you please add a photo or some other context? Or is your question more a usability-process-related one?
Comment: It is more process related. I think a lot of people have experienced these, but if not, just consider yourself lucky. So far.
Comment: Here's a bit more background:  http://www.telegraph.co.uk/finance/newsbysector/retailandconsumer/7957800/Self-service-checkouts-have-not-cut-supermarket-queues.html
Comment: And there's a few more actual facts in this : http://www.telegraph.co.uk/journalists/alastair-jamieson/7957846/Bleep-it-and-weep-the-frustration-of-using-self-service-checkouts.html
Answer: I think there are five main issues with auto-checkouts - each with its own particular cause.
Issue 1 The machine doesn't make smart decisions, or let me short cut its workflows - e.g. if I've entered a debit card, I automatically want to pay by card, but the machine insists I remove the card, press 'pay by card' and try again.
Possible cause? Designers who take for granted the workflow the supermarket imagines users will take rather than practical insights into the ways shoppers actually work. Lack of attention to the 'NATty principle' ('Never Ask Twice').
Issue 2 Autocheckouts rely too much on human supervisors arbitrating decisions, when assistants are usually in short supply and often busy directing customers to terminals.
Possible cause? Miscommunication about the context of the product. I strongly suspect that whereas the designers were assured that supervisors would always be on hand to help, supermarkets have 'sold' the service internally as a way to reduce supervisor workload. That would mean staffing managers under-resourcing autocheckout lanes, yet designers assuming a supervisor will always be able to help.
Issue 3 Poor item detection. Too many items get flagged as 'invalid', and I have to get a supervisor to help.
Possible cause? Probably just limitations in item detection combined with excessive concerns about shoplifting and malicious users. Misunderstanding that failures make a serious impact in this context, because assistants are not always readily at hand.
Issue 4 Intolerant timeouts - if I'm having trouble bagging something, and I take a little too long, the entire terminal closes down, and I can't continue - even if I do eventually bag the item in question.
Possible cause? This could be simply a lack of practical research, combined with hasty assumptions about how long something 'should take' - when research will indicate something very different.
Issue 5 Cannot rebag items; performs poorly when I have multiple bags.
Possible cause? Hasty assumptions that I would never remove an item from a bag after I'd bagged it, and that I'd always have one small basket - in other words, assumptions that I'd work to the workflow the designer or supermarket imagines is likely, not what actually happens in practice. Inability to accept alternative workflows.
How could the designers have done better?

better thinking about the pragmatics of deployment, and not assuming the availability certain resources (supervisors to assist; maintenance to keep touchscreens clean and thus responsive)
field research into how undirected shoppers will actually proceed; healthy scepticism about assumptions regarding workflows and behaviour
better handling of failures in workflows; better research into impact of 'lockdowns'
Comment: With regards to issue five; I hate it when I bring my own bags and they make it impossible to use them.
Comment: Lack of research seems to be a common theme. It is just sad that in this day and age, no-one bothered doing the basic research.
Answer: My suggestion for them would just be to give Joe Public a simple display; a hand held scanner; a card terminal and a flat workbench area to work on.
People are quite capable of using a scanner without the machine trying to control the transaction. I think a lot of the problems come from the constrained physical layout.
The transaction really should be quite simple, and the machine doesn't need to control it:
1 - Scan items
2 - Insert Card and Pay.
The only complication required is a 'remove button item' for anything scanned in error.
Rather than all the 'bagging area' weighing problems, the issue of stopping people not paying for stuff would be dealt with by having a very visible camera and possibly a monitor showing the customer what the camera is recording.
Not only would this arrangement be easier to use - but it would also be a lot cheaper to build !

And the actual answer to the question is: UX people aren't involved in their design. (presumably)
Comment: Maybe the real answer is: the engineer got conflicting requirement analysis. "We need to trust the user, but control him anyway", is a bad starting assumption.
Comment: What you are proposing is far better! UX principles clearly shown, that the main route is the straightforward one, and then allowing for exceptions ( deletions etc ).

Self Service Checkouts


Knuth-Morris-Pratt algorithm for bidirectional iterators

Question: Is there any Knuth-Morris-Pratt algorithm implementation for bidirectional iterators? In Boost.Algorithm there is version for random-access iterators.
Comment: I'm not sure if one can do it efficiently. We need to make long "jumps" over the input string when we don't have a transition.
Comment: It's actually doable (there's even a purely functional linear time implementation), but it requires a little bit more memory.
Comment: I know it. But i did not find any docs about it.
Comment: Well, you can do it yourself. You just need to store the next char along with the value of `p[i]` for all `i` in the pattern.
Comment: Oh, how can we do it?
Answer: Let's take a look a standard implementation. The only place where we actually need random access is comparing pattern[i] and the current character after making jump i = p[i]. Instead of accessing pattern[i] directly (which would require linear time in the worst case for bidirectional iterators), we can store the next character c in the pattern along with p[i] when we build the transitions table.
However, it's not that useful. Storing a symbol for each i is essentially the same thing as copying the pattern to a structure that supports random access, so it would be easier to do it directly.
Comment: Thank you a lot. Do you know any effective search algorithms for bidirectional iterators?


Well pump keeps losing prime - no leaks in system

Question: I've been chasing this problem for a few months now. My well pump loses prime and throws air into the lines if I run the system hard - that means doing a large load of laundry, dishes, flushing toilets etc all on a busy morning. The largest culprit of this is a toilet that likes to seal improperly and run. If I miss that and don't wiggle the handle, I lose water.
The system holds pressure overnight - there are no leaks in the system.
Waiting a bit, re-priming the pump and then running it again gives me back (airy for a while) water. This seems to point to the well running dry. What confuses me is that this happens regardless of the water table level. I live on a sand peninsula with serious flooding issues - while the water table was well into most people's basements, I was still losing water quite often.
The previous owners of the house seem to have done some sort of calcium treatment to the well (I found an old bottle of calcium treatment tablets in the garage), but I'm not sure a) how to use them and b) how that would prevent the situation I'm having now (my water does not seem overly hard).
What are the next steps I can take to diagnose this problem?
Comment: Does your pump have one pipe to the well, (implying a shallow-well pump) or two (implying a deep-well-jet pump?)
Comment: It is a two pipe deep-well pump
Answer: This would appear to be a normal case of overdrawing the well - the system holds and does not leak, so the air is coming in when the water level in the well is pulled down below the pump intake.
You either limit the water use to what's available, or you spend a typically rather large sum on having a well driller deepen and/or hydrofracture the well, or drill a new well. If it's purely the drawdown rate that's an issue, having a slow pump filling a large cistern/reservoir/tank from which your house pump draws water at whatever rate you require (buffered by 1000-25,000 gallons of storage) is another solution.
It's possible (but not overly likely) that you might have more well than your pump setting, and the intake could be lowered, but usually there isn't a lot of extra hole below the pump intake. Though I did once live in a house where the pump was a shallow-well pump (so intake 25-27 feet down the hole, since that's as far as that pump type can suck) but the actual hole was 78 feet - however, while I lived there, anyway, the top 25 feet of the well was adequate for our water needs.
The water flow rate into your well can be limited by the hydrogeology around your well such that you can overdraw it even if the water table is high. Depending on the details of your well (unknown to us, and perhaps to you) it may not be drawing directly from surface water anyway (typically considered a good thing as it reduces the odds of contamination from the surface.)
At this point in my life, a troublesome toilet that resists repair gets replaced by a modern water-saving toilet (unlike the old ones, the new ones actually have hydraulic engineering so they actually flush on 5 or 6 liters or less.) Especially if that's going to save me an expensive well driller visit.
If you are on a well and have not had your water tested, you probably should do that (then you'll know how hard it is or isn't, and as many other things as you pay for - though basic hardness testing you can often get for free) but that's not going to have any direct impact on your well sucking air.
Comment: All good points - my largest concern is that this is relatively new (4-5 months) in a house I've lived in for 3 years. Can water tables change that quickly?
Comment: @BrydonGibson You're confusing water table with the well's water level. They are not the same. See Ecnerwal's paragraph 4.
Comment: Right, still getting the hang of the lingo. Would this point to an "issue" with my well, though? Should I be concerned that the refill rate is (potentially, maybe my water usage habits are different) changing?


Where can I find Master Ore?

Question: The blacksmith in Hyrule says he can temper my Master Sword if I bring him two Master Ores. Where can I find them?
Answer: There are 4 Master Ores in the game. Bringing 2 to each Blacksmith will upgrade your sword (First in Hyrule, then in Lorule)

Lorule Cemetary Dungeon: Enter the Lorule Cemetary through the crack in the Sanctuary. Lift the big rock in the top right corner of the cemetary, then complete the dungeon. The Master Ore is in a big chest at the end. Requires the Titan's Mitts.
Skull Woods Dungeon: After reaching the 2nd eyeball near the end of the dungeon you'll see a large chest on a very narrow platform. Merge with the wall ad move towards the platform and open the chest for a Master Ore.
Thieves' Hideout: After lowering the water level with the Thief Girl, make your way to the two floor switches on the bottom-left of the room to reveal a long corridor with red rupees and a big chest at the end containing Master Ore.
Dark Palace: On the top floor with the 6 windows, place a bomb by the lower switch and quickly merge with the top wall's upper-half with the Boss's face on it. You'll go into a room with a large chest containing a piece of Master Ore.

Source: http://www.zeldainformer.com/walkthrough/page/collectibles-guide
Comment: FYI you'll need the Titan Glove for flip some stuff at the cemetery.
Comment: @Krazer: Yes, I mentioned it in its entry

Where can I find Master Ore?


Making Firebase Database ultra secure

Question: I am trying to write perfect database rules for Firebase to block people from seeing each other's data. Every user has a API key saved on the database like this:
<code>-users:
    -user1:
       -APIKEY: "123asdasasd"
</code>
I am allowing the users to only set their API keys but they are not even able to see their saved API keys themselves. This is my security rule for that:
<code>"users": {
        "$userID": {
            ".write": "auth != null && auth.uid === $userID",
            ".read": "auth != null && auth.token.admin === true "
        }
    },
</code>
So even if someone impersonates some other user, they cannot access their data, only they can change it, and that is not a security problem for my app.
Because my app needs to be ultra secure, I also want to add cryptography to the database. I want the client to encrypt the API keys before saving on the database, and only my server will know the key to decrypt those API keys. So the keys stored on the database will be encrypted.
Is there any way a hacker who has access to my whole database be able to decrypt people's API keys without knowing the decryption key?
What are some good methods for cryptography in node.js? If the server knows a private key and no-one else knows that private key, is it simply secure?
Comment: Are you stating that *even if someone impersonates some other user, they cannot access their data, only they can change it,*. So if I impersonate you, and change your key to something I know then I would know your key, right? That doesn't sound very secure - maybe I misunderstand? Also, storing an API key on the client in the clear can be a security problem as well. I would suggest not leaning to hard on 'API keys' and leverage user accounts with authentication for security - Firebase authentication works well for that purpose.
Comment: Please explain what it means for a hacker to have "hacked my whole database".
Comment: @DougStevenson seeing whatever there is in my database
Comment: The only way that could happen is if someone had your Google account password.  At that point, your project could be in seriously bad shape, and I'm not sure what you could really do to stop them.
Answer: You're using the term "keys" for a few different things, which unfortunately makes it hard to answer. I'll give it a try though, since the main thing to consider is where you store the keys used for encrypting/decrypting the data.

If you store the encryption/decryption keys in the same database as the values that you encrypt with them, then anyone with access to that database can decrypt the data.
If you store the encryption/decryption keys in another database than where you store the encrypted values, then a malicious will need access to both databases to be able to decrypt the values with the key.

Of course both approaches are susceptible to brute force attacks. So if your encryption is not sufficiently strong, the whole point of encrypting the data is moot.
Recommending specific libraries for encryption is off-topic on Stack Overflow btw, but a few well targeted Google searches should give you plenty of good candidates.

Making Firebase Database ultra secure


Three Way Switch Works With Power Off

Question: I have a switch box with 3 switches in it, each powering a different light.  All three switches are supplied by pigtails from one incoming cable.
Two switches are simple single pole switches and when the breaker is turned off those lights stop working.
The third is a 3-way switch and when the breaker is turned off, the light continues to work.
All four combinations of both 3-way switches work as expected, with the breaker off.
When the 3-way switched light is lit, it does NOT back-feed the other two lights.
I read online that there used to be a technique used where two breakers/fuses on the same phase were connected through some black magic to power a light, but I can't envision how it works.
Sadly half of the wires are knob and tube so I can't see any neutrals.
Comment: The incoming supply cable.   Does it have 3 conductors  black red white?
Comment: Can you turn off a different breaker along with the first one and make the 3-way controlled light turn off?
Comment: The supply to the box is a single wire, pigtailed to all 3 switches.  On the 3-way switch it is connected to the Common terminal.    Yes, I've identified another breaker that cuts power to the light.
Answer: It looks like a Carter-style 3-way (as you state that have knob&tube). In my opinion you have a 3-way on a circuit and the other on another circuit with a shared neutral.
Comment: I agree that it sounds like the Carter system, amd that explains the comment I saw about same-phase hots.   Wikipedia's diagram of the Carter system seems to show that there is one traveler wire, but the common connection on my 3-way switch is connected to a cable known to go back to a breaker, and not to the light fixture.
Comment: You can verify: get a test-light (not the touch-less model), with all breakers on, switch the light off, unscrew the bulb and test both connectors, if you have both cold flip both switches (light should still be off but switches should be in the opposite position than in the first test) and test again, if you got 2 hots on the bulb contacts it's the proof you're on carter system
Comment: Another hypotesis is that your 3-way is connected to another fuse and the only thing that your switches share is the wall box
Comment: Thank you, I will test the fixture to see if there is a combination that results in the socket being Hot-Hot while off.

Three Way Switch Works With Power Off


Parenthesis vs brackets for matrices

Question: When I first learned linear algebra, both the professor and the book used brackets like [ and ] to enclose matrices. However, in my current differential equations textbook, matrices are enclosed by parenthesis, and I suddenly realize everybody else are using them too.
So are brackets/parenthesis for enclosing matrices always totally interchangeable?
Answer: It is just a question of notation and what you are comfortable with. The only thing you might want to be aware is |A| stands for determinant of the matrix A and hence cannot be used in place of () or [] to represent the matrix
Answer: They're interchangeable. I think a lot of people tend to use parentheses just because they're easier to write by hand.
Comment: @Michale Lugo: and less easy to confuse with vertical bars, which denote determinants (at least to me)...
Comment: I actually used to hate parentheses for matrices for some reason; it always seemed "less rigorous." Then I had to TA for linear algebra... It is much easier to slap some parentheses on the board than brackets =)
Comment: Bey, I'm teaching game theory this semester. Lots of matrices. You bet I'm using parentheses. (And I even use parentheses in things I write up in LaTeX, like solutions to the homework, just for consistency.)
Answer: There are two notations for matrices, ( ), [ ]. Use the one with which you are comfortable with.
Below are examples of both for the 3x3 Identity matrix.
$$
\begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{pmatrix}
\\
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
$$
Answer: This is a common questions that I've been asked time to time. Whether or not you choose to use:
\begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{pmatrix}
or
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
is up to you.
The difference between the notations is that the parenthesis notation
\begin{pmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{pmatrix}
is mostly used by mathematicians.
However, the square bracket notation
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
is mostly used by engineers or physicists (i.e. all other science disciplines other than mathematics). This is analogous to the reason why the spherical coordinate system used by physicists and engineers have the two angles labelled the other way, compared to that used by mathematicians. As a mathematician, I tend to stick with using the parenthesis notation.
Having said that, it is worth noting that | | notations denotes its determinant, not a matrix itself.
Answer: In general, if you want to write a matrix, use square brackets [] or parentheses (). Personally I tend to use the square brackets to denote that the matrix is of linear nature, the parentheses for nonlinear matrices.
So, as an example, when doing a linearisation of the nonlinear matrix B around $x = [0,0]^T$, I would write it like this:
\begin{equation}
B =
\begin{pmatrix}
x_2 \\
-x_2 - \frac{g}{l}\sin(x_1)
\end{pmatrix}
\Rightarrow
B^* =
\begin{bmatrix}
0 & 1 \\
-\frac{g}{l} & -1
\end{bmatrix}
\end{equation}
As already mentioned by others, what matters most is that you do NOT use the absolute bars to denote a matrix. So NOT like this:
\begin{equation}
A =
\begin{vmatrix}
a & b \\
c & d
\end{vmatrix}
\end{equation}
The vertical lines represent the determinant. (Although a lot of people will write $det(A)$ instead.)

Parenthesis vs brackets for matrices


cross product of a position vector and a vector field

Question: The problem is to simplify the following expression: $$\nabla\times[\frac{(\vec{B}\cdot\vec{r})}{r^3}\vec{r}]$$ where $\vec{B}$ is a constant vector and $\vec{r}$ is a position vector.
So $(\vec{B}\cdot\vec{r})$ is scalar product and $\frac{(\vec{B}\cdot\vec{r})}{r^3}$ is a scalar field. Which means the identity $$\nabla \times (\Phi\vec{r}) = \Phi(\nabla\times\vec{r}) - \vec{r}\times(\nabla\Phi)$$ can be applied. And $\Phi = \frac{(\vec{B}\cdot\vec{r})}{r^3}\vec{r}$.
Then $(\nabla\times\vec{r})=0 $ and $\nabla\Phi$ is a vector field $\vec{A}$.
So the expression is left with $-\vec{r}\times\vec{A}$.
The question is: how do I find the cross product between a position vector and a vector field?
Comment: The curl ($\nabla \times \vec{F}$) of a radial vector field of form $\vec{F} = f(r) \vec{r}$ is always zero.
Comment: ok! Thanks a lot!
Answer: If $\vec B$ is a constant vector, then we have
$$\begin{align}
 \nabla \left(\frac{\vec B\cdot \vec r}{r^3}\right)&=\nabla \left(\frac{ B_r}{r^2}\right)\\\\
&=B_r\nabla\left(\frac1{r^2}\right)+\frac1{r^2}\underbrace{\nabla (B_r)}_{=0}\\\\
&=B_r \left(-\frac{2\vec r}{r^4}\right)
\end{align}$$
Hence, we have
$$\vec r\times \nabla \left(\frac{\vec B\cdot \vec r}{r^3}\right)=0$$
Comment: @mathlover Much appreciated!
Comment: Thank you very much!
Comment: Thank you! I think i get it now!
Comment: Hi again! I tried to figure out the notation Br but I still don't understand. And how  r^3 became r^2? Thanks a lot!
Comment: You're welcome my pleasure.
Comment: Note that $B_r=\frac{\vec r}{r}\cdot \vec B=\hat r\cdot \vec B$ and $\frac{\vec r}{r^3}=\frac{\hat r}{r^2}$
Comment: @Bella As you are new to this site, thought of letting you know. If this answer helped you, you could accept it by using the tick mark. If you cannot figure out how, this might help -  https://math.meta.stackexchange.com/questions/3286/how-do-i-accept-an-answer/3287#3287.
Comment: @Bella Hi and Happy New Year. Please let me know how I can improve my answer and feel free to up vote an answer as you see fit of course. ;-)


Ubuntu via (Windows Linux Subsystem) and Docker

Question: I have started using Windows 10's Linux Subsystem and having great success using Ubuntu 14.04. No luck so far though with Docker - is this a limitation of the platform or is Docker+WLS combination going to feasible in the future?
I have quite a few scripts that need both Linux and docker presence.
Comment: I'm fairly certain WLS doesn't have all the necessary infrastructure to set up Docker.  The core issue is that WLS, while having Linux-isms, is not really truly full-featured Linux.  This is something that many are just accepting as a limitation...
Comment: There *is* a Docker for Windows; is there any particular reason you're trying to run it on the WLS environment compared to the Windows environment directly?
Comment: I know - I suppose I could configure the Ubuntu instance to connect to docker-engine via TCP but was wondering if WLS was "complete" enough to support Docker (as it would make it even closer to my linux dev machine)
Comment: Also see: http://serverfault.com/questions/767994/can-you-run-docker-natively-on-the-new-windows-10-ubuntu-bash-userspace/801138#801138
Answer:
As of September 2016, No.
All current implementations of Docker on Windows use virtualisation,
  Docker 1.12 uses a hypervisor in Windows -thus removing the advantage
  of containerisation over virtualisation.
Docker needs more than just using Linux systems calls.
It needs process control groups (cgroups), a stackable filesystem
  (aufs), plus other Linux-based systems outside the kernel.
Neither cgroups nor aufs are natively in the Windows 10 kernel.
There is an implementation of Windows Server 2016 here:
  https://msdn.microsoft.com/en-gb/virtualization/windowscontainers/quick_start/quick_start_windows_server
  ..but this will only run some Windows services, e.g. IIS, and not
  Ubuntu

The source (thanks to muru) has answers with more detail and insight.
Thomas stated it quite well and short:

I'm fairly certain WLS doesn't have all the necessary infrastructure to set up Docker. The core issue is that WLS, while having Linux-isms, is not really truly full-featured Linux. This is something that many are just accepting as a limitation…


IOS web app zooms in on rotate when keyboard is shown

Question: <!doctype html>

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=600,user-scalable=no">

<input type=text>

When opening file above from Home Screen and tapping into input box in landscape mode, then rotating phone to portrait mode, screen zooms in and there's no way to zoom out. Doesn't happen when opening in Safari.

Steps to Reproduce:
1. Save the bookmark to file to Home Screen
2. Open bookmark from Home Screen
3. Turn phone to Landscape mode
4. Tap into input field, keyboard appears
5. Turn phone to Portrait mode

Expected Results:
Screen shouldn't zoom in.
Actual Results:
Screen zooms in.
Version:
IOS 9
Notes:
Didn't happen prior to IOS9. Doesn't happen in Safari, only in Web Clip.
Any ideas for workaround?
Answer: Found a solution over here:
https://github.com/scottjehl/iOS-Orientationchange-Fix
Although for me there's no need for accelerometer, simply setting meta content to "maximum-scale=1" does the trick:

 var meta = document.querySelector( "meta[name=viewport]" ),
            initialContent = meta && meta.getAttribute( "content" ),
            disabledZoom = initialContent + ",maximum-scale=1";

        function restoreZoom(){
            meta.setAttribute( "content", disabledZoom );

        }
window.addEventListener( "orientationchange", restoreZoom, false );


What is a "Vulkan Extension"?

Question: When creating a VkInstance, you need to setup the API's extensions that are going to be used by your application (for example you need an extension to interface with the window system on desktop platforms).
What are these extensions? What do they represent? Are they just a way to tell Vulkan to use a certain feature implemented by a driver?
Answer:
Are they just a way to tell Vulkan to use a certain feature implemented by a driver?

Well... yes. Vulkan extensions are simply additional features that Vulkan implementations may provide if they so choose to. They add new functions, structs, and valid enumerators to the API, and they can change some of the behavior of existing functions.
You have to detect whether the implementation supports these extensions before creating an instance/device. And you have to explicitly ask for such extensions when you create the instance/device.

What is a "Vulkan Extension"?


How to create sticky full-page vertical lines with CSS

Question: I have a React project. I use React-Bootstrap as UI library.
I want to create vertical lines like this, but i want it always visible over the content. How should I write CSS for this?
enter image description here
Answer: Create a div like this on absolute position

Answer: You can just add an  div with length of 100%, width of 2-5px and background-color of your liking.


How can I count characters in Perl?

Question: I have the following Perl script counting the number of Fs and Ts in a string:
my $str = "GGGFFEEIIEETTGGG";
my $ft_count = 0;
$ft_count++ while($str =~ m/[FT]/g);
print "$ft_count\n";

Is there a more concise way to get the count (in other words, to combine line 2 and 3)?
Answer: my $ft_count = $str =~ tr/FT//;

See perlop.

If the REPLACEMENTLIST is empty, the
  SEARCHLIST is replicated. This latter is useful for counting
  characters in a class …

  $cnt = $sky =~ tr/*/*/;     # count the stars in $sky
  $cnt = tr/0-9//;            # count the digits in $_

Here's a benchmark:
use strict; use warnings;

use Benchmark qw( cmpthese );

my ($x, $y) = ("GGGFFEEIIEETTGGG" x 1000) x 2;

cmpthese -5, {
    'tr' => sub {
        my $cnt = $x =~ tr/FT//;
    },
    'm' => sub {
        my $cnt = ()= $y =~ m/[FT]/g;
    },
};

        Rate     tr      m
     Rate     m    tr
m   108/s    --  -99%
tr 8118/s 7440%    --
With ActiveState Perl 126.96.36.1996 on 32 Windows XP.
The difference seems to be starker with
C:\Temp> c:\opt\strawberry-5.12.1\perl\bin\perl.exe t.pl
      Rate      m     tr
m   88.8/s     --  -100%
tr 25507/s 28631%     --
Comment: Your benchmark is letting the "m" case get away with just finding the first match, since the regex match is in scalar context. If I fix that line to "my $cnt = () = $y =~ m/[FT]/g;", "tr" ends up around 3000% better than "m" (on my Linux box).  Incidentally, the original code is about twice as fast as "m".
Comment: Of course tr/// isn't a regex so *technically* it doesn't answer the specific question :-) It's much better then using a regexp though.
Comment: @Sinan +1 for suggesting `tr///`. I think your benchmark has a bug. In order to count replacements with regex, you need an intervening list context: `my $cnt = ()= $y =~ m/[FT]/g;`. When you run it that way, `tr///` is much faster than `m//`. I'm also on v5.10 under ActivePerl.
Comment: @Sinan Ünür This is why it is a good idea to have a test section before the benchmark.  I normally stuff the lambdas to be tested into a hash, iterate over the hash printing its return value, and then performing then benchmark.  If any of the values differ, then I know I have a bad benchmark.
Comment: this should be `my $ft_count = $str =~ tr/FT/FT/;`, otherwise it will remove the characters from `$str`
Comment: It counts the brackets. Must be `tr/FT//`
Comment: @FM Geez. I could have sworn I had typed everything correctly. Thank you also @aschepler. My sanity has been restored.
Answer: When the "m" operator has the /g flag AND is executed in list context, it returns a list of matching substrings.  So another way to do this would be:
my @ft_matches = $str =~ m/[FT]/g;
my $ft_count = @ft_matches; # count elements of array

But that's still two lines.  Another weirder trick that can make it shorter:
my $ft_count = () = $str =~ m/[FT]/g;

The "() =" forces the "m" to be in list context.  Assigning a list with N elements to a list of zero variables doesn't actually do anything.  But then when this assignment expression is used in a scalar context ($ft_count = ...), the right "=" operator returns the number of elements from its right-hand side - exactly what you want.
This is incredibly weird when first encountered, but the "=()=" idiom is a useful Perl trick to know, for "evaluate in list context, then get size of list".
Note: I have no data on which of these are more efficient when dealing with large strings.  In fact, I suspect your original code might be best in that case.
Comment: very useful to get this weird but effective syntax explained
Answer: Yes, you can use the CountOf secret operator:
my $ft_count = ()= $str =~ m/[FT]/g;

Comment: Also known as the goatse operator ;) `=()=`
Comment: oh god why.... tyvm Daenyth...... :O this all to tell that informaticians are indeed crazy
Answer: You can combine line 2, 3 and 4 into one like so:
my $str = "GGGFFEEIIEETTGGG";
print $str =~ s/[FT]//g; #Output 4;

Comment: Being a comment on another answer, this would be better as a comment than an answer :)
Comment: @ysh,thanks for the comment. I didn't realize my answer is actually a comment on another answer, is it? The OP asks [Is there a more concise way to get the count (in other words, to combine line 2 and 3) and here's my answer to the question. Had someone already mentioned what I suggested?
Comment: @ysth, the original post is a possible duplicate of this [http://stackoverflow.com/questions/1849329/is-there-a-perl-shortcut-to-count-the-number-of-matches-in-a-string/1850686#1850686] and I posted a similar solution to that question. I think this post can be combined with that one.

How can I count characters in Perl?


What is this dog sniffing out here?

Question: Sometimes my dogs go crazy and report lots of tunnels with a big icon and leave some yellow flags behind. What exactly does he find, because no tunnel shows up and it is also mostly on the inside of the prison walls, which makes no sense.

So what exactly found he there?
Comment: Wow, those are some fancy cells.
Comment: @Studoku Yeah, I called that savegame "Hotel Escobar".
Comment: I know it's unrelated to the question but did you consider adding walls and a (basic) door to the en-suite bathrooms? You can still count it as part of the same cell.
Comment: @Studoku I don't see how this would make a difference.
Answer: Dogs are not 100% reliable. They will sometimes miss tunnels and they will sometimes report tunnels even though there aren't any. When a dog reports a tunnel in a location which is very implausible (any cells would have a far shorter route to freedom), you can just ignore them.
However, in this case there might be a tunnel. Groups of tunneling prisoners first build tunnels to connect their cells to each other. This allows them to build tunnels heading for the prison perimeter far quicker. In this case the tunnel-marker is right between the toilets of the two adjacent cells, so these two cells cooperating that way is not implausible. Try deconstructing the toilets in them and you might be in for a surprise (searching the cell does not give you a 100% chance to discover the tunnel - deconstructing the toilet ist the only way to be 100% sure).
Comment: Apparently, unless this has been changed back, ordering a search on the toilet itself (on its own, not as part of a cell search or shakedown) is just a effective as dismantling it.
Answer: If memory serves me right you need to find either the tunnel entrance or exit to uncover the whole tunnel.
Try searching the nearby cells or performing a shakedown on the whole cell block to see if you can find the entrance before they get outside the wall.
Be aware that this is not guaranteed to uncover all the tunnels according to the Prison Architect Wiki:

As of Alpha 34, manually searching a toilet will reveal any escape tunnels stemming from that toilet. This does not include searching a cell or cell block, but rather the suspected toilet itself. This does not get rid of the random chance that tunnels will be found on a blanket search, but now if you want the check a specific toilet, you don't have to dismantle it.

Just be careful with your prisoners as they seem rather unhappy already and the search is not going to help with that.
Comment: Regarding prisoner happiness and searching: It only increases the heat level when *prisoners* are searched unnecessarily. But searching their cells doesn't bother them. When you want to look for contraband and tunnels without angering any prisoners, you can order a cell block search when no prisoners are in it (yard time, for example). This will trigger a search on all pieces of furniture, but not on the prisoners, even when they return into the cell block while the search operation is ongoing.

What is this dog sniffing out here?


Groovy Script and C# Integration

Question: We have a console application running in C#, and we need to integrate a groovy script with that. Is there a way to do that? Of course I google it before coming here, and the only useful result I got, it was this one here below:
https://jnbridge.com/blog/groovy-to-net-integration
But we need to use C#, not any external libraries. So, basically what we need a way to integrate a groovy script in our C# code.
Thanks,
Comment: What do you expect from integration? Why it's not just running groovy command line from your code?
Comment: This script has to be triggered automatically when the user follow some procedures. Unfortunately, I can't do that.
Answer: take a look at IKVM.NET I do think this is what you are wanting, "IKVM.NET is an implementation of Java for Mono and the Microsoft .NET Framework. IKVM is free software, distributed under a permissive free software license."  this allows usage of java to C# bridge and vice versa.
Comment: Project is closed since 2017
Comment: there are forks of it,  https://github.com/jessielesbian/ikvm

Groovy Script and C# Integration


Copy Event from One Calendar to another

Question: I am creating an app in asp.net for Google calendar integration. When we insert a particular event to the calendar then at the same point i want to copy the same calendar event in to another calendar and i want to do the same process in a single request. So may any one please guide me for this problem. I am using google calendar version 3 for this. Thanks in advance
Answer: Is it necessary that they be two separate Calendar events? If not, you should be adding the second calendar as an attendee of the event rather than creating a copy of the event. See the events reference and look for the attendees list attribute. This can be achieved in a single API call.
If it is indeed necessary that the events are entirely separate and independent of each other, it will require two events.insert() operations, one on each calendar. However, as long as the user you are authenticating as has access to both calendars, it should be possible to batch the two operations into a single HTTP call.
Comment: thanks for your reply but my problem is that, I am having two calendars one is private and another one is shared, if i am going to insert an event in my private calendar then it should generate a separate copy to my shared calendar also, so that other can see to my shared calendar. i can do this process in a single process and i am having the calendar ID of both calendar.

Copy Event from One Calendar to another


Best Method for Fastening 4x4 Posts to Deck for Pergola Construction?

Question: I'm planning to build a pergola on my existing deck and am looking for advice on how to securely fasten 4x4 posts to the deck. The deck is approximately 2 feet off the ground and is supported by concrete footings. I intend to place the 4x4s directly above these footings. I will be using brackets to hold the 4x4s in place, but I'm unsure about the best method to fasten these brackets to the deck and underlying joists.
Some of the options I'm considering include:

Drilling fasteners directly into the deck joists from above.
Using blocking between joists for additional support.
Using long concrete fasteners to attach the brackets directly to the concrete footings below the deck.

Additional Information:

I live in the South, where high winds are a possibility.
I haven't fully designed the pergola so can't provide exact details yet
Given the exposure to high winds, I'll consider corner braces, maybe a railing for some additional support, etc.
I've included below a picture of a concrete footer and the deck beams

Questions:

What is the most secure method for fastening the brackets to the deck and joists?
Are there any specific types of fasteners or brackets that you would recommend for this project?

Related questions:
there are a number of related questions that don't quite answer mine.
This being Stack Exchange, always good to note, especially in case someone is looking through here someday in the future.

Adding a pergola to existing deck, post anchors?: answer provides helpful considerations but doesn't specify how to attach the bracket to the deck beam or joist
How can I extend my deck posts to support a pergola?: focuses on a case where there are already posts for a railing
Adding a pergola to an existing deck?: suggests lag-bolting the posts to the adjacent joist -- this might work but I'm not sure how to do that here. Have never done much with decks.
Comment: The deck boards will not hold
Comment: @mbarete if you're able to remove the deck boards in the area where your posts will go, you could add some blocking that you can screw into.
Comment: @Ruskes do you mean that I can't just fasten to the deck boards? If so that's why I'm asking for advice on connecting to the beam/joist
Comment: is it 8 foot long ? it would apply to much share pressure to a single deck board, that will snap
Comment: You'd need to connect *through* the deck boards to the joists or posts.
Comment: @Huesmann -- makes sense, just trying to figure out the best way to do that. Fasten two 2x8 boards (either to beam-joist corner or give up some space and attach them between two joists) then screw through the deck boards down into that?
Comment: If I don't add blocking, I can probably get into joists on 2 or 3 of the 4 corners of the anchor bracket, would that be enough?
Answer: See where you want the posts and remove the boards. You can use concrete footings (if you do put a couple of inches of crush and run under them) or the the metal spike ones. Secure the 4x4s to the footings. You can also screw them to the joists as well.
Mark the boards and cut them so the post can go through. Best to place the post between 2 boards so each board so you can split the cut. Re-install the boards.
Answer: Attaching to the deck boards isn't a big deal as long as they're aligned with the beam plus foundation below. Use a hot-dip galvanized equivalent or better post base and use hot-dip galvanized fasteners--the screws laying in your image are inappropriate. Simpson brands their hot-dip equivalent or better post bases as ZMAX, where I assume the zee is for "zinc." If someday you need to replace the deck boards but not the pergola, then you might regret not notching the deck boards so that the posts sit directly on the beam.
Your question is actually about preventing sway in the wind. Detailing the post connection to prevent that sway is a waste of time because you've announced that you're fine with railing preventing sway and because your deck is so low. With the low deck, no handrail is required, so you don't need to implement the IRC's finer handrail details. To brace each post against sway, just install an X-brace in the handrail bay beside the post. Wire rope is probably the easiest to detail. Just remember

that your rail has to be somewhat substantial. This is because the X brace starting at the post base ends at the rail and uses the rail to push back against the post.
Also, the connections between rail posts and deck surface are critical.
Also, the connections between X-braces and posts are critical, where any eye bolts should have shoulders.
Comment: Amazing thanks for answering a question I had assumed to be dead


Issue on PowerPack Controls and Graphics upon clearing and redrawing

Question: To briefly explain:

I have a win form written in C# that contains a panel.
The panel contains a shape container, through that I have programmatically added some oval and line shape controls from VisualBasic.PowerPacks to the panel.
The reason of using such shapes was I needed to perform some operations on their MouseHover and MouseClick events.
I have also drawn some graphics like strings and ellipse on the panel using Graphics in Paint(object sender, PaintEventArgs e) method of the panel.
The application has zoom in and zoom out buttons and whenever user clicks on them the size of shapes and graphics are supposed to be changed based on the scale.
To redraw graphics after scaling, I needed to clear the old ones before drawing new graphics in the new scale, otherwise they remained on the panel. So, I used Clear(Color color) method of the graphic to do so.

Now, the problem I have is upon using Clear(Color color), everything including shape controls gets disappeared. By my perception, I do not expect shapes to be disappeared because they should be treated as controls, unless I am missing something here. How can I avoid this issue? Any advice would be appreciated.
Answer: Solved the problem by invalidating "shape.Invalidate()" shape controls.


How do I fix wp super cache error message?

Question: I am using wp super cache in WordPress. After months of using it, i tried deactivating. But after activating it again, i am prompted with the error below below:

WP-Cache Config Sample File See wp-cache.php for author details. */
  $wp_cache_mobile_browsers = '2.0 MMP, 240x320, 400X240, AvantGo,
  BlackBerry, Blazer, Cellphone, Danger, //Added by WP-Cache Manager ?>
  Error: Your cache directory () did not exist and couldn't be created
  by the web server. Check permissions.

I am currently using WP Super Cache Version 1.4.8
Do you know how can I fix this or do I just need to update to a recent version?
Comment: did you `Check permissions` yet?
Answer: I was able to solve this problem by checking my wp-cache-config.php. Upon checking  wp-cache-config.php, I saw that the contents became binary codes.
I was able to revert this by using the code that was saved from my localhost server.
Comment: I had a similar problem: during a migration, this file was copied, preserving the previous path, which obviously turned invalid in the new host. Thanks for the tip!
Answer: I know this is an old question, but if you change the $cache_path variable to use ABSPATH instead, this will be fixed.  I don't know why WP Super Cache would not use this wordpress definition instead tbh.  So it should be changed to look like this in the wp-content/wp-cache-config.php file:
$cache_path = ABSPATH . '/wp-content/cache/';

Comment: Why would this be better than `$cache_path = WP_CONTENT_DIR . '/cache/';` This makes the assumption that `WP_CONTENT_DIR` is the default. It exists as a changeable constant to allow options.
Answer: mkdir wp-content/cache/
chmod 777 wp-content/cache/


private named parameter in dart

Question: I am new to Dart. Let's say I have a final List <Character> _characterList; which should be private. But how do I use CharacterList ({Key key, this._characterList}): super (key: key); if the named parameter cannot start with _?
Answer: The name of the parameter is independent of the name of the member.  Constructors offer the this.name syntactic sugar for convenience if the names happen to be the same, but you don't have to use that.  You could give the parameter its own name and explicitly initialize the member variable separately:
CharacterList({Key? key, required List<Character> characterList})
  : _characterList = characterList,
    super(key: key);

final List<Character> _characterList;

Answer: It is Dart limitation
Named optional parameters can't start with an underscore

You can use a constructor with optional positional parameter instead
CharacterList (Key key, [this._characterList]): super (key: key)

private named parameter in dart