Dynamic classes/objects ML.net's PredictionMoadel Train()

Question: I am using Microsoft's ML.net library.
I would like to train data based on a model who's contract is generated at run-time (meaning the fields are not known at compile-time). Can this be achieve using the current ML.net's Train() method siganture?
So far i am trying to call this Train method by passing in the instance of the TInput and TOutput objects (rather than the T class).
Comment: I'm not sure if this helps or not, but the [TestDatasetInference](https://github.com/dotnet/machinelearning/blob/c023727b76970ab913ec1ce38276508835c17bcf/test/Microsoft.ML.Predictor.Tests/TestDatasetInference.cs) may be of some use.
Answer: According to the docs, LearningPipeline only has one method, Train<TIn, TOut> for training, and it implies that TIn and TOut are actual classes: TIn an input to prediction, and TOut an output.
The underlying ML.NET code doesn't actually depend on knowing the schema ahead of time: the Train<TIn, TOut> method is a convenience method that we decided to expose to the users. The side effect of that decision was that we essentially prohibited use cases like yours.
Of course, you can still use Reflection to generate the class signatures at runtime, when you know the schema of the data, but it is an awkward workaround.
The new ML.NET API that we are working on (see issues in this project) would lift this requirement: you will be able to train on data which schema is not known at compile time.
Comment: nvm, I found the blog at https://blogs.msdn.microsoft.com/dotnet/2018/10/08/announcing-ml-net-0-6-machine-learning-net/
Comment: Zruty, do we have an expected API release date? I'm having the same problem. Thanks
Comment: It is available now in ML.NET 0.6
Comment: is there a sample code to illustrate the new API? I'm using ML.NET 0.6


regular expression back referencing

Question: why this snippet:
'He said "Hello"' =~ /(\w)\1/

matches "ll"? I thought that the \w part matches "H", and hence \1 refers to "H", thus nothing should be matched? but why this result?
Answer:
I thought that the \w part matches "H"

\w matches any alphanumerical character (and underscore). It also happens to match H but that's not terribly interesting since the regular expression then goes on to say that this has to be matched twice – which H can't in your text (since it doesn't appear twice consecutively), and neither is any of the other characters, just l. So the regular expression matches ll.
Answer: You're thinking of /^(\w)\1/. The caret symbol specifies that the match must start at the beginning of the line. Without that, the match can start anywhere in the string (it will find the first match).
Answer: and you're right, nothing was matched at that position. then regex went further and found match, which it returned to you.
\w is of course matches any word character, not just 'H'.
Answer: The point is, "\1" means one repetition of the "(\w)" block, only the letter "l" is doubled and will match your regex.
A nice page for toying around with ruby and regular expressions is Rubular

regular expression back referencing


java sorted node list example

Question: I am new to node lists and I need to search check whether a PersonNode associated with the given ID is in the list
the is my PersonNode class
public class PersonNode
{
// instance variables
private int m_ID;
private String m_name;
private PersonNode m_link;

// constructor
public PersonNode(int ID, String name)
{
    m_ID = ID;
    m_name = name;
    m_link = null;
}
// getters and setters
public void setID(int ID)
{
    m_ID = ID;
}
public int getID()
{
    return m_ID;
}
public String getName()
{
    return m_name;
}
public void setName(String name)
{
    m_name = name;
}
public void setLink(PersonNode link)
{
    m_link = link;
}
public PersonNode getLink()
{
    return m_link;
}
}

here is my method class, constructor and instance variable.  The method I don't know how to do is the contains method.
I edited this Class and I am still having so much trouble with this any help would be greatly appreciated.
public class SortedPersonList
 {   // instance variables
private PersonNode m_first;
private int m_numElements;

// constructor
// Do not make any changes to this method!
public SortedPersonList()
{
    m_first = null;
    m_numElements = 0;
}

// check whether the list is empty
// Do not make any changes to this method!
boolean isEmpty()
{
    if (m_first == null)
        return true;
    else
        return false;
}

// return the size of the list (# of Person nodes)
// Do not make any changes to this method!
public int size()
{
    return m_numElements;
}

// check whether a PersonNode associated with the given ID is in the list
public boolean contains(int ID)
{This Method I need help with!!
}
// search for and return the PersonNode associated with the given ID
public PersonNode get(int ID)
{  PersonNode current=m_first;
  while(current!=null)
   {if (current.getID()==ID)
       return current;
   }
   return null;
}

// add a new PersonNode to the list with the given ID and name
public boolean add(int ID, String name)
{ PersonNode newNode=new PersonNode(ID,name);
  PersonNode previous=null;
    if (m_first == null)
  { // add element to an empty list
   m_first = newNode;
   m_first.setLink(previous);
    m_numElements++;}
   else
   {if (newNode.getID()<m_first.getID())
   {previous=m_first;
   m_first=newNode;
   m_first.setLink(previous);
   m_numElements++;
   }
   else
  { m_first.setLink(newNode);
    newNode.setLink(previous);
   m_numElements++;}}

    return true; // replace this statement with your own return
}

// remove a PersonNode associated with the given ID from the list
public boolean remove(int ID)
{PersonNode remove = get(ID);
while(remove.getID()==ID)
{m_first=null;
m_first.setLink(remove.getLink());}
 m_numElements --;
return true;}

public String toString()
{
    String listContent = "";
    PersonNode current = m_first;

    while (current != null)
    {
        listContent += "[" + current.getID() + " | " + current.getName() + "] ";
        current = current.getLink();
    }

    return listContent;
}

}
If it helps the goal is to fix the add, contains, remove and get methods to implement a sorted linked list.
Answer: Let's assume you have a List<PersonNode> lst. You want to check if a PersonNode with id = ID is in this list lst. You can do that rather easily by just iterating over the list:
public boolean contains(int ID) {
    for (PersonNode node : lst) {
        if (node.getID() == ID)
            return true; // node found, we can finish iterating
    }
    return false; // no node with id = ID was found
}

Take note that as of this moment you don't have a list in your SortedPersonList class. You probably want to have one as an instance variable.
Alternatively, if you decide that what you wanted to implement is an equivalent of a LinkedList, then you can do the same iteration just without foreach and instead advance with node.getNext()...
Comment: That is where I am kind of confused.  I am not allowed to use a list and a getNext() method is unavailable as well. The test class initiates a   SortedPersonList myList = new SortedPersonList();
Comment: @Jennifer then it is impossible. Inquiry into it with your professor as to how he expects you to accomplish this (or other classmates)
Comment: You probably misunderstood the assignment, since there is no point in even having a `contains` method when the object isn't or doesn't contain a list, do you understand?

java sorted node list example


How many rats does it take to get to the center of a corpse-pop?

Question: I'm starting a ghost/non-lethal run of Dishonored and I know I need to avoid rats eating my victims. I've noticed that single rats do not appear to go after corpses, but big swarms definitely do. So how many rats is enough to start eating corpses? I've noticed they only seem to eat corpses in "swarms" that will also attack the player.
But leaving a single or just a couple rats alive around bodies is okay...right? from further experience it appears that, rarely, randomly spawned rats may be enough to kill unconscious people! I found four rats in the general area of a dead guy, however I'm not 100% sure the rats killed him, as his corpse wasn't eaten to the bone, and I didn't see the rats attack him. It'd be extra useful to know whether or not randomly spawned rats will spawn in great enough numbers to kill an unconscious person.
Comment: I've never made it without Blinking...
Comment: I always elevate the bodies, just to be sure.
Comment: I think it's something around 8, but I've uninstalled the game a while ago, so I can't check. You could probably test it fairly easily with some save scumming by tossing an unconscious guard at a pack of rats, taking note of their number, then reloading, killing half the rats, and tossing the guard in again. Repeat until you find X.
Keep in mind that unconscious characters die if they fall a certain distance or touch water. A couple of rats is usually not a problem, and I haven't seen small groups spontaneously grow into an aggressive swarm.
Comment: Hm, I left someone in a bush and found them dead (but not chewed to bits) with 4 rats nearby later. I'm unsure if the rats actually killed him though.
Comment: Yeah, but the rats also random spawn, i stunned a guy on the floor and i walked the wrong way. Out of no where some rats spawned so i had to go run faster then them pick up the guy and dump him in a dumpster.
Comment: @Lyrion they're randomly spawned? That's good to know
Comment: @Pvt.Grichmann good idea. I've been killing all the rat swarms I see so I hadn't even thought of that
Answer: The number of rats is irrelevant. All you need to make sure is that the body cannot be eaten. In that regard, Steve V. is right, the best practice is to elevate the body or put it in a garbage, ... You get the idea.
Be careful though, as you can easily kill someone without paying attention. I already kill a man just by trying to drop the body on the ground. His head knock the wall and he was dead. Or the best: I failed a blink and fallen on a guy I just dropped on the ground a little earlier. Apparently it was from too high because he died... So frustrating.
Anyway, just remember, don't care about the number of rats, just pay attention to where you drop the body: if they cannot touch the body, they'll never eat it.
Good luck for your achievements, I know how good it felt when I got mine ;)


Program don't work correctly when object is changed to object pointer

Question: I use example of mDNSResolver library to resolve a local Host name to IP address as following :
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <mDNSResolver.h>

#define WIFI_AP         "myap"
#define WIFI_PASS       "mypass"
#define NAME_TO_RESOLVE "myhost.local"

using namespace mDNSResolver;

WiFiClient wifiClient;
WiFiUDP udp;
Resolver resolver(udp);

void setup() {
  Serial.begin(115200);
  int WiFiCounter = 0;
  // We start by connecting to a WiFi network
  Serial.println("Connecting to ");
  Serial.println(WIFI_AP);

  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_AP, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED && WiFiCounter < 30) {
    delay(1000);
    WiFiCounter++;
    Serial.print(".");
  }

  Serial.print("Resolving ");
  Serial.println(NAME_TO_RESOLVE);

  resolver.setLocalIP(WiFi.localIP());

  IPAddress ip = resolver.search(NAME_TO_RESOLVE);
  if(ip != INADDR_NONE) {
    Serial.print("Resolved: ");
    Serial.println(ip);
  } else {
    Serial.println("Not resolved");
  }
}

void loop() {
  // Required to clear the UDP buffer, as we can't unjoin a multicast group yet
  resolver.loop();
}

It work as i expect i.e the IP is resolved successfully and printed on serial console as :

Resolved: [RESOLVED IP ADDRESS, FOR EXAMPLE:] 192.168.1.33

But when i change resolver object to a pointer as following :
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <mDNSResolver.h>
#include <WiFiClient.h>

#define WIFI_AP "myap"
#define WIFI_PASS "mypass"
#define NAME_TO_RESOLVE "myhost.local"

using namespace mDNSResolver;

WiFiClient wifiClient;
WiFiUDP udp;
Resolver *resolver;

void setup()
{
  Serial.begin(115200);
  int WiFiCounter = 0;

  // We start by connecting to a WiFi network
  Serial.println("Connecting to ");
  Serial.println(WIFI_AP);

  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_AP, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED && WiFiCounter < 30)
  {
    delay(1000);
    WiFiCounter++;
    Serial.print(".");
  }

  resolver = new Resolver(udp);
  resolver->setLocalIP(WiFi.localIP());
  IPAddress ip = resolver->search(NAME_TO_RESOLVE);
  if (ip != INADDR_NONE)
  {
    Serial.print("Resolved: ");
    Serial.println(ip);
  }
  else
  {
    Serial.println("Not resolved");
  }

}

void loop()
{
  // Required to clear the UDP buffer, as we can't unjoin a multicast group yet
  resolver->loop();

}

The program can't resolve any local host name anymore and following statement will print on serial console :

Not resolved

The if... else... statement in setup() function determine either IP is resolved successfully or no :
  if (ip != INADDR_NONE)
  {
    Serial.print("Resolved: ");
    Serial.println(ip);
  }
  else
  {
    Serial.println("Not resolved");
  }

Did i use object pointer correctly? If no, how must i fix that?
Comment: Please remove the "C++: " from the title, that's what tags are for. Further, you're doing some serial communication there, too, is that relevant? Also, read [ask]. In particular, you don't describe the error you get at all, just "don't work" is not a description. BTW: When and how do you call `loop()`? It looks unused...
Comment: @Ulrich Arduino development environment is C++ with a few training wheels. There's an assumed call to `setup()` and a periodic call to `loop()` in particular, with no direct access to `main` - so Arduino programming ends up with a lot of global variables. It's not inherently bad, because these programs aren't supposed to be very large anyway, so globals are little more grokable.
Comment: Can you please show the exact, specific, copy-and-pasted code that you have successfully run with the expected result? Right now, all I know is that the code you have shown doesn't work, I don't know what "doesn't work" means, and I don't know what the code that worked does look like. Also specify what "working" means. That means describe the specific observable output that you expect versus what you see.
Comment: @JohnFilleau I edit my post for you
Answer: Call resolver = new Resolver(udp); before setup():
WiFiClient wifiClient;
WiFiUDP udp;
Resolver *resolver = new Resolver(udp);

Edit1:
For some reason, some boards must to be configured globally, and even if you pass a pointer to the object created it does not work. This is a behavior that is under discussion yet, as you can see in this post:
Class Instantiation only works globally but not in set up
So that is why I suggesting to declare and instantiate it globally.
Comment: Maybe add some more context as to why that would help?
Comment: I change it but my problem is not resolved.
Comment: Sorry, I write the suggestion when I was in a hurry. The motivation of the suggestion was added in the Edit1.


Is there a way to change the directory to which the Android Asset Studio saves resources?

Question: Every time I use the Android Asset Studio to add a new vector drawable to my localized app, the drawable gets saved to the res-localizable/drawable folder and I need to go in there and manually change it to res/drawable.
It's a pain to always have to remember to change it. Is there a way I could change the default directory?
I tried adding source sets to my build.gradle with no luck
<code>sourceSets {
    main {
        res.srcDir(file("src/main/res"))
        resources.srcDir(file("src/main/res"))
        assets.srcDir(file("src/main/res"))
    }
}
</code>
Answer: So after updating to Electric Eel and deleting the jre folder, now I can see the option of saving to both my res and res-localizable folder in the Asset Studio Source Set input.


Node.js - Download .docx file exported as html from onedrive using microsoftgraph api call

Question: When making a call like this example from here
<code>client
    .api('/me/drive/root/children/Doc.docx/content')
    .getStream((err, downloadStream) => {
        let writeStream = fs.createWriteStream('Mydoc.docx');
        downloadStream.pipe(writeStream).on('error', console.log);
    });
</code>
It works as expected. What I want is to get the .docx file as html. Is there any way to download it in html format? Or do I have to save the file and then try to export it to html. Thanks
Answer: Word Documents (.docx) do not use HTML, they use Office Open XML (OOXML). Technically they are a zipped package that contains several elements along with the raw OOXML of the document.
OneDrive itself does not provide any document conversion tools, it is just the cloud storage the document is stored in.
In order to convert a document from one format to another (OOXML to HTML for example), you'll need to use a 3rd party tool or service for that purpose. I'd suggest taking a look as Aspose. They offer a slew of file format conversion tools including one for Word. I've had a number of developers report good results using their Aspose Cloud services as well.
Comment: Thank you for the clarification! I do not think that I can follow this suggestion but it gives me a really good start.
Answer: You can add the query parameter format=html to download in html format but supposedly you have to use the beta endpoint.


Should we discourage divulging the mechanics of Neuropsychological tests here?

Question: I am trying to model the Wisconsin Card Sorting Test, which is why I've asked many questions on this site in regards to that topic.
One of my questions is in regards to the rules of the test. According to this Wikipedia talk page, divulging rules and methodologies of psychological tests undermines the reliability of neuropsychological tests.
What is the opinion of this site on the matter?
Answer: I would say that given the pervasiveness of research on the WCST in academic papers and textbooks, we are not in danger of revealing any information that isn't available to an potential examinee at the public library.  That said, a question along the lines of "How do I cheat the WCST?" outlining how to get around the test would probably need to be culled.  It's really up to those posting questions on the site to police themselves, as I don't think a formal policy would be very effective, and might smother good discussions about the cognitive characteristics that are being tested.
I understand the point that the neuropsychologists are making on the Wikipedia Talk page, which amounts to the idea that people knowing the scoring system can undermine the test.  Parenthetically, I think they are overestimating the damage this could cause.  In research, where this foreknowledge of the exam would be most damaging, an experienced investigator would be screening subjects anyway, and in the clinic, there are a battery of other tests and signs that are available to confirm the results of the WCST.
So, in summary, being judicious about what you elect to disclose is probably the best approach.  Stack Exchange is a medium for the exchange of knowledge and ideas, so completely censoring talk about what is a critical part of neuropsychological research would be counterproductive.
Comment: @JoshGitlin That depends whether you're coming at it from a research or clinical perspective. For research purposes, such tests are obviously a last-resort option for multiple reasons, but for clinical purposes, whatever gets the job done has real value that we should avoid diminishing by posting test items. Discussing the tests and their methods more generally is always acceptable, of course.
Comment: I think as long as we're not disclosing the actual items or materials of a test, there's no real problem.
Comment: I also wonder how much a test is flawed if knowing how it works makes it ineffective. But that's a separate question :-)
Comment: Very true, @josh


Finding A Max Number Out Of Three

Question:
Q: Implement a function that takes as input three variables, and
  returns the largest of the three. Do this without using the Python
  max() function!

I Was Working On This Problem And I Almost Finished This But I Am Encountering A Very Silly Problem Of How To Call This Function:
def findingmax(a, b, c):
    if (a > b) and (a > c):
        print(f"Max Number Is: {a}")
    elif (b > a) and (b > c):
        print(f"Max Number Is: {b}")
    elif (c > a) and (c > b):
        print(f"Max Number Is: {c}")
    else:
        pass

Numbers = input("Enter Three Numbers: ")
print(findingmax(Numbers)

Comment: looks like you're missing a parenthesis
Comment: Does this answer your question? [How to input 2 integers in one line in Python?](https://stackoverflow.com/questions/23253863/how-to-input-2-integers-in-one-line-in-python)
Comment: Does this answer your question? [3 values (numbers) in 1 input separation. Python 3](https://stackoverflow.com/questions/18808307/3-values-numbers-in-1-input-separation-python-3)
Comment: https://stackoverflow.com/questions/23253863/how-to-input-2-integers-in-one-line-in-python ; https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers Have you done any research?
Answer: Your input is a string so you can do something like this:
n1 = int(input("Enter the first number"))
n2 = int(input("Enter the second number"))
n3 = int(input("Enter the third number"))

print(findingmax(n1, n2 n3))

Answer: Here's a fancy way:
Numbers = map(int, input("Enter Three Numbers: ").split())
print(findingmax(*Numbers))

This lets you enter 3 numbers on one line, splits them, and converts them to a integers. *Numbers splits them up so you can use them as arguments.
Additionally, your function will not return anything if 2 of the numbers are tied for the maximum, and you also said that you wanted to return the largest one, which is different from printing the largest one.  Here's an updated version of findingmax() which returns the max rather than printing it, and will work correctly in the case of a tie:
def findingmax(a, b, c):
    if (a > b) and (a > c):
        return a
    elif b > c: #if reached this point, b or c must be >= a
        return b
    else:
        return c

Answer: So here you can use this code for simple max finder program.
You have to change the input style like the following so you can take input in multiple variables at a time, .split() function is used to differentiate the characters by space and split them and input function insert that value accordingly.
The format() method formats the specified value(s) and insert them inside the string's placeholder ({}).
def findingmax(a, b, c):
    if (a > b) and (a > c):
        print("Max Number Is:{}".format(a))
    elif (b > a) and (b > c):
        print("Max Number Is: {}".format(b))
    elif (c > a) and (c > b):
        print("`enter code here`Max Number Is: {}".format(c))
    else:
        pass

a, b,c = input("Enter a 3 value: ").split()
a=int(a)
b=int(b)
c=int(c)
print(findingmax(a,b,c))

Finding A Max Number Out Of Three


how to expand onclick

Question: here's my html code:
echo "
";
echo '<video controls><source src="stuff/' . $entry . '"></video>';
echo "
";

here's my js code:

i want to go back to the original attributes. But i already tried everything. Should i use divs?
Comment: what are you trying to do ? can you take an example ?
Comment: a) Your PHP code is irrelevant to the question. Post the rendered output. b) if you're using jQuery please update the tags.
Comment: Your question is rather vague and lacking any constructive syntax to work with. Please reform. Also look into jQuery `.slideDown()` or `.animate()` functions.
Comment: If you want to go back to the original attributes you need to store them at the start. Then set it back to them with `.attr()`.
Answer: Expansion is a transitional event. Do you mean changing the width/height?
Here are expansion methods. As I had mention, check out jQuery's .slideDown() feature. Is this what you were looking for?
Simply replace the code for the .videocontainer with a video frame.

$(document).ready(function(){

  $(function(){

    var videos = $('.video'),
        state = false;

    videos.each(function(){

      var videocon = $(this),
          btn = videocon.find('.expandvideo'),
          video = videocon.find('.videocontainer');

      btn.on('click', function() {

        if ( state == false ) {

          video.slideDown('fast', function() { state = true; btn.html('Close Video'); });

        } else {

          video.slideUp('fast', function() { state = false; btn.html('Show Video'); });

        }

      });

    });

  });

});
.videocontainer {
  display: none;
  width: 500px;
  height: 380px;
  background-color:gray;
}

.expandvideo {
  cursor: pointer;
  color: blue;
}

.expandvideo:hover {
  color: red;
}

  Show Video

Also to expand the frame look into jQuery's .animate() function.

$(document).ready(function(){

  $(function(){

    var videos = $('.video'),
        state = false;

    videos.each(function(){

      var videocon = $(this),
          btn = videocon.find('.expandvideo'),
          video = videocon.find('.videocontainer');

      btn.on('click', function() {

        if ( state == false ) {

            video.animate({width: '500px', height: '500px'}, 'fast', function() { state = true; btn.html('Close Video'); });

        } else {

          video.animate({width: '100px', height: '80px'}, 'fast', function() { state = false; btn.html('Show Video'); });

        }

      });

    });

  });

});
.videocontainer {
  width: 100px;
  height: 80px;
  background-color:gray;
}

.expandvideo {
  cursor: pointer;
  color: blue;
}

.expandvideo:hover {
  color: red;
}

  Show Video

Comment: thanks for your answer. im trying to do the same thing that 4chan does, just find a thread with embed webms and you will understand my question.
Answer: I'm not sure exactly what you are trying to achieve, as your description seems rather vague... If you are wanting a video to be displayed on the click of another element...
echo '
';
echo '<video controls><source src="stuff/' . $entry . '"></video>';
echo '
';
echo 'Show Video';

If that is not what you are trying to do, then please more descriptive and I'll try to help the best I can.
Answer: Your question is hard to understand, but based on your js code, maybe is this what you want

how to expand onclick


Netty Websocket SSL client not working after a successful handshake

Question: I want to create a secure websocket client-server communication using Netty framework. I looked at the netty examples and there is an example with websocket ssl server: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/http/websocketx/sslserver
and there is also another example with websocket client, but without ssl: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/http/websocketx/client
So I've put the SslHandler as the first hander in the ChannelPipelinehandle as suggested here: How can use netty websocket client with wss?
But it still does not work. Client successfully connects to server (handshake succeeds), but then when client sends a message to server (for example PingWebSocketFrame or any other WebSocketFrame) nothing happens. Server does not receive any message.
Do you have an idea what might be wrong?
EDIT: I use 4.0.0.CR5 and to be exact, server always receives something, but only first SSLHandler. Next handler in the pipeline (HttpRequestDecoder) then receives a message only sometimes, and when it does, it creates DefaultHttpRequest with this failure:
decodeResult: failure(java.lang.IllegalArgumentException: invalid version format: |LZSᄎ
Those weird characters should probably represent an HTTP version, but it looks like SSLHandler did not decode them correctly?
Answer: I had the same issue (you can see the stackoverflow post here).
The sample code on the client uses the channel.write() method, which seems not to forward the messages to the Websocket ssl server. By using the channel.writeAndFlush() instead, messages are correctly sent to the server.
All these were tested using the netty 4.0.9.Final version


PHP is_writable() to check if file can be written?

Question: I've read that I can use is_writable() to check if a folder or a file is writable.
How do I check if a file can be written to a folder?

Do I check the folder and if the folder is writable? Then the file is allowed to be put into that folder?
What if the file has been written to the folder, how do I check if that is writable again (edited)? Do I need to? If so, do I check the file instead of the folder?
Is it a safe method (correct) to do it?
Comment: Did you read the official [documentation](http://php.net/manual/en/function.is-writable.php) by any chance?
Answer: The PHP function is_writable is exactly for this purpose. If you want to check if file is still writable after you've written the file, you can use the same function.
Answer: Read the documentation as linked in the question you pointed to. is_writable() is working on files and directories.
But mind: If you have code like this:
if (is_writeable("foo.txt")) {
    $fp = fopen("foo.txt", "w");
    /* ...*/
}

This might still fail. For instance there might be a lock or a race condition (permissions change between the two commands). Better simply try to open and then handle the error.
$fp = @fopen("foo.txt", "w");
if (!$fp) {
    report_error_in_some_way();
}

Comment: Mh, PHP4 File functions.
Comment: Using the @ operator is asking for trouble.. imagine your report_error_in_some_way() function is broken, you'll have a very hard time finding the real issue. Never ever use the @ operator.


Is using an entire banner as a link bad usability?

Question: I am working on a eCommerce site which has a large hero banner space which scrolls through a number of 865 X 450 px banners. Each of these banners is linked to a specific offer in the site.  When I initially planned the design, my plan was to have a call to action button in each banner which would be the link to the offer.
But due to technical restrictions we found that the only way we can have a linked call to action button on each banner was by hard coding an image map which would not work well if the image banner was changed as the button position would be fixed and the relative context of the button would be lost with regards to the text. The option of creating a new image map is also out of the question since the site is going to be handed over to a client who has no idea about the technical details of the implementation
So the only alternative option seems to be directly link each banner image to the offer.
I was just wondering if this is bad usability since the user could accidentally click on a large scrolling banner and suddenly find himself transported to a section of the site without understanding how he got there.

download bmml source – Wireframes created with Balsamiq Mockups
Comment: If I read you correctly, it seems that considering your technical limitations your options are either this method or no link at all. Is that right?
Comment: pretty much but I am just trying to weigh the possibility of how much it must frustrate users
Answer: No, it's the other way around. As your having a carousel, there is a  timing issue to address. The carousel switches images and users have to quickly click on the banner to get to the offer currently visible, before it swiches again.

According to Fitts's Law, illustrated above, the time it takes a user to click an area is a function of distance and target area. If you have a large target area - the less time it takes a user to click the banner link.
The issue with the mock-button is solved by applying the same style of the carousel images as the rest of your site design. That way the carousel images doesn't look like adds, but part of your site.
Problem solved, tecnically and form a User Experience view.
Comment: I agree with your answer. However, there is one caveat. If the "banner" is designed to look like an interactive form with "mock" buttons and other interactive elements, making the whole banner clickable can be a problem. I'm thinking of obnoxious banner ads that invite people to interact when, in reality, they're just baiting clicks. I haven't met a user yet that actually likes being deceived like that.
Comment: @mawcsco True! But lose the mock-button and let your banner have the same style as the rest of your site. It'll work fine. We have that at our company... take a look at http://www.fishbonesystems.com/
Answer: I don't think it's a bad idea.
Having entire banners clickable is quite common and some users even expect it. Consider graphical ad banners (like those on Google AdSense). Even if they have a call to action button, the entire banner is always clickable.
Also, I don't think that on a desktop computer, users really accidentally click. Clicking your mouse button requires effort. Since you're designing a site, your main target audience is probably desktop browsers. Accidental "clicking" makes more sense on mobile touch devices. I can see a user accidentally tapping the screen though, especially when scrolling your content. Mobile devices usually handle this by showing a short animation prior to changing content. For example, slide the new content from the side (iPhone navigation), or highlight the entire link prior to acting upon it. If the transition is animated, it helps the user understand that his interaction is what caused the content to change. It may still be accidental, but at least the user understands and can click "back".
An animated transition can be a pretty nice idea anyways. Consider darkening the entire banner just a little bit (a simple brightness filter / showing a semi-transparent black overlay) either when the mouse hovers over the banner, or when the click was made. This will be a pretty good indication that the banner is interactive.
Also, on desktop browsers don't forget that the cursor changes when hovering over clickable areas. This can be stated by CSS if it doesn't happen by default (cursor: hand;). This also makes it pretty clear..
Answer: Using the entire banner as a link is a good choice. It provides a larger target size and supports users who assume entire images are hyperlinks (I have seen this behaviour in testing). Accidental clicks are not much of an issue (they are hard to do), and so long as you don't break the back button by opening a lightbox or a page in a new window, you'll be fine.


How to setup and access session of Shopify using SQLite?

Question: Is this the correct way to setup a shop with SQLiteSessionStorage?
const storage = new SQLiteSessionStorage(DB_PATH)
const shopify = shopifyApp({
  api: {
    apiVersion: LATEST_API_VERSION,
    restResources,
    billing: undefined, // or replace with billingConfig above to enable example billing
    scopes: ['write_products', 'read_locales'],
  },
  auth: {
    path: '/api/auth',
    callbackPath: '/api/auth/callback',
  },
  webhooks: {
    path: '/api/webhooks',
  },
  sessionStorage: storage,

});
export default shopify;

If so, how can I access this session from anywhere in my app?
Answer: E.g. like this:
shopify.js (assuming you use the shopifyApp and SQLite as db):
import { shopifyApp } from "@shopify/shopify-app-express";
import { SQLiteSessionStorage } from "@shopify/shopify-app-session-storage-sqlite";

const dbFile = join(process.cwd(), "database.sqlite");
const sessionDb = new SQLiteSessionStorage(dbFile);

const shopify = shopifyApp({
    [...]
    sessionStorage: sessionDb,
});

folder/your.function.js:
import shopify from "../shopify.js";

const sessionId = await shopify.api.session.getOfflineId('myshop.shopify.com');
const session = await shopify.config.sessionStorage.loadSession(sessionId);
const restClient = new shopify.api.clients.Rest({ session });

Comment: This only get the session id, but how to get the actual session from the storage?
Comment: @SamTest, pardon, my bad, updated the answer


list starts loading from the beginning after screen rotation

Question: In my fragment I have list. This list is is constantly filling. But after screen rotation list starts loading from the beginning. And the data that was in the vertical orientation is lost because in the horizontal orientation the list starts to load again. So, I added all what I could read in the internet:
in my Manifest file:
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"

in Activity class:
if (savedInstanceState == null) {
            firstFragment = FirstFragment()
            supportFragmentManager
                .beginTransaction()
                .add(R.id.frameLayout, firstFragment!!, "firstFragment")
                .commit()
        } else {
            firstFragment = supportFragmentManager
                .findFragmentByTag("firstFragment") as? FirstFragment
        }

but it did not help.
Comment: try using [viewModel](https://developer.android.com/topic/libraries/architecture/viewmodel?gclid=Cj0KCQiA9P__BRC0ARIsAEZ6irhs9OW0Lxva5YiFU6wPMQxRbBikflfYtrHL0cdA_ppD6FobQOb1ohQaAnQ4EALw_wcB&gclsrc=aw.ds)
Comment: yes, I know that this can fix the problem. But I need do it without `ViewModel`
Answer: Please set setRetainInstance(true); in fragment code.
It will prevent recreating fragment instance.
Comment: [`setRetainInstance()`](https://developer.android.com/reference/android/app/Fragment#setRetainInstance(boolean)) is deprecated now .. Although this will solve the problem now, in the future this won't work any more .. you should rely on `ViewModels` instead


Custom ListView Items are not clickable

Question: I am working on an application which contains Custom ListView on its main activity. It was working fine but the day before yesterday, list view items are suddenly become non-clickable. I've searched a lot, but no answer solved my this issue. It is strange. Normal list view is working good, but custom isn't. What may be the problem?
Edit: Custom List View is as normal as it is, nothing odd. I am giving here CustomAdapter class.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null){
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.custom_list, null);
    }
    ClassDetailPedia detailPedia = personDetail.get(position);

    if(detailPedia !=null){
        TextView txtPersonName = (TextView) convertView.findViewById(R.id.txtPersonName);
        TextView txtReason = (TextView) convertView.findViewById(R.id.txtReason);
        TextView txtTags = (TextView) convertView.findViewById(R.id.txtTags);
        TextView txtDate = (TextView) convertView.findViewById(R.id.txtDate);
        ImageView imgPerson = (ImageView) convertView.findViewById(R.id.imgPerson);

        txtPersonName.setText(detailPedia.getTitle());
        txtReason.setText("Description: " + detailPedia.getDescription());
        txtTags.setText("Tags: " + detailPedia.getTags());
        txtDate.setText(GetFormattedDate(detailPedia.getDated()));

        if(detailPedia.getImage() != null) {
            imgPerson.setImageURI(detailPedia.getImage());
            imgPerson.setScaleType(ImageView.ScaleType.CENTER);
        }
    }
    return convertView;
}

and it extends ArrayAdapter<ClassDetailPedia>
And here I am setting CustomAdapter
ListView lstPersons = (ListView) findViewById(R.id.lstDetail);
lstPersons.setAdapter(new CustomAdapter(getApplicationContext(), R.layout.custom_list, pediaList));

custom_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_list"
android:gravity="center">
<ImageButton
    android:layout_width="80dp"
    android:layout_height="60dp"
    android:src="@drawable/empty_picture"
    android:id="@+id/imgPerson"
    android:scaleType="centerCrop" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginTop="2dp">

    <TextView
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Friday, April 1, 2016 @ 8:30pm"
        android:id="@+id/txtDate"
        android:textStyle="italic"
        android:textSize="12sp"
        android:layout_below="@+id/txtTags"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginTop="3dp"
        android:layout_marginRight="3dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:text="Mr. Bill Gates"
        android:id="@+id/txtPersonName"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginStart="3dp"
        android:singleLine="true"
        android:textSize="17sp"
        android:layout_marginBottom="3dp"
        android:textStyle="bold"/>

    <TextView
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reason: Marketing Strategy"
        android:id="@+id/txtReason"
        android:layout_below="@+id/txtPersonName"
        android:layout_alignParentStart="true"
        android:layout_marginStart="3dp"
        android:singleLine="true"
        android:layout_marginTop="-3dp"
        android:textSize="13sp"/>

    <TextView
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tags: business, start-up"
        android:id="@+id/txtTags"
        android:layout_below="@+id/txtReason"
        android:layout_alignParentStart="true"
        android:layout_marginStart="3dp"
        android:singleLine="true"
        android:textSize="13sp"/>
</RelativeLayout>
</LinearLayout>

Comment: Why use custom ListView and if necessary post source of custom ListView
Comment: I think it was not necessary, but may be it contains problem, so I've edited and posted the source. Using custom list view is the demand of application.
Answer: Try add android:descendantFocusability="blocksDescendants" for the root view of your custom list item (in your case it is LinearLayout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_list"
android:gravity="center"
android:descendantFocusability="blocksDescendants"
>
...
</LinearLayout>

Comment: I've done this, and it is working. But it doesn't look like it is clicked. Like, it is forced to perform click operation. That effect which android provide on clicking item is not being seen.
Answer: I made new Application, copied and pasted all the files and code and it's working fine. I don't know what caused the problem and why it is working perfectly know.

Custom ListView Items are not clickable


How to remove Twitter names from a string with regex

Question: I would like to remove all twitter nicknames (@xxx) from a string like this:
Hi @xxx and @yyy and @zzz.
I would like to get a string that will contain only (Hi and and).
Answer: PHP:
$text = preg_replace('/(\s+|^)@\S+/', '', $Text);

Perl:
$text =~ s/(\s+|^)@\S+//g;

Optionally you can use \w+ (word characters) instead of \S+ (non-whitespace characters).
Comment: Probably `\w+` is a better choice, otherwise you'll trim off trailing punctuation too!
Answer: Using PHP, you can use preg_replace function :
<?php
   $str = "Hi @xxx and @yyy and @zzz.";
   echo preg_replace('/@\w+/', '', $str);
?>

/@\w+/ will search for every at sign followed by a word.
For each name found, you just have to replace it by an empty string.
Comment: This will mess up any emails that the string may contain, you should make sure the @ isn't part of an email address.
Answer: Ruby version of the code:
/\A[^@]+\z/


Take user directly to the page where event date matches the current date (pagination)

Question: So i have the below function to get my posts, but i want user to go directly on a page where posts have date "today" thats not a event publish date but an date for when event is happening , like if i have events that have man_date field 2015-4-12 and today is 2015-4-12 i will see directly the page where that event is without taking those events on first page.
function get_table(){
                global $wpdb;
                $c_cid = $_REQUEST['cat'];
                if(isset($_REQUEST["page"])){
                    $page_number = filter_var($_REQUEST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
                    if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
                }else{
                    $page_number = 1; //if there's no page number, set it to 1
                }
                $item_per_page = 20;
                //get total number of records from database for pagination
                $get_total_row = $wpdb->get_results("SELECT wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) WHERE wp_term_taxonomy.taxonomy = 'tipo_manifestazione' AND wp_term_taxonomy.term_id = $c_cid AND wp_posts.post_status = 'publish' AND (wp_posts.vip = 'NULL' OR wp_posts.vip IS NULL) AND wp_posts.post_type = 'manifestazione' GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC");
                $get_total_rows = count($get_total_row);
                //break records into pages
                $total_pages = ceil($get_total_rows/$item_per_page);

                //get starting position to fetch the records
                $page_position = (($page_number-1) * $item_per_page);

                ?>

                                                <select id="months" name="months">
                                                  <option value="" selected>Seleziona Mese</option>
                                                  <option value="01">Gennaio</option>
                                                  <option value="02">Febbraio</option>
                                                  <option value="03">Marzo</option>
                                                  <option value="04">Aprile</option>
                                                  <option value="05">Maggio</option>
                                                  <option value="06">Giugno</option>
                                                  <option value="07">Luglio</option>
                                                  <option value="08">Agosto</option>
                                                  <option value="09">Settembre</option>
                                                  <option value="10">Ottobre</option>
                                                  <option value="11">Novembre</option>
                                                  <option value="12">Dicembre</option>
                                                </select>

                                                  <input type="text" name="location_search" id="location_search" placeholder="Luogo..."/>

                                                <?php echo paginate_function($item_per_page, $page_number, $get_total_rows, $total_pages); ?>

                                                Voto

                                                Data

                                                Manifestazione

                                                Località

                                                Percorso Lungo

                                                Info

                                              <?php
                                                   $query = "SELECT wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) WHERE wp_term_taxonomy.taxonomy = 'tipo_manifestazione' AND wp_term_taxonomy.term_id = $c_cid AND wp_posts.post_status = 'publish' AND (wp_posts.vip = 'NULL' OR wp_posts.vip IS NULL) AND wp_posts.post_type = 'manifestazione' GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC LIMIT $page_position, $item_per_page";

                                                      $posts = $wpdb->get_results($query);
                                                      foreach($posts as $post){
                                                        $permalink = get_permalink($post->ID);
                                                        $locations = $wpdb->get_results("SELECT * FROM wp_locations WHERE post_id = $post->ID");
                                                        $l = $locations[0];
                                                  ?>
                                              <article id="row_<?php echo $post->ID;?>" class="table_row">

                                                  <?php echo do_shortcode('[ratings id="'.$post->ID.'"]');?>

                                                  <?php echo date("d-m-Y", strtotime(get_field('m_f_data',$post->ID)));?>

                                                  <a href="<?php echo $permalink;?>"><?php echo $post->post_title;?>

                                                 <a href="<?php echo site_url();?>/geo/?location=<?php echo $l->luogo;?>"> <?php echo $l->luogo;?>

                                                  <?php echo get_field('m_f_percorso_lungo',$post->ID);?>

                                                  <a href="javascript:void(0);" onclick="show_info('div_<?php echo $post->ID;?>','row_<?php echo $post->ID;?>');" class="show_button">Info +

                                              <div id="div_<?php echo $post->ID;?>" class="div_content">
                                                <?php get_post_fields($post->ID);?>

                                                  <?php
                                                  }
                                                ?>

                <?php
                exit();
            }

function paginate_function($item_per_page, $current_page, $total_records, $total_pages)
    {
        $pagination = '';
        if($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages){ //verify total pages and current page number
            $pagination .= '
';

            $right_links    = $current_page + 3;
            $previous       = $current_page - 3; //previous link
            $next           = $current_page + 1; //next link
            $first_link     = true; //boolean var to decide our first link

            if($current_page > 1){
                $previous_link = ($previous==0)?1:$previous;
                $pagination .= '
«
'; //first link
                $pagination .= '
<
'; //previous link
                    for($i = ($current_page-2); $i < $current_page; $i++){ //Create left-hand side links
                        if($i > 0){
                            $pagination .= '
'.$i.'
';
                        }
                    }
                $first_link = false; //set first link to false
            }

            if($first_link){ //if current active page is first link
                $pagination .= '
'.$current_page.'
';
            }elseif($current_page == $total_pages){ //if it's the last active link
                $pagination .= '
'.$current_page.'
';
            }else{ //regular current link
                $pagination .= '
'.$current_page.'
';
            }

            for($i = $current_page+1; $i < $right_links ; $i++){ //create right-hand side links
                if($i<=$total_pages){
                    $pagination .= '
'.$i.'
';
                }
            }
            if($current_page < $total_pages){
                    $next_link = ($i > $total_pages)? $total_pages : $i;
                    $pagination .= '
>
'; //next link
                    $pagination .= '
»
'; //last link
            }

            $pagination .= '
';
        }
        return $pagination; //return pagination links
    }

ajax:
jQuery("#get_table").load(ajaxurl,{'action':'get_table','cat':cat,'page':page});

The code is working good , to get posts and also pagination working good , the only thing i'm unable to figure out , that how i can make this thing happen to take use directly on page where posts with current matching date are.
Answer: I figured this out by my self.
By using the below query i get the posts with current date and the dates that are passed.
$date = date("Y-m-d");
$posts_c = $wpdb->get_results("SELECT * FROM wp_posts WHERE wp_posts.man_date <= $date");

with above code i will get the rows and now let's convert them to a count
$get_count = count($posts_c);

Now what i did was divide the number of posts by number of posts per page which is  20
 $page_on = ceil($get_count / 20);

Thats it $page_on object contains the value of page where we will send our user.
Comment: Isn't this the answer I posted two days earlier?
Comment: Yes, sorry for that , don't know why i did posted that, btw changed the accepted answer and awarded you a bounty . :).
Answer: You have to check on the index of the item you want to display. You can do that using the same query you are using to count the total rows but excluding everything that is later then the selected date. Then you can find out the page you are suppose to be on by dividing the rows found by the page size.
Simple version would be (simplified code):
$page_size = 10;
$total_rows = count($db->query("SELECT * FROM events;"));
$past_present_rows = count($db->query("SELECT * FROM events WHERE date <= '2015-05-24';"));
$desired_page = ceil($past_present_rows / $page_size); // Use floor() if the first page is 0, ceil() is first page is 1.

So if we apply it to the code supplied:
function get_table(){
    global $wpdb;
    $c_cid = $_REQUEST['cat'];
    $item_per_page = 20;
    if(isset($_REQUEST["page"])){
        $page_number = filter_var($_REQUEST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
        if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
        }else{
            $get_past_row = $wpdb->get_results("SELECT wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) WHERE wp_term_taxonomy.taxonomy = 'tipo_manifestazione' AND wp_term_taxonomy.term_id = $c_cid AND wp_posts.post_status = 'publish' AND (wp_posts.vip = 'NULL' OR wp_posts.vip IS NULL) AND wp_posts.post_type = 'manifestazione' AND wp_post.man_date <= '2015-05-24' GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC");
            $get_past_rows = count($get_past_row);
            $page_number = ceil($get_past_rows / $item_per_page);
        }
        //get total number of records from database for pagination
        $get_total_row = $wpdb->get_results("SELECT wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id) WHERE wp_term_taxonomy.taxonomy = 'tipo_manifestazione' AND wp_term_taxonomy.term_id = $c_cid AND wp_posts.post_status = 'publish' AND (wp_posts.vip = 'NULL' OR wp_posts.vip IS NULL) AND wp_posts.post_type = 'manifestazione' GROUP BY wp_posts.ID ORDER BY wp_posts.ID DESC");
        ...


How should I replace 14/2 in wall with new 14/3?

Question: Im trying to wire some can lights. There is a switch box that goes to an existing can light to which I want to run some 14/3. The reason I want 14/3 is to keep the existing can light on a separate switch and the new ones on their own switches.
There is 14/2 running to the existing can light. I want to replace the old 14/2 with 14/3. Could I attach the new 14/3 to the old 14/2 and pull the 14/2 out, replacing it with 14/3? Would it work?
Comment: Not quite, @mmathis. This is about using existing wiring as a fish tape.
Comment: You can get wireless light switches for under fifty bucks each these days. Consider comparing the cost of wireless switches vs whatever you value your time at, painfully attempting to fish wires.
Comment: Possible duplicate of [Can I pull a new single conductor alongside an existing 14/2 wire for a fan+light install?](https://diy.stackexchange.com/questions/112849/can-i-pull-a-new-single-conductor-alongside-an-existing-14-2-wire-for-a-fanligh)
Answer: No. The original wiring was stapled many times to framing, and likely passes through one or more small holes in wall plates. You simply cannot pull it like a fish tape.
The best bet is usually to carefully remove the switch box by cutting the nails with a rotary tool, poke your new cable down from the attic, and install a new "old work" switch box.
Comment: I agree this is the best way to update the wiring. Some times if I can't get to the nails I break up the old box as they are usually plastic. Metal ones get left inside the wall. I have done this many times without damaging the sheetrock or existing wiring. No staple is required on the fished in cable inside the wall.
Comment: @Keith I think the point here is that the wiring to the light stays intact.  If you want to add new lights on a separate switch, there's no need to involve the wiring to the other can.  If I understand, you just need to run 14-2 from the new switch to the new lights.  It sounds like you will need to make holes.  Work like this is often best paired with a new coat of paint.  Some eggshell mug spray texture can be a real help too.
Comment: Do you just leave the old cable in place? Bring it in to the new box and wire nut each end?
Comment: No attic access. 1st floor. Only a cavity for access.
Comment: @Keith, we can't really offer more advice with what we (don't) know about your home. The original question was answered. If you have another one, go ahead and make a new post. Don't forget to upvote or accept any helpful answers.


How to repair shower p-trap

Question: The P-trap in our master shower has apparently broken. We were getting a sewer gas smell coming out of it when we used the guest shower so we had a plumber come out and have a look. He did a "smoke test" where they pump some smokey gas in through cleanout and see which P-traps it makes it through. Here is what the master shower looked like:

Kind of cool.
The house is almost 60 years old so it could be due to normal wear and tear. We've also had foundation problems which were corrected but I suppose that could have also contributed.
The plumber told me that fixing the broken P-trap involves removing the shower tiles (at least on the bottom, but I doubt we'd find matching tile so we'd probably have to replace it all), chipping up the foundation to expose the P-trap, replacing it, repouring the foundation, and retiling the shower. All that and more can be mine for the high high price of somewhere between $7,500 and $10,000.
Soooo that's kind of a lot of money. I guess my question is do I have any other cheaper options here? To be clear I'm not questioning whether or not that's a fair price. He's been a good plumber and I'm sure it's a reasonable price for the work. I'm mainly looking for other, inherently less expensive, means of addressing the issue.
Comment: Does the "master shower" get used often? In other words, is this just a simple case of the shower not being used frequently, allowing the water in the trap to evaporate, allowing gas to vent out that drain? If so, simply re-fill the trap periodically.
Comment: Pou a plug in the drain when you are not using it
Comment: I'm not a pro but why Wouldn't a pipe lining be a good alternative?
Answer: The procedure described is accurate.
My advice:
Hire your plumber (or a different plumber, if yours doesn't have the equipment) to inspect the drain with a camera to confirm that the trap is the only part of the drain that is damaged. You don't want to dig up the trap only to find later that there are additional issues and you don't want to do "exploratory surgery".
If you wanted custom candlesticks you would not hire a butcher or baker, you would hire a candlestick maker. Have a tile professional give you a bid on the job, for re-tiling and repairing (or replacing) the shower pan and tile, explain the reason and have him/her include excavation and replacement of the trap and drain assembly in the bid.
Done correctly you can just replace the floor and lower wall tiles (the "pan"); most folks choose a contrasting or complementary color and tile style and it looks ok. Be advised that this involves some waterproofing steps and it is not a simple job. Tile pros  are usually very competent with the plumbing associated with the shower; they know best how to set the trap and drain assembly to ensure that it is at the correct height for the finished tile surface. Have them include everything in the bid.
Alternatively, have your plumber give a bid on just repairing/replacing the trap with it already chipped out for him/her by the tile contractor. The plumber should work with the tile contractor to ensure the drain and stuff will be correct.
Note: prices for services are off topic here. Always hire through personal references, always hire reputable licensed contractors, always get multiple bids (it's ok to be honest and tell potential service providers that you are getting multiple bids).
P.S.- I live in So Cal and had my entire sewer main dug up and replaced (6' deep X 50' long) for $6,000...
Comment: Good advice. I concur. This is a job for two different tradespersons; a plumber and a tiler with expertise in shower construction. Get detailed quotes with labor scopes. To make it a cheaper job, you could do the demo of the tiled showerpan and underpayment yourself. It would shave off some of the cost.
Answer: Sure there's a less expensive option: excavate the trap yourself. This might be a sledgehammer or jackhammer, but you can bust the floor up yourself. You might save some money doing it too. Maybe.

The house is almost 60 years old

There's a decent chance this will be cast iron, then. You'll want to switch to PVC, but cutting cast iron will make the excavation seem easy. It's solid metal and heavy. Now you want to support the cast iron (I hope it's in better shape than the trap) while attaching PVC pipe with a rubber tension connector.
It's probably better to get a plumber to price the whole job, however. This is taxing work, and you don't want to have to re-excavate things.

How to repair shower p-trap


Errors running NPM commands after posting React app to github pages.

Question: Everything was working before deploying to github pages, and the first deploy worked no problem. But ever since, now when running any NPM commands in the project, I'm getting this set of errors:

geekcentric => npm start
npm ERR! file /mnt/c/Users/GeekCentric/Documents/ReactJS/the_app/package.json
npm ERR! code EJSONPARSE
npm ERR! JSON.parse Failed to parse json
npm ERR! JSON.parse Unexpected token / in JSON at position 611 while >parsing near '...": "^1.2.0"
npm ERR! JSON.parse   }
npm ERR! JSON.parse }
npm ERR! JSON.parse
npm ERR! JSON.parse
npm ERR! JSON.parse // geekcentric => np...'
npm ERR! JSON.parse Failed to parse package.json data.
npm ERR! JSON.parse package.json must be actual JSON, not just >JavaScript.
npm ERR! A complete log of this run can be found in:
npm ERR!     /home/geekcentric/.npm/_logs/2018-09-11T00_38_07_636Z->debug.log

The error is in my package.json file but I can't find anything that would throw the error or what's going wrong.

{

"name": "the_app",
"version": "0.1.0",
"private": true,
"homepage": "http://me.github.io/the_app", //added
"dependencies": {

"axios": "^0.18.0",
"firebase": "^5.4.2",
"react": "^16.4.2",

"react-dom": "^16.4.2",
"react-router-dom": "^4.3.1",
<code>"react-scripts": "1.1.5"
</code>

},
"scripts": {
<code>"start": "react-scripts start",

"build": "react-scripts build",

"test": "react-scripts test --env=jsdom",

"eject": "react-scripts eject",

"predeploy": "npm run build", //added

"deploy": "gh-pages -d build" //added
</code>
},
"devDependencies": {
      "gh-pages": "^1.2.0"
    }
  }

I'm using the create-react-app and the gh-pages npm module.
Any help would be very appreciated, thanks for taking the time to read.
Answer: I updated my text editor (VSCODE) and its working fine now. I use the built in terminal with WSL so I can only imagine I inadvertently screwed up a critical path. Still really curious to know what happened and why only after posting to gh-pages but the errors are gone and everything is running as you would expect.


How to authenticate a Windows Forms client using SAML?

Question: I have been looking into using an identity provider (IDP) to provide user authentication for a Windows Forms client. The user credentials will be hosted by Auth0. After creating a trial account with Auth0 I have downloaded a sample C# Windows Forms client application that can be used to authenticate to the Auth0 IDP using OpenID Connect ("OIDC"). The WinForms sample application pops up a web browser component, displays the Auth0 login screen, I login to the Auth0 IDP (having setup some test credentials in Auth0) and the WinForms application then is sent an authentication token. All well and good, and if I try to login a second time I no longer need to enter my credentials.
However... the company that I will be fetching authentication data from in production would like to use SAML. Is there any way to do this? Based on what I have read, SAML needs a "Service Provider" that will receive credentials from the IDP. The Service Provider is (typically?) a web site. That does not seem to match very well with what I am trying to do (authenticate a windows client). Is there any way of using SAML to do essentially what I have done using OIDC (fetch authentication information for a user from an IDP)? Would I need to develop a separate Service Provider component for this?
Answer: Sounds like what you've done so far is fine architecturally:

A modern desktop app following OIDC standards

This puts you in a good position architecturally, where:

Your app gets tokens from Auth0 using OIDC
Auth0 can reach out and do federated authentication with other standards based identity providers, which could be SAML, OIDC, WS-Federation or anything else
This can be done without changing any code in your app - and your app does not need to understand SAML

Feels like you need to set up a federated connection from Auth0 to the SAML Service Provider, and most commonly this involves these steps:

You give the partner your Entity Id and Response URL, to post tokens to
They give you am Entity Id, Public Key Certificate and request URL
You configure rules around account linking, so that users can be matched between their system and yours

There are prerequisites though, and the external identity provider needs to be SAML 2.0 compliant. My Federated Logins Article may help you to understand the general concepts, though I do not drill into SAML details here.
Comment: Thanks for the information.The question is asking basically how would I go about making our Windows application work with a SAML IDP. After learning more about the subject, it seems that this will be challenging because SAML is designed to work with web applications. So it seems I would need to implement some sort of a web SAML "proxy" (service provider). You are right that Auth0 itself can talk SAML.


Will Unity run well on my 9400GT?

Question: I'd like to ask whether Ubuntu will run better or worse with Unity on my NVidia GeForce 9400 GT.
Thank you.
Answer: Natty's Unity is build on top of Compiz, so, if desktop effects in the Desktop Edition work for you now, then Unity will run too. As long as your graphics card is supported (which your is), it will work very well.
Furthermore, your graphics card is more than fast enough to run Unity very smoothly.

Will Unity run well on my 9400GT?


Default gender, "Male" or "Female"

Question: Should our default gender when selecting male/female on the dropdown list be based on the local sex ratio (if a country have more female than male then female is the default value)?
Comment: So if someone forgets to enter their gender, you plan on recording it as whatever the default is?
Comment: Even sex isn't a simple Male/Female - at least allow a blank option for the few who don't fall into either
Comment: FYI you're asking for sex not gender, at least presumably gender is less relevant. Besides, sex ratio is usually almost exactly a 50% split with about 2% margin of error--I would never assume a default based on numbers, even ignoring the reasons others have stated below
Comment: Why do you need the gender? Is there a real, true, legitimate need for it? How about just leaving it out entirely?
Comment: IMHO, I'd first ask if this is even information that is really important to collect.
Comment: Or you could just add one more option of "I'd rather not share".
Comment: Building on what @JuliusA said, check out the ISO standard for the representation of human sexes: Not known, Male, Female and Not applicable.
https://en.wikipedia.org/wiki/ISO/IEC_5218
Comment: I will add two more options, "Unknown" and "Indeterminate"
Comment: Every time I come across a form with male / female / rather not say, it annoys me. It should be male / female / other / rather not say, at a minimum. I am happy to disclose my gender, if the form actually gives me an option to do so accurately.
Comment: Choose whatever produces the least number of clicks for the majority that are filling in the form.  If the site is directed for women then women.  Same for men.  If it is a 50/50 split, then provide a 'please fill in' option instead to not put anyone's nose out of joint.
Comment: It depends. What are you creating? How and where are you marketing it? The number of men or women in a country is not what makes the difference. For example, a website about makeup will probably have more female visitors than male, even if it's a city of mostly men. Also, it might be worth considering whether you need gender. Article about this: http://www.sarahmei.com/blog/2010/11/26/disalienation
Comment: Add another "why are you asking?" question. If you have a real need to know, then that need will *significantly* influence any answer I might give.  In particular, if you actually need to know, then you need to consider that gender is a lot more complex than the answers on offer here suggest.

If you *don't* have have a real need to know, then don't ask.

If you have to ask, have a look at this similar question:
http://ux.stackexchange.com/questions/19923/should-gender-be-required-or-is-there-a-better-way-to-collect-this-informatio?rq=1
Comment: @BenBrocka there are a number of countries with large skew's in the ratio due to selective abortions.
Comment: I always want to select "Alpha-Male", but those radio-buttons never let me...

@Ben Brocka: Don't assume a 50/50 ratio on each site. Depending on the topic you could get more than 90% of the one or other gender (tech/gadgets/cars vs. diet/cooking etc.)
Comment: @Darren you seem to be neglecting the cost of an error, which can be much more than a single click, and the probability of which is increased by your suggestion.  A plausible scenario is it's 60/40 women/men.  By your logic, the form should have "woman" checked, so that only 40% of people need to click to switch it. The problem is, each time a man mistakenly neglects to switch it, it's now wrong and the recipe for fixing it is likely *far* more complicated than a single click, if it can even be found or even exists at all.  For this reason, perhaps it's better to not have a default.
Comment: That said, it's sad if a site is directed for women more than men or vice versa.  I'd much rather not ask at all, and not be asked, as a user.
Comment: default: none. Users may want to avoid sharing this information anyway, so make the default and empty option.
Answer: You don't select a default at all
Using a drop down list or a radio group - you let the user decide - and this also prevents accidental submission of a form without the user setting this value (assuming it's gets validated) because there is no other way of validating it - only the user knows their gender so there is no right/wrong validation other than 'is it set'
Here are examples from Windows Live ID sign-up, Facebook sign-up, Yahoo sign-up

In fact in my own survey of over 100 high profile sign-up forms:
Only 20% of those sites asked the gender of which:

20 did not pre-select - by using one of the options above.
2 forms prefilled with the option 'Female' (bebo and foursquare)
0 forms prefilled with 'Male'

Furthermore - of the 20 that did not pre-select:

2 sites - TypePad and Etsy, gave options to not provide gender via a third option:

Grooveshark go the extra mile (although I'd at least expect consistency)

to try and make it clearer by using symbols on their sign up:

or in their 'edit profile' they use another version in which the wording has clearly been carefully considered and accounts for the gender/sex issue as to how the user identifies themselves:
Comment: Not sure that Grooveshark's symbols actually make anything *clearer*. (What if I want to log in as male but I'm not wearing a baseball cap???)
Comment: +1 for mentioning the "rather not say" option. This is a pretty sensitive subject. When Google+ launched, having a published sex was mandatory. This caused an enormous stir. Randall Munroe wrote [a comprehensive post](https://plus.google.com/111588569124648292310/posts/SeBqgN9Zoiu) on the subject.
Comment: "Rather not say" is a step in the right direction, but it still excludes "I'd like to say, but I'm neither!"
Comment: Check out the wording on the Grooveshark one. Remember that some people do find it difficult to answer these questions. Maybe you could edit your answer to include this example? http://imgur.com/odxmx
Comment: +1 Good answer, my thoughts exactly. Would be interesting to do some empirical testing to find out how many people would "forget" to change the gender (i.e. how many males are registered as female for bebo and foursquare).
Comment: TypePad and Etsy have the right idea: no default, and offer an option to rather not say. Depending on the audience, you may want to offer more choices.
Comment: @RogerAttrill - The one I got a screenshot of was from the "Edit Profile" section. I'm surprised they differ, really! But my point was the wording of "I identify as" includes people who's legal sex differs from their gender.
Comment: Got an external article you can link to where you provide more info about it all?
Comment: @ChrisMorgan Sorry, *wish* I could say yes but no not at the moment - not enough hours in the day!
Comment: @billynomates1 - thanks! I have added grooveshark - but using the current iconified version
Comment: @billynomates1 - ok I didn't realise there were going to be two different versions depending on the form!! Ive added that one as well because it does address some sensitive isues. Thank you.
Answer: How about asking the user to select their gender in the form of their preferred third-person pronoun ("his", "her", "their"), instead of providing their biological sex?
Listing "their" rather than "its", because I doubt anyone wants to be referred to as "it".  For example:
Which sentence sounds right?
[ ] <user> updated his profile.
[ ] <user> updated her profile.
[ ] <user> updated their profile.

Comment: +1. This looks rather odd at first, but "Which pronouns do you prefer?" is actually the **standard** way to ask questions about gender in spaces which are friendly to trans and genderqueer people.
Comment: this only works in some languages like English. You can't use this in some other languages
Comment: I feel this comes with the extra price of confusing every or almost every user. You have to stop and think what's being asked.
Comment: Similar to this, I've seen in a lot of sites where you choose how you prefer to be called: Mr/Mrs/Ms. Which can be adapted to other languages than english.
Comment: @Luciano, not really. I don't think many languages differentiate between Mrs and Ms.
Comment: @RuudLenders Portuguese does: Sra / Srta. Similar for Italian / Spanish, so possibly other languages as well. You don't need many more languages than those to cover good part of the world. But that's beside the point.
Comment: Forgot to mention the neutral pronouns, besides They/Them, some people prefer Ey/Em, Ze/Hir, Ze/Zir, Ze/Zem, etc.
Comment: The question is about what the default should be, not what the options should be. Although there are questions covering just that!
Answer: Unless you have a good reason to have the gender, I would agree with @Roger that not pre-selecting is the best option. I would also add that not validating at all, and allowing a selection of Male and Female is probably the best option.
The clientelle of the site is also important, and not always obvious. Females are far more common users of web sites - especially e-commerce - than are normally expected. Knowing your users is critical if you insist on setting a default - many of the sites I have worked on, female would be default.
Answer: In form fields like that, I usually make the first value null, to indicate no item was selected.
As far as order, I would either defer to the audience, then just go standard
M/F
For the drop down, make it optional, with the default value of null (so as to allow form submission without error)
Gender:
Select one  <null>
Male        <male>
Female      <female>

Answer: I believe you should not leave a default option if you want to get this information. Just use radio buttons, for example. And validate that the user has selected an option on submit.
Comment: Radio buttons should have a default selection. Point 9 http://www.nngroup.com/articles/checkboxes-vs-radio-buttons/
Comment: @rk Yes. This comment should be on most answers on this question, from the look of it.

Default gender, "Male" or "Female"


Can I tell if all tests passed under Perl's Test::More?

Question: I have a Perl test script written using Test::More.  Right before exiting, and if all tests passed, I'd like to perform some cleanup actions.  If any tests failed, I want to leave everything in place for troubleshooting.
Is there a flag within Test::More, or some other best practice within a single test script, to tell if "all is well" once the tests themselves are complete?
Answer: You can access the current status of the tests with Test::Builder, available via Test::More->builder:
use strict;
use warnings;
use Test::More tests => 1;

ok(int rand 2, 'this test randomly passes or fails');

if (Test::More->builder->is_passing)
{
    print "hooray!\n";
}
else
{
    print "aw... :(\n";
}

Alternatively, you can just do your cleanup at the end of the script, but exit early if things go awry, with Test::More's BAIL_OUT("reason why you are bailing");.
There's lots of other data and statistics you can gather about the state of your tests; see the documentation for Test::Builder.
Comment: Test::Builder->is_passing() was added in version 0.89_01, see the CHANGES file: http://cpansearch.perl.org/src/MSCHWERN/Test-Simple-0.94/Changes
Comment: I've got Can't locate object method "is_passing" via package "Test::Builder" at ./put.pl line 9.
with Perl v5.8.4 with 31 registered patches (on Solaris 10) :o(
Comment: I got this too with Test::More version 0.8, but had better luck with Test::More version 0.93 .
Answer: Here is what I came up to in order to avoid the "Can't locate object method" error shown at the bottom of this answer :
#! /usr/bin/perl

use strict;
use warnings;
use Test::More tests => 1;

ok(int rand 2, 'this test randomly passes or fails');

my $FAILcount = 0;
foreach my $detail (Test::Builder->details()) {
    if (${%$detail}{ok}==0) { $FAILcount++; }
}

if ($FAILcount == 0) {
    print "hooray!\n";
} else {
    print "aw... :(\n";
}

On Solaris 10, with Perl v5.8.4 (with 31 registered patches), I got the following
Can't locate object method "is_passing" via package "Test::Builder"

Comment: You need to upgrade your Test::Simple distribution - see the notes in the other answer.
Comment: I know you're under Solaris, but on ActivePerl upgrading Test::Simple is the way.  Test::Builder doesn't have its own PPM entry in my Win32 5.10 installation.  It took me a few minutes to track down so maybe this note will save someone else the time.


Is the Cyber Buster effective against aircraft and tanks?

Question: I'm contemplating a change to my weapon loadout in Saints Row 3.  I have access to the "Cyber Blaster" now, which is a weapon you use during one of the Decker missions.  So far I've kept the RC Possessor in this slot, and the Annihilator in the explosive weapon slot.
I'd want to replace the Annihilator with Satchel Charges, and the RC Possessor with the Cyber Buster, but I'm not certain if the Cyber Buster is capable as an anti-aircraft weapon.  The Annihilator locks on, and can take down most VTOLs/choppers with one hit, which makes this sort of thing a breeze.
If I take the Cyber Buster and the Satchel Charges, will I be at a disadvantage against aircraft?
Answer: The Saints Row Wiki says that a single fully-charged Cyber Buster shot will kill aircraft instantly. So, no, you'll be fine.
EDIT: I've since used the weapon myself. Basically, fully-charged shots instantly kill all occupants of any vehicle it hits. In the case of helicopters, this leaves it with nobody to keep it from spinning about and smacking into buildings.
Comment: Have you tried it yourself?  Can you link to the wiki page where you read that?
Comment: Here's a link to the wiki page http://saintsrow.wikia.com/wiki/Cyber_Buster


PostgreSQL - Start A Transaction block IN Function

Question: I'm trying to use create a transaction block inside a function, so my goal is to use this function one at time, so if some one use this Function and another want to use it, he can't until the first one is finish i create this Function :
CREATE OR REPLACE FUNCTION my_job(time_to_wait integer) RETURNS INTEGER AS $$
DECLARE
  max INT;
BEGIN
   BEGIN;
       SELECT MAX(max_value) INTO max FROM sch_lock.table_concurente;
       INSERT INTO sch_lock.table_concurente(max_value, date_insertion) VALUES(max + 1, now());
       -- Sleep a wail
       PERFORM pg_sleep(time_to_wait);
       RETURN max;
   COMMIT;
END;
$$
LANGUAGE plpgsql;

But it seams not work, i have a mistake Syntax error BEGIN;
Without BEGIN; and COMMIT i get a correct result, i use this query to check :
-- First user should to wait 10 second
SELECT my_job(10) as max_value;

-- First user should to wait 3 second
SELECT my_job(3) as max_value;

So the result is :
+-----+----------------------------+------------+
|  id |              date          | max_value  |
+-----+----------------------------+------------+
|  1  | 2017-02-13 13:03:58.12+00  |      1     |
+-----|----------------------------+------------+
|  2  | 2017-02-13 13:10:00.291+00 |      2     |
+-----+----------------------------+------------+
|  3  | 2017-02-13 13:10:00.291+00 |      2     |
+-----+----------------------------+------------+

But the result should be :
+-----+----------------------------+------------+
|  id |              date          | max_value  |
+-----+----------------------------+------------+
|  1  | 2017-02-13 13:03:58.12+00  |      1     |
+-----|----------------------------+------------+
|  2  | 2017-02-13 13:10:00.291+00 |      2     |
+-----+----------------------------+------------+
|  3  | 2017-02-13 13:10:00.291+00 |      3     |
+-----+----------------------------+------------+

so the third one id = 3 should have the max_value = 3 and not 2, this happen because the first user Select the max = 1 and wait 10 sec and the second user Select the max = 1 and wait 3 sec before Insertion, but the right solution is : I can't use this Function Until the First one finish, for that i want to make something secure and protected.
My questions is :

how can i make a Transaction block inside a function?
Do you have any suggestion how can we make this, with a secure way?

Thank you.
Comment: oh my god, and what should i do @a_horse_with_no_name any suggestion?
Comment: Unfortunately this is not possible. A function can not use commit or rollback.
Comment: Why don't you simply use a sequence to generate numbers. That will be a **lot** faster and much more scalable.
Comment: @a_horse_with_no_name this is just an example, i have another job, i do i should to  make it in a Function some calculation
Comment: @a_horse_with_no_name what if two users take the same value? i should to use this value to make some calculation, not just a number
Comment: One note, you can probably have the second user set the transaction level to `READ UNCOMMITTED` as a temporary workaround, but this has implications you want to really understand before you do that.
Answer: Ok so you cannot COMMIT in a function. You can have a save point and roll back to the save point however.
Your smallest possible transaction is a single statement parsed and executed by the server from the client, so every transaction is a function.  Within a transaction, however, you can have save points.  In this case you would look at the exception handling portions of PostgreSQL to handle this.
However that is not what you want here.  You want (I think?) data to be visible during a long-running server-side operation.  For that you are kind of out of luck. You cannot really increment your transaction ids while running a function.
You have a few options, in order of what I would consider to be good practices (best to worst):

Break down your logic into smaller slices that each move the db from one consistent state to another, and run those in separate transactions.
Use a message queue (like pg_message_queue)in the db, plus an external worker, and something which runs a step and yields a message for the next step.  Disadvantage is this adds more maintenance.
Use a function or framework like dblink or pl/python, or pl/perlu to connect back to the db and run transactions there.  ick....
Comment: this is really sad :( ok i will try to follow your suggestions, thank you any way :)
Comment: Chris Travers check my answer i don't know if it is a good idea or not, but it gives me the right result
Answer: You can use dblink for this. Something like :
CREATE OR REPLACE FUNCTION my_job(time_to_wait integer) RETURNS INTEGER AS $$
DECLARE
  max INT;
BEGIN
   SELECT INTO RES dblink_connect('con','dbname=local');
   SELECT INTO RES dblink_exec('con', 'BEGIN');
   ...
   SELECT INTO RES dblink_exec('con', 'COMMIT');
   SELECT INTO RES dblink_disconnect('con');
END;
$$
LANGUAGE plpgsql;

Answer: I don't know if this is a good way or not but what if we use LOCK TABLE for example like this :
CREATE OR REPLACE FUNCTION my_job(time_to_wait integer) RETURNS INTEGER AS $$
DECLARE
  max INT;
     BEGIN
       -- Lock table so no one will use it until the first one is finish
       LOCK TABLE sch_lock.table_concurente IN ACCESS EXCLUSIVE MODE;

       SELECT MAX(max_value) INTO max FROM sch_lock.table_concurente;
       INSERT INTO sch_lock.table_concurente(max_value, date_insertion) VALUES(max + 1, now());
       PERFORM pg_sleep(time_to_wait);
       RETURN max;
     END;
     $$
LANGUAGE plpgsql;

It gives me the right result.
Comment: As I understand the question it is that user 2 needs to see inserts that are currently happening in user 1's query.  I dont think this addresses that.
Comment: @ChrisTravers this work fine, so when the first use finish it insert `max_value = 2`, so the second user select this value and use it to insert `max_value = 3`, so we have a secure access to this value, it used by only and only one user in the time
Comment: Ah so your solution is a table lock.  I guess that works as well.
Comment: (at the cost of concurrency)
Comment: yes, @ChrisTravers so do you find that is a good way or maybe it makes problems in future ?
Comment: Your problem with a lock is that it kills concurrency.  If you do that, make sure to keep your transactions short as the lock will be maintained until the transaction completes.
Comment: thank you @ChrisTravers so much, i really appreciate it


How to create an exe to run SQL commands which ask for parameters

Question: I have a series of fairly simple SQL update commands that are used to update order owners in one of our databases. i.e.
<code>UPDATE POHEAD
SET BYRUSR_ID = upper('J123456')
WHERE BYRUSR_ID = upper('J654321')
  AND po_st IN (1, 4, 5, 6, 10,11);

COMMIT;
</code>
I want to enable our business users to make the changes, and thought that the best solution would be to create an application file that takes the parameters (olduser, newuser) and when the user clicks OK, the file opens a connection to the database (oracle) to make the updates.
While investigating I found a number of guides for creating exe files with .net but none that used SQL or asked for parameters. I haven't used .net before, so don't know where to start.
Using a PHP webform was considered but is not feasible.
Appreciate any help you can provide.
Comment: SQL isn't a client language, it's the language used by the Oracle server.  You need to write your user/client application in a client language that sends SQL commands to the Oracle server.  For .Net, that would be something like c#, VB.net, etc.
Comment: I think that is my question.
Comment: ?? Not sure I understand.  What part of my comment is your question?  Please state it clearly because the mods are about to close your question for being "too broad" (ie, too vague).
Comment: Googling "*Oracle SQL from C#*" produces many promising links, articles and tutorials.
Comment: Thanks RBarryYoung. I will look into this. I guess I just needed pointing in the right direction.
Answer: It's a rather vague question so I hope that this is what you need:
Usually, the best way to build a standalone-application which connects to SQL is via PHP. If you know a tiny bit of HTML, you can even create an HTML page in which your users can enter data and click on a button and the PHP script in the back-end will connect to the SQL-database and return the results on the next page.
Here a link for the beginning:
http://www.w3schools.com/php/php_mysql_connect.asp
There are also alternatives to connecting PHP with SQL (SparkSQL, Hadoop, ...) but I think that this is the simplest way of creating such an app.
Comment: Thanks Jan, That was my initial thought, I have done similar before and it was my preferred option, however, my company didn't want to go down that route.


Extending ArrayList - Cannot instantiate the type String?

Question: I want to extend ArrayList. I wanted to extend it such that the child class can contain only Strings and nothing else. Why am I getting an error in my code?
import java.util.*;

public class ExtendedStringArray<String> extends ArrayList<String>{

    public String getAString() {
        return new String("Test");
    }

}

Comment: Just make it: `public class ExtendedStringArray extends ArrayList {`
Comment: Yes, it also causes a warning in eclipse - The type parameter String is hiding the type String
Answer: You don't need the generic type in your class declaration, just in the extends clause:
public class ExtendedStringArray extends ArrayList<String> {

    public String getAString() {

        return new String("Test");

    }

}

What you are saying here is that ExtendedStringArray extends a specific type of ArrayList, the ArrayList parameterized with the String type. Since you aren't using any generic type parameters for your class's implementation you don't need the <> in your class declaration.
Answer: The compiler thinks that you are declaring a generic type parameter named String, which ends up hidding the actual String class. You cannot instantiate type parameters, hence the error.
You instead want:
class ExtendedStringArray extends ArrayList<String> {
     ...

Answer: Because you are using String either in your class declaration either in what it extends from. This means that String is literally used as a type variable and your code is indeed equivalent to
public class ExtendedStringArray<T> extends ArrayList<T>{

  public T getAString(){
    return new T("Test");
  }

}

But this is not correct, as you can't instantiate a object of a generic type T.
Use: class StringArrayList extends ArrayList<String> { .. so that you specify that you are specializing an ArrayList<String> and not declaring a generic class.


vb6 suppress keyboard strokes with API? (making a hotkey)

Question: I've searched, and can't seem to find an answer, so any help would be appreciated.
I want to make a hotkey, but when the hotkey is pressed, I don't want the actual "character" to be displayed, just the action to be performed.
So for example, I have this:
 Private Declare Function GetAsyncKeyState Lib "user32" _
 (ByVal vKey As KeyCodeConstants) As Long

 Private Const VK_A = &H41

 Private Sub keyboardTimer001_Timer()
    If KeyDown(VK_A) Then
       ' do my stuff, but DONT DISPLAY the letter "A"
    End If
 end sub

So this basically just has a timer (interval 1) checking the async keyboard. If it detects that the letter "a" was pressed, I perform an action. But I want it to do this WITHOUT printing the letter "a".
How would I remove the key from the keyboard buffer/prevent it from displaying? (Side note - not sure if something like 'PeekMessage' would work - if so - does anyone know where I can find a good vb6 code sample where I can peek for stuff like 'ctrl+a' or 'ctrl+alt+a', etc, etc and then just clear the buffer, and perform my action?)
Thanks!
Comment: Have you considered (or tried) setting the form's `KeyPreview` to `True` and eating the keystroke in the `_KeyPress` event?
Comment: yes, doesn't work - I want it to work globally (i.e., when the form has lost focus). keypreview only works if the form currently has focus.
Answer: You can use a combination of RegisterHotKey and PeekMessage.  The following code defines Key-A and Ctrl-A to perform actions:
Main Form
Option Explicit

Private Done As Boolean

Private Sub Form_Activate()
   Done = False
   RegisterHotKey Me.hWnd, &HBBBB&, MOD_NONE, vbKeyA
   RegisterHotKey Me.hWnd, &HBBBA&, MOD_CONTROL, vbKeyA
   ProcessMessages
End Sub

Private Sub ProcessMessages()
   Dim Message As Msg

   Do While Not Done
      WaitMessage

      If PeekMessage(Message, Me.hWnd, WM_HOTKEY, WM_HOTKEY, PM_REMOVE) Then
         If Message.wParam = &HBBBB& Then
            MsgBox "This is my Key-A action"
         ElseIf Message.wParam = &HBBBA& Then
            MsgBox "This is my Ctrl-A action"
         End If
      End If

      DoEvents
   Loop
End Sub

Private Sub Form_Unload(Cancel As Integer)
   Done = True
   Call UnregisterHotKey(Me.hWnd, &HBBBB&)
   Call UnregisterHotKey(Me.hWnd, &HBBBA&)
End Sub

The above code works well, but in a production app I might lean towards subclassing the main window.  If you prefer subclassing, you will need to use a technique of your choosing and replace the ProcessMessages method with something like this:
Private Function ISubclass_WindowProc(ByVal hwnd As Long, ByVal iMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
   Select Case iMsg
      Case WM_HOTKEY
         If wParam = &HBBBB& Then
            MsgBox "This is my Key-A action"
         ElseIf wParam = &HBBBA& Then
            MsgBox "This is my Ctrl-A action"
         End If
   End Select
End Function

As you can see, subclassing is a little cleaner.  Of course, you need to define the Win API stuff.  So in a module, place the following code:
Module
Option Explicit

Public Declare Function RegisterHotKey Lib "user32" (ByVal hWnd As Long, ByVal id As Long, ByVal fsModifiers As Long, ByVal vk As Long) As Long
Public Declare Function UnregisterHotKey Lib "user32" (ByVal hWnd As Long, ByVal id As Long) As Long
Public Declare Function PeekMessage Lib "user32" Alias "PeekMessageA" (lpMsg As Msg, ByVal hWnd As Long, ByVal wMsgFilterMin As Long, ByVal wMsgFilterMax As Long, ByVal wRemoveMsg As Long) As Long
Public Declare Function WaitMessage Lib "user32" () As Long

Public Const MOD_NONE = &H0
Public Const MOD_ALT = &H1
Public Const MOD_CONTROL = &H2
Public Const MOD_SHIFT = &H4
Public Const MOD_WIN = &H8
Public Const PM_REMOVE = &H1
Public Const WM_HOTKEY = &H312

Public Type POINTAPI
   x As Long
   y As Long
End Type

Public Type Msg
   hWnd As Long
   Message As Long
   wParam As Long
   lParam As Long
   time As Long
   pt As POINTAPI
End Type

Comment: hi, thanks! just noticed this - I will try this shortly and let you know the result, thanks! yes - basically I want to be able to make like a macro typer using keybd_event - so I don't want the code to be called a 2nd time while I 'type' things out... will this work with that? (I'm assuming I could just have a flag so the processing messages stops when I start the actual 'typing', and I restart again when I am finished, correct?) thanks!
Comment: I'm not sure exactly what you mean, but this code will certainly do what you requested in the original question.


Getting String value of Dynamic SQL into Select query in SQL Server

Question: I need to reach a return value from Dynamic SQL. I execute select query as string with sp_executesql. I have to reach results. Here is sql query:
DECLARE @dynsql nvarchar(max)
SET @dynsql = 'select @InvoiceNo=InvoiceNo from '+ QUOTENAME(@DynDB) +'.[dbo].[TableName] where UserID = '+
        cast(@UserID as nvarchar)
EXEC sp_executesql @dynsql

Problem: This @dynsql is string value and I have to reach a value in this sql query.
Answer: The best solution is:
We can add our output parameter to query then we should add it to execute line like this:
DECLARE @dynsql nvarchar(max)
SET @dynsql = 'select @InvoiceNo=InvoiceNo from '+ QUOTENAME(@DynDB) +'.[dbo].[TableName] where UserID = '+
        cast(@UserID as nvarchar)
EXEC sp_executesql @dynsql, N'@InvoiceNo int OUTPUT',@InvoiceNo = @InvoiceNo OUTPUT
select @InvoiceNo as InvoiceNo

And the result is: InvoiceNo = 11111 (int value)
Comment: This is awesome.


Spark Streaming to MongoDB

Question: I am accessing the data from Apache Kafka through Apache Spark Streaming so I want to store the Data in the MongoDB   so How Can i store it in mongoDB ?
Comment: Did you try [google](https://databricks.com/blog/2015/03/20/using-mongodb-with-spark.html)?
Answer: The output operations are quite limited, but you can always use foreachRDD() where you have access to any processed RDD in this timeframe. So any custom logic can be placed here, i.e. having a connection to MongoDB perform a simple insert/update operation explicitly.

Spark Streaming to MongoDB