text:
Q: integration tests vs test coverage My company has a rule to reach 75% test coverage, either by unit or by integration tests. due to the complexity of the overall system, developers tend to write integration tests (e.g. using selenium webdriver against the running application) instead of taking the burden of mocking away dependent services/classes.
I am not a friend of that and wonder what the test-coverage data for i-tests actually means:
In my opinion, a test should define expected behavior and test that. If an i-test goes deep into the application, through many services, possibly down to the DB-layer and back again, it will cover a lot of lines, but it is absolutely not clear what the expected behavior of such a covered line is. Thus the quality of the coverage data is questionable IMHO and -- even worse -- increases maintenance efforts.
Is that POV correct? How can I back it up when it comes to discussion with management ?

A: Blind percentage rules about test coverage aren't really ideal. Integration tests are a perfect example of that. If something breaks, can you tell exactly what broke? What if you have multiple integration points (e.g. a single request hits a database, a web service, and sends an email)? There's too much going on there for the test to really have meaning.
Can you have 100% coverage without testing all possible outcomes? Can you write 10,000 tests and still fail to cover the most important classes in a piece of software? Blind metrics are bad and have no real outcome on quality.
Typically, it is much more valuable to have smaller, more discrete tests. We do this by stubbing out integration points and mocking them away in tests. Then you can set up the scenario, "If the database does this, then my code does this." This type of problem is much easier to solve in memory than setting up a database to do that exact thing on a repeatable basis. How would you automate an integration test a server disconnect? That's very hard. Stubbing out the database handling that specific SQL Exception is much easier and repeatable.

A: What will happen if you couldn't reach the 75% of test coverage before deadline or even if you reach it,what about the rest 25%,so your company aren't concentrating to get a product with less obvious defects rather concentrating on the percentage of test coverage.Explain your way of approach in a credible way despite you use selenium or whatever so called.


text:
Q: use selenium to infinite scroll down don't work I am trying to use selenium to scroll down infinitely this webpage https://gfycat.com/discover/trending-gifs
I try this code:
from selenium import webdriver
options = webdriver.ChromeOptions()

options.add_argument("start-maximized")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(options=options, executable_path=r"C:\chromedriver.exe")

driver.get(url)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")

driver.quit()

But no scroll down happened.
I also tried:
from selenium.webdriver.common.keys import Keys

for i in range(10):
     driver.find_element_by_css_selector('html').send_keys(Keys.END)

But no scroll down happened too.

A: For infinite of Scrolling website you can using this methods of coding in Selenium as you can see I am using while for making infinite in addition you should be import time module for time out of loading website
def scroll(driver):
    timeout = 5

    # Get scroll height
    last_height = driver.execute_script("return document.body.scrollHeight")

    while True:
        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # load the website
        time.sleep(5)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass facebook access token to server my application is a basic php application. I use facebook authentication only for login purposes and have to store basic user information in the database after the user logs in. I also have to set the session variables in php after the user logs in. I plan to use Javascript SDK for the facebook authentication.
How can I pass the user information after the user has successfully logged in (i.e. "status=connected")  for storage in the database and set the php session variable?
Any help is appreciated!

A: facebook Js SDK sets a cookie in the client browser session that is to be used to get the client access token and other basic user information.


text:
Q: Reduce the size of a file I have two files, each one contain more than 3GB in /var/log partition, I need to free some space without deleting or moving the files cause it will interrupt my system.
I also can't delete the lines in files with vi + dd. There are thousands of lines.
Any useful ideas?
Files:
1- messages
2-  My web server log file.

A: You may be able to truncate the files, which unlike using rm will release the disk space even if the files are still open:
> /var/log/big1.log
> /var/log/big2.log

But please test it on a separate system first.  Check if the file's inode numbers change.  If not, you're good.

A: If you want to keep the full content of the existing files you will need to compress them to some temporary space elsewhere and then replace each uncompressed file with its compressed equivalent. Otherwise just delete the older log files or archive them elsewhere.
Here is a proposal to compress the log files without losing their contents. However, you need to be aware that if you keep growing log files it will only defer the problem of your filesystem filling up and not resolve it permanently.
Identify the older files that are to be compressed. (None of these must be in use or open right now for logging.) In my example this is big1.log.
Identify a chunk of filesystem that can hold the largest of these uncompressed files. In my example I'm going to assume this is /home.
In your real-world scenario you can use a for loop to iterate across a series of files. Here are the steps for a single file:
logfile='/var/log/big1.log'                      # The logfile to be compressed

if gzip -c "$logfile" >/home/log.gz
then
    touch --reference "$logfile" /home/log.gz    # Capture timestamp of last update
    chown --reference "$logfile" /home/log.gz    # Capture ownerships
    chmod --reference "$logfile" /home/log.gz    # Capture permissions
    rm -f "$logfile"                             # Make space
    mv -f /home/log.gz "$logfile.gz"             # Rename with correct suffix
fi


text:
Q: MySQL query: multi level category on the same table Good day earthlings,
This is my table structure
acctCode| refAcctCode | acctName
------    ----------    --------
 AC001                    SALES
 AC002                    AR
 AC003     AC001          FURNITURE
 AC004     AC003          OFFICE FURNITURE
 AC005     AC002          INVOICE
 AC006     AC001          UTILITIES

and expected output would be
SALES
    FURNITURE
        OFFICE FURNITURE
    UTILITIES
AR
    INVOICE

however it its not only limited on level 3 alone but to the nth
eg:
Parent1
  Child1
    child1.1
      child1.1.1
        child1.1.1.1
  child2
  child3
  child3

parent2
  child1
  child2
  child3

Given the table structure format, how do I query to get that output?
thanks

A: Here is a solution based on a user defined procedure:
CREATE PROCEDURE list()
BEGIN
 DROP TABLE IF EXISTS tmp; -- for collecting the records
 CREATE TABLE tmp (id varchar(1024), name varchar(128));
 SET @i=-5; SET @s=0;      -- @i: offset for id comparison
                           -- @s: space padding for name column
 INSERT INTO tmp           -- fill in entries without refAcctCode
 SELECT a.acctCode, a.acctName FROM tbl a WHERE a.refAcctCode is null;

                           -- do as often as necessary ...
 WHILE ROW_COUNT() > 0 DO
  SET @i=@i+6; SET @s=@s+2;-- increment variables
  INSERT INTO tmp
  SELECT CONCAT(id,' ',a.acctCode), CONCAT(SPACE(@s),a.acctName)
  FROM tbl a INNER JOIN tmp b ON SUBSTR(id,@i)=a.refAcctCode;
 END WHILE;

 SELECT * FROM tmp ORDER BY id;  -- list the consolidated temp. table
END;

By executing it with
CALL list()

You get the following output:
    id                name
------------------------------------------
1   AC001             SALES
2   AC001 AC003         FURNITURE
3   AC001 AC003 AC004     OFFICE FURNITURE
4   AC001 AC006         UTILITIES
5   AC002             AR
6   AC002 AC005         INVOICE

You can find a working Demo here: http://rextester.com/ZRXN57872
I used spaces to prefix the accName column. This makes it easier to see the category levels in the results listing. Feel free to play around with the procedure to make it fit your particular needs.


text:
Q: In /proc/meminfo, does Dirty include or exclude Writeback?
Dirty %lu - Memory which is waiting to get written back to the disk.
Writeback %lu - Memory which is actively being written back to the disk.
-- man proc

Does Dirty include Writeback?  Or is it excluded?
My kernel version is 4.18.16-200.fc28.x86_64.

A: "Dirty" and "Writeback" are separate stats and page states; for proof of this, see for example node_dirty_ok:
nr_pages += node_page_state(pgdat, NR_FILE_DIRTY);
nr_pages += node_page_state(pgdat, NR_UNSTABLE_NFS);
nr_pages += node_page_state(pgdat, NR_WRITEBACK);

return nr_pages <= limit;

If one included the other, that would be taken into account here.
/proc/meminfo doesn't process the corresponding values either:
show_val_kb(m, "Dirty:          ",
        global_node_page_state(NR_FILE_DIRTY));
show_val_kb(m, "Writeback:      ",
        global_node_page_state(NR_WRITEBACK));

A: I think Dirty excludes Writeback.
dd if=/dev/zero of=~/X.img bs=1M count=1 ; sync & for i in 1 2 3; do grep -E '^(Dirty:|Writeback:|MemFree:|Cached:)' /proc/meminfo ; done
1+0 records in
1+0 records out
1048576 bytes (1.0 MB, 1.0 MiB) copied, 0.00316564 s, 331 MB/s
[1] 13140
MemFree:         1461832 kB
Cached:          1475188 kB
Dirty:               132 kB
Writeback:          1032 kB
...

(Although this is only proof if /proc/meminfo is guaranteed 100% consistent).


text:
Q: Is this good way to get path to desktop? just want to ask if this code in python is valid to use on any OS, i mean, i want to use the path then for exporting txt file to desktop so for example if user on Mac will not have problem, or is there another way to do it?
def get_path():
    PATH = os.path.normpath(os.path.expanduser('~/Desktop'))
    return PATH

A: On windows you can easily get Desktop path by joining with the environment variable of user. Here is an example:
import os

desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

A: This should work for most users, Windows as well as Linux and MacOS have their desktop (typically) located under ~/Desktop. Do note however this location can be changed by the user so there is no guarantuee.
Windows: Usually ~/Desktop but can be changed, see https://superuser.com/q/1663587/138216
Linux: Typically ~/Desktop but could be something else, see https://unix.stackexchange.com/questions/391915/where-is-the-path-to-the-current-users-desktop-directory-stored
Mac: Also typcially ~/Desktop http://etutorials.org/Mac+OS/mac+os+x+power+tools/Part+II+Files+Finders+Docks+and+Apps+Including+Classic/Chapter+5+Finagle+Files+and+Foil+Finder+Frustration/The+Desktop+and+the+Desktop+Folder/#:~:text=In%20Mac%20OS%20X%2C%20because,these%20folders%20in%20Chapter%201).


text:
Q: Cox PH model and time splitting I have question about the 'setup' for the data for Cox PH survival modelling in case of modelling time to 'breakdown'.
My data are houses and roof repair. For each house I have either the age of the house when it was repaired (Event_01=1) or, if was not repaired, the age at the time of sampling (Event_01=0). So I have the time to event (Event_Year) and the event itself (Event_01).
Furthermore I have some variables for use as explanatory variables like roof type, house price, square meters etc.
In most examples I have seen the age is the age of the 'object' (a person for instance) at the time of the treatment or whatever it is that is examined. However here the 'treatment' is building the house so the (start-)age is always 0 since the time starts when the house is brand new. But the age of the house is an important parameter when it comes the predicting the risk of repair - I would expect the risk to increase as the house age increases. What do you do in this case?
What I did was making time splits for several times like 5, 10, 15 etc. years. Like this:
Original data:
    House ID Event_Year Event_01
           1          3        0
           2          7        1
           3         11        0
           4         13        1

With splits at 5 and 10 years it becomes:
    House ID Split_Time Event_Year Event_01
           1          0          3        0
           2          0          5        0
           2          5          2        1
           3          0          5        0
           3          5          5        0
           3         10          1        0
           4          0          5        0
           4          5          5        0
           4         10          3        1

This way my model showed that the higher the split-year, the higher the hazard which matched my expectations.
So my question(s) is: Is this a good way to do it - did I misunderstand something completely? Is there a more simple way to include the house age in this case? Did I violate all assumptions about independence so it is useless?

A: I don't see any need to do this.  You can do a survival analysis on the original data, you just don't have a "treatment".  Your only independent variable is "age of house".  Some of your cases are censored (that is, no event occurred) but that's fine - that is the issue that survival analysis was designed for.


text:
Q: xslt cascading structure should generate multi files and catalogue (result-document?) I got a structure like this:
<chapter 1>
    .. some infos of Chapter 1
    <Chapter 1.1>
        .. some infos of Chapter 1.1
        <Chapter 1.1.1>
         ... rekursiv going down here

       .. some infos of Chapter 1.1
    </Chapter 1.1>
    <Chapter 1.2>
        .. some infos of Chapter 1.2
        <Chapter 1.2.1>
         ... rekursiv going down here

       .. some infos of Chapter 1.2
    </Chapter 1.2>

    .. some infos of Chapter 1
</Chapter 1>

should result in following files:
chapter_1.xml
chapter_1.1.xml
chapter 1.1.1.xml
chapter 1.2.xml
chapter 1.2.1.xml
and(!) a contentfile showing the structure of files.
a) I guess xsl:result-document would work to generate all the chapterFiles while going recursively the structure.
b) to generate the contentfile it would need a document (some sort of file handler) open all the time to write the content in parallel
OR
a second loop over the structure just fpr the content
Would you please give me your opinion/best way how to handle a) and b)

A: This all falls out naturally with a structure like this:
<xsl:template match="Chapter">
  <!-- add a link from the containing chapter to the contained chapter -->
  <link href="Chapter{@id}">Chapter {title}</link>
  <!-- process the contained chapter -->
  <xsl:result-document href="Chapter{@id}">
     <article>
        <xsl:apply-templates/>
     </article>
  </xsl:result-document>
</xsl:template>

In other words, at any "time" in your processing (though it's best to avoid temporal language when describing a functional program) there's a stack of open result documents corresponding to the stack of chapter elements in the input, and new elements are added to the result document that's on the top of this stack.
Saxon-EE will in fact write multiple result documents in parallel (in separate threads) but that's not something you need to be aware of.
See the play.xsl sample stylesheet in the saxon-resources download at saxonica.com for an example of this - it's not recursive, it has a fixed three levels of play/act/scene, but the principle is the same.


text:
Q: Fetch graphql query result on render and re-renders BUT LAZILY I have a React Apollo app and what I am trying to do is that I have a component that renders some data using charts. For this data, I have some filters that I save in the local state of the component (Using hooks)
const [filters, setFilters] = useState(defaultFilters);

Now what I want is that whenever the component mounts, fetch the data using the default filters. But I also want to re-fetch data when the user updates the filters AND CLICKS ON SUBMIT and I'd fetch the results using new filters.
Since I also want to fetch the results on filter update, I am using useLazyQuery hook provided by apollo
const [getData, {data}] = useLazyQuery(GET_DATA_QUERY, { variables: {filters} });

useEffect(getData, []); // this useEffect runs only when the component mounts and never again

But, what happens is whenever my state, filters, updates the getData function is automatically run! ALWAYS! (BEHIND THE SCENE)

*

*How do I handle such cases, where I want to fetch results on mounting and re-rendering.
I have tried using useQuery and refetch provided by it but I get the same problem there, whenever I update the state, the component rerenders and the useQuery hooks is run and makes the call. (That's how I believe it runs)

*How do I fix my current code. Calling the getData function inside the useEffect function makes it run on every re-render.
I think I the problem defined in this stackoverflow-question is somewhat similar to mine.

A: Part of the problem is that you really have two different states that you're trying to utilize a single hook for. You have state that represents your inputs' values in the UI, and then you have state that represents the filters you want to actually apply to your charts. These are two separate bits of state.
The simplest solution is to just do something like this:
const [inputFilters, setInputFilters] = useState(defaultFilters)
const [appliedFilters, setAppliedFilters] = useState(inputFilters)
const { data } = useQuery(GET_DATA_QUERY, { variables: { filters: appliedFilters } })

const handleSubmit = () => setAppliedFilters(inputFilters)
const handleSomeInputChange = event => setInputFilters(...)

This way, you use inputFilters/setInputFilters only to manage your inputs' state. When the user clicks your submit button, the appliedFilters are set to whatever the inputFilters are at the time, and your query will update to reflect the new variables.


text:
Q: How to format inputted data and output it I'm looking to creat a  code which asks for input and then  add data to a tab delimated file in the output form of say :
      Author.Year.Title.Journal

But I also need to format the input in a way that if there are two authors the out put
will be :
 Author1 &Author2.year.title.journal

and if they are 3 authors the output will be
 Author1,Author2&Author3. year. title. journal

here is my code so far :
try:
    import csv
    file = raw_input('Enter Filename:')
    with open(file,'a') as openfile:
      writer = csv.writer(openfile,delimiter='.')
      ans=True
      while ans:
        print ("""
        1.
        2.
        3
        """)
       ans = raw_input("How Many Authors?")
       if ans=="1":
         author = raw_input('Enter Author Name:')
         title = raw_input('Enter Title Name:')
         year= raw_input('Enter year:')
         journal = raw_input('Enter Journal:')
         writer.writerow([author,title,year,journal])

      elif ans=="2":
           auhtor_1 = raw_input('Enter First Author''s Name:')
           author_2 = raw_input('Enter Second Author''s Name:')
           title = raw_input('Enter Title Name:')
           year= raw_input('Enter year:')
           journal = raw_input('Enter Journal:')

      elif ans=="3":
           auhtor_1 = raw_input('Enter First Author''s Name:')
           author_2 = raw_input('Enter Second Author''s Name:')
           author_3 = raw_input('Enter Third Author''s Name:')
           title = raw_input('Enter Title Name:')
           year= raw_input('Enter year:')
           journal = raw_input('Enter Journal:')

except IOError:
    print 'Sorry Something went Wrong'

This is where I'm stuck.

A: Use a list to store the author names.
authors = []
num_authors = int(raw_input("How Many Authors? "))
for i in range(num_authors):
    authors.append(raw_input("Enter Author's Name ({}): ".format(i+1)))

Apart from handling an arbitrary number of authors, a list of authors is generally more useful than a formatted string of authors; e.g. it's easy to determine the number of authors, to sort the authors, or to output the list with different formatting.
To achieve your desired output you can add punctuation using str.join():
authors_string = ' & '.join([', '.join(authors[:-1]), authors[-1]]
                                if len(authors) > 2 else authors)

The inner str.join() joins with commas all authors except the last one or, if there are fewer than 2 authors, no join takes place. The outer join adds the ampersand between the final 2 authors if required.


text:
Q: PHP add addition feature to existing class i have class and set of methods in my library.
class name is called classA which have the method call generateCSS method. in these function some set of meta TAG are defined already. now i want to add some more meta tag to the existing function generateCSS. As well these over riding should not disturb the existing function generateCSS also i want my new meta tag in that generateCSS function.
Here every one accessing generateCSS method. so my new meta tag change should reflect in that as well.
class classb extends classa{

    public function add_generateCSS (){
        parent::generateCSS();
        return $html = "<script src='new.js'></script>";
    }
}

A: I'm not completely sure if I understood the question right, but I think you are looking for this:
class classb extends classa{

  public function add_generateCSS (){
    $html = parent::generateCSS();
    return $html . "<script src='new.js'></script>";
  }
}

You were calling the generateCSS() method on the parent and then disposing the result immediately. You should save that result in a variable and concatenate your additional code to it. Then return that.


text:
Q: ng-disable with few options (refactor needed) I'm looking for help with refactoring my code. I wrote this:
button.btn.btn-primary ng-click="ok()" ng-show="!params.page_name && !image_thumb" ng-disabled="(!params.project_name || !logo_thumb)" Ok, create
button.btn.btn-primary ng-click="ok()" ng-show="params.page_name || image_thumb" ng-disabled="(!params.page_name || !image_thumb)" Ok, create

First condition is:
(!params.project_name || !logo_thumb)

Second condition is
(!params.page_name || !image_thumb) if params.page_name || !image_thumb

but I would like use only one button with ng-disabled. Do you have any idea what I can do?

A: You can combine ANDs && and  ORs || with parans to get a combination of the things you want.
button.btn.btn-primary ng-click="ok()" ng-show="(!params.page_name && !image_thumb) || params.page_name || image_thumb" ng-disabled="((!params.page_name && !image_thumb) && (!params.project_name || !logo_thumb)) || ((params.page_name || image_thumb) && (!params.page_name || !image_thumb))" Ok, create


text:
Q: Are images, flash contents are also treated as hypertext by the HTTP server and the web browser? I am having a doubt about the working of the HTTP protocol.
We know that HTTP is used for transfering the hyperText only.
Now suppose if I type some url in my browser and press enter the web page is loaded in the browser also the images and the some flash contents(if any) in the in the web page are displayed.
Now my question is that are the images and the flash contents in the web page also treated as hypertext by the HTTP server and the web browser?

A: A GET request is designed to retrieve data from the server. It doesn't really matter what the data is. It's just a resource that can be called by name and is handled by the browser.


text:
Q: How to take data from multiple nodes in a xml file use them in different text file using c#? I have a sample xml file which is like below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD with OASIS Tables v1.0 20120330//EN" "JATS-journalpublishing-oasis-article1.dtd">

<front>
<journal-meta>
<journal-id journal-id-type="publisher-id"/>
<journal-title-group>
<journal-title>Eleventh International Conference on Correlation Optics</journal-title>
</journal-title-group>
<issn pub-type="epub">0277-786X</issn>
<publisher>
<publisher-name>SPIE</publisher-name>
</publisher>
</journal-meta>

10.236/12.205210

<title-group>

So you think you can dance?

</title-group>
<contrib-group>
<contrib contrib-type="author">
<name>
<surname>Cena</surname>
<given-names>John</given-names>
</name>
<xref ref-type="aff" rid="a1">a</xref>
</contrib>
<contrib contrib-type="author" corresp="yes">
<name>
<surname>Pal</surname>
<given-names>G.S.</given-names>
</name>
<xref ref-type="aff" rid="a2">b</xref>
</contrib>
<aff id="a1">aCNRS, France</aff>
<aff id="a2">bMIT, USA</aff>
</contrib-group>

</front>

<sec id="S1">
1.

Today is your lucky day

</sec>
<sec id="S2">
2.

Today is not so lucky

</sec>

I'm tying to get contents of some of the nodes(first node found) and put them in variables and then use regex replace using them in a different TXT file in efficient manner.
I'm trying something like
 XDocument doc=XDocument.Load(@"D:\MyFiles\1235-12-3053\230\124\124.xml",LoadOptions.PreserveWhitespace);
                var s=from a in doc.Descendants("surname")
                    select a.First();
                var l=from x in doc.Descendants("label")
                    select x.First();
            ... so on
    File.WriteAllText(@"C:\Desktop\text.txt", Regex.Replace(File.ReadAllText(@"C:\Desktop\text.txt"), @"[^<]+", @"s"));
    File.WriteAllText(@"C:\Desktop\text.txt", Regex.Replace(File.ReadAllText(@"C:\Desktop\text.txt"), @"[^<]+", @"l"));
    ... so on

But First() method is giving an error, and also using WriteAllText many times, is that a good practice? Can I do multiple replaces in one go?

A: Instead of loading and saving the file to the hard drive multiple times, you should consider loading the text to a variable (string).
When i memory you can use regex to search and replace for multiple different patterns as you wish, and when completely done save the file.

A: Try something like this
XDocument doc=XDocument.Load(file,LoadOptions.PreserveWhitespace);
    var s=(from a in doc.Descendants("surname")
     select a).First().Value;
    var l=(from x in doc.Descendants("label")
     select x).First().Value;
 string text = File.ReadAllText(file);
            text = Regex.Replace(text,  @"[^<]+", @""+s+@"");
            text = Regex.Replace(text,  @"[^<]+", @""+l+@"");
            File.WriteAllText(file, text);

This should do if I understand correctly what you wanted from this program.
There is also a method called UpdateText I believe, to do the updating of the file but I'm not that familiar with it...maybe someone else can help you on that method.


text:
Q: is there a way to modify the contents of an HTML tag that is inside a Vue component? I'm new to Vue.js and haven't yet understood it.
So I was wondering if there is a way in which I can make my custom Vue component(UnorderedList) manipulate the content that is inside my custom component(UnorderedList)
if I have some
 tags inside my component like this :
<UnorderedList :dashed="true">

some sentence here

some sentence here

</UnorderedList>

then this is what it would look like when the page renders

some sentence here
some sentence here

What I want my component here to do, is add a "-" before every
 tag, so that when the page renders it should look like this :
- some sentence here
- some sentence here

This is my UnorderedList.vue right now
<template>

    -

</template>

This above code obviously doesn't work the way I want it to.
So, basically I want to add a "-" before everything that is inside the custom component (UnorderedList).
How can I do this ?
I apologize in advance if this is a silly question

A: you can use vue Filters

            Vue.filter('dash', function (value) {
              if (!value) return ''
              value = `- ${value}`;
              return value;
            })

            var app = new Vue({
                      el: '#app',
                      data: {
                        message: 'Hello Vue!'
                      }
                    })

        {{message | dash}}

after you created filter you can use it in html template like above (message | dash )


text:
Q: Sangria: How to handle custom types trying work with Sangria and Slick. New to both of them.
I have bunch of tables which share a list of common fields. Slick's representation of this is below:
case class CommonFields(created_by: Int = 0, is_deleted: Boolean = false)

trait CommonModel {
  def commonFields: CommonFields
  def created_by = commonFields.created_by
  def is_deleted = commonFields.is_deleted
}

case class User(id: Int,
                name: String,
                commonFields: CommonFields = CommonFields()) extends CommonModel

Slick tables:
  abstract class CommonTable [Model <: CommonModel] (tag: Tag, tableName: String) extends Table[Model](tag, tableName) {
    def created_by = column[Int]("created_by")
    def is_deleted = column[Boolean]("is_deleted")
  }

  case class CommonColumns(created_by: Rep[Int], is_deleted: Rep[Boolean])

  implicit object CommonShape extends CaseClassShape(
    CommonColumns.tupled, CommonFields.tupled
  )

  class UsersTable(tag: Tag) extends CommonTable[User](tag, "USERS") {
    def id = column[Int]("ID", O.PrimaryKey, O.AutoInc)
    def name = column[String]("NAME")

    def * = (id,
      name,
      CommonColumns(created_by, is_deleted)) <> (User.tupled, User.unapply)
  }

  val Users = TableQuery[UsersTable]

The problem is with Graphql:
 lazy val UserType: ObjectType[Unit, User] = deriveObjectType[Unit, User]()

When I try to create UserType using derivedObjectType Macro, it complains that

Can't find suitable GraphQL output type for .CommonFields. If you have defined it already, please consider making it implicit and ensure that it's available in the scope.
[error]   lazy val UserType: ObjectType[Unit, User] = deriveObjectType[Unit, User](

How do I tell Sangria/Graphql how to handle this nested list of fields (from CommonFields) ?
Please help.

A: You are deriving the Type for User but user also has CommonFields which you have not derived. So it's not able to find Type information for CommonFields. Derive both and make the derivation implicit for CommonFields.
implicit val CommonFieldsType: ObjectType[Unit, CommonFields] = deriveObjectType[Unit, CommonFields]
implicit val UserType: ObjectType[Unit, User] = deriveObjectType[Unit, User]


text:
Q: Do all AWS Node.js apps require the cluster module? I was following the tutorial here, and noticed the index file (app.js) of the example code is quite different than a usual Express.js application. The code is wrapped inside the cluster module as follows:
// Include the cluster module
var cluster = require('cluster');

// Code to run if we're in the master process
if (cluster.isMaster) {

    // Count the machine's CPUs
    var cpuCount = require('os').cpus().length;

    // Create a worker for each CPU
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }

    // Listen for terminating workers
    cluster.on('exit', function (worker) {

        // Replace the terminated workers
        console.log('Worker ' + worker.id + ' died :(');
        cluster.fork();

    });

// Code to run if we're in a worker process
} else {
    var AWS = require('aws-sdk');
    var express = require('express');
    var bodyParser = require('body-parser');
    // the usual code ..
}

Is this necessary, or can I just deploy the regular code without the cluster module, like this:
var AWS = require('aws-sdk');
var express = require('express');
var bodyParser = require('body-parser');
// the usual code ..

Thanks,

A: It's not necessary.  The cluster module is a way to make better use of the machine (virtual or physical) processing capabilities, but it is not necessary just to run on AWS.


text:
Q: Get the data type from a field in MSproject I'm trying to get the data type of a selected field in MSProject. there are 8 types of data(Cost, date, text,....) and I'd like to develop a small addin with Visual studio wich makes some calculation depending on the type of data I have selected.
With the help of this site, I found how to get the name of the field:
Application.ActiveSelection.FieldNameList[0]

(It could be helpful for the next step, If I select more than one field ==> Do nothing)
but I'm not able to find a way to return the data type of the selected field
Someone has an idea how I could do that?
For example, if I select this field, my programm has to return : text

A: You will need to build a map of FieldName or FieldID to data type.
Keep in mind that date fields can also contain text (e.g. ActualStart will contain NA until there is a date in that field).
Also, use the task's native property to get the data rather than the ActiveCell property or the GetField method which return the displayed value.
For example, if the active cell is a duration field showing 2 days:

*

*ActiveCell returns "2 days", "2d", or "2 d", etc. depending on the user's configuration.

*ActiveCell.Task.GetField(pjTaskDuration) returns the same thing.

*ActiveCell.Task.Duration returns 960 (Int32).
Update
For custom fields that the end user creates, TryParse can be used to determine the likely data type. Here's a simplistic vb example:
Dim s As String
Dim d as Date
With Application.ActiveSelection
    s = .Tasks(0).GetField(.FieldIDList(0))
End With
If Date.TryParse(s, d) Then
    ' it is a date
Else
    ' it's not a date, maybe check to see if it's an integer
End If


text:
Q: Integer solutions of $x^2-5y^2=1342$ with $0\leq x,y<400$ $x^2-5y^2=1342$, where $x,y \in \mathbb N \ and \ x,y<400$., how many pairs of $(x,y)$ possible here.
what would be my approach here?

A: Suppose $x,y$ is a solution. Calculating modulo $4$, we get $x^2 - y^2 \equiv 2 \pmod{4}$. However, $x^2$ and $y^2$ have a residue of $0,1$ modulo $4$, so there are no solutions.
Another way to see this is to look modulo $5$: a solution $x,y$ satisfies $x^2 \equiv 2 \pmod{5}$. However $x^2$ has a residue of $0,1,4$ modulo $5$, so there are no solutions.

A: There are no solutions. Hint: Work modulo $4$.


text:
Q: Cannot convert google maps poly line values into string to decode it I can able to retrieve the poly line values(JSONObject values) from google directions api in encoded form to decode this value I need to convert poly line JSONObject values into String.
when i used .toString() method it throws Exception like,
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err: org.json.JSONException: Value czmbAml`uM@\?F@B@B@@ at points of type java.lang.String cannot be converted to JSONObject
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at org.json.JSON.typeMismatch(JSON.java:100)
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at org.json.JSONObject.getJSONObject(JSONObject.java:578)
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at com.ats.routemapdemo.DirectionsJSONParser.parse(DirectionsJSONParser.java:36)
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at com.ats.routemapdemo.MapsActivity$JSONtask.doInBackground(MapsActivity.java:146)
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at com.ats.routemapdemo.MapsActivity$JSONtask.doInBackground(MapsActivity.java:117)
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-16 00:22:08.014 21481-22032/com.ats.routemapdemo W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-16 00:22:08.024 21481-22032/com.ats.routemapdemo W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-16 00:22:08.024 21481-22032/com.ats.routemapdemo W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-16 00:22:08.024 21481-22032/com.ats.routemapdemo W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-16 00:22:08.024 21481-22032/com.ats.routemapdemo W/System.err:     at java.lang.Thread.run(Thread.java:841)

Please Help to convert that into String values.

A: Add these to your project
private class draw_ConnectAsyncTask extends AsyncTask<Void, Void, String>
{
    String url;

    draw_ConnectAsyncTask(String urlPass) {
        url = urlPass;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if (result != null) {
            drawPath(result);
        }
    }

JSONParser.java
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            //decoding from bytes to char using "iso-8859-1"
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

and add these methods
public String makeURL(double sourcelat, double sourcelog, double destlat, double destlog)
{
    //make the url that will be passed to the JSONParser
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=false&mode=driving&alternatives=false");
    return urlString.toString();
}

public void drawPath(String result)
    {
        try {
            //Transform the string into a json object
            final JSONObject json = new JSONObject(result);
            //retrieving and decoding the polylineInitial
            JSONArray routeArray = json.getJSONArray("routes");
            JSONObject routes = routeArray.getJSONObject(0);
            JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
            String encodedString = overviewPolylines.getString("points");
            List<LatLng> list = decodePoly(encodedString);

            rectLine = new PolylineOptions().width(8).color(
                    Color.BLUE);

            //drawing the polyline by traversing all the LatLang the the list
            for (int z = 0; z < list.size(); z++) {
                rectLine.add(list.get(z));
            }

            polyline = map.addPolyline(rectLine);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private List<LatLng> decodePoly(String encoded)
    {

        //translating the encoded string to a list we can understand in android map
        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }

then call the AsynTask like this
draw_ConnectAsyncTask(makeURL(double,double,double,double));


text:
Q: golang package import failed I have following folder structure in my project folder. vendor folder added as suggested here.
my_project
   |
   main.go
   - vendor
       |
       - user_register
           |
           - user_register.go

In user_register.go I have following function

func getEmail(register_response http.ResponseWriter, register_request *http.Request) {
...
}

When I try to import user_register package in my main.go, it gives an error.
I tried go install from my project folder, and I got

go install: no install location for directory
  /home/sachith/Documents/Personal/Projects/my_project outside
  GOPATH

Is there a way to solve this problem? Without moving my project into /home/sachith/go directory?
I have refereed following SO threads, but they didnt solve my problem.
Golang import package inside package
Golang import package error

A:
Is there a way to solve this problem? Without moving my project into [GOPATH]?

Yes: Use Go modules by turning GO111MODULE=on.


text:
Q: How to filter hardcoded list via table in DB2? I am new to DB2 and facing a problem right now.
I have a hardcoded list of identityNo's and a table which has a column called identityNo. I want to find the identityNo's such that they will be in the hardcoded list, but not in the any row of the table.
Example:
List: 1, 2, 3, 4
select count(*) from myTable where identityNo = 1 => 3

select count(*) from myTable where identityNo = 2 => 0

select count(*) from myTable where identityNo = 3 => 1

select count(*) from myTable where identityNo = 4 => 0

Expected Result: 2 and 4 (any format acceptable)

A: In DB2, you can do:
select i.id, count(t.identityNo)
from (select 1 as id from sysibm.sysdummy1 union all
      select 2 from sysibm.sysdummy1 union all
      select 3 from sysibm.sysdummy1 union all
      select 4 from sysibm.sysdummy1
     ) i left join
     mytable t
     on t.identityNo = i.id
group by i.id
order by i.id;

A: Try
VALUES (1),(2),(3),(4) MINUS SELECT identityNo FROM myTable

i.e.
create table myTable(identityNo int);
insert into myTable values (1),(3);
VALUES (1),(2),(3),(4) MINUS SELECT identityNo FROM myTable;

1
-----------
          4
          2

  2 record(s) selected.


text:
Q: Retrieve unique results with Core Data, NSPredicate? I need to be able to do the equivalent of the following SQL using Core Data:
SELECT DISTINCT(foo) FROM bar
Is there a way of doing this with NSPredicate? Or any other way for that matter?

A: I believe all you need to do is add this to your NSFetchRequest
[request setReturnsDistinctResults:YES];


text:
Q: JS- Show html based on wrapper class I'm using the following code to show more/show less on a page.
CSS
#more {display: none;}
.read-more-less{padding-bottom: 20px;text-align: center;display: block !important;margin:auto;width: 200px;height: 40px;font-size: 16px;margin-top: 15px;}

JS
function myFunction() {
  var dots = document.getElementById("dots");
  var moreText = document.getElementById("more");
  var btnText = document.getElementById("myBtn");

  if (dots.style.display === "none") {
    dots.style.display = "inline";
    btnText.innerHTML = "Show more";
    moreText.style.display = "none";
  } else {
    dots.style.display = "none";
    btnText.innerHTML = "Show less";
    moreText.style.display = "inline";
  }
}

HTML

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Show more

This the jsfiddle
Now if the html block is placed within another div (like an include) where "class="change"

            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

                Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

                Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        Show more

Is there a way of changing the child div class class="show-more"  to class="show-none"
How could this be done?

A: You can use CSS to do this.
It is easiest if you always print the span tag and then only display it when necessary. Also, instead of using 'show-button', it would be easier to use 'hide-button':

EDIT (in response to edited question):
There are a couple of ways to get the element that you want to change the class for. You can use either of the following lines of code:
// Get an element using its class name
var elem = document.getElementsByClassName('show-more')[0];

// OR

// Get an element using its CSS selector
var elem = document.querySelector('.show-more');

Once you have the element that you want to adjust the classes for, you can make the adjustments using code similar to the following:
// 'show-more' class is present
if (elem.classList.contains('show-more')) {
    elem.classList.remove('show-more');
    elem.classList.add('show-none');

// 'show-more' class is NOT present
} else {
    elem.classList.remove('show-none');
    elem.classList.add('show-more');
}


text:
Q: Embedding javascript on all blog platforms (creating a javascript badge) We would like to create a widget that basically acts as a badge for users to copy and paste on their blog. The way we're doing it is as follows -
We require the user to paste code similar to as follows into the HTML side of their blog post -
<script src="http://[our-remote-js]?blogg_id=XXXXXX">
<div id="div-name">

In our remote javascript file, we are querying our database for (blogg_id=XXXXXX) via ajax, constructing HTML at run time, and then setting the innerHTML for "div-name" to the HTML for the badge.
What we're running into is on Blogger, some templates will strip out the JavaScript and just leave the <div> tag.
On wordpress.org sites, the javascript is stripped out completely.
Is there a cleaner solution to this? One way I was thinking was, kinda as is done in PHP, where you can pass a querystring parameter to an image (blogg_id=XXXXXX), can you do that in .NET?
Any thoughts? Examples?


text:
Q: Postgres - permission denied on updating pg_catalog.pg_cast I'd like to update pg_catalog.pg_cast from the restricted user (on Postgres 9.3).
However running the query I need:
 update pg_cast set castcontext = 'i' where oid in ( select c.oid from pg_cast c inner join pg_type src on src.oid = c.castsource inner join pg_type tgt on tgt.oid = c.casttarget where src.typname like 'int%' and tgt.typname like 'bool%');

ends up with error:
    ERROR:  permission denied for relation pg_cast

However permissions seems to be correctly set. See the steps I made since DB and USER creation till query:
psql -c "create database test1 WITH ENCODING 'UTF8' LC_COLLATE='en_GB.UTF8' LC_CTYPE='en_GB.UTF8' TEMPLATE=template0;" -U postgres
psql -U postgres test1;
test1=# CREATE USER test1 PASSWORD 'test1';
test1=# GRANT ALL ON SCHEMA public TO test1;
test1=# GRANT ALL ON ALL TABLES IN SCHEMA public TO test1;
test1=# GRANT SELECT ON TABLE pg_catalog.pg_cast TO test1;
test1=# GRANT SELECT ON TABLE pg_catalog.pg_type TO test1;
test1=# GRANT UPDATE ON TABLE pg_catalog.pg_cast TO test1;
test1=# \q

sudo service postgresql-9.3 restart

PGPASSWORD=test1;psql -U test1 test1

test1=> \z pg_catalog.pg_cast
                  Access privileges
   Schema   |  Name   | Type  | Access privileges | Column access privileges
------------+---------+-------+-------------------+--------------------------
 pg_catalog | pg_cast | table | =r/postgres      +|
        |         |       | test1=rw/postgres |
(1 row)

test1=> \z pg_catalog.pg_type
                  Access privileges
   Schema   |  Name   | Type  | Access privileges | Column access privileges
------------+---------+-------+-------------------+--------------------------
 pg_catalog | pg_type | table | =r/postgres      +|
        |         |       | test1=r/postgres  |
(1 row)

test1=> SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_name='pg_cast';
 grantee | privilege_type
---------+----------------
 test1   | SELECT
 test1   | UPDATE
(2 rows)

test1=> update pg_cast set castcontext = 'i' where oid in ( select c.oid from pg_cast c inner join pg_type src on src.oid = c.castsource inner join pg_type tgt on tgt.oid = c.casttarget where src.typname like 'int%' and tgt.typname like 'bool%');
ERROR:  permission denied for relation pg_cast

What more should I do, to enable query execution with the test1 user?
Thanks.

A: You really should not be updating system catalogs directly. The "permission denied" error is Postgres trying to protect you from shooting yourself in the foot.
If You really want that (and if you break something, you get to keep both pieces...) start here: https://serverfault.com/questions/300123/how-to-edit-system-catalogs-in-postgresql-8-1

A: I have had similar problem updating Greenplum system catalog, the cue is:

ERROR: permission denied: "pg_filespace_entry" is a system catalog,

the solution was using the following command before I tried to modify system table:
set allow_system_table_mods='dml';


text:
Q: How to build a cheap device to determine where Wi-Fi interference is coming from? In this post, the ServerFault guys use a fancy tool to map out the WiFi spectrum under normal conditions, with a microwave running, and with a baby monitor on.  The baby monitor and microwave cause a surprising amount of interference.
Having had to deal with Wifi interference in the past, a tool like that could be very useful.  However, its price - $200 to $1000+ - is way outside my price-range.
I'd like to build something to serve a similar purpose, but my experience with building analog devices is, shall we say, non-existent.

*

*What's the cheapest way to determine where Wi-Fi interference is coming from?  My idea was rig up an old radio to somehow receive around the 2.4Ghz frequency, but I have no idea how to do that.

*How can I tell which channel has the least interference?
Please let me know if this is off-topic.  Thanks!

A: The WiSpy is based on a Chipcon (now TI) CC2500 chip, which is a general-purpose 2.4GHz digital radio.  By scanning through the channels, it can be turned into a spectrum analyzer. http://tim.cexx.org/?p=646
So you need a board with a CC2500 radio.   Search ebay for "CC2500" and you can find them for http://www.ebay.com/itm//260900652131
Here is a similar project with a Chipcon chip at a different frequency:
http://ossmann.blogspot.com/2010/03/16-pocket-spectrum-analyzer.html

A: Before you go any further with this idea, I would suggest that you try out the free software first. inSSIDer will tell you what channels are being used (by wifi routers only). This will give you a good starting point as to how much wireless router interference you are dealing with. If you truly want to do spectrum analysis I would suggest going with this tool first, at a more reasonable price of $70 (with free software). Building a analyser will take a long time especially with designing the software as well.
Good luck with this.
EDIT:
shortly after writing this I stumbled upon this article. I hope it helps.


text:
Q: UITableView: How to get heightForHeaderInSection inside viewForHeaderInSection I am creating a custom section header view for my UITableView.
But how do I get the tableHeight in my viewForHeaderInSection method? I am currently doing the below and tableHeight holds the value 0.
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (includeButton)
        return 55;
    else
        return 30;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CGFloat tableHeight = [tableView headerViewForSection:section].frame.size.height;
    ........
}

A: The two methods are in the same view controller. Just call your implementation and pass the table view and section, like so:
CGFloat tableHeight = [self tableView:tableView heightForHeaderInSection:section];

A: You are setting your table header section height based on
if (includeButton)
    return 55;
else
    return 30;

Similarly, you can do the same when you want to get the section height.
 CGFloat tableHeight = (includeButton)?55:30;

But you have to make sure that the "includeButton" exist for each section.
Hope that helps.


text:
Q: Google cloud Compute Engine refuse outer access through apache2 Today, I tried to make a blog with Google Cloud Platform.
So, I made a Computer Engine Instance and install Apache2 on Ubuntu 16.
And then, clicked the Outer IP address, but it show me "connection denied.."
Why this happen?
I allowed HTTPS % HTTP Traffic also.
And I can't find a menu like AWS's Security Group...
So, this problem irritate me...
(I'm not a English native, so documentation is so hard read.. please, give me a tip for this matter)

A: TL;DR - You need to open up ports using firewall rules to allow ingress traffic into your VMs.
Google Compute Engine (GCE) blocks all traffic to your VMs by default for the purpose of keeping your infrastructure secure. You can open up ports as needed and manage the security yourself. The default created network has few exceptions in terms of allowing traffic from other VMs in the network, but still does not allow traffic from outside the network.

Firewalls
Each VPC network has its own firewall controlling access to the
  instances.
All traffic to instances, even from other instances, is blocked by the
  firewall unless firewall rules are created to allow it. The exception
  is the default VPC network that is created automatically with each
  project. This network has certain automatically created default
  firewall rules.
For all VPC networks except the automatically created default VPC
  network, you must create any firewall rules you need. To allow
  incoming network connections on a manually created VPC network, you
  need to set up firewall rules to permit these connections. Each
  firewall rule represents a single rule that determines what
  connections are permitted to enter or leave instances. It is possible
  to have many rules and to be as general or specific with these rules
  as you need. For example, you can create a firewall rule that allows
  all traffic through port 80 to all instances, or you can create a rule
  that only allows traffic from one specific IP or IP range to one
  specific instance.
Firewall rules are connection tracking, and therefore only regulate
  the initial connection. Once a connection has been established with an
  instance, traffic is permitted in both directions over that
  connection.

Since you say apache2 package on Ubuntu, the instructions I share here will guide you on how to open up port 80 on your VM and make it accessible through the VM's public IP. You can do the same for any additional ports as needed.
Using gcloud to allow ingress traffic for tcp:80 into your VM
# Create a new firewall rule that allows INGRESS tcp:80 with VMs containing tag 'allow-tcp-80'
gcloud compute firewall-rules create rule-allow-tcp-80 --source-ranges 0.0.0.0/0 --target-tags allow-tcp-80 --allow tcp:80

# Add the 'allow-tcp-80' tag to a VM named VM_NAME
gcloud compute instances add-tags VM_NAME --tags allow-tcp-80

# If you want to list all the GCE firewall rules
gcloud compute firewall-rules list

Using Cloud Console to allow ingress traffic for tcp:80 into your VM

*

*Menu -> Networking -> Firewall Rules

*Create Firewall Rule

*Choose the following settings for the firewall rule:

*

*Name for the rule - rule-allow-tcp-80 or any other name you prefer for this firewall rule.

*Direction is ingress

*Action on match is Allow

*Targets is Specified target tags

*Target tags is allow-tcp-80

*Source IP ranges is 0.0.0.0/0 (or if you have a set of IP ranges you know will be the only ones accessing this, use them instead for stronger restriction)

*Protocols and ports is tcp:80

*Select Create button to create this firewall rule.

*Once you've created the above firewall rule you will need to add the tag allow-tcp-80 to all the instances where this rule needs to be applied. In your case:

*

*Open up the GCE VM Instances page

*Select the instance where Jenkins is running

*In the VM instance details page, select the Edit link on the very top.

*In the Network Tags box, enter allow-tcp-80 to apply the tag to this instance.

*Select Save to save the changes.

Now give it a few seconds to a few minutes for the changes to take effect and you will be able to access the jenkins web URL.
You can also go through the documentation for Firewall rules to get a better understanding of how they work and how to configure them.
WARNING: By using a source range of 0.0.0.0/0, you're opening up the port on the VM to the entire internet. This lets clients anywhere in the world to connect to the application running on this port. Be fully aware of the security implications of doing this.


text:
Q: Unexpected behavior of Dropdown field when using of Slideup and Slidedown jQuery function on another field I am getting an unexpected behavior on my dropdown input field when the Slideup jquery function works simultaneously. Requirement is that when user writes in the CustomerName text field, a message should appear above it and when user comes out of that field the message should disappear. Everything works fine but when I click on the dropdown box to select a state, I am getting a gap between the dropdown field and the selectable List. How can I remove this gap?
HTML Code-

     If customer is an active , please contact your.

                            Customer Name

                            <input id="txtCustomerNamer" type="text" data-ng-model="CustomerInfo.CustomerName" class="form-control" maxlength="60" placeholder="Customer Name" />

                        Zip Code

                        <input id="txtZipcode" type="text" data-ng-model="CustomerInfo.ZipCode" class="form-control" placeholder="Zip Code" maxlength="5" />

                        State

                        <select id="ddlSitusStates" class="form-control dropdown" data-ng-model="CustomerInfo.SelectedSitusState" title="{{CustomerInfo.SelectedSitusState.SitusStateName}}"
                            data-ng-options="situsState.SitusStateName for situsState in SitusStates track by situsState.SitusStateId">
                            <option value="">Select</option>
                        </select>

jquery code-
$(document).ready(function () {
$("#txtCustomerNamer").focusin(function () {
    $("#Warning-alert").slideDown(500);
   });
$("#txtCustomerNamer").focusout(function () {
    $("#Warning-alert").show().slideUp(200);
   });
});

Image with Slidedown function-

Image with Slideup function-


text:
Q: Why Sceneform 1.17.1 displays only audio and not video corectly? I am creating an AR app using Sceneform, and no matter what I have tried this far Sceneform doesn't display a video correctly over an image. This is the result I get when the camera detects the image:
The Video Image that I get
Here is the code I have on the corresponding class:
texture = new ExternalTexture();
    mediaPlayer = MediaPlayer.create(this, R.raw.video);
    mediaPlayer.setSurface(texture.getSurface());
    mediaPlayer.setLooping(true);

    ModelRenderable
            .builder()
            .setSource(this, Uri.parse("video_screen.sfb"))
            .build()
            .thenAccept(modelRenderable -> {
                renderable = modelRenderable;
                modelRenderable.getMaterial().setExternalTexture("videoTexture",
                        texture);
                modelRenderable.getMaterial().setFloat4("keyColor",
                        new Color(0.01843f, 1f, 0.098f));
            })
            .exceptionally(
                    throwable -> {
                        Toast toast = Toast.makeText(this, "Unable to load video renderable", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                        return null;
                    });

    arFragment = (com.stratos.syrostownhall.CustomArFragment)getSupportFragmentManager().findFragmentById(R.id.arFragment);

    if (arFragment != null) {
        scene = arFragment.getArSceneView().getScene();
    }

    scene.addOnUpdateListener(this::onUpdate);

}

private void onUpdate(FrameTime frameTime) {

    if (isImageDetected)
        return;

    Frame frame = arFragment.getArSceneView().getArFrame();

    Collection<AugmentedImage> augmentedImages =
            frame != null ? frame.getUpdatedTrackables(AugmentedImage.class) : null;

    for (AugmentedImage painting : Objects.requireNonNull(augmentedImages)) {
        if (painting.getTrackingState() == TrackingState.TRACKING) {

            if (painting.getName().equals("painting")) {

                isImageDetected = true;

                playVideo(painting.createAnchor(painting.getCenterPose()), painting.getExtentX(),
                        painting.getExtentZ());

                break;
            }

        }
    }

}

private void playVideo(Anchor anchor, float extentX, float extentZ) {

    mediaPlayer.start();

    AnchorNode anchorNode = new AnchorNode(anchor);

    texture.getSurfaceTexture().setOnFrameAvailableListener(surfaceTexture -> {
        anchorNode.setRenderable(renderable);
        texture.getSurfaceTexture().setOnFrameAvailableListener(null);
    });

    anchorNode.setWorldScale(new Vector3(extentX, 1f, extentZ));

    scene.addChild(anchorNode);

}

Also, I add the asset manually using the following syntax:
sceneform.asset ('sampledata/video_screen.obj',
        'default',
        'sampledata/video_screen.sfa',
        'src/main/assets/video_screen')

A: The problem was caused by the video_screen.sfb file.
If anyone else is facing the same issue try using the following video_screen file:
https://github.com/heyletscode/Play-Video-On-Augmented-Image/blob/master/Project/app/src/main/assets/video_screen.sfb


text:
Q: Does creating an object directly in a vector, and then removing it from the vector, calls to a destructor? Say i have a class named test, and a vector
std::vector<test> Tests;

If i execute this code:
Tests.push_back(test());

and then
Tests.pop_back();

What happens to the test object? Is its destructor being called upon?

A: This example might show a little bit better what happens.
Live demo here : https://onlinegdb.com/c6-N-vyPc

Output will be :
Creating first vector (push_back)
>>>> Test constructor called
>>>> Test move constructor called
<<<< Test destructor called
Destroying first vector
<<<< Test destructor called

Creating second vector (emplace_back)
>>>> Test constructor called
Destroying second vector
<<<< Test destructor called

Example code :
#include <iostream>
#include <vector>

class Test
{
public:
    Test()
    {
        std::cout << ">>>> Test constructor called\n";
    }

    Test(const Test&)
    {
        std::cout << ">>>> Test copy constructor called\n";
    }

    Test(Test&&)
    {
        std::cout << ">>>> Test move constructor called\n";
    }

    ~Test()
    {
        std::cout << "<<<< Test destructor called\n";
    }
};

int main()
{
    // scope to manage life cycle of vec1
    {
        std::cout << "\nCreating first vector (push_back)\n";
        std::vector<Test> vec1;
        vec1.push_back(Test{});
        std::cout << "Destroying first vector\n";
    }

    // scope to manage life cycle of vec2
    {
        std::cout << "\nCreating second vector (emplace_back)\n";
        std::vector<Test> vec2;
        vec2.emplace_back();
        std::cout << "Destroying second vector\n";
    }

    return 0;
}


text:
Q: QDockWidget -- keep widgets as close as possible when resizing window I have a QDockWidget containing several QGroupBoxes. (The content of the QGroupBoxes is shown/hidden upon mousePressEvent.) I'm looking for a way to keep the QGroupBoxes positioned as tightly together as possible, preferably at the top of the DockWidget. It should look something like this:

However, when increasing the size of the DockWidget, the GroupBoxes drift apart:

...which is very convenient in most cases, I know. But is there a way to override this behavior and get a nice, expandable, list-like grouping of Widgets?
The DockWidget contains a QGroupBox; the QGroupBoxes 'Foo', 'Bar' and 'Baz' are added to that box's QVBoxLayout.

A: Try adding an expanding spacer to the end of the vbox:
vbox.addStretch()


text:
Q: Regular Expression to split 'VS Teamnames' string  I have scraped titles from YouTube videos. Which I have reduced to strings similar to these:
string1 = "Red~VS~Blue";
string2 = "oRange v wHite";
string3 = "black knights verses purple people";

team0 = string.split(regexp)[0];
team1 = string.split(regexp)[1];

I am trying to use Javascript's string.split method to break up each string into an array of two teamnames. It doesn't matter if spaces or delimiters get through, as they can be easily cleaned later. I also want the regexps to have some basic typo catching functionality.
Regular Expressions:
regexp = /\Wv(s|\W)/i; \\Should match " v " or " vs", gives 3 results instead of 2
regexp = /\Wv[s\W]/i; \\Works as I thought the above should
regexp = /\W(vs|v\W|vers[eu]s)/i \\attempt at dealing with typos, doesn't work

When I add more parenthesis () instead of encasing whatever I've written, it tends to add extra results to the split. I've read these tutorials on regexps here and here and a few answers on stackoverflow but I can't find anything relevant to help me. How can I resolve this issue?

A: result = subject.split(/\W+v(?:ers[ue])?s?\W+/i);

correctly splits all your example strings.
Explanation:
\W+        # Match one or more non-word characters
v          # Match v
(?:        # followed by
 ers[ue]   # ersu or erse
)?         # (optionally)
s?         # followed by s (optionally)
\W+        # Match one or more non-word characters

This also matches versu or verse, though.


text:
Q: Concat fields into one I have this query below:
var query = {
    $and:
    [
        {
            uf:
            {
                $exists: true,
                $ne: ""
            }
        },
        {
            municipio:
            {
                $exists: true,
                $ne: ""
            }
        },
        {
            $or:
                [
                    {
                        email:
                        {
                            $exists: true,
                            $ne: ""
                        }
                    },
                    {
                        telefone:
                        {
                            $exists: true,
                            $ne: ""
                        }
                    }
                ]
        },
    ]
}

var mod = {
    atividade_principal: 1,
    $concat: [
        "$logradouro", ", ", "$numero", " - ", "$bairro", ", ", "$municipio", " - ", "$uf", ", ", "$cep",
    ],
    telefone: 1,
    email: 1,
    qsa: 1,
    nome: 1,
    natureza_juridica: 1,
    tipo: 1
}

db.empresas.find(query, mod).limit(1000);

and I want to concat this line:
$concat: [
    "$logradouro", ", ", "$numero", " - ", "$bairro", ", ", "$municipio", " - ", "$uf", ", ", "$cep",
]

But as what i was seeing that it is not allowed in find() function, but I have no idea how to use aggregate to do that, because aggregate framework is showing that what it allows is get many documents and transform them into a one document grouping all the other documents, if I am wrong, please clarify me.
Thank you!!!

A: There is no such difference between find and aggregate function. Aggregation is just used to reshape the data nothing else. And there are some operators available to reshape that data in aggregate function.
In find query first parameter is for filter and the second one is for projection and the same role $match and $project do here in aggregation
const query = {
  "$and": [
    { "uf": { "$exists": true, "$ne": "" } },
    { "municipio": { "$exists": true, "$ne": "" }},
    {
      "$or": [
        { "email": { "$exists": true, "$ne": "" }},
        { "telefone": { "$exists": true, "$ne": "" }}
      ]
    }
  ]
}

const projection = {
  "atividade_principal": 1,
  "concatinatedField": { "$concat": ["$logradouro", ", ", "$numero", " - ", "$bairro", ", ", "$municipio", " - ", "$uf", ",", "$cep"] },
  "telefone": 1,
  "email": 1,
  "qsa": 1,
  "nome": 1,
  "natureza_juridica": 1,
  "tipo": 1
}

db.empresas.aggregate([
  { "$match": query },
  { "$limit": 1000 },
  { "$project": projection }
])


text:
Q: Should I use .gitignore for Laravel? I am wondering if it is an acceptable practice NOT to use .gitignore entirely and commit everything there is, at least for small to medium projects.
Laravel, as any framework I can imagine, has a lot of dependencies so they are set up to be ignored by git. This is what my default .gitignore file looks like:
/vendor
/node_modules
/public/storage
Homestead.yaml
Homestead.json
.env

I understand that vendor and node_modules contain the dependencies. Homestead files are local machine settings, and .env contains environment settings and differs between local and remote servers. I am not sure what storage has in it.
I ran into a problem when I pulled a lot of dependencies, which I haven't kept a good track of, and my node_modules and vendor directories exploded into 1 gb with 150,000 files. I quickly realized that it was a mistake and tried to roll back to a previous version. That, of course, failed because those two folders weren't tracked.
After spending a day rebuilding my project from scratch, I am now tempted to delete all .gitignore files from my Laravel project. Given that I only use git locally and don't push to live server, is it a good idea to commit everything? Does anyone else do that?

A: Two part answer.
The explosion
You mentioned that your vendor/node_modules folders exploded in size. Even though you don't have them in version control - if you are using composer and npm correctly (by using the --save directive for npm), all modules should be listed in composer.json and package.json respectively. Meaning even if the installed libraries (in vendor + node_modules) weren't in version control, the package.json and composer.json should be - meaning you should be able to go back through time, and install the packages at that point in time using your composer/package jsons.
Should I...
Second part to this answer is should you include vendor/node_modules in version control? This is a fair question, and one often asked. I think ultimately it depends on your intention to deploy.
Do you have essentially unlimited space on your origin (github, bitbucket, etc) and you want your deployment to be a simple super git push to your production version? You can probably just commit everything, including vendor libraries. That way you have complete control of what is going up to your server.
Realistically, you might need to php artisan migrate when you push, so in turn, you might start to consider git hooks, and the process starts to become a bit more complex (but arguably better/scalable/robust). With those hooks in place, you could start to look at running composer install + npm install against the package.json and composer.json files (without the entire vendor libraries in git). If you go this avenue, you want to make sure your composer/package jsons are nice and locked down - no '3.x.x' version numbers - you want locked down versions that you know work and have been tested.

A: Dependencies
You generally should gitignore dependencies. (See this FAQ from Composer docs). If you wanted to rollback to a previous version, you can just remove the vendor / node_modules folders, and run composer install / npm install again to install the dependencies inside the composer.json / package.json of that specific commit.
.env file
For the .env file, aside from the fact that the settings differ between servers, it also contains private information such as database credentials, so you should gitignore that as well unless you're absolutely certain you won't be pushing it to some place that other people can see (e.g. a public GitHub repository).
storage folder
The storage folder is usually where things like uploaded files are saved and it depends on your application if you should ignore it or not.


text:
Q: How to combine multiple sed commands into one I have 4 different sed commands which I am running on a file. And in order to tune in the performance of these 4 commands, I want to combine them into one.
Each command is a complex command with -E switch. Searched many many forums but could not get my specific answer.
sed -i -E ':a; s/('"$search_str"'X*)[^X&]/\1X/; ta' "$newfile"
sed -i -E '/[<]ExtData[>?" "]/{:a; /Name=/{/Name="'"$nvp_list_ORed"'"/!b}; /Value=/bb; n; ba; :b; s/(Value="X*)[^X"]/\1X/; tb; }' "$newfile"
sed -i -E ':a; s/('"$search_str1"'X*)[^X\<]/\1X/; ta' "$newfile"
sed -i -E ':a; s/('"$search_str2"'X*)[^X\/]/\1X/; ta' "$newfile"

And i want to combine them say something like

sed -i -E 'command1' -e 'command2' -e 'command3' -e 'command4'
  "$newfile"

But it is not working. Because may be -E and -e can't be combine.
Please let me know.
Thanks !! Puneet

A: -E means "extended regex" and is a standalone flag, -e means "expression" and must be followed by a sed expression.
You can combine them, but each of your sed expression must be preceded by a -e if you want multiple of them, which isn't the case of your first one.
sed -i -E -e 'command1' -e 'command2' -e 'command3' -e 'command4' "$newfile"

A second option is to write each command in the same expression :
sed -i -E 'command1;command2;command3;command4' "$newfile"

However, since you're using labels I wouldn't rely on this option ; some implementations may not support it as John1024 pointed out.
Lastly, as mentionned by Mad Physicist, you can write your sed expressions to a file which you'll reference through the -f option.
The file must contain a single sed expression by line (you can write multiline expressions by suffixing each line but the last by a \, thus escaping the line-feed).

A: Simply pipe them:
sed -E 'A' file | sed -E 'B' | ... >file.tmp && mv file.tmp file

A: As @Aaron observed, if you want to give multiple separate expressions to sed, you must designate them as -e options; they will be combined.  You can also combine a bunch of expressions into one by separating the pieces with semicolons.
Your case is a bit special however: your particular expressions use labels and branch instructions, with one of the label names (a) repeated in each expression.  In order to combine these, each label should be distinct, and each branch (either conditional and absolute) should specify the correct label.  That would look something like this:
sed -i -E \
    -e ':a1; s/('"$search_str"'X*)[^X&]/\1X/; ta1' \
    -e '/[<]ExtData[>?" "]/ {:a2; /Name=/ {/Name="'"$nvp_list_ORed"'"/ !b}; /Value=/ bb2; n; ba2; :b2; s/(Value="X*)[^X"]/\1X/; tb2; }' \
    -e ':a3; s/('"$search_str1"'X*)[^X\<]/\1X/; ta3' \
    -e ':a4; s/('"$search_str2"'X*)[^X\/]/\1X/; ta4' \
    "$newfile"

Do note that even with proper quoting from a shell perspsective, which you appear to have, your approach will not do what you expect if the value of any of the interpolated shell variables contains a regex metacharacter.

A: Warning: It is not always possible to combine multiple sed scripts into a single one without change. Sometimes you might have to do a redesign of your algorithm.

Sed makes has two concepts of memory. The pattern space and the hold space. Concatenation is only working if these two spaces are identical in both sed commands. Below you find an example where the pattern space changes:
$ echo aa | sed -e 's/./&\n/' | sed -e '1s/a/b/g'
b
a
$ echo aa | sed -e 's/./&\n/' -e '1s/a/b/g'
b
b
$ echo aa | gsed -e 's/./&\n/;1s/a/b/g'
b
b

In the original pipeline, the first sed command works on the pattern space aa, while the second script's pattern space is only a.


text:
Q: Best practice for incrementing a number from within a function in Python Within my function I want to increment various counts which are established outside of the function. These are count for different scenarios (e.g. count of successful completions, and various forms of errors). In total I have about 10 different counts i use.
While Python allows e.g. appending values to lists which were established outside of the function (e.g. list.append(new_running_count), trying to increment a number with the following code running_count = running_count + 1 throws up the error "local variable running_count referenced before assignment".
What is the most python way of dealing with this? Are global variables / passing the integers into the function the only way of doing it? (i am reluctant to do either, since passing and then returning 10 counts into the function would be clumberson, and also want to avoid global variables)

A: Clearly, if you have ten counters, it is better to put them in a dictionary (or a list, but dictionaries have meaningful keys).
To use the dictionary in your function, the three usual solutions are global variable, argument or class variable. Argument is probably the clearer way.


text:
Q: Cloud functions for firebase - Function structure with several promises being returned Need to know if my function is well structured and returning promises correctly. I am handling new and deleted data with a main conditional if statement. If data exists I am performing a database set and returning a promise return ProposalsRef.child(recipient).set. If data does not exists I return return ProposalsRef.once('value').... Whenever the function is triggered it will return only one promise (this way it should never timeout). Also I am implementing an else{return null;} at the end just to avoid timeouts (not sure if this is a good practice)
exports.ObserveJobs = functions.database.ref("/jobs/{jobid}").onWrite((event) => {
    const jobid = event.params.jobid;
    if (event.data.exists() && !event.data.previous.exists()) {
        const recipient = event.data.child("recipient").val();
        if (recipient !== null) {
            let ProposalsRef = admin.database().ref(`proposals/${jobid}`);
            return ProposalsRef.child(recipient).set({
                budget: event.data.child("budget").val(),
                description: event.data.child("description").val(),
                ischat: false,
                isinvitation: true,
                timing: event.data.child("timing").val(),
            });
        };
    } else if (!event.data.exists() && event.data.previous.exists()) {
        let ProposalsRef = admin.database().ref(`proposals/${jobid}`);
        return ProposalsRef.once('value').then(snapshot => {
            if (snapshot.hasChildren()) {
                const updates = {};
                snapshot.forEach(function(child) {
                    updates[child.key] = null;
                });
                return ProposalsRef.update(updates);
            }
        });
    }else{
      return null;
    };
});

I would also like to know, let's say I would have to perform several database operations instead of one. See example bellow:
return contractRef.once('value').then(snapshot => {
    let client = snapshot.child("contractor").val();
    let freelancer = snapshot.child("talent").val();
    const clientRef = admin.database().ref(`users/${client}`);
    const freelancerRef = admin.database().ref(`users/${freelancer}`);
    clientRef.child("/account/jobcount").transaction(current => {
        return (current || 0) + 1;
    });
    freelancerRef.child("/account/jobcount").transaction(current => {
        return (current || 0) + 1;
    });
    clientRef.child("/notifications").push({
      timestamp: admin.database.ServerValue.TIMESTAMP,
      key: contractid,
      type: 4
    });
    freelancerRef.child("/notifications").push({
      timestamp: admin.database.ServerValue.TIMESTAMP,
      key: contractid,
      type: 4
    });
});

I am returning only return contractRef... promise, should promises within contractRef be returned as well (freelancerRef, clientRef)? if so, should I create an array of promises and then return Promise.all(arrayOfProimises); or I can return the promises individually return freelancerRef.child("/notifications").push({...

A: Promise.all([...]) will create a single promise that is fulfilled only when all the other individual promises are fulfilled.  This is what you should return from then (which will should then be returned by the entire function) to make sure it waits for all the work to complete before cleaning up.  You won't be able to return individual promises separately.


text:
Q: Should authors of a code-golf question not refer to the sources for their entries? I (as a lot of people) enjoy the high-quality code-golf questions posted by user LiraNuna, I've even participated a few times.
I interpreted those questions as 'completely new/original' entries but then found a lot of them were just copied over verbatim (including input / output examples sometimes) from other sites. I think at least a reference (link) to the source should be included.
Consider the following links (I'll give the Stackoverflow link and what I consider the source):
Sierpinski's Triangle:
SO: Code Golf: Sierpinski's Triangle
SOURCE: http://golf.shinh.org/p.rb?Sierpinski+Fractal
Morse code:
SO: Convert a string into Morse code
SOURCE: http://golf.shinh.org/p.rb?Morse+decode
The Wave:
SO: Code Golf: The wave
SOURCE: http://golf.shinh.org/p.rb?wave+line
Musical Notes:
SO: Code Golf: Musical Notes
SOURCE: http://codegolf.com/musical-score
Seven Segments
SO: Code Golf: Seven Segments
SOURCE: http://golf.shinh.org/p.rb?LED+counter
...
What do you guys think?

A: The wave: I will admit this one was a direct copy - because it was, imo, a good question right in the path I was thinking of. This was the only question I deliberately copy-n-pasted. Someone commented on the source during the challenge was taking place and that sparked many other solutions that were semi-copied from there.
Morse code: That was my first question, and was completely original - nothing inspired it. I did not know of golf.shinh.org when I started.
Musical notes: This was indeed inspired by the link you gave, but it's reverse, not to mention the note structure is different as well (that has impact on the solution by a large degree).
Sierpinski's Triangle: Was not deliberately copied from golf.shinh.org, it was my own idea and I actually ASCII'd the solutions in gedit. It was one of my first ideas (it was about to be posted after Morse code) and was saved for an 'emergency' I-ran-out-of-ideas.
Seven Segments: Same as Morse code - I was not aware of golf.shinh.org at the time. Also of note that this question is reversed, which changes the answer by a really large margin. It was also my first and only question I added a restriction, and people did not like that (I was trying to discourage the use of figlet related libraries/services).

As for source attribution for code golf - as much as I love giving credit where it's due, I think it ruins the fun. People go - check out - and ruin the solution for themselves. Mostly because those sites contain answers already. While not a direct copy of challenges (regardless of 'The wave'), I think that it would spoil the fun for those who really want to try. Remember humans - by nature - are very curious creatures, and saying stuff like "Just don't click the link" will encourage clicking even further :)
As for the other questions - they are completely original - Lasers, Beehive, Playing cubes, Hourglass and Spider webs - all original, and were inspired by my personal life experiences.
If the community does, however, "force" me to put sources, I will change every question that has a semi-direct relationship that I know of, will get added and posted in the future.
Summary:
Personally I would hate it if I was forced to put a link to 'related' questions - I think it'll spoil the fun.
I only knew of two direct attribution links - The wave (was indeed a direct copy) and Musical Notes (Provided inspiration and guideline, I had an early idea about notes already).
Another thing to note is that The Wave has the most answers of all my questions (at time of writing)! This confirms my concern that giving the source (if applicable) will ruin fun and increase participation at a cost of ruining people's fun.

A: Being a student at a university, of course I agree with Bill's answer: attribution is important. Then again, LiraNuna's concerns w.r.t. human nature are justified.
So we are now in a situation where the right thing to do spoils the fun (at least in part). I would therefore like to toss an alternative coin, as a middle ground between attribution and non-attribution: why not add a link to any source of inspiration after a week (or a similar time span)? Most people will have posted an answer by then, yet any late visitors (including users of golf.shinh.org) will see the attribution.
And indeed it's true that after some time very few people visit these code-golf questions, this late answer of mine is the shortest solution in that thread, yet still has received no up-votes at all...

A: I'd leave a comment for the OP saying that they should add the link showing where they got the original idea. If they don't respond, and you've got enough Rep to edit the question, I say add the link in yourself.

A: I've generally considered any plagiarized and/or unattributed content on SO to be grounds for a "flag for moderator attention", and if in a question, "vote to close as blatantly offensive" (with an explanatory comment). This includes links to copyright violations, as well as pasted content.

A: Yes, they should include a link.  Any content, whether question or answer, that you copy or paraphrase from another site should be cited.  It's just good manners to give credit to the original authors.


text:
Q: Does Rust define what happens when you cast a non-finite float to an integer? I believe that traditionally, all degenerate floats are referred to as "NaN", but Rust seems to distinguish between three kinds of degenerate floats: +inf, -inf, and nan (that's why I use the term "non-finite" in the title instead of "nan" or "infinite").
What happens when you try to cast these to an integer, such as u64? Is there a defined behavior? If so, what is the defined behavior?
I would assume that this is undefined. A 7 year old thread on reddit says it's undefined, but things might have changed since then.
In "Rust by Example", it seems to say that nan gets converted to 0.
Based on my experiments, it does not panic in practice, so unless there is a blatant bug in the compiler, I assume the behavior is not defined as "panics".

A: This is defined in the Rust Reference here as:

Numeric cast
Casting from a float to an integer will round the float towards zero

*

*NaN will return 0

*Values larger than the maximum integer value, including INFINITY,
will saturate to the maximum value of the integer type.

*Values smaller than the minimum integer value, including
NEG_INFINITY, will saturate to the minimum value of the integer type.


text:
Q: Sampling distribution need not be bell shaped? Considering the following sample $X = $  [32.5,  31.7,  29.2,  28.8,  29. ,  28.9,  29.9,  30.4,  26.9,  26.5]
I planned to evaluate the hypothesis of this sample having been generated from a normal distribution with an hypothetic $\mu$ and $sigma^2$ trough the use of the Kolmogorov Smirnov test statistic.
My strategy was to solve this problem using bootstrapping, so for each simulation I sampled from $X$ and computed the functional $T(X^*)$ where $T$ is the maximum distance from the empirical distribution of $X^*$ and the theoretical distribution of the distribution I considered.
After all the simulations were through I had enough data to plot the empirical distribution of the t statistic, which I am right to call sampling distribution right?!
But when plotting an histogram of this same sampling distribution of the kolmogorov smirnov test statistic I got the following graphic:

My sample size is very low and some discretization was made to the observation, fixed precision.
Is this distribution ok and perfectly normal? I am trying to understand if this can happen of (I speculate that it can), or if I messed up during the implementation of the ks-test.
Here's my implementation of the ks-test in R:
$H_0: Sample ~ N(\mu, \sigma^2)$
kstest = function(Xsample, mu, var) {

  n = length(Xsample)
  X_sample = sort(Xsample)

  #List of differences
  diffs = numeric(2*n)

  for(j in 1:n){
    f = pnorm(X_sample[j],mean=mu,sd=sqrt(var))
    diffs[j*2-1] = j/n - f
    diffs[j*2] = f - (j - 1)/n
  }
  return(max(diffs))
}

A: As @whuber suggested the bootstrap distribution, sampling distribution, can exhibit strong multimodality and points of discontinuity. For the sample mean there are only $C^{2N-1}_{N-1}$ possible values that $\bar{X}^*$ can take, this means that such a small sample as mine will have a very discrete behaviour like above. Fortunately as $N \rightarrow \infty$ the sampling distribution becomes more continuous.
I solved the problem by using the parametric bootstrap instead of the non parametric strategy I was using before. That is, I assume that X is normally distributed and estimate the distribution parameters through maximum likelihood. Then at each bootstrap I sample from the estimated distribution and apply the kstest to that sample. The sampling distribution becomes much more well behaved using this alternate strategy:

This really helped me understand concepts such as sampling distribution, parametric and non parametric bootstrap much better. For reference, in cases such that no prior distribution can be assumed and we are forced to use a non parametric bootstrap then we can also use a smoothed bootstrap to force a more or less well behaved sampling distribution.


text:
Q: Rails Tutorial: nokogiri-1.5.2 error on bundle install After working through the RVM setup, rspec and guard sections of chapter 3 of the Ruby on Rails Tutorial, whenever I run bundle install I get the following error dump:
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- mkmf (LoadError)
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from extconf.rb:5:in `<main>'

Gem files will remain installed in /home/dan/.bundler/tmp/17577/gems/nokogiri-1.5.2 for inspection.
Results logged to /home/dan/.bundler/tmp/17577/gems/nokogiri-1.5.2/ext/nokogiri/gem_make.out
An error occured while installing nokogiri (1.5.2), and Bundler cannot continue.
Make sure that `gem install nokogiri -v '1.5.2'` succeeds before bundling.

In the gem_make.out:
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file --mkmf (LoadError)
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from extconf.rb:5:in `<main>'

I've been debugging for a while now and I think I'm stuck. Help would be GREATLY appreciated!

A: You need the header files for compiling extension modules for Ruby.
You can get the proper version for your version of ruby with:
sudo aptitude install ruby-dev


text:
Q: Is there a way to store spawn object (child_process) in database and reuse it? Why I need this?

*

*Client make request to server

*Server receive request, starts python script with spawn (child_process)

*If python script needs more information to proceed running, I must send user email with link which leads to page with only one input field

*When user fill that, I must continue SAME process (running script) and enter that in command line with ls = spawn('command', args) and then ls.stdin.write()

How I can do this? My idea is, to get object from
const { spawn } = require('child_process');

const ls = spawn('command', [args]);
insertInDb(JSON.stringify(ls));

And then use it with
const ls = JSON.parse(databaseInput);

ls.stdin.write(input);

But it doesn't work.

A: No, but I can't imagine a scenario in which you would want to. What if your user emails back tomorrow? Or next week? Or never? You just have these dangling python processes clogging up your system.
If you're positive you'll get quick feedback you can talk your python script via a shared file descriptor:
const cp = spawn(cmd,args,{
  stdio:['pipe','pipe','pipe','pipe']
});
cp.stdio[3].on('data',(data)=>{
  // data from python's fd 3
});
cp.stdio[3].write('foobar'); // write to python's fd 3

But you almost certainly should just have two different python scripts.


text:
Q: How to support upload on PHP installed with IIS 7.0? I install PHP on IIS 7.0 at Windows Server 2008 and Windows 7. I have setup Wordpress and Joomla and config finished.
But I find I can not upload any file with PHP program but okay under ASP.NET.
I had,

*

*Config the every permission with write of Upload folder to IUSR and IIS_USRS

*Config the PHP.ini with file_uploads = On

*Setup a temp directory and config for every permission with write.  upload_tmp_dir = "E:\Webware\PHP.Upload.Tmp"

*Reboot IIS

But I still can not upload file via PHP program.

A: When you run phpinfo() what is the value of your upload_tmp_dir?
I'd wager your upload_tmp_dir variable in the [PHP] configuration section of php.ini file is being overwritten in the [WebPIChanges] configuration section, towards the end of your php.ini file...
Depending on how you installed PHP, there may be two upload_tmp_dir variables in your php.ini file, and if the the second one is set, it will overwrite the first.

A: Take a look at this site, it may help you: http://www.radinks.com/upload/config.php
Also i suggest you to don't modify upload_temp_dir


text:
Q: Comparing $n!$ and $(\frac n3)^n$
Compare which of $n!$ and $\left(\dfrac n3\right)^n$ will stay larger for $n$ large enough?

The answer is undoubtedly $n!>\left(\dfrac n3\right)^n$ and I'm trying to prove this.
My first approach was to prove that $$n+1>\dfrac{(n+1)^{n+1}}{3n^n}\tag{1}$$ for $n$ large enough. This could establish the inductive relationship $$n!>\left(\dfrac n3\right)^n\implies(n+1)!>\left(\dfrac{n+1}3\right)^{n+1}$$thus solve the problem. (Geogebra graph told me this is true) However I found $(1)$ hard to prove.

My second approach was the Stirling formula$$n!\approx\sqrt{2\pi n}\left(\frac ne\right)^n.$$So$$n!>\left(\dfrac n3\right)^n\Leftrightarrow\sqrt[2n~~~]{2\pi n}>\frac e3.$$
I again failed to complete the proof. I'm now out of ideas so I need help.

A: Rearranging (1) yields
$$3 > \left(1 + \frac{1}{n}\right)^n.$$
The right-hand side converges to $e$ as $n \to \infty$.


text:
Q: Clarification regarding Pending Intent Say I have an application A that uses an intent to launch an application B's component. Then if I wrap that intent into a pending intent and pass it to an application C, does this mean that app C will launch app B's component, using app A's permissions?

A: Yes, you have the flow correctly described. Note that App B is not specifically involved in this flow. The Intent could point to a component in App A, B, C, D, E, etc. The only specific parties are:

*

*App C, which sends the PendingIntent, and

*App A, which created the PendingIntent and therefore is considered the actual originator of the request for security purposes


text:
Q: Declaring a private method static Can there ever be a good reason to declare a private method static if no other methods within the class that are public static call it?  Even if the method does not require any instance variables, e.g. adds two input parameters together.  Is there any overhead to declaring a method static, which, in a case like this would make it worthwhile to not be static even if it can be run independent of an instance of the class in which it resides?

A: Instance methods have the overhead of having to pass the this reference to the method, even if it's not used in the method, so if anything calling a static method is cheaper than calling an instance method.
Optimization-wise it doesn't add anything: the method is already private so the JVM is free to inline it if it wants to. Being static or non-static makes no difference.
Design-wise: it's a private method, so you are free to do whatever you want.

A: The reasons for declaring a method static or not have nothing to do with whether it's private. You can declare it static if it doesn't refer to any instance variables, and some may consider it good practice to do so.