How can I update the Java timezone information with a IANA file newer than the one used by the latest TZupdater release?

Question: The latest Time Zone Updater tool (TZUpdater) for Java contains an older timezone data file, which does not have the timezone changes for Chile scheduled for this weekend.
The IANA Time Zone DB has the latest information for the Chile time zone changes.
How can I use the latest IANA file (tzdata2013a.tar.gz) with TZupdater?
Answer: If your application uses Joda Time exclusively, it appears to be possible to update the DB for Joda time. But I haven't seen a sanctioned way to use a time file on the whole JVM.
However, this SF post may be helpful... I would test heavily on an IDENTICAL but disposible OS/jvm system first if you go this route.
Comment: Gus, Thanks. Problem with the SF post approach is that it points to changing "Timezone definintions are exploded in the jre/lib/zi directory tree."  Those definitions are in some encoded format (ie: no the ascii used in the latest TZData files from IANA).
Comment: Not terribly surprised. Oracle/Sun probably did that to avoid people doing just what you contemplate. They may see it as a risk that they could wind up spending money trouble shooting bugs and having their product loose reputation for accuracy due to people making inappropriate updates to the files. As noted in the SF answer, it's probably best to wait for the Updater Utility if possible.
Answer: Oracle finally posted a note that the updated TZupdater is available:

TZUT v1.3.54 which contains the Olson 2013a update is available now
  for customers that have a supported ORACLE product using Java or are
  holding a Java SE contract. Please contact your local Oracle Support
  Office to obtain this version. For questions, please contact Oracle
  Support.

Besides providing almost two full days notice so you have plenty of time to test, the file is not available yet on the web page and you have to contact Oracle Support to get a copy.
Well that's one way to make sure you pay for your support "Pay or Else, we are afraid somethong bad might happen to your software"


How can I prevent my asp.net site from being screen scraped?

Question: How can I prevent my asp.net 3.5 website from being screen scraped by my competitor?
Ideally, I want to ensure that no webbots or screenscrapers can extract data from my website.
Is there a way to detect that there is a webbot or screen scraper running ?
Comment: @AndrewBarber... the OP is NOT asking for code.
Answer: It is possible to try to detect screen scrapers:
Use cookies and timing, this will make it harder for those out of the box screen scrapers. Also check for javascript support, most scrapers do not have it. Check Meta browser data to verify it is really a web browser.
You can also check for requests in a minute, a user driving a browser can only make a small number of requests per minute, so logic on the server that detects too many requests per minute could presume that screen scraping is taking place and prevent access from the offending IP address for some period of time. If this starts to affect crawlers, log the users ip that is blocked, and start allowing their IPs as needed.
You can use http://www.copyscape.com/ to proect your content also, this will at least tell you who is reusing your data.
See this question also:
Protection from screen scraping
Also take a look at
http://blockscraping.com/
Nice doc about screen scraping:
http://www.realtor.org/wps/wcm/connect/5f81390048be35a9b1bbff0c8bc1f2ed/scraping_sum_jun_04.pdf?MOD=AJPERES&CACHEID=5f81390048be35a9b1bbff0c8bc1f2ed
How to prevent screen scraping:
http://mvark.blogspot.com/2007/02/how-to-prevent-screen-scraping.html
Comment: His question is, is it possible to detect. It is, and it is easy to make it a pain to write a program to scrape the site, it is not 100% but it will make it harder. If a user can bring it up in the browser, it can be scripted, unless you use captcha to access the info you don't want scraped.
Comment: +1 good answer. but... I have beaten most of those guards, thus my answer. ;-)
Comment: Yes, you are right. I am guilty of answering a different question.
Answer: Unplug the network cable to the server.
paraphrase: if public can see it, it can be scraped.
update: upon second look it appears that I am not answering the question. Sorry. Vecdid has offered a good answer.
But any half decent coded could defeat the measures listed. In that context, my answer could be considered valid.
Comment: +1 best answer yet, might not be what the op wanted to hear, but it's the only solution.
Comment: indeed. It's like when it was trendy to prevent right-click to steal images.
Answer: I don't think it is possible without authenticating users to your site.
Comment: Authentication Will not even hinder it, if they want to scrape they will script out that process easily.
Comment: @Raj, so authentication will prevent that (of course the competition can register and run a s/s )
Comment: Wasn't sure if you had a list of authorized users that could access your app. Obviously this is not the case here.
Answer: You could use a CAPTCHA.
Also, you can mitigate it instead by throttling their connection. It won't completely prevent them from screen scraping but it will probably prevent them from getting enough data to be useful.
First, for cookied users, throttle connections so you can see at most one page view per second, but once your one-second timer is up you experience no throttling whatsoever. No impact on normal users, lots of impact on screen scrapers (at least if you have a lot of pages they're targeting).
Next, require cookies to see the data-sensitive pages.
They'll be able to get in, but as long as you don't accept bogus cookies, they won't be able to screen scrape much with any real speed.
Answer: Ultimately you can't stop this.
You can make it harder for people to do, by setting up the robots.txt file etc. But you've got to get information onto legitimate users screens so it has to be served somehow, and if it is then your competitors can get to it.
If you force users to log in you can stop the robots all the time, but there's nothing to stop a competitor registering for your site anyway. This may also drive potential customers away if they can't access some information for "free".
Comment: @ChrisF, is there a way to detect that there is a webbot or screen scraper running ?
Comment: @user - check out the other answers from people with more experience in this area than me
Answer: If your competitor is in same country as you, have an acceptable use policy and terms of service clearly posted on your site. Mention the fact that you do not allow any sort of robots/screen scraping etc. If that continues, get an attorney to send them a friendly cease and desist letter.
Answer: I don't think that's possible. But whatever you'll come up with, it'll be as bad for search engine optimization as it will be for the competition. Is that really desirable?
Answer: How about serve up every bit of text as an image?  Once that is done, either your competitors will be forced to invest OCR technologies, or you will find that you have no users - so the question will be moot.


Ajax Listen Event on a Button Click then Runs a Php file

Question: I need the AJAX to listen to if a button is click. Then if it is I need it to run a PHP script. I am having troubles by the AJAX not correctly listening to the Button Click and so it never runs the script.
Any Error in my code you may see?
Any advice on how I should do this?
The Button:
<input id="button_1" type="button" value="favorites1" onclick="favfunct();" />

The AJAX that calls it is: (ajaxlisten.js)

Php File (addtofavorites.php)
<?php
$con = mysql_connect("localhost","root","student");

if ($_POST["action"] = 'favorites1')
{
    if (!$con);
    {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("tvid", $con);

    $sql="INSERT INTO tv (userid, favorites) VALUES (345,77);"
    if (!mysql_query($sql,$con));
    {
        die('Error: ' . mysql_error());
    }
    echo "Your Video was Added To Your Favorites";
    mysql_close($con);
}
?>

Comment: It does not run the addtofavorites.php script. The button does nothing, even though I have referenced it to do something when clicked.
Comment: There's no `method` property for `$.ajax`. There's `type` which determines whether it's `POST` or `GET`. Anyway, what does it mean that it doesn't "listen correctly"? Are you getting an error of any kind or nothing happens?
Answer: Try rewriting the click function:
$(document).ready(function () {
   $('#button_1').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        favfunct();
   });
});

Then the favfunct:
function favfunct() {
// AJAX Call Below
// rest of your code

That should get your favfunct running. After that you can further debug the code if necessary.
You can also take the onclick off the button:
<input id="button_1" type="button" value="favorites1" />

Fiddle demo: http://jsfiddle.net/sbybd/
Example of ajax call:
$.ajax({
     type: "POST",
     url: "js/addtofavorites.php",
     data: { "get" : "runfunction", "action" : "favorites1" },
     success: function (response) {
         alert ("successfully loaded");
     }
 });

Comment: any idea to how to get the AJAX to successfully call upon the Php file to add to the database?
Comment: @JulianNeill You need to write it correctly. Refer to the [jquery docs](http://api.jquery.com/jQuery.ajax/) for more information and I updated my answer to include an example.
Comment: Thank You will look more into it


Why won't my volume control work?

Question: I recently installed Gnome 3 in Ubuntu 11.04 on a Lenovo Thinkpad T61p. Since then, my hard volume buttons have stopped working, and my manual volume control via the top-right corner has had no impact on whether or not my computer releases sounds. As a matter of fact, I seem to have no OS-wide volume control whatsoever: it's always on. Going into the Gnome 3 "Sound Settings" makes me feel like there might be drivers missing, as it doesn't recognize any of my hardware, or acknowledge that said hardware exists.
I imagine this has something to do with drivers, but the drivers were working fine until I installed Gnome 3. So I suppose my main question is "Why isn't Gnome 3 listed as the alpha software it is?" with a hefty side of "does anybody know what happened to my sound drivers," and "is there a magic wand I can wave to get them all back?"
Answer: You installed a PPA for Gnome 3? That's why you can't install it from the repo's. Everything from a PPA should be thought of as alpha. What directions did you use to install it?
Comment: Uh... Too many. Too many different sets of directions, because no one of them got the job done. I have no idea what a PPA is, but I've seen enough instructions that involve them that I tried that without question. At first, it failed. Then, I was told to go into the software center, add the ppa to my software sources (instead of via the command line), and then a whole Gnome 3 section showed up on the left side of my software center, and I just forced it to work from there. It was totally legit.
Comment: If it had been legit, you wouldn't have forced it to work or used so many different sets of instructions.
Comment: That last sentence was supposed to be sarcasm. Anyway, my audio is working again... But the question still stands, I guess: does gnome 3 mess with your drivers?
Comment: I suppose you did at least answer the question -- it won't work because I installed shady software.

Why won't my volume control work?


Is there Windows analog to supervisord?

Question: I need to run python script and be sure that it will restart after it terminates. I know that there is UNIX solution called supervisord. But unfortunately server where my script has to be run is on Windows. Do you know what tool can be useful?
Thanks
Answer: Despite the big fat disclaimer here, you can run Supervisor with Cygwin in Windows; it turns out that Cygwin goes a long way to simulate a Posix environment, so well that in fact supervisord runs unchanged. There is no need to learn a new tool, and you will even save quite a bit of work if you need to deploy a complicated project across multiple platforms.
Here's my recipe:

If you have not done it yet, install Cygwin. During the installation process, select Python.
From the Cygwin terminal, install virtualenv as usual.
Create a virtualenv for supervisord, and then install as usual:
pip install supervisord

Configure supervisord in the usual way. Keep in mind that supervisord will be running with Cygwin, so you better use paths the Cygwin way (C:\myservers\project1 translates to /cygdrive/c/myservers/project1 in Cygwin).
Now you probably want to install supervisord as a service. Here's how I do it:
cygrunsrv --install supervisord --path /home/Administrator/supervisor/venv/bin/python --args "/home/Administrator/supervisor/venv/bin/supervisord -n -c /home/Administrator/supervisor/supervisord.conf"

Go to the Windows service manager and start the service supervisord that you just installed.

Point 5 installs supervisord as a Windows service, so that you can control it (start/stop/restart) from the Windows service manager. But the things that you can do with supervisorctl work as usual, meaning that you can simply deploy your old configuration file.
Comment: A short notice: it is `pip install supervisor` now and it requires python 2.4+ but it doesn't work with any 3+ versions.
Answer: You likely want to run your script as a Windows Service. To do so you'll need the python-win32 library.  This question has a good description of how you go about doing this, as well as a bunch of links to other related resources. This question may also be of use.
A Windows Service is how you want to wrap up any script that needs to run continuously on Windows. They can be configured to automatically start on boot, and handle failures. Nothing is going to stop anyone from killing the process itself, but to handle that potential situation, you can just create a bat file and use the sc command to poll the service to see if it is running and if not restart the service. Just schedule the bat file to run every 60 seconds (or whatever is reasonable for your script to potentially be down).
Comment: Running python script as Windows service will make it only run in background. It is not enough. My goal is to make script running unbreakable. Script must be restarted even if someone kills it.
Comment: In that case, use a bat file, the sc command and the system scheduler to handle a 'killed' process. See my edit.
Comment: Perhaps this was true 11 years ago.  But today if you go to the Recovery tab on the properties page for a Windows service there are options to restart on failure.
Answer: If you want a supervisord-like process manager that runs on most posix OS and is Python-based like supervisord, then you should look at honcho which is a Python port of foreman (Ruby-based):
http://pypi.python.org/pypi/honcho/
It works great on mac, linux but (actually) not yet windows... (editing my initial answer where I had said optimistically it was already working on Windows based on a pull request that has been discarded since)
There is a fork that provides Windows support here https://github.com/redpie/honcho
and some work in progress to support Windows here https://github.com/nickstenning/honcho/issues/28 ... at least it could become a possible solution in a near future.
There is also a foreman fork to support Windows here: https://github.com/ddollar/foreman-windows that may be working for you, though I never tried it.
So for now, a Windows service might be your best short term option.
Comment: The latest TRUNK of honcho now has windows support :) use and enjoy
Comment: Hi, lil' question about Honcho: is it really supposed to restart failed tasks, like supervisor ? It doesn't when I `kill` one. So do we have to use a combination of supervisor and honcho ? Thanks.
Comment: Actually honcho is more like foreman than supervisor.  See also https://blog.codeship.com/using-honcho-create-multi-process-docker-container/
Answer: supervisor for windows worked for us on python27 - 32 bit. I had to install pypiwin32 and pywin32==223.
Answer: As it is an old question with old answers I will update it with latest news:
There is a supervisor-win project that claims to support supervisor on Windows.
Answer: No, supervisord is not supported under Windows.
BUT what you can do is, to restart it automatically from a wrapper script:
#!/usr/bin/python
from subprocess import Popen

file_path = " script_to_be_restarted.py"
args_as_str = " --arg1=woop --arg2=woop"

while True:
    print("(Re-)Start script %s %s" % (file_path, args_as_str))
    p = Popen("python " + file_path + args_as_str, shell=True)
    p.wait()

Is there Windows analog to supervisord?


Why doesn't C++ print anything if I copy a string onto a NULL pointer?

Question: I just wanted to try out this code...
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main() {
      char *outFile1 = NULL;
      char *outFile2 = NULL;
      cout << "HI";
      outFile1 = "//tmp//Softwares//v//vdisk";
      strcpy(outFile2, outFile1);
      cout << "HI";
}

If I run this code... nothing gets printed. and if I comment the "strcpy(outFile2, outFile1);"... both the "HI" gets printed. Why is this t case?. It doesnt throw me any error though.
Comment: My guess is the process dies because of the strcpy and buffering prevents you from seeing "Hi".
Comment: Just because it doesn't throw an error doesn't mean there aren't any errors. C++ likes to wait until you're down before kicking you.
Answer: You're writing to an invalid location. Your program is crashing silently on the strcpy(). The first HI doesn't print since the output is buffered. If you change the first cout to this:
cout << "HI" << endl;

...you'll probably get it.
As for why your program is crashing, this puts the address of a string into outfile1:
outFile1 = "//tmp//Softwares//v//vdisk";

This copies that string to location zero, which (depending on the OS) would normally kill your program:
strcpy(outFile2, outFile1);

Comment: If a program has undefined behaviour, crashing is the *best* you can hope for.
Comment: It probably is crashing, jut not that noisily.
Answer: There is no memory allocated for either string.  You just set a pointer to the string literal "//tmp//Softwares//v//vdisk".  Now when you go to copy it from outFile1 to outFile2 you are most likely overwriting stuff you shouldn't be or for some reason strcpy is causing issues elsewhere (hard to tell since it's undefined).  That's just a guess though.
Comment: It's a good guess, but it's not necessarily true. Undefined behaviour takes orders from no one.
Answer: A few problems with your code, one the char string outFile2 has not been allocated, so your program is probably corrupting the stack and preventing the output from being properly displayed.
Try using allocating some memory using malloc() to hold the string that you want to copy, or look into using the C++ std String class (http://www.cplusplus.com/reference/string/string/).  The C memory allocation would be something like,
int slen=strlen(outFile1)+1;
outFile2 = (char *)malloc(sizeof(char)*slen);
strncpy(outFile2, outFile1, slen);

Comment: And the C++ memory allocation would be like this: `std::string outFile2;` with an optional `= outFile1;`


python os.system issue: "sh: 1: [command] not found"; command works interactively

Question: I'm trying to run a system call from Python. I have a line that reads this in my Python script:
return os.system("crux tide-index")

crux is a program existing in my /home/ directory, and if I type the command crux tide-index into a terminal, it seems to work properly.
When I run my Python script, it reaches the line above and then outputs this line to stderr (i.e. it shows up in the output of my terminal):
sh: 1: crux not found
I don't understand why I can run the command in my terminal, but not in a Python script. Is there something I'm missing? Is the fact that crux is in my /home/ folder possibly the problem?
Comment: have you tried calling `return os.system("/home/crux tide-index")` ?
Comment: Alternatively, you can add it to your [`PATH`](http://askubuntu.com/questions/322772/how-do-i-add-an-executable-to-my-search-path), then call it from anywhere.
Comment: Normally, `crux tide-index` won't actually work for something in your home directory, unless you've added your home directory to your PATH, or have an alias or shell function wrapping it. The alias approach seems likely -- a PATH update will be inherited by subprocesses (including Python), but an alias or non-exported shell function won't.
Comment: BTW, inasmuch as `*` has actual literal meaning to a shell, putting it in your question title was a bit unclear.
Comment: What's the output of running `type crux` in your terminal?
Answer: Possible Reasons
There are several reasons you could be able to run this in your terminal, but not in a Python script.

It could be defined as an alias.
If you have alias crux=~/crux in your .bashrc or similar, that would explain the issue.
It could be defined as a function.
crux() { ~/crux "$@"; } is an example of a shell function that starts the crux executable. However, like any other function, this is local to the shell wherein it's defined. (Bash has "exported functions", but these aren't available in POSIX sh, and you need to go out of your way to use them anyhow).
You could have a different PATH between your interactive CLI and your script.
If you have PATH=$PATH:$HOME somewhere in your shell's dotfiles, this will add your home directory to the location searched for new executables. On its own, this will be exported to subprocesses, so searched by the /bin/sh instance started by os.system() in Python -- but if your script is being started by cron or another service, it wouldn't have that PATH update.

Debugging
Run type crux in your interactive shell. Output will be of the form of one of the following:

crux is aliased to `/home/kestrel/crux' means that it works in your interactive shell only due to an alias. Update your PATH to include /home/kestrel, or modify your Python script to fully-qualify the script's location.
...or if you get:
crux is a function
crux ()
{
    /home/kestrel/crux "$@"
}

...it means exactly what it says: crux is a function that in turn invokes /home/kestrel/crux. You can then put /home/kestrel/crux directly in your Python script.
...or if you get either of:
crux is hashed (/home/kestrel/crux)

or
crux is /home/kestrel/crux

then crux is directly in the PATH for your interactive command prompt, but not for your Python script. Edit the PATH associated with your script appropriately.
Answer: This was because PyCharm's os.system did not load bashrc's env variable values unless you start your Pycharm in your terminal and not quit.
So you should manually try the command below in your terminal to get the absolute path of crux:
whereis crux
then use absolute path of crux instead of crux in your PyCharm.
Answer: this error caused by the confusing path to the executable file.
so you can fix this erro through pointing th explicit path to the executable file.
like this:
>>> a = os.popen("TMscore ./download/pdbs/1ACF.pdb ./download/pdbs/1ACF.pdb")
>>> /bin/sh: 1: TMscore: not found
>>> a = os.popen("~/bins/TMscore ./download/pdbs/1ACF.pdb ./download/pdbs/1ACF.pdb").readlines()
>>> a
['\n', ' *************************************************************************\n', ' *
                     TM-SCORE                              *\n', ' * A scoring function to ass

ess the similarity of protein structures     *\n', ' * Based on statistics:


Evince shows small frame in Presentation mode

Question: I recently noticed that Evince started showing the following unusual behavior when in Presentation mode (after F5 is pressed) on my laptop: instead of making the slide occupy most of the screen, it keeps it to a pretty low dimension, and fills the rest in black, as in screenshot below.
Zooming seems disabled in Presentation mode, despite working outside Presentation mode, and I couldn't find any other related options to adjust, so I can't find a way to enlarge the slide back.
This makes it quite unusable for seminars and for screen sharing. Does anybody have any suggestion? Many thanks!
Comment: Do yo have enabled display scaling in your monitor? I have the same problem and turns out it was because of the scaling. Just disable it for your presentation and it will work as expected. No ideal solution though. Check https://askubuntu.com/questions/1262353/document-viewer-presentation-mode-show-small-frame-when-display-scale-is-200
Comment: Did you find a work-around for this at all?
Comment: No, not at all..
Comment: Thank you for your suggestion, I indeed had display scaling enabled. I tried to disable it, but the problem with Evince actually persists. Might it be due to the fact that my monitor has a very high resolution (hence the need to scale manually)?
Comment: @Mariano Ruiz you should post this as an answer
Answer: I'm using Ubuntu 20.04 and evince 3.36.7. I have met the issue.
After searching in evince official repository issues I think the answer is in:
https://gitlab.gnome.org/GNOME/evince/-/issues/1486
https://gitlab.gnome.org/GNOME/evince/-/issues/1504

Basically, the issue is introduced when fixing an issue on Wayland but forgetting to limit the fix to Wayland.
You should either use Wayland protocol, or use a newer version of envice (you can install the newer version from snap, flathub, etc). For example, use evince from snap:
sudo snap install evince

Comment: This seems to work quite well, thank you!
Answer: This is likely only tangentially related to your problem, but for the sake of creating a tutorial video in a given resolution, I needed fullscreen mode with a fixed size of 1280×720.  Unable to find anything in Evince's command line arguments and options that would have helped, in the end I turned to running an Xnest server with the given resolution and started Evince inside.
I experienced exactly the problem you described.  In my case, the culprit was that Evince started with its (X server given?) default window size and had no window manager available to tell it what size it actually wanted to be at.  Starting xfwm4 in that artificial Xnest server helped: now Evince could ask to go fullscreen.
What does this imply for your problem?  Not much likely, except that the configuration of your window manager is likely the best place to be looking for with regard to why the window resizing in presentation mode goes wrong, or even does nothing at all.  And it might be worth trying out a different window manager (if necessary, by using a different desktop environment).  If all else fails, using Xnest may work in the context of "screen" sharing though it would help more with specific application problems rather than, say, finding the best way to do something using your standard desktop.
Answer: It seems as of this year (2023) this is still an unfixed issue in some cases: https://gitlab.gnome.org/GNOME/evince/-/issues/1600 - possibly when using Wayland with fractional or just non-100% scaling. I am still getting a small frame in presentation mode for Beamer slides as well, with Evince 45 under a gnome-shell 45.1 Wayland session with 150% display scaling (on arch linux).
The main workaround seems to be to temporarily switch to 100% scaling in the system display settings, which did work for me, but consequently makes all the UI toolbars tiny on my HiDPI screen.
An alternative quick workaround mentioned here is if you run Evince with WAYLAND_DISPLAY="", this forces it to start in X mode. It looks blurry for me on fractional scaling but at least fills the screen properly in presenter mode.
Comment: I'm using 125% fractional scaling with a 2256x1504 screen on Ubuntu 22.04. Using a newer version as the accepted answer suggests didn't work for me, but forcing X did. I don't see any blurriness in my case, but I imagine that might depend on many factors. This is how I applied the workaround: `cp /usr/share/applications/org.gnome.Evince.desktop ~/.local/share/applications & sed -i 's/Exec=evince %U/Exec=env WAYLAND_DISPLAY="" evince %U/' ~/.local/share/applications/org.gnome.Evince.desktop & update-desktop-database ~/.local/share/applications`


Is it possible to colorize permissions-part of the output of `ls`?

Question: In the rwx permissions that are listed by ls -l, is it possible to put the first set of rwx in red, the next in blue and the third in green?
For example, is the following possible:
Answer: Parsing ls output is notoriously error prone, but here's a working version based on find:
while IFS=$'\t' read -r -d '' perms name
do
    echo "${perms:0:1}$(tput bold; tput setaf 1)${perms:1:3}$(tput setaf 4)${perms:4:3}$(tput setaf 2)${perms:7:3}$(tput sgr0) ${name}"
done < <(find . -maxdepth 1 -printf "%M\t%f\0")

Answer: Have a look at Arbitrary Command Output Colourer. It can, well, colourize arbitrary command outputs. There is no working DEB archive, but installation trivial (once you have ruby installed). Configuration is via regular expressions and can do whas you want.
Comment: Super! And in Ruby too!


Non-unique way of expressing vector in Hilbert space

Question: Let $H$ be a Hilbert space, $(b_{i})_{i\in\mathbb{N}}$ are linear independent set with dense span. If $b_{i}$ fail to be a Schauder basis, does that mean there exists $x\in H$ such that $x$ can be expressed non-uniquely by $b_{i}$? In other words, $x=\sum_{n=1}^{\infty}a_{n}b_{n}=\sum_{n=1}^{\infty}a'_{n}b_{n}$, where $a_{n}, a'_{n}$ are different.
By linear independence, I think it is quite impossible to happen, but things are weird in infinite dimension case, so I am not sure.
Edit Assume $x$ also takes a form $\sum_{n}\sum_{k}^{n}c_{nk}b_{k}$, can  we conclude $\sum_{n}c_{nk}=a_{k}$?
Comment: There is no guarantee that every vector $x$ is of the form $\sum a_nbn$.
Comment: See [this answer](https://math.stackexchange.com/questions/3171184/is-a-linearly-independent-set-whose-span-is-dense-a-schauder-basis/3171188#3171188)
Comment: @geetha290krm If $x$ has the representation $=\sum_{n}a_{n}b_{n}$, can we conclude that if $x=\sum_{n}\sum_{k}^{n}c_{nk}b_{k}$ also, then $\sum_{n}c_{nk}=a_{k}$?
Comment: The comments seem to be ignoring that the question is about uniqueness!
Answer: Uniqueness may indeed fail.  For an example,
let $H$ be a separable Hilbert space with orthonormal basis $\{e_n\}_{n\geq 1}$, and define, for every $n\geq 0$,
$$
  f_n=\left\{\matrix{
    \hfill\displaystyle-\frac{e_1}2, & \text{if } n=0,\cr
    e_n- \displaystyle\frac{e_{n+1}}2, & \text{if } n\geq 1,\cr
  }\right.
  $$
Then it is clear that $\{f_n\}_{n\geq 0}$ is a linearly independent set.  Moreover
$$
  \sum_{n=0}^\infty  2^{-n}f_n=
  -\frac{e_1}2 + \sum_{n=1}^\infty  2^{-n}(e_n- \frac{e_{n+1}}2) = $$$$ =
  -\frac{e_1}2 + \sum_{n=1}^\infty  2^{-n}e_n- \sum_{n=1}^\infty  2^{-(n+1)}e_{n+1} = $$$$ =
  -\frac{e_1}2 + \sum_{n=1}^\infty  2^{-n}e_n- \sum_{n=2}^\infty  2^{-n}e_{n} = 0.
  $$
This provides an alternative way to represent zero besides $\sum_{n=0}^\infty  0\ f_n$.


Can not get list in a model which I get it AsQuerable in ef?

Question: public class Product
{
    public int Id{get;set;}
    public int UserId{get;set;}

    public Users User{get;set;}
}

I have set the Users to Product's relative:
b.HasOne("User").WithMany().HasForeignKey("UserID");

When I use entityframework to get the list of products.
The User is returned null, why?
There is a value in User table and the UserId is right in Product Table.
var list = _context.Products.AsQueryable();

the items in list has the User=null.
Comment: Please add the code in which you're trying to get the User with
Comment: @MohamadMousheimish thank you.I have added.
Comment: And can you please add a snapshot to your context? I think it's a DbSet right?
Answer: You need to Include the entity you're looking for. For example, let's suppose I have the following context.
AppDbContext.cs
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
    public DbSet<Notification> Notifications { get; set; }
    public DbSet<Offer> Offers { get; set; }
}

Notification.cs
public class Notification
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int? OfferId { get; set; }
    public virtual Offer Offer { get; set; }
}

If you want to use the Offer entity from Notification, you need to use the following statement:
context.Notifications.Include(n=> n.Offers).ToList();
// Your code goes here

In your situation:
var list = _context.Products.Include(p=> p.User).AsQueryable();

Comment: what about FindAsync? var list=_context.Products.FindAsync(id);
Comment: `FindAsync` will not includeb`User`. The `User` entity will still be returned Null
Answer: You have to explicitly ask to include the users in the returned list.
_context.Products.Include(p => p.Users).AsQueryable();


How to change partitions on Ubuntu virtual machine?

Question: Original Question: How to resize root partition without live CD?
I have a virtual machine that I need to make bigger. I made the VM img larger and now I need to resize the partitions so I can use the extra space.
This is my current partition table and the goal is to combine /dev/vda1 and /dev/vda2.
vda1 is my current root partition
vda2 is an extended partition that contains vda5(swap)
Device Boot      Start         End      Blocks   Id  System
/dev/vda1   *        2048    18874367     9436160   83  Linux
/dev/vda2        18876414    20969471     1046529    5  Extended
/dev/vda5        18876416    20969471     1046528   82  Linux swap / Solaris

This would be simple with Gparted and a live CD, but I can only ssh to the server, or open it in virt-manager but it is still command line only. How can I possibly resize the root partition?
The VM is Ubuntu server 12.04.
Comment: So you can delete/remove vda2 and vda5?
Answer: You need to connect your VM with the iso of a live CD - the file you can download. I assume you are not using a GUI-Tool (like virt-manager ), so you will have to do it from the command line.
You can use virsh to get an XML file of the VM config (I called my VM qemu1)
virsh dumpxml qemu1 > qemu1-config.xml

Now edit that file, look for something like
<disk type='file' device='cdrom'>
  <driver name='qemu' type='raw'/>
  <target dev='hdc' bus='ide' tray='open'/>
  <readonly/>
  <alias name='ide0-1-0'/>
  <address type='drive' controller='0' bus='1' target='0' unit='0'/>
</disk>

and replace it with
<disk type='file' device='cdrom'>
  <driver name='qemu' type='raw'/>
  <source file='/media/data/isos/gparted-live-0.13.0-1.iso'/>
  <target dev='hdc' bus='ide'/>
  <readonly/>
  <address type='drive' controller='0' bus='1' target='0' unit='0'/>
</disk>

The important points are

adapt the paths and file names
the line <source file=.../> contains the iso-file
the line <target .../> should not contain tray open now

And now you put the new settings into effect with
virsh define qemu1-config.xml

The VM will need a restart.
Answer: Here is what worked in the end:
Enlage the img (virtual disk image) file for the VM:

Create raw disc file
sudo qemu-img create -f raw addon.raw 10G

Backup current img
sudo mv domain.img domain.old.img

Combine original and extra to create img file of new larger size.
sudo cat domain.old.img addon.raw >> domain.img

Now we have a larger image but the VM still has old partition table.
Now the tricky part.
The next steps are done on the host machine with VM shutdown
Download iso file for gparted:
wget -c http://sourceforge.net/projects/gparted/files/gparted-live-stable/0.6.4-1/gparted-live-0.6.4-1.iso

Boot the iso with the virtual image as the harddrive in the virtual system
kvm -m 512 -hda domain.img -cdrom gparted-live-0.6.4-1.iso -boot d

We are basically launching a virtual system kvm that will boot from the cdrom -boot d and gparted is in the cdrom -cdrom gparted-live-0.6.4-1.iso and in this virtual system treat domain.img as the harddrive -hda domain.img and allocate 512mb memory for this virtual system-m 512.
Now gparted pops up with a nice GUI (there is probably a command line option as well) ready to repartition your virtual disk.
Now you can manipulate the partition table just like you were using a liveCD on a real machine.
Most of this information was taken from this blog post by Chris Walden.
Thanks guntbert for pointing me in the right direction (i.e. it is possible to boot a VM from a liveCD).
Answer: You can use gParted and the resize from command line. Type...
sudo -i
parted

It will show
GNU Parted 1.7.1
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted)

list will show a lot of commands ...

(parted) list
  check NUMBER                             do a simple check on the file system
  cp [FROM-DEVICE] FROM-NUMBER TO-NUMBER   copy file system to another partition
  help [COMMAND]                           prints general help, or help on COMMAND
  mklabel LABEL-TYPE                       create a new disklabel (partition table)
  mkfs NUMBER FS-TYPE                      make a FS-TYPE file system on partititon NUMBER
  mkpart PART-TYPE [FS-TYPE] START END     make a partition
  mkpartfs PART-TYPE FS-TYPE START END     make a partition with a file system
  move NUMBER START END                    move partition NUMBER
  name NUMBER NAME                         name partition NUMBER as NAME
  print [free|NUMBER|all]                  display the partition table, a partition, or all devices
  quit                                     exit program
  rescue START END                         rescue a lost partition near START and END
  resize NUMBER START END                  resize partition NUMBER and its file system
  rm NUMBER                                delete partition NUMBER
  select DEVICE                            choose the device to edit
  set NUMBER FLAG STATE                    change the FLAG on partition NUMBER
  toggle [NUMBER [FLAG]]                   toggle the state of FLAG on partition NUMBER
  unit UNIT                                set the default unit to UNIT
  version                                  displays the current version of GNU Parted and copyright information

print will show the disc lay-out and add a number to a disc;
resize {number} will let you resize a disc.
This will only work on umounted partitions ;)

I never used it this way myself so be careful when issuing commands.
Comment: "This will only work on unmounted partitions". That is my hangup. I can't unmount the root partition.
Comment: So all you can do is create a directory on the 2nd partition and symlink to it ;)
Answer: You can use parted command line tool for this.
First you need to delete extended partition.
List partitions using parted
parted /dev/vda

Note down your extended partition number with starting and ending blocks and delete it.
(parted) rm 2

Where is 2 is your extended partition number
Check it without using
(parted) print

You will get your extended partition removed.
Now make primary partition in remaining space.
(parted) mkpart primary <starting block no.>   <ending block no.>

With starting and ending block numbers previously noted.
Check it with again
(parted) print

Reboot your system to see the effects.
Resize your root partition:
resize2fs /dev/vda

You have to just check disk space using.
df -lh

You will get your root partition extended.


Wiring - 230V on a 120V 18/2 wire?

Question: I have brought US lamps to the UK. The sockets are rated 300W, but the cables are 18/2 gauge rated 10A/120V (UL rated, purchased 3 years ago).
What would happen if I ran 230V at 0.05 amp with a 9W UK Edison E27 bulb? The cables also have a switch on it.
I called several electricians and they all offered to replace the plug but not to rewire the lamp and said the amps were so low it didn't matter, but I figured I'd ask the group re: safety.
Thanks!
Mark
Comment: @Turbo J - Interesting question. I trust Wikipedia (which is as / more reliable than Encyclopædia Britannica). Also, I tend to trust someone who has no skin in the game more than someone trying to make a quick buck by chopping a cable, replacing the plug and calling it a day for £100. And, when the electrician doesn't know the difference between E26 and E27, I lose all trust I had left.
Comment: Electrically, the lamp would lit up and stay lit without issues until you turn it off or it breaks. You will however violate the rules/law/void some warranty by doing so.
Comment: You trust random people on the internet that did not even see the hardware *more* than local electricians?
Answer: The cable is not the problem.  It takes less current to supply the same power at 240 V as it does at 120 V.  The wires intended for 120 V operation therefore have excess current capability.
However, you have to consider voltage on other parts.  The switch has to withstand more voltage when open, and so does the insulation between you and the high voltage.  Probably both of these can handle the extra voltage.  However, if something happens, the liability is on you.  If the lamp catches fire and burns the house down, the insurance company would have a legitimate reason not to pay.  If someone got electrocuted by touching this lamp, you could be in serious trouble.
All around, this is a bad idea.  Leave the US lamp in the US.  Get a UK lamp for use in the UK.
Comment: @MarkK. It's quite common for cables and switches to have their voltage ratings printed on them, or embossed into the plastic.  Have a good look at them to see.
Comment: Thank you! That's what I was worried about and didn't trust the electricians' answers.

Wiring - 230V on a 120V 18/2 wire?


Rspec/Rails/Nokogiri: Undefined namespace prefix

Question: Here is the output of node.to_xml
<rsm:ExchangedDocumentContext>
  <ram:GuidelineSpecifiedDocumentContextParameter>
    <ram:ID>urn:cen.eu:en16931:2017</ram:ID>
    <ram:GuidelineVersionID>2.1.1</ram:GuidelineVersionID>
  </ram:GuidelineSpecifiedDocumentContextParameter>
  <ram:BusinessProcessSpecifiedDocumentContextParameter>
    <ram:ID>urn:cen.eu:en16931:2017:poacc:billing:3.0</ram:ID>
    <ram:BusinessProcessVersionID>1.0</ram:BusinessProcessVersionID>
  </ram:BusinessProcessSpecifiedDocumentContextParameter>
</rsm:ExchangedDocumentContext>

Here is the corresponding rspec test:
  describe '#to_node' do
    subject(:node) { exchanged_document_context.to_node }

    it 'returns the XML representation of the document' do
      expect(node).to be_a(Nokogiri::XML::Node)

      # Check the attributes of the ExchangedDocumentContext node
      expect(node.name).to eq('rsm:ExchangedDocumentContext')

      puts node.to_xml

      # Check the attributes of the GuidelineSpecifiedDocumentContextParameter node
      # rspec error is showing for the line below
      expect(node.at_xpath('ram:GuidelineSpecifiedDocumentContextParameter')).to be_a(Nokogiri::XML::Node)

      # Check the attributes of the BusinessProcessSpecifiedDocumentContextParameter node
      expect(node.at_xpath('ram:BusinessProcessSpecifiedDocumentContextParameter')).to be_a(Nokogiri::XML::Node)
    end
  end

But I'm getting this error:
 Nokogiri::XML::XPath::SyntaxError:
   ERROR: Undefined namespace prefix: ram:GuidelineSpecifiedDocumentContextParameter

Answer: because of the colon symbol (:), the XPath treated ram as a namespace instead of a node.
try this pattern instead:
...
nokogiri.at_xpath("//*[name()='ram:GuidelineSpecifiedDocumentContextParameter']")


Similar CSS chunks in Next.js

Question: I'm trying to figure out why Next.js inserts two similar chunk of CSS, like so
<link rel="preload" href="/_next/static/css/styles.chunk.css" as="style"/>
<link rel="stylesheet" href="/_next/static/css/styles.chunk.css"/>

I want only one with rel equals "preload". What can I do for this?
In my next.config.js is nothing criminal:
const withImages = require('next-images')
const withSass = require('@zeit/next-sass')
const TerserPlugin = require('terser-webpack-plugin')

const env = process.env.NODE_ENV || 'development'

const configs = {
  development: {
    BASE_URL: 'http://localhost:8110'
  },
  production: {
    BASE_URL: 'https://some-url'
  }
}[env]

module.exports = withSass(
  withImages({
    minified: true,
    optimization: {
      minimizer: [new TerserPlugin()]
    },
    env: {
      ...configs,
      ...other options
    }
  })
)

Thanks.
Answer: This is how preloading with link tags works.
If you check out the example on the MDN you will see a very similar layout as yours with a preload link, and then the stylesheet link.
Preloading Content With rel=preload

Similar CSS chunks in Next.js


Will Wall of Light Kills count as your kill?

Question: There are achievements that require not killing any enemy during a mission or even the whole game.
But, also, there are parts of the game where you can rewire the Walls of Light in order to be able to pass through them. The downside is that, if a guard passes, he will be obliterated.
Will this count towards a kill for you, ruining the achievement ?
I know i can remove tha whale oil from the reactor, deactivating the wall by the way.
Thanks in advance
Answer: Yes, kills with Wall of Lights will count as your kill.

Kills by Rewired traps will contribute to your kill amounts and Chaos;
  that's Watchtowers, Arc Pylons, and Wall of Lights.

Source: Notes on Stealth Detection, Chaos, and Trophies/Achievements by Gstaff (Bethesda Community Manager)


Can I listen for a Windows service event that I've created?

Question: I have a Windows service that writes messages to the Event Log. I also have a form application that reads that Event Log and displays the messages. The Windows service has an event that it fires which sends 2 key pieces of information in its EventArgs that I would like to be able to access from my form. Is there a way for me to hook into the service from the form to listen for this event?
Answer: Is this something you are looking for
http://ashishware.com/websocksample.shtml
http://www.codeproject.com/Articles/4857/A-realtime-event-log-monitoring-tool
Comment: I have that part already setup and working. What I am looking for is a way for that application to listen for an event from a windows service, which in this case I happen to have made.
Comment: @Zholen - Are you saying you want to monitor only events that come from Windows Service? Just filter it by EventLog Source and create custom EventLog source for event logs created by windows service. There wouldn't be any way of intercepting windows service event itself unless you expose a WCF service in your WinForms applicaiton that Windows service can access and notify WinForm app of any change
Comment: I have that, but i want to access 2 values(or event) from the service which are not posted in the log. The service has an event that it fires with these values, i would like to be able to listen for that event from my form.
Comment: @Zholen - You cannot really listen to WindowsService events, your windows service will have to notify your WinForms application of any events (you can use WCF to do that). ALternatively you could write these values into some temp file/folder that WinFors application can monitor for changes.


Any way to authenticate with a websense server from delphi?

Question: We use a websense internet filter at my workplace.  I have an application that tries to retrieve information from the internet.
On my client machine, I have to authenticate with websense manually (i.e., open firefox and give my username / password) or I'll get an error in my application when it tries to do the download.
The error message is:
HTTP/1.0 302 Moved.

Does anyone know of a way to authenticate with websense from code?  Examples in any language are welcome- I am using Delphi and Indy's TIdHTTP component.
Answer: Answering my own question; this is what worked for me.
The custom user agent string is only required if you want the authentication to let MSN / Live messenger get through, as described under "notes" at the end of this article.
In a command line application:
uses
  ... IdHTTP ...;

...
var
  httpGetter: TIdHTTP;
...
httpGetter.Request.Username := username;
httpGetter.Request.Password := password;
httpGetter.HandleRedirects := True;
httpGetter.Request.BasicAuthentication := True;

//custom useragent required to let live messenger work
httpGetter.Request.UserAgent := 'MSN Explorer/9.0 (MSN 8.0; TmstmpExt)';

httpGetter.Get(url,MS);
...

Answer: I would try HTTP authentication
http://en.wikipedia.org/wiki/Basic_access_authentication


Can I launch Tomboy Notes over ssh

Question: I have a few machines running Ubuntu and often I need to run an application from one machine on another. So I use ssh to do this as I already have it set up and it is simple to do.
For example
ssh -X netbook liferea

This works well for me as I don't have to sync files or install applications on all my machines.
When I try to do this with Tomboy Notes I get errors:
ssh -X netbook tomboy

Unhandled Exception: System.Exception: Unable to open the session message bus. ---> System.ArgumentNullException: Argument cannot be null.
Parameter name: address
  at NDesk.DBus.Bus.Open (System.String address) [0x00000] in <filename unknown>:0
  at NDesk.DBus.Bus.get_Session () [0x00000] in <filename unknown>:0
  --- End of inner exception stack trace ---
  at NDesk.DBus.Bus.get_Session () [0x00000] in <filename unknown>:0
  at NDesk.DBus.BusG.Init () [0x00000] in <filename unknown>:0
  at Tomboy.GnomeApplication.Initialize (System.String locale_dir, System.String display_name, System.String process_name, System.String[] args) [0x00000] in <filename unknown>:0
  at Tomboy.Application.Initialize (System.String locale_dir, System.String display_name, System.String process_name, System.String[] args) [0x00000] in <filename unknown>:0
  at Tomboy.Tomboy.Main (System.String[] args) [0x00000] in <filename unknown>:0

Is it possible to launch Tomboy Notes over ssh?
Comment: Maybe you can use [tomboycli](http://code.google.com/p/tomboycli/).
Answer: As a quick hack, launch dbus-launch tomboy.
Comment: I get `ssh netbook dbus-launch tomboy

[INFO 16:28:04.342] Initializing Mono.Addins
` and nothing happens
Comment: @Richard Holloway: nothing seems to happen, but have you seen in the panel if the icon appears? It appears on my test.
Comment: No, no icon either.

Can I launch Tomboy Notes over ssh


How to find the source code of the class OpenHashMapBasedStateMap in Apache spark project

Question: I I am trying to find a source code of OpenHashMapBasedStateMap which is used in the link given below. However I couldn't find the implementation anywhere in the spark repository. What could be the reason for this and how can I look at the source code of that Scala class
https://github.com/apache/spark/blob/branch-2.0/streaming/src/main/scala/org/apache/spark/streaming/util/StateMap.scala
Comment: is it defined on line 84 of the linked file?
Answer: It's just in the StateMap.scala:

/** Implementation of StateMap based on Spark's [[org.apache.spark.util.collection.OpenHashMap]] */
private[streaming] class OpenHashMapBasedStateMap[K, S](
    @transient @volatile var parentStateMap: StateMap[K, S],
    private var initialCapacity: Int = DEFAULT_INITIAL_CAPACITY,
    private var deltaChainThreshold: Int = DELTA_CHAIN_LENGTH_THRESHOLD
  )(implicit private var keyClassTag: ClassTag[K], private var stateClassTag: ClassTag[S])
extends StateMap[K, S] with KryoSerializable {
  ...
}

Till now(Aug. 23) it's from line 84
Comment: I don't know how I missed that. Thanks very much for the reply.


Encoding of string returned from 'system' command

Question: I am trying to read some meta-date returned from ffmpeg on a Linux machine. I am doing it from Matlab using the system command. My call to regexp fails to find what I am looking for (it works ok on Windows). The line I am parsing looks like this:

Duration: 06:33:42.17, start: 0.000000, bitrate: 65 kb/s

and I am parsing the duration with a call like this:

dur = regexp(w, 'Duration: [[0-9]+:]+.[0-9]+','match');

where w holds the string returned from the call to ffmpeg. The result is that dur is empty, meaning regexp failed to match the query. If I save w and load it on a Windows machine, I see this (I truncated the line but you can get the idea):

[0m[0;39m[0m[0;39m[0m[0;39m  Duration: [0m[0;39m[0m[0;39m[0m[0;39m06:33:42.17[0m[0;39m[0m[0;39m[0m[0;39m

which made me suspect some encoding issues.
Any ideas?
Comment: What is your exact call to the `system` command?  How are you getting the output into `w`?
Comment: `[s, w] = system([ffmpeg ' -i ' fnm]);`, where `ffmpeg` holds full path to the executable, and `fnm` is the input audio file.
Answer: Those look like terminal control codes; ANSI color codes to be more specific. (See http://en.wikipedia.org/wiki/ANSI_escape_code#Colors ) You may need to look into passing a flag or something to suppress those, if ffmpeg has such an option. (Usually, programs will auto-detect if stdout is an interactive terminal and figure out this on their own)
Comment: Great. ffmpeg does have this option, by setting an environment variable called AV_LOG_FORCE_NOCOLOR (http://ffmpeg.org/ffmpeg.html#Generic-options), which solved the problem. Thanks!


Replacing special characters in Java

Question: I'm reading out data from some old Cobol binary data files through a JDBC connection in Java on Linux (Ubuntu). The Swedish characters å,ä,ö,Å,Ä and Ö comes out as small boxes with four characters in them. Here is an example.

When running the program they actually just comes out as `` empty boxes in the console. I get the boxes with the text in them when I copy paste the output to a text editor. I think these characters are coded with ISO/IEC 8859-15 but I'm not sure. I like to replace the characters and thought I do myOutptString.replace("", "Ä"); and then I'll do the same thing for the other characters. The problem is that I'm not able to put the empty boxes as target in the replace function. What should I put in the target? Maybe it is not even possible to use the replace function for this.
Comment: You need to read the file with the correct encoding.
Comment: Isn't it the other way around when replacing characters/strings? As in `myOutputString.replace("Ä", "a");`. Now `Ä` will be replaced with `a`, unless those boxes are not read as `Ä` anymore.
Comment: @SLaks. I tried setting the encoding but it seems like it is not `ISO-8859-15`. Is there anyway I can do the replacement?
Comment: @steven No I want to replace to the Swedish characters å,ä,ö,Å,Ä and Ö.
Comment: Maybe this can help you set the right encoding? [Wiki source](https://en.wikipedia.org/wiki/%C3%85#On_computers)
Answer: Try reading the info as bytes and then try to construct your String using UTF-8 encoding. Your problem most likely is that your default encoding is different from that of your info. So in your code java tries to interpret the bytes according to your default encoding and fails. So if you just read bytes say into byte[] buf and then try to read it in this way:
new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf), "UTF-8"));

it might help. Ultimately you just need to figure out the encoding of your datasource
Comment: I'm not sure what the encoding is. Now though I managed to copy the "boxes" from the console into the editor and then it came out as codes, one example looks like this `\u0086` with this I'm able to replace it with regular characters.
Comment: Those are unicodes. So you can read them as UTF-8. Also, If you want a tool to convert Unicodes into Strings and vise-versa you can use my Open Source Library "Open Source Java library with stack trace filtering, Silent String parsing Unicode converter and Version comparison". See the paragraph "String Unicode converter". Here is the link to the article that explains in detail about the utilities in the library and how to use this library: https://www.linkedin.com/pulse/open-source-java-library-some-useful-utilities-michael-gantman

Replacing special characters in Java


C - Search for same values close to each other in an array?

Question: I have an array that contains x elements. I want to search through each element in the array to see if it matches my input value. However, there is a rule: The integer to search for must be in at least two elements of the array AND these elements must either be next to each other, or have maximum one element between each other. So this is what I came up with:
#include <stdio.h>

int main(void)
{

    int elements;
    int input;
    int i;

    printf("How many elements in the array? ");
    scanf("%d", &elements);

    int array[elements];

    printf("Ok, please input %d integer values: ", elements);

    for(i=0; i < elements; i++)
    {
            scanf("%d", &array[i]);
    }

    printf("Which integer should I search for? ");
    scanf("%d", &input);

    for(i=0; i < elements; i++)
    {
            if((array[i] == input && array[i+1] == input) || (array[i] == input && array[i+2] == input))
            {
                    printf("Match!\n");
                    break;
            }

            else
            {
                    printf("Match not found!\n");
                    break;
            }
    }

    getchar();
    getchar();
    getchar();

    return 0;
}

It doesn't work like intended, because if there are two elements between the integers I search for, it will still find a match.
Example of how the program should look:
Array: 1, 2, 3, 4, 5, 5
Integer to search for: 5
Match found! // 5 and 5 are next to each other

Array: 1, 2, 3, 2, 4, 5
Integer to search for: 2
Match found! // 2 and 2 has only one element (3) between each other

Array: 1, 2, 1, 1, 2, 5
Integer to search for: 2
Match not found! // 2 and 2 has more than one element between each other

Comment: If you loop from `0` to `elements-1`, then `array[i+2]` will be out of bounds if `i = elements-1`, same for array[i+1].
Comment: array[i+1] and array[i+2] accesses elements that are not part of your array.
Comment: Your `for` loop always stops at a first iteration.
Comment: I tried but it didn't work either. It's getting so messy that it's hard to understand. Andrey, my for loop is looping through the whole array (as long as a match not is found, but if a match is found there is no reason to keep looping through it)?

`(array[i-1] == input && array[i+1-1] == input) || (array[i-1] == input && array[i+2-1] == input)`
Comment: Ah, now I see what you mean, Andrey. I shouldn't have `break;` in the else statement.
Comment: You have `break` in both ways: `if(cond) { break; } else { break; }`
Answer: Strange enough.In my gcc 4.6.3
it shows
How many elements in the array? 6
Ok, please input 6 integer values: 1
2
1
1
2
5
Which integer should I search for? 2
Match not found!

Answer: You might want to improve your loop
            for (i = 0; i < elements - 2; i++)
            {
                if ((array[i] == input && array[i + 1] == input) || (array[i] == input && array[i + 2] == input))
                {
                    printf("Match!\n");
                    break;
                }
                else if (i + 1 == elements - 2)
                {
                    if (array[i + 1] == input && array[i + 2] == input)
                    {
                        printf("Match!\n");
                    }

                    else
                    {
                        printf("Match not found!\n");
                    }
                }

            }

Comment: @user2928113, effectively i+2 should be less than elements. Otherwise when you do array[i+2] you will be accessing elements not in the scope of your array.Else if statement is to compare the last two elements in your array. You can put some value in the elements(say 5) and trace the flow.
Comment: the `else` branch still breaks the loop at the first iteration
Comment: @Ingo, didn't realize the else part was only trying to fix the indexing part. Made the changes.
Comment: I have trying to understand but I can't understand why you have the else if statement in the code. And I don't understand why it's `elements -2`.


remove paint from carving

Question: the new place i just moved into has this gorgeous carving around the light fixture but as you can see the previous owners gave it the landlord special

i have no idea what the material is but i want to strip the paint so all the detail can be seen. how would I go about such a thing?
Answer: Just replace it. Ceiling medallions can be cheap especially if you buy them at large online housewares retailers rather than designer architectural suppliers. Stripping all the paint out of the nooks and crannies will be very difficult at best, and if it is made from an absorbent material it will be impossible. Preparing this thing for repainting is possible, but stripping it back to its raw glory is not, especially since it is probably made of foam or plaster and was never glorious until painted.

remove paint from carving


C++: Creating new thread using pthread_create, to run a class member function

Question: I have the following class:
class A
{
    private:
        int starter()
        {
             //TO_DO: pthread_create()
        }

        void* threadStartRoutine( void *pThis );
}

I want to create a thread from inside starter() to run threadStartRoutine(). I get compile time errors with regard to the third argument, which should take the address of the start routine.
What would be the correct way to call pthread_create() to create a new thread that starts executing threadStartRoutine() ?
I have come across articles online that say that most compilers do not allow non-static member functions to be invoked using pthread_create(). Is this true? What is the reason behind this?
I am compiling my program on Linux-x64 using G++.
Comment: make thread start routine static
Comment: @neagoegab: I cannot make threadStartRoutine static. The class is multi-threaded. Making threadStartRoutine static results in memory leak errors that I'm trying to get rid of.
Comment: possible duplicate of [The fouth parameter in pthread_create function](http://stackoverflow.com/questions/8920441/the-fouth-parameter-in-pthread-create-function)
Comment: possible duplicate of [cannot convert '*void(MyClass::*)(void*) to void*(*)(void*) in pthread_create function](http://stackoverflow.com/questions/12006097/cannot-convert-voidmyclassvoid-to-voidvoid-in-pthread-create-fu)
Comment: Unless you're stuck in the past for some reason, you should consider the standard thread library. And even if you are stuck in the past, Boost.Thread might be a better option than rolling your own wrapper around pthreads.
Answer: Declare the threadStartRountine() as static:
static void* threadStartRoutine( void *pThis );

Otherwise, the type of threadStartRoutine() is:
void* (A::*)(void*)

which is not the type of function pointer that pthread_create() requires.
Comment: The sentence "The class is multi-threaded" makes absolutely no sense. That's not how C++ and programming work.
Comment: @ShaileshTainwala: Do not make the function static. Instead write a new static function that calls yours, and use this new function as argument to `pthread_create()`. And everybody happy! Naturally you will need to pass on the `this` argument so that the static function can call a non-static one. But that's why you have the `pThis` argument.
Comment: @ShaileshTainwala - they're functions, ie. code, with stack parameters, ie. different for each thread.  There is no problem calling a static function from multiple threads, passing a 'this' pointer and then calling a method on 'this'.  Problems arise when involving static data mambers that are shared by all callers.
Comment: I cannot. The class is multi-threaded. Making threadStartRoutine static results in memory leak errors that I'm trying to get rid of.
Comment: @ShaileshTainwala, I am unsure how either of those two arguments prevent you from making the function `static`?
Comment: By "the class is multi-threaded" I assume you mean that multiple threads might use the same object.  As hmjd says, I don't see what that has to do with the problem.  Naturally using an object in multiple threads will make it harder to correctly destroy it; but that probably has nothing to do with the start routine.
Comment: Sorry, bad language. The program that consumes this Class A was modified and made multi-threaded. This change has led to several memory errors that are very difficult to pin-point due to environment constraints. I have traced them to this part of the program, using *exhaustive* trial-and-error. All my research says that mixing static member functions and multi-threading is a bad idea. Hence the question.
Comment: @ShaileshTainwala Your memory leak is most likely not caused by making a method static. Use valgrind to pinpoint where you are leaking memory.
Comment: @anio - Using Valgrind, gdb or other tools is not possible, I am building a library for a much larger program. One which I cannot rebuild with debugging info.
Comment: @ShaileshTainwala That makes no sense, why can't you build with debugging info? It is a simple compiler argument: -g. I've run massive programs under valgrind and found memory leaks.
Comment: I think rodrigo has the right idea about my guess is that you are using a static function in some particular way that happens to be a subtle anti-pattern.  As for not using these debugging info - even if you could recompile the bigger program, you should also have a test rig so that you can isolate your library.
Comment: @rodrigo: Technically, you must only pass functions to `pthread_create` which have `extern "C"` linkage.
Comment: @KerrekSB: Could you give a reference for this? I don't see why the linkage of the function should matter at all. And the `extern "C"` syntax only changes the name mangling, right? (and maybe something about exceptions...).
Answer: Do you have a reason for using pthreads? c++11 is here, why not just use that:
#include <iostream>
#include <thread>

void doWork()
{
   while(true)
   {
      // Do some work;
      sleep(1); // Rest
      std::cout << "hi from worker." << std::endl;
   }
}

int main(int, char**)
{

  std::thread worker(&doWork);
  std::cout << "hello from main thread, the worker thread is busy." << std::endl;
  worker.join();

  return 0;
}

Answer: Just use a normal function as a wrapper.  As hjmd says, a static function is probably the nicest kind of normal function.
Answer: If you insist on using the native pthreads interface, then you must provide an ordinary function as the entry point. A typical example:
class A
{
private:
    int starter()
    {
        pthread_t thr;
        int res = pthread_create(&thr, NULL, a_starter, this);
        // ...
    }
public:
    void run();
};

extern "C" void * a_starter(void * p)
{
    A * a = reinterpret_cast(p);
    a->run();
    return NULL;
}


retrieving session variable from another controller

Question: Is is possible to retrieve a Session variable from a different controller it was created from?
I create this in my Account controller
System.Web.HttpContext.Current.Session["Session"] = sessionGuid;

and from a different controller I'm trying
if (System.Web.HttpContext.Current.Session["Session"] != null)
{
    return Json(System.Web.HttpContext.Current.Session["Session"].ToString());
}
    return null;

which always returns null.
as a Test I added some code to my Login controller and in that part i do get the value out of it
if (System.Web.HttpContext.Current.Session["Session"] != null)
    {
        test = System.Web.HttpContext.Current.Session["Session"].ToString();
    }
        else
    {
        test = "no";
    }

i always got the actual result, not the"no" part of the code
Comment: [Read this](https://msdn.microsoft.com/en-us/library/system.web.httpcontext.session(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp). You are probably not saving/setting the session state correctly
Answer: For some reason its different into how i have to access the session, at the other controller i changed to this code and it worked
if (HttpContext.Session["Session"] != null)
{
  return Json(HttpContext.Session["Session"].ToString());
}
return null;

Comment: I shared a link earlier in an comment to your question. Read that to understand the reason.
Comment: There's a difference between `HttpContext.Session` and `HttpContext.Current.Session`
Answer: if controller is within the same website/virtual directory then YES, however if you are saying your session was created in a different site and you trying to access it within a controller which belongs to different site then you cannot.
Comment: both of them are created in the same site, and even though i am getting null
Comment: try this: https://forums.asp.net/t/1926258.aspx?The+Session+object+is+null+in+ASP+NET+MVC+4+webapplication+once+deployed+to+IIS+7+W+2008+R2+


bcp randomly fails in a batch of 100+ jobs

Question: I have a Python program that generates over 300 files and uses bcp to move them to MSSQL. There is a high level of concurrency as about 21 files are being generated and bcp'd in at the same time. Here is the critical part of the program:
    cmd = ['bcp', self.bcptbl, 'IN', outfile, '-f', 'bcpfmt.fmt', '-m1', '-U', uid, '-S', self.srv, '-P', pwd]
    subprocess.check_output(cmd)

Three batch threads go at a time, 7 sub-threads each, so 21 concurrent processes. At a random file bcp fails with error:
[Microsoft][SQL Server Native Client 11.0]Unable to open BCP host data-file
The error might have something to do with the way I create file before BCP is invoked:
with open(outfile, 'a') as outf:
    proc = Popen('ext_prog.exe', stdin=PIPE, stdout=outf, stderr=PIPE)
    _, err = proc.communicate(input='\n'.join(patterns).encode('latin1'))

Something tells me that the file handle is not released by the external program, even though file open and close is seemingly handled by me.
This is not a typical error, as permissions, folders, paths, etc are all set up correctly, since it copies 80 ~ 150 files successfully before failing.
BCP call in the code above failed frequently until I inserted the following check before the bcp call:
@staticmethod
def wait_file_is_ready(outfile):
    try:
        with open(outfile, 'r'):
            print("File {} is ready for reading".format(outfile))
    except BaseException as e:
        print("File {} is not ready: {}".format(outfile, e))

My reasoning is that Windows does not mark the file as closed in time so opening and closing it helps. This fixed 99% of errors but with the massive job I got today it came back to haunt me.
Things I tried to recover from error:

Adding a 1 hour sleep before re-running same bcp command - fails
Making a copy of the input file and re-running bcp command - fails
Running the BCP command manually from command line always works

More detailed code excerpt:
MAX_THREADS = 7

def start_batch(self):
    ts = []
    self.patternq = queue.Queue()
    self.bcptbl = '"tempdb.dbo.outtbl_{}"'.format(randint(0,1E15))
    for thread_no in range(MAX_THREADS):
        tname = "thread_{:02}_of_{}".format(thread_no, MAX_THREADS)
        t = Thread(name=tname, target=self.load, args=(thread_no,))
        t.start()
        ts.append(t)

    for t in ts:
        t.join()

def load(self, thread_no):
    outfile = "d:\\tmp\\outfile_{}_{:02}.temp".format(
        randint(0,1E15), thread_no)
    try:
        os.unlink(outfile)
    except FileNotFoundError:
        pass
    while True:
        try:
            patterns = self.patternq.get_nowait()
        except queue.Empty:
            break
        with open(outfile, 'a') as outf:
            proc = Popen('ext_prog.exe', stdin=PIPE, stdout=outf, stderr=PIPE)
            _, err = proc.communicate(input='\n'.join(patterns).encode('latin1'))

    cmd = ['bcp', self.bcptbl, 'IN', outfile, '-f', 'bcpfmt.fmt', '-m1', '-U', uid, '-S', self.srv, '-P', pwd]
    try:
        subprocess.check_output(cmd)
    except subprocess.CalledProcessError as e:
        # OK, it failed because "Unable to open BCP host data-file"
        # How can I recover from it?
        raise

Answer: I went around the problem by using ODBC to insert the records, slowly and carefully. That worked 2 out of 3 times. Here is the error I got on third iteration:
os.unlink(outfile)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'd:\tmp\outfile_678410328373703.temp_03'
And a feasible explanation for the error:
Seems to be an issue long standing and a bug inherent with Windows 7

Found this in MS forums
Seems to be an issue long standing and a bug inherent with Windows 7.
There has been no "official" statement from MS acknowledging this bug hence a patch or fix release is unlikely. Some users in the thread above have offered "fixes" but they are way too time consuming and inefficient in regards to workflow productivity. This shouldn't be an issue one has to deal with when purchasing a new OS ...


Pandas groupby count values greater than given values in each group

Question: I want to count how many values are greater than a given set of values in each group.
For instance, the DataFrame df is like:
print(df)

  item   A   B   C
0    a  -4  17 -15
1    a  19 -16  -3
2    a -18 -11 -13
3    b  -2   9   7
4    b  -9 -15 -14
5    b -20   2 -10
6    c -19   0 -10
7    c  11   3   4
8    d   5   0 -17
9    d   7   1  -1

and the condition c is another DataFrame, like
print(c)

  item  value
0    a      5
1    b     -1
2    c      2
3    d      1

The desired result looks like
        count
item   A   B   C
a      1   1   0
b      0   2   1
c      1   1   1
d      2   0   0

I searched questions about using the pandas.groupby() function with conditions, but the answers were based on "greater than one value", not for a set of values.
The pseudo-code might write as following...
I know it does not work properly...
df.groupby("item")[["A", "B", "C"]].apply(lambda x: x > c["value"] if df["item"] == c["item"]).size()

It would be greatly appreciated if any of you could help me.
Many thanks.
Comment: I see count of 2 for (b, B).
Comment: Sorry, that's my mistake. I have revised. Thank you, @jpp for pointing it out.
Answer: IIUC
(df.set_index('item')).sub(c.set_index('item').reindex(df.item).value,axis=0).gt(0).groupby(level=0).sum()
Out[646]:
        A    B    C
item
a     1.0  1.0  0.0
b     0.0  2.0  1.0
c     1.0  1.0  1.0
d     2.0  0.0  0.0

Comment: So the logic is to subtract the values of items in `c` from the values of corresponding items in `df` and then sum the results which greater than zero. The trick is setting `item` as indexes for both `df` and `c` then reindexing according to the indexes of `df `.
Comment: @Huan if it is what you need can you consider accept it?


How to change my Website direction LTR to RTL with CSS

Question: I have a website urdu.gvnews.live i want to flip the direction from Ltr to rtl please help me how can i change it.
the css link is http://gvnews.live/urdu/css/style1.css
Answer: Maybe this is something you are looking for
https://css-tricks.com/snippets/css/reversing-text/
Go through it and try changing.


What's the main difference of pipeline process between Vulkan and DX12?

Question: DX12 introduces a new feature of pipeline named 'Bundle'. It seems that can optimize the command list, and send it to final pipeline. Vulkan invent some different pipeline: The graphic pipeline and the compute pipeline. The graphic pipeline seems just the same with the original, the compute pipeline is used as an accessor of image memory.
My CG knowledge is pretty basic, and can not confirm that cognition is correct. Would someone kindly provide some explanations for it - The main difference of pipelines between them ?
References:

https://msdn.microsoft.com/zh-cn/library/mt617309
https://www.khronos.org/registry/vulkan/specs/1.0/xhtml/vkspec.html#pipelines
Answer: D3D12 has 4 separate kinds of command lists: direct, bundle, compute, and copy.
Vulkan has similar concepts, but they happen in a different way. Command buffers are allocated from command pools. And command pools are directly associated with a queue family. And command buffers allocated from a pool can only be submitted to the queue family for which the pool was built.
Queue families specify the kinds of operations that the queue can take: graphics, compute, or memory copying operations. D3D12's command queues have a similar concept, but D3D12's command list API has you to specify the list type. Vulkan's gets this information from the queue family the pool is meant for.
The D3D12 "bundle" command list type seems similar on the surface to Vulkan secondary command buffers. However, they are quite different.
The principle difference is this: bundles inherit all state from their executing direct command list, except for the bound PSO itself. This includes resource descriptor bindings.
Vulkan secondary command buffers inherit no state from their primary command buffer execution environment, except for secondary CBs that execute in a subpass of a renderpass instance (and queries). And those only inherit the current subpass state (and queries).
This means you do different things with them, compared to D3D bundles.
Bundles are sometimes used to modify descriptor tables and render stuff, on the assumption that the direct command list they're executed within will have set those tables up. So bundles are kind of like light-weight OpenGL display lists, only without all of the bad things those do. So the intent with bundles is that you build them once and keep them around. They're supposed to be small things.
Vulkan secondary CBs are essential for threaded building of commands intended for a single render pass instance. This is because a render pass instance can only be created within a primary CB, so for optimal use of threads, there needs to be a way to create commands meant to execute in the same subpass in different threads. That's one of the main use-cases of secondary CBs. So the intent is that you'll probably build secondary CBs each frame (though you can reuse them if you want).
So in the end, bundles and secondary CBs are intended to solve separate problems. Bundles are generally dependent on the executing environment, while secondary CBs are more stand-alone.
At the same time, Vulkan secondary CBs can do something bundles cannot: they can execute on compute/copy-only queues. Since Vulkan makes a distinction between the primary/secondary level of the command buffer and the queues where that CB can be sent, it is possible in Vulkan to have secondary command buffers that execute on compute or copy-only queues.
Direct3D 12 can't do that with bundles. The ExecuteBundle function can only be called on a direct command list. So a copy-only command list cannot execute bundles.
Granted, because Vulkan doesn't inherit anything between secondary CBs except for subpass state, and compute/copy operations don't use render passes, there isn't much to be gained from putting such commands in a secondary CB rather than a primary one.

D3D12 has the same separation between compute pipelines and graphics pipelines that Vulkan does. However, when issuing commands, D3D12 has only one pipeline binding point, to which you can bind any kind of pipeline. By contrast, Vulkan has separate binding points for compute and graphics pipelines. Of course, Vulkan doesn't have different descriptor binding points for them, so the two pipelines can interfere with one another. But if you design their resource usage carefully, it is possible to invoke a dispatch operation without disturbing the needs of the graphics pipeline.
So overall, there's no real difference in pipeline architecture here.
Answer: The main difference with the pipelines is that DirectX12 is focus is on multi-threading or using the multiple cores most efficiently as possible according to the rendering state of an object.
As for Vulkan, they are separating the management of the threads into different types of pipelines, compute and graphical.
As stated in the reference from MSDN, DirectX12 is utilizing PSO (Pipeline State Object). The optimization occurs in this way by preparing the commands to the pipeline before. Seemingly, DirectX12 uses PSO to create a object of the state of rendering to better manage changes in state to the hardware more efficiently.
Hope that helps!
Comment: @PaulHK, according to the DX12 article, that would be case. Looks, like VUlkan is using multiple threads as well: https://www.khronos.org/registry/vulkan/specs/1.0/xhtml/vkspec.html#fundamentals-threadingbehavior
Comment: You means, DX12 only has one pipeline, but it optimized comprise process of PSO with multi-thread and multi-cores. Vulkan has 2 pipelines, reside on different threads, each thread has its own commands managements, but only 2 threads ?
Comment: Vulkan is using system-on-a-thread ? Were as DX12 is fully multi-threaded?
Comment: Am not sure if DX12 is using one pipeline, might be worth looking at the documentation for DX12 for the specifics.


sql command for wordpress to remove random text from posts

Question: i have like 80k posts in wordpress
all posts have text like that

read more: uguguf

read more: hjgjgf

read more: ihih

read more:ugff

after text "read more: random text
so only way to find this random text is search and replace for 'read more:'
i try this sql command
UPDATE wpw8_posts SET post_content = REGEXP_REPLACE(post_content, 'read more:".*"', '') WHERE ID = 237955;

to test it at post id 237955
after use sql i see only remove read more:
like that

uguguf

hjgjgf

ihih

ugff

how to remove this random text
Comment: So what do you want to happen?
Comment: that the result looks like the last table in the post @Eric
Comment: You don't need a regexp. Just `REPLACE(post_content, 'read more:', '')`
Comment: Your regexp shouldn't even match. It has `"` around `.*` but that doesn't appear in the content.
Comment: @Barmar he has sometomes spaces behind the read me:
Comment: @nbk I don't think spaces at the beginning of a `` are significant, so it's OK to leave them.
Comment: @Barmar his endreslt has no spaces before the random text, so it maters
Comment: @nbk He probably doesn't realize that it doesn't matter.
Comment: i want remove full like so after read more is random text
Comment: @Eric problem is not space problem is text after "read more:"
Answer: As you only want to remove read more: wuth or without a space you can use '(read more:)([[:space:]]*)' as pattern
CREATE TABLE wpw8_posts
    (`post_content` varchar(41))
;

INSERT INTO wpw8_posts
    (`post_content`)
VALUES
    ('
read more: uguguf
'),
    ('
read more: hjgjgf
'),
    ('
read more: ihih
'),
    ('
read more:ugff
')
;

UPDATE wpw8_posts SET post_content =
  REGEXP_REPLACE(post_content, '(read more:)([[:space:]]*)', '') ;

Rows matched: 4  Changed: 4  Warnings: 0

SELECT * FROM wpw8_posts

post_content

uguguf

hjgjgf

ihih

ugff

fiddle
if you need to remove read more inclusive the random text
UPDATE wpw8_posts SET post_content =
  REGEXP_REPLACE(post_content, '(read more:)(.*)', '') ;

Rows matched: 4  Changed: 4  Warnings: 0

SELECT * FROM wpw8_posts

post_content

fiddle
or the hole thing
UPDATE wpw8_posts SET post_content =
  REGEXP_REPLACE(post_content, '
(read more:)(.*)
', '') ;

Rows matched: 4  Changed: 4  Warnings: 0

SELECT * FROM wpw8_posts

post_content

fiddle
Comment: thank you but i want remove full line not only read more :
Comment: i don't understand what you want to delete, what do you mean by the hole line all from  to ?
Comment: if i have full line like that "read more: grhghirhi" i want delete it so problem is after read more is random text
Comment: see if the update helps, else you need to demonstrate what the endreult should be , because you have rows and columns and not lines
Comment: thank you for help i test it now and it work good
Comment: if after read more or after space how to get it like that "read more : fhvrgurh"
Comment: you can see here howit is done https://dbfiddle.uk/Pj4ETAxB maybe you should take a look at regular expressions
Comment: thank you i try it work good but if have enter between p tag and text,sorry but regular is hard for me i try like 50 time and fail for that i ask here
Comment: like you old answer space code are enter have code for it?
Comment: It takes some time to understand the logic, but you can use reg101 https://regex101.com/ to test your patterns
Comment: i try \n i don't know what code to new line
Comment: Try \r\n, but can make a fiddle and post here to see what you I am slightly confusef
Comment: i think enter is hard to replace , but after i try on same posts 0 effect this is my code (UPDATE wpw8_posts SET post_content = REGEXP_REPLACE(post_content, '(شاهد ايضا: )(.*)', '') WHERE ID = 169254;)
to replace (شاهد أيضًا: ما معنى قربانة في المسيحية)
Comment: Add your text as insert to the dblink , your pattern doesn't match the samples yo have given, regex needs an exact pattern that must be equal in the posts. Asong as I don't know what the data looks like , you must test your patterns in regex101
Comment: is arabic char have problem with that? test work on same and other not and i dont why this happen my data like that شاهد أيضًا: ما معنى قربانة في المسيحية


Projection of a Polyhedron on xy Plane with CGAL

Question: I am trying to project a Polyhedron on the xy plane with CGAL, which should result in a (2D) polygon.
I wonder, if there is an elegant way to achieve it?
Of course, I can iterate over all surfaces and build 2D-Segments from the 3D-Segments by throwing away the z coordinate and then reassemble the polgon cycles.
But I feel, that somehow using Projection_traits_xy_3 it should be possible to solve that task more elegant, however, I couldn't find a way. Is this possible?
Answer: A possible way to do this is tracing the silhouette edges of the polyhedron and projecting them to a 2d polygon only at the end of the process.
A silhouette edge (in your context) is defined by its neighboring facets having one upwards and one downwards normal (i.e., one positive normal z-coordinate and one negative). This can be checked using Polyhedron_traits_with_normals_3 or you can compute the normals yourself on-the-fly.
If you only need the outside polygon, you can start with an extreme vertex (e.g., the one with minimal x-coordinate), circulate over its incident halfedges (using Halfedge_around_vertex_circulator), take the one that is a silhouette edge and continue tracing with its next vertex until you close the cycle.
If you also need inside (hole) polygons, a possible solution can be to gather the silhouette edges from all the polyhedron, and trace the cycles from this set.


Draft inducer motor - what is this noise?

Question: I have a Bryant 355BAV042060 natural gas furnace that I had to replace the draft inducer motor assembly on at the beginning of 2018. It's been working fine in the winter seasons since then keeping the house warm. For the last year or so, it's been making a noise when blowing heat. I can hear this noise through the air vents, and also when I'm outside I can hear the noise coming through the furnace air vent/exhaust, echoing off the neighbor's house into our back yard. It's gotten progressively louder over the past. When it's just the fan (circulating air), the noise isn't there.
I took the cover off and it looks like the noise is coming from the draft inducer motor assembly that I replaced six years ago that's making the noise. Here's a video of the draft inducer motor assembly making the noise.
I'm not sure the noise indicates a problem at all, but it wasn't there for the first four years, and it's getting louder, so it seems like a symptom of something not right.
I assume the issue is a bad bearing. When the draft inducer kicks on, the pitch of the noise starts low and increases as the speed of the draft inducer does, and when it turns off, the pitch slowly goes down as the draft inducer slows down.
My goals:

Identify the problem. Does a bad bearing indeed seem the most likely cause of the noise?

Identify the cause. In my head, it's possible that a bearing just went bad. But it's also possible that I (regular DIY guy, no formal HVAC training) installed the part incorrectly. I followed the instructions, and used the special Momentive RTV 162 high-temp silicone to seal up the collector box as instructed. But I also starting using MERV-13 air filters maybe 18 months ago, and I'm not sure if that may be too restrictive of a filter for my furnace.

Identify the solution. If this is indeed a bad bearing, is it likely it can be replaced? I've found a couple YouTube videos where people are replacing bearings, and I do have a puller. Or would the recommendation be to replace the entire assembly again.

Updates

The draft inducer motor's bearings are sealed, so no maintenance to perform on them.

Pushing on the motor while it is running does not affect the sound. Video.
Comment: Is it "permanently lubricated" or are you supposed to be oiling bearings every 6-12 months? If you are not getting overtemp (high cutout) errors, I doubt your filters are a problem, and in any case they should have nothing to do with the draft inducer.
Comment: Installation is not maintenance, as instructions go. Normally if meant to be oiled there are oil holes and either stamped in text or labels mentioning the frequency and type of oil. The instructions **do** bring up the possibility that the noise might be from the fan itself squealing due to contact with the housing, inferred from the "spacer" part of the instructions.
Comment: Huh, I'm not sure. I don't remember reading anything about regular maintenance on it, but I'll have a look. Thanks!
Comment: @Ecnerwal - the draft inducer motor assembly is part number 340793-762 and I can't find anything on the internet that suggests I should be oiling any bearings. Here's a link to the installation instructions: https://www.shareddocs.com/hvac/docs/1009/Public/07/IIK-340793-762-01.pdf
Comment: Try gently pressing or moving the angle of the fan motor, a very small amount, and see if the noise changes. If so it is hitting the housing. You could remove it and see where it is hitting. The solution could be as simple as remounting it.
Comment: @Ecnerwal - the draft inducer motor's bearings are sealed.
Comment: @Gil - pushing on the fan motor does not affect the noise. Video: https://youtube.com/shorts/ldWkPOpTXis?feature=share.
Answer: From everything you  have tried I would assume the fan motor has failed. I recommend you purchase another fan motor after you verify that it is no longer in warranty. Then maybe February when it is real cold you will be able to replace it immediately when it fails. Or change it now an and keep the old for an emergency.
When you remove it, shift it slightly if you can, tighten it then try to see if it then works properly.  If not remove it check the fan blade/cage for any wear marks or shiny surface. Good Luck.
Comment: I appreciate the advice! I actually do have the old one still. Perhaps I'll focus on repairing that one as a backup. But, I'm not ready to give up on this one just yet. I'm planning to remove the motor assembly from the furnace and spin the motor both electrically and manually. If the noise still happens outside the furnace, and it is indeed coming from the motor, isn't repair still a possibility? I really don't want to pay another US$1100 to replace the entire assembly and discard the old one when a US$20 worth of bearings and a couple hours of time could get me back in business.
Comment: Check if it's dirty? Does it make that sound away from the furnace? https://youtu.be/Zax02itYHkU in desperation maybe oil after cleaning it?
Comment: Any luck? Ideas that come to mind are: if you push it while it's running does it change sound? Might be able to get a cheaper one on eBay or just replace the inducer blower wheel instead of the entire motor?  Or just grommets?


cloning template Jquery

Question: I have a rather long complicated form to be used to record field data. One section of the form requires the ability to add a "Field Blank" section with no data recorded AND the ability to add a duplicate section where everything (including the data from the field blank section) is duplicated. The only different thing that would change on the duplicate would be the SampleID
The field blank script

The duplicate script

My form

Water Samples

      <fieldset id="template">

 Sample ID: <input type="text" id="SampleID" name="SampleID">

   Collection Method

         <input type="radio" id="radGrab" value="grab" name="Collection" />
      Grab
          <input type="radio" id="radEWI" value="EWI" name="Collection" />
      EWI

    <fieldset>

  QA Sample ID:<input type="text" id="QASampleID" name="QASampleID">

 Collection Method

         <input type="radio" id="radGrab1" value="Grab" name="Collection1" />
      Grab
          <input type="radio" id="radEWI1" value="EWI" name="Collection1" />
      EWI

 Analyte:
     <select class="analysis" id="analysis" name="analysis" data-iconpos="left" data-icon="grid">
    <option>Select</option>
           <option value = "TN">TN</option>
           <option value = "TP,NO2+3">TP,NO2+3</option>
           </select>
      Preserved
      <select class="select_preserve" id="preserve" name="preserve" data-iconpos="left" data-icon="grid">
        <option>Select</option>
           <option value = "HNO3">HNO₃</option>
           <option value = "H2SO4">H₂SO₄</option>
    </select>
     Cooled
    <select class="select_cool" id="cool" name="cool" data-iconpos="left" data-icon="grid">
        <option>Select</option>
           <option value = "Ice">Ice</option>
           <option value = "Frozen">Frozen</option>
           <option value = "None">None</option>
        </select>

  </fieldset>

  </fieldset>

 <button type="button" data-theme="b" data-icon="plus" id="moreFields" onclick="moreFields()">ADD FIELD BLANK</button>
 <button type="button" data-theme="b" data-icon="plus" id="add_FieldDup">ADD FIELD DUP</button>

I got the duplicate to work (when the field blank wasn't hidden) but I cannot get the field blank to work. Any assistance would be greatly appreciated!
Answer: You should extract your javascript from your dom, put it in separate js and make function work in any of this blocks, create class="template" block and inside give any needed interaction buttons and inputs classes so there can exist multiple parent elements with same inside structure... then cloning does not get in a way of your interaction logic.
In js go like:
$(document).ready(function() {
$(".template .interaction_button_one").on('click', function(){
    //... here you go traversing like
    $(this).parents('.template').find('.some_important_div').show();
})
});

Notice .on(), this is delegation, and it will give same interaction bindings to all of your elements.

cloning template Jquery


How to select Excel range in powershell

Question: I have the following code in a function:
function Excel2PPT{

param ($xslx, $targetsheet, $targetrange, $pptx, $targetslide, $npath)
    $Excel = New-Object -ComObject Excel.Application
    $workbook = $Excel.workbooks.open($xslx)
    $Excel.Visible= $true
    $worksheet = $workbook.worksheets.Item($targetsheet)

$range = $worksheet.Range($targetrange)
$range.select()
$range.copy()

I am using it in another function which passes to it "A1:O12" as $targetrange
This worked in previous testing but now yields an error and unexpected behavior.
I reference it as:
Excel2PPT $IncomingABCExcel 1 'A1-O12' $testPPT2 $Targetslide $testPPT3

The error is:
Exception from HRESULT: 0x800A03EC
At C:\...\Excel2PPT.ps1:16 char:1
+ $range = $worksheet.Range($targetrange)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

You cannot call a method on a null-valued expression.
At C:\...\Excel2PPT.ps1:17 char:1
+ $range.select()
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\...\Excel2PPT.ps1:18 char:1
+ $range.copy()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

What can I do to fix it? It should be copying and pasting $targetrange to the intended PPT slide but it appears to be copying and pasting "$IncomingABCExcel" (not the variable, the variable name) onto the slide.
Comment: Where are you defining `$targetrange`? and have you checked if it is NULL?
Comment: Please see the edit
Comment: Can you print the value of `$targetRange` prior to line 16 `$worksheet = $workbook.worksheets.Item($targetsheet)` ?
Comment: I tried and it appears to be null, which matches the behavior but that's so odd. Am I not passing it in correctly?
Comment: It could be that you are not passing to the function correctly or that you have not assigned a value to the variable beforehand, just print the value of it before the function call. If it prints then you know it is in the function call.
Comment: I tried playing around with passing it using single or double quotes. Now it prints target range but it still yields the same error and similar wrong behavior
Answer: The issue you are having is that you are using 'A1-012' As the range. This should be 'A1:012':
function Excel2PPT {
    param ($xslx, $targetsheet, $targetrange, $pptx, $targetslide, $npath)

    $Excel = New-Object -ComObject Excel.Application
    $workbook = $Excel.workbooks.open($xslx)
    $Excel.Visible= $true
    $worksheet = $workbook.worksheets.Item($targetsheet)
    $range = $worksheet.Range($targetrange)
    $range.select()
    $range.copy()
}

Excel2PPT $IncomingABCExcel 1 'A1:O12' $testPPT2 $Targetslide $testPPT3

How to select Excel range in powershell