text:
Q: Owl Carousel addItem issue I'm currently using Owl Carousel and populating via AJAX. When I use the addItem method Owl Carousel goes to the first item, but I want the carousel to go to the item that was added. So to get that I used jump to, but the problem here is the carousel goes to first and then jumps to added item. I just need the carousel to go to latest item.

A: i had the same issue so i used lazyLoad : true,
I resolved it using this code below:
var itemBlock ='<div> slider item </div>'; \\ add your code in ajax

$('#owl-slider').html(itemBlock).trigger('create');

$("#owl-slider").owlCarousel({
        // Most important owl features
        ltr:true,
        items : 5,
        itemsCustom : false,
        itemsDesktop : [1199,8],
        itemsDesktopSmall : [980,5],
        itemsTablet: [768,4],
        itemsTabletSmall: false,
        itemsMobile : [479,2],
        singleItem : false,
        itemsScaleUp : false,

        //Basic Speeds
        slideSpeed : 200,
        paginationSpeed : 800,
        rewindSpeed : 1000,

        //Autoplay
        autoPlay : false,
        stopOnHover : false,

        // Navigation
        navigation : false,
        navigationText : ["prev","next"],
        rewindNav : true,
        scrollPerPage : false,

        //Pagination
        pagination : false,
        paginationNumbers: false,

        // Responsive
        responsive: true,
        responsiveRefreshRate : 200,
        responsiveBaseWidth: window,

        // CSS Styles
        baseClass : "owl-carousel",
        theme : "owl-theme",

        //Lazy load
        lazyLoad : true,
        lazyFollow : true,
        lazyEffect : "fade",

        //Auto height
        autoHeight : false,

        //JSON
        jsonPath : false,
        jsonSuccess : false,

        //Mouse Events
        dragBeforeAnimFinish : true,
        mouseDrag : true,
        touchDrag : true,

        //Transitions
        transitionStyle : false,

        // Other
        addClassActive : false,
        activeClass:true,

        //Callbacks
        beforeUpdate : false,
        afterUpdate : false,
        beforeInit: false,
        afterInit: false,
        beforeMove: false,
        afterMove: false,
        afterAction: false,
        startDragging : false,
        afterLazyLoad : false
    });

var owls = $("#owl-slider").data('owlCarousel');
owls.goTo($('.item').length);

A: By stepping through the execution of addItem() I've noticed that the entire carousel is "destroyed" first then rebuilt with the new item added. So for now there is no real solution to your problem.
If you wish to jump to the latest item while keeping the sliding animation (not starting from the first then whoosh to the last), try jumpTo() to the second last item, set a timeout of like 10 milliseconds (will not work if omitted in my case), then call next().
owl.jumpTo(/*second last item index*/);
setTimeout(function() {
  owl.next();
}, 10);


text:
Q: What options are there for visualising class relationships in a Python program I am maintaining a Python program, and am struggling to understand the relationships between the various classes. I think it would be helpful to see a diagram of how the classes interact.
What options are there available that might allow me to do this?

A: Just my 2 cents.
Case tools like Enterprise Architect can generate class diagrams from python code, however for the purpose of understanding I prefer to coarsely model the classes and relationships by hand.
I too use UML when I want to understand new code, to get a coarse overview of the collaborations between classes, and to get a view of inheritance heirachies.
Most IDEs have means to explore the code, but I find small cohesive UML diagrams easier to digest and memorize.
I also find domain models easier to understand when on a class diagram.

A: If you are seeking IDEs that have that feature, then:

*

*Komodo

*Pydev for eclipse

A: gaphor has a feature to import python module and generate uml class diagrams, anyway it's not so good.
Anyway, code analysis tools on python don't work very well since no one can "predict" which arguments will be passed (or returned) by functions and so on. Most of them "guess" the type passed.
Hoping that python 3 with the "function annotation" can solve this sort of "problem"

A: Great question! Depending on how hands-on you are, you can consider using the trace module on a run of your code.
python -m trace -T yourprogram.py

Will give you who-called-who information. You can either parse this, or write some code that uses trace programatically to extract your call graph.
Once that's done, a bit of dot hacking, and you've got a diagram. Once you've done this, it'd make a cool blog post about what you did and how it worked out.

A: Check out epydoc. It's generally thought of as a documentation generator, but check out the (automatically generated) graph in this example:
http://epydoc.sourceforge.net/api/epydoc.apidoc.RoutineDoc-class.html

A: If it's Django you can also do
./manage.py graph_models

if you are using Django Command Extenstions

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change song using jquery and  I've been trying to create a webpage that plays several different songs when the user clicks a button. I've been using the value attribute on buttons to store what the name of the song to send to the audio player. When the button is clicked the song stays as the default, any help would be appreciated!
HTML
<button value="newsong.mp3">NEW SONG</button>
<audio controls id="player" src="sound/default.mp3" autoplay></audio>

Javascript
var song;
$(document).ready(function(){
  $("button").click(function(){
    song=$(this).attr("value");
    $("#player").attr("src","sound/"+song);
    });
  };
});

 Edit: switched names on accident copying code; both ids are player not music

A: You are using an extra }; in your JS code:
var song;
$(document).ready(function(){
  $("button").click(function(){
    song=$(this).attr("value");
    $("#player").attr("src","sound/"+song);
  });
});

See this Fiddle

A: Audio tag has id music and you try to change attribute on tag with id player. Since there is no such tag, song will not change.


text:
Q: CFMail not sending to email address that has a single quote in it How can I use cfmail to send an email to an address that has a single quote in it? For example:

firstname.o'flanagan@example.com

For some reason I can't get an email sent to that address no matter what I do. Here's the cfmail tag code I'm using. I've tested all the variables and they're all defined:
<cfmail from="#getEmail.from_email#"
        to="#email#"
        subject="#getEmail.subject#"
        type="HTML"
        cc="#cc_email#"
        bcc="#attributes.bcc_email#"
        charset="UTF-8">

Am I missing something? Thanks for the help.

A: Did you try
<cfmail from="#getEmail.from_email#"
 to="#preserveSingleQuotes(email)#"
 subject="#getEmail.subject#" type="HTML"
  cc="#cc_email#" bcc="#attributes.bcc_email#" charset="UTF-8">

using the PreserveSingleQuotes should allow you to send to that address. Unfortunately using a single quote is valid in an email.


text:
Q: Swift: Need to move data stored using a button to another View Controller Using a button to collect a phone number and then reading and storing the phone number under the button function.
@IBAction func viewRewardsButtonTapped(_ sender: UIButton) {
    view.endEditing(true)
    // Validate format
    let phoneNumberInput = phoneInput.text
}

Is there a better way to store the phone number phoneNumberInput and get it to another UIViewController?
I currently can't get the other UIViewController to recognize the variables stored under the @IBAction function.

A: You could use UserDefaults:
// Set phone number
UserDefaults.standard.set(phoneInput,text, forKey: "phoneNumber")

// Get phone number
UserDefaults.standard.string(forKey: "phoneNumber")

Or if you want to segue at the same time that you´re clicking the button use this:
self.performSegue(withIdentifier: "showVC2", sender: phoneNumber.text)

override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
    if (segue.identifier == "showVC2") {
        if let phoneNumber = sender as? String {
            let vc = segue.destination as! YourSecondVC
            vc.phoneNumber = phoneNumber
        }
    }
}

So you basically create the segue and declare a variable for phoneNumber in your second VC so that you can pass the value to it.

A: Your phoneNumberInput variable is only stored in the scope of your action handler method viewRewardsButtonTapped, so once this method is left the value is lost. You should add a member variable (var phoneNumber: String?) to your class and use this for storing the value. Then, when you open the next view controller, you can pass the value in as a parameter.
If you are using storyboard segues (which I assume), you have to implement performSegue withIdentifier, cast the destination view controller to the concrete type and set the value (e.g. targetVC.phoneNumber = self.phoneNumber).


text:
Q: XQuery: find max value and return relevant information I have a XML file containing elements with the following structure:
<listing>
    <auction_info>
        <num_bids>29</num_bids>
    </auction_info>
    <item_info>
        <result>item A</result>
    </item_info>
</listing>
<listing>
    <auction_info>
        <num_bids>12</num_bids>
    </auction_info>
    <item_info>
        <result>item B</result>
    </item_info>
</listing>

I need a query to calculate the max of num_bids and return the result.In my example,the num_bids 29 is the max number,so need return item A.But in my code below,it returned all results.
let $x := //listing
let $max := max($x/auction_info/num_bids)
return $x[//num_bids = $max]/item_info/result

Thank you for help.

A: What your expression asks for is "give me all $x where there is a num_bids, anywhere in the document, which is equal to $max."  Which is different than "give me all $x for which its own num_bids is equal to $max."  The following should do (not tested):
let $in  := //listing
let $max := max($in/auction_info/num_bids)
return
   $in[auction_info/num_bids eq $max]/item_info/result

If you really want to use the descendant axis, you can change $x[//xxx] to $x[.//xxx] (see the extra dot?)  The first one says "for each $x, any xxx descendant from its root," the second says "for each $x, any xxx descendant from itself."  But from your example input, the query above is most likely what you want.


text:
Q: How to add labels to nodes in a CIRCULAR GRAPH with networkx in python I'm drawing a circular graph using the method:
nx.draw_circular(G, node_color='b', edge_color='#909090', node_size=500)

Basically what I want to do is to add labels to the nodes but I don't find the way to add them in this type of graphs. I tried using:
nx.draw_networkx_labels(G,labels=labels,pos=nx.spring_layout(G),font_size=16)
but there is a problem with the position layout, it is not next/in each node.

A: Solved!
G=nx.Graph()
G.add_nodes_from(range(20))
e = [(0,1),(0,2)]
G.add_edges_from(e)

# some labels
labels={}

nx.draw_circular(G, node_color='y', edge_color='#909090', node_size=500,labels=labels)

plt.axis('equal')

A: Use the draw_networkx_labels() function with pos from nx.circular_layout():
G = nx.Graph()
e = [(0, 1), (0, 2)]
G.add_edges_from(e)

pos = nx.circular_layout(G)
nx.draw_networkx_labels(G, pos)
nx.draw_circular(G, node_color='#2ea28a', node_size=1000)

plt.show()


text:
Q: Titles in revision history are bold if (and only if) the title changed I noticed this behaviour when looking at the revision history of a hot MathOverflow question:

The question title is in bold if and only if the body was changed. This behavior only occurs in the two parsed output views, not in the markdown view.

.
You can also reproduce this in the formatting sandbox. (With bold title (revision 262), With narrow title (revision 8))
The problem is that the bold font looks like it is a heading (#, ##, ###) from the body and is not so easily distinguished from the body except for spanning both columns


text:
Q: iterate for loop over dataframe rows I am new to python and learning to use dataframes and list comprehensions.
I have the following dataframe:
df1=pd.DataFrame({'names':[[['Hans Peter'],['Harry Potter']],[['bla bla'],['some string']]]})

now i want to split each sublist into words.
For a single list of lists i could use
x=[['Hans Peter'],['Harry Potter'],['bla bla'],['some string here']]
res=[]
for list in x:
    res.append(str(list[0]).split())

but how can i iterate this over a dataframe? i think i have to build a list comprehensions and then use the apply() method to overgo the .append? but i dont know how to do this.
I would build the list comprehension for a single list like this:
res = [str(list[0]).split for list in x]

but i get a list containing this functions:
[<function str.split(sep=None, maxsplit=-1)>,...]

the expected output for a DataFrame would be
 0 [['Hans','Peter],['Harry','Potter']]
 1 [['bla','bla'],['some','string']]

A: First, you need to call the split function, because otherwise str.split is an object:
''.split
<built-in method split of str object at 0x1005a3ab0>

''.split() # call with parentheses
[]

Second, you need to get down to the sub-lists within names. You can simulate this with a for loop first:
for x in df1.names:
    for a in x:
        print(a)

['Hans Peter']
['Harry Potter']
['bla bla']
['some string']

You'll be left still with lists, so you can use a.pop() to get the strings out, then use str.split() on the result of pop():
df1.names = [[a.pop().split() for a in x] for x in df1.names]

df1
                              names
0  [[Hans, Peter], [Harry, Potter]]
1      [[bla, bla], [some, string]]


text:
Q: Why for all $g\in \mathcal C_0[0,T]$, there is a unique $f\in \mathcal C_0[0,T]$ s.t. $f(t)-\int_0^t b(f(s))ds=g(t)$ We denote $$\mathcal C_0([0,T])=\{f:[0,T]\to \mathbb R\mid f\text{ continuous and }f(0)=0\}.$$
Suppose $b:\mathbb R\to \mathbb R$ is a Lispchitz continuous function. Set $$L(f)(t)=f(t)-\int_0^t b\big(f(s)\big)ds.$$
Why for all $g\in \mathcal C_0[0,T]$ there is a unique $f\in \mathcal C_0[0,T]$ s.t. $L(f)(t)=g(t)$ ?
For existence I really don't know. For unicity I tried as follow : Let $f$ and $h$ two solutions. Then
$$|f(t)-h(t)|\leq \int_0^t |b(f(s))-b(g(s))|ds\leq K\int_0^t |f(s)-h(s)|ds,$$
so using Gronwall, we get $|f(t)-g(t)|\leq K\exp(t)$, but I can't really conclude that $f=g$. Any idea ?

A: You want to use the Banach fixed point theorem (also known as the contraction mapping theorem). The space $\mathcal C_0([0,T])$ is complete with respect to the supremum norm $$\|f\|_\infty = \sup_{t \in [0,T]} \lvert f(t) \rvert.$$ Fix $g \in \mathcal C_0([0,T])$ and consider the operator $A : \mathcal C_0([0,T]) \to \mathcal C_0([0,T])$ defined by $$(Af)(t) = g(t) + \int_0^t b(f(s))ds, \,\,\,\,\, f \in \mathcal C_0([0,T]).$$ Note that for $f,h \in \mathcal C_0([0,T])$, $$\lvert (Af)(t) - (Ah)(t) \rvert \le \int^t_0 \lvert b(f(s)) - b(h(s))\rvert ds \le KT\| f - h \|_\infty, \,\,\,\, \forall t \in [0,T].$$ Passing to the supremum shows that $\| Af - Ah\|_\infty \le KT \|f-h\|_\infty$. Now if $T < 1/K$, then $A$ is a contraction, and thus by the Banach fixed point theorem, you have a unique fixed point $Af = f$ which is the unique solution to the desired equation.
If $T \ge 1/K$, then you can't immediately conclude. However, in that case, you can "restart" the problem at $T_1 = 1/2K$. You have existence and uniqueness up to time $T_1$; you can step forward and establish existence and uniqueness up to $T_2 = T_1 + 1/2K$, then to $T_3 = T_2 + 1/2K$, etc. By taking enough steps you will get existence and uniqueness on the entire interval $[0,T]$.


text:
Q: Problems with video card or motherboard I am using a Sony VGN-SZ32CP laptop, which is equipped with a nVidia GeForce Go 7400 video card with a 128MB memory, and a integrated card which is "Intel Corporation Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics". Everything used to be fine before 3.0, but since it released, the computer has never ever used the nVidia card, but the intel's instead. The system seems doesn't detect it at all.
Here is the lspci result:
00:00.0 Host bridge: Intel Corporation Mobile 945GM/PM/GMS, 943/940GML and 945GT Express Memory Controller Hub (rev 03)
00:02.0 VGA compatible controller: Intel Corporation Mo`enter code here`bile 945GM/GMS, 943/940GML Express Integrated Graphics Controller (rev 03)
00:02.1 Display controller: Intel Corporation Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics Controller (rev 03)
00:1b.0 Audio device: Intel Corporation NM10/ICH7 Family High Definition Audio Controller (rev 02)
00:1c.0 PCI bridge: Intel Corporation NM10/ICH7 Family PCI Express Port 1 (rev 02)
00:1c.1 PCI bridge: Intel Corporation NM10/ICH7 Family PCI Express Port 2 (rev 02)
00:1c.2 PCI bridge: Intel Corporation NM10/ICH7 Family PCI Express Port 3 (rev 02)
00:1c.3 PCI bridge: Intel Corporation NM10/ICH7 Family PCI Express Port 4 (rev 02)
00:1d.0 USB controller: Intel Corporation NM10/ICH7 Family USB UHCI Controller #1 (rev 02)
00:1d.1 USB controller: Intel Corporation NM10/ICH7 Family USB UHCI Controller #2 (rev 02)
00:1d.2 USB controller: Intel Corporation NM10/ICH7 Family USB UHCI Controller #3 (rev 02)
00:1d.3 USB controller: Intel Corporation NM10/ICH7 Family USB UHCI Controller #4 (rev 02)
00:1d.7 USB controller: Intel Corporation NM10/ICH7 Family USB2 EHCI Controller (rev 02)
00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev e2)
00:1f.0 ISA bridge: Intel Corporation 82801GBM (ICH7-M) LPC Interface Bridge (rev 02)
00:1f.1 IDE interface: Intel Corporation 82801G (ICH7 Family) IDE Controller (rev 02)
00:1f.2 IDE interface: Intel Corporation 82801GBM/GHM (ICH7-M Family) SATA Controller [IDE mode] (rev 02)
00:1f.3 SMBus: Intel Corporation NM10/ICH7 Family SMBus Controller (rev 02)
06:00.0 Network controller: Intel Corporation PRO/Wireless 3945ABG [Golan] Network Connection (rev 02)
07:00.0 Ethernet controller: Marvell Technology Group Ltd. 88E8036 PCI-E Fast Ethernet Controller (rev 15)
09:04.0 CardBus bridge: Texas Instruments PCIxx12 Cardbus Controller
09:04.1 FireWire (IEEE 1394): Texas Instruments PCIxx12 OHCI Compliant IEEE 1394 Host Controller
09:04.2 Mass storage controller: Texas Instruments 5-in-1 Multimedia Card Reader (SD/MMC/MS/MS PRO/xD)

As you can see, the nVidia card is not on the list.

A: Try to check you nVidia card with
sudo lspci -H 1

or
sudo lspci -H 2

If this doesn't work, try to go into sleep mode and then wake up, and execute the above commands. If you still don't see you nVidia card, then the last option is tochange BIOS settings. If you see your nVidia card, then it may be not easy to make it working. Loading modules with "modprobe nvidia" didn't work for me and I will need to try to make advanced PCI resources tuning.


text:
Q: Writing to a Shapefile I'm having trouble writing/reading a Shapefile in python. I have an array of points that I would like to write to a polygon using pyshp.  The relevant parts of the code are:
dividedRects = [(7598325.0, 731579.0, 7698325.0, 631579.0), (7598325.0, 631579.0, 7698325.0, 611641.0), (7698325.0, 731579.0, 7728636.0, 631579.0), (7698325.0, 631579.0, 7728636.0, 611641.0)]

def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
        w.field("ID", "C", "40")
        w.field("Events", "C", "40")
        w.record(str(i), str(0))
    w.save('cellFile')

createPolys(dividedRects)

This causes an error:
IndexError                                Traceback (most recent call last)
<ipython-input-36-503affbe838b> in <module>()
----> 1 createPolys(dividedRects)

<ipython-input-35-4c552ae29bc7> in createPolys(dividedRects)
     10         w.field("ID", "C", "40")
     11         w.field("Events", "C", "40")
---> 12         w.record(str(i), str(0))
     13     w.save('cellFile')
     14 #     topLeft = [dividedRects[1][0],dividedRects[1][1]]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in record(self, *recordList, **recordDict)
    967         if self.fields[0][0].startswith("Deletion"): fieldCount -= 1
    968         if recordList:
--> 969             [record.append(recordList[i]) for i in range(fieldCount)]
    970         elif recordDict:
    971             for field in self.fields:

IndexError: tuple index out of range

If I remove the field and records lines from createPolys:
def createPolys(dividedRects):
    w = shapefile.Writer(shapefile.POLYGON)
    for i in range(0, len(dividedRects)):
        print i
        topLeft = [dividedRects[i][0],dividedRects[i][1]]
        topRight = [dividedRects[i][2], dividedRects[i][1]]
        bottomRight = [dividedRects[i][2], dividedRects[i][3]]
        bottomLeft = [dividedRects[i][0], dividedRects[i][3]]
        w.poly(parts=[[topLeft,topRight,bottomRight,bottomLeft]])
#         w.field("ID", "C", "40")
#         w.field("Events", "C", "40")
#         w.record(str(i), str(0))
    w.save('cellFile')

Then I get an assertionerror when reading the records from the file:
createPolys(dividedRects)

sf2 = shapefile.Reader("cellFile")
print sf2.records()
shapes = sf2.shapes()
bbox = shapes[1].bbox
#['%.3f' % coord for coord in bbox]
print bbox
points = shapes[1].points
print points

AssertionError                            Traceback (most recent call last)
<ipython-input-37-597af0b882ba> in <module>()
      1 sf2 = shapefile.Reader("cellFile")
----> 2 print sf2.records()
      3 shapes = sf2.shapes()
      4 bbox = shapes[1].bbox
      5 #['%.3f' % coord for coord in bbox]

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in records(self)
    528         """Returns all records in a dbf file."""
    529         if not self.numRecords:
--> 530             self.__dbfHeader()
    531         records = []
    532         f = self.__getFileObj(self.dbf)

C:\Users\Me\Anaconda2\lib\site-packages\shapefile.pyc in __dbfHeader(self)
    464             self.fields.append(fieldDesc)
    465         terminator = dbf.read(1)
--> 466         assert terminator == b("\r")
    467         self.fields.insert(0, ('DeletionFlag', 'C', 1, 0))
    468

AssertionError:

When I removed the loop and wrote one record it seemed to work ok.  What's going on?

A: I do not know about pyshp library, but I'll try to help anyways.
The two w.field() commands occur in the for loop.  This may cause the two columns "ID" and "Events" to be defined multiple times.  When you write only one record (polygon), it works fine (i.e. the w.record() command contains two values).  After the first iteration, there would be 4, 6, etc columns.  That would explain the behavior you describe.
Try moving the two w.field() lines before the for loop.
When you comment the w.record(), you obtain a shp (and shx) file with a number of records different from the corresponding dbffile.  That explains the assertion error when reading.
Unrelated to your problem, you could also simplify your code with enumerate (built-in function).
w = shapefile.Writer(shapefile.POLYGON)
w.field("ID", "C", "40")
w.field("Events", "C", "40")
for i,rect1 in enumerate(dividedRects):
    print i
    topLeft = [rect1[0],rect1[1]]
    topRight = [rect1[2], rect1[1]]
    bottomRight = [rect1[2], rect1[3]]
    bottomLeft = [rect1[0], rect1[3]]
    ....

(I cannot test since I do not have pyshp)  Good luck!


text:
Q: Webscraping with rvest, error "no applicable method for 'xml_find_first' applied to an object of class "character"" I'm trying to use rvest package to scrape job titles from webpage, but getting an error:
Error in UseMethod("xml_find_first") :
  no applicable method for 'xml_find_first' applied to an object of class "character"

Any advice? Am I missing some part of the code? My code is below:
library(dplyr)
library(rvest)
library(stringr)

url <- "https://www.cvmarket.lt/darbo-skelbimai"
# save the url
html <- read_html(url) # read the url

get_links <- function(html) {
  html %>%
    html_nodes(xpath = '//*[contains(concat( " ", @class, " " ), concat( " ", "limited-lines", " " ))]') %>%
    html_attr(name = "href")
}
# now we call the function and save it
links <- get_links(html)
links

links <- paste0("https://www.cvmarket.lt", links)

link <- links[1]
html <- read_html(link)

# position title
get_title <- function(html) {
  html %>%
    html_node(xpath = '//*[(@id = "main-job-title")]') %>%
    html_text() %>%
    unlist()
}
#test
get_title(link)

A: I would change your functions to accept an uri as input parameter. Use faster css selectors with more specificity so that you get faster matching, in the case of using id, and no duplicates, in the case of the css class combination. You can use url_absolute to complete urls within the get_links function. This also handles the current error where you are passing an url, instead of html, into your get_title function and then calling read_html on it.
library(dplyr)
library(rvest)
library(stringr)

get_links <- function(url) {
  read_html(url) %>%
    html_nodes('.main-column > .f_job_title') %>%
    html_attr(name = "href") %>% url_absolute(url)
}

# position title
get_title <- function(link) {
  read_html(link) %>%
    html_node('#main-job-title') %>%
    html_text()
}

url <- "https://www.cvmarket.lt/darbo-skelbimai"
links <- get_links(url)
link <- links[1]

#test
get_title(link)


text:
Q: Can I use the plantUML language in LaTeX? I want to create diagrams. Preferable in LaTeX. Normally, I use the PlantUML language.

A: I use the website https://www.planttext.com/ to export to/download as SVG (which btw includes the plantuml code as XML comment) and after that save as PDF with inkscape. This can be used with \includegraphics

A: You could also write the plantuml diagrams localy and convert them via plantuml -teps your-file to lossless eps files. These can be directly included in latex via the \includegraphics command.
This way you do not have to go the way via inkscape.

A: It is possible to use the PlantUML language direcly inside LaTeX using the plantuml package.
Here is a minimal example:
\documentclass{scrartcl}
\usepackage{plantuml}
\begin{document}
\begin{plantuml}
  @startuml
  Alice -> Bob: Hello
  Alice <- Bob: Hi!
  @enduml
\end{plantuml}
\end{document}

For building LaTeX with PlantUML the PLANTUML_JAR environment variable has to be set and Java must be installed.
To build this document, run lualatex --shell-escape documentname
The result should look like this:

A more detailed example can be found here: https://koppor.github.io/plantuml/
Prerequisites
# to get tikz, install pgf
tlmgr install pgf
tlmgr install koma-script
tlmgr install xkeyval
tlmgr install adjustbox
tlmgr install collectbox
tlmgr install luacode
tlmgr install luatexbase

A: I have worked out a solution that works with pdflatex as well. It produces vector graphics. I tested it with Ubuntu Linux 20.04 LTS and TeX Live. Should work with macOS as well.
My code requires, that you have installed:

*

*PlantUML (thus, also Java)

*Inkscape (converting svg to pdf)

Due to calling external commands, you have to use the -shell-escape option to compile:
pdflatex -shell-escape my-file.tex

Depending of how you installed PlantUML, you might have to call it like this:
\immediate\write18{java -jar /home/NAME/Downloads/plantuml.jar -tsvg #1.txt}

... instead of ...
\immediate\write18{plantuml -tsvg #1.txt}

Here is the full code as minimal example:
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{graphicx} % enables us to use graphics
\usepackage{fancyvrb} % enables us to write to disk
\usepackage{float}    % enables us to use [H] for figures

% Define an verbatim environment for PlantUML:
\newenvironment{plantuml}[1]{\VerbatimOut{#1.txt}}{\endVerbatimOut}

% Process a PlantUML code:
\newcommand{\process}[3]{%
    % Call PlantUML to produce a svg vector graphcis:
    \immediate\write18{plantuml -tsvg #1.txt}
    % Call Inkscape to convert the svg to a pdf (pdflatex cannot use svg):
    \immediate\write18{inkscape #1.svg --export-filename=#1.pdf}
    % Include the pdf:
    \begin{figure}[H]
        \includegraphics[width=#2]{#1.pdf}
        \caption{#3}
    \end{figure}
    % Remove all intermediate files:
    \immediate\write18{rm #1.txt #1.svg #1.pdf}
}

\begin{document}

% Note: timeline1 gets used as filename.
%       You must re-use this name for the
%       corresponding \process command!
\begin{plantuml}{timeline1}
    @startgantt
        [Prototype design] lasts 15 days
        [Test prototype] lasts 10 days
    @endgantt
\end{plantuml}
\process{timeline1}{0.8\textwidth}{The proposed timeline.}

\begin{plantuml}{activity1}
    @startuml
        :Hello world;
        :This is on defined on
        several **lines**;
    @enduml
\end{plantuml}
\process{activity1}{5cm}{An activity diagram.}

\end{document}

I hope this is helpful to someone.


text:
Q: Error Code: 1292. Truncated incorrect DOUBLE value I am trying to insert data, by the query:
insert into email (emailAddress, isPreferredEmail, customer_id, upload_id)
select cast(Email as char(100)) a,
       TRUE,
       (select id from customer c where c.dbvehregno=ChassisNo),
       uploadid
  from hyundaiindividualreport
 where id in (select max(id)
                from hyundaiindividualreport
               where length(Email>=5)
                 and uploadid=900
               group by ChassisNo);

But it's throwing:

  Error Code: 1292. Truncated incorrect DOUBLE value

Email Table structure:
 Table: email
Columns:
email_Id bigint(20) AI PK,
emailAddress varchar(300) ,
isPreferredEmail bit(1) ,
updatedBy varchar(255) ,
customer_id bigint(20) ,
upload_id varchar(255)

A: This expression does not look right:
length(Email >= 5)

I think you mean:
length(Email) >= 5

However, it seems surprising that it would generate that particular error in MySQL.


text:
Q: How to catch and fix the reason of WebView not showing web-content with JS I have simple JavaFX application with WebView element on form and I load web-content with ace-editor into that element.
In result on my PC form shows me content in the style of ace-editor but on pc of my colleague this JS style is not showing.
I'm looking for some way to catch the reason for that trouble.
I tried to check it on my laptop, home PC and work PC - it works with no troubles.
Also, I thought that console can show me some error but there are no errors.
I know only that trouble is independent of the platform (i checked it on Windows 10  and my colleague has the same windows - the difference only between antiviruses but if my colleague runs clear HTML with the same code it would work as expected - with styles).
There is a initialize procedure where I set content
@FXML
public void initialize() {
    wbView.getEngine().loadContent(content);
}

I can't put here full HTML of content. And I think it doesn't metter because on my PC it works anyway.
As result on my PC it looks like that:

On my colleague's PC (but should be like on mine):

upd#1
I tried to add this code.
public void initialize() {
    wbView.getEngine().loadContent(content);
    System.out.println("Errors from wbView: " + wbView.getEngine().onErrorProperty());

    System.out.println("worker error : " + wbView.getEngine().getLoadWorker().getMessage());

    wbView.getEngine().getLoadWorker().stateProperty().addListener(
            new ChangeListener<State>() {
                public void changed(ObservableValue ov, State oldState, State newState) {
                    if (newState == State.SUCCEEDED) {
                        System.out.println("load state: "+ newState);
                    }
                }
            });
}

In result:
Errors from wbView: ObjectProperty [bean: javafx.scene.web.WebEngine@13d4522, name: onError, value: null]
worker error : Loading
load state: SUCCEEDED


text:
Q: Unable to upload folder file onto Google Drive in .Net MVC using webAPI? I am working on .Net MVC WebAPI .I have fetch the data from my local database in visual studio and stored into csv file at my local machine in C drive. Now I want to upload to my  google drive what should i do next?
[HttpGet]
[Route("Get")]
public void ExportcontentCSV()
{
    StringBuilder sb = new StringBuilder();
    var get = db.Clients.ToList();

    sb.AppendFormat("{0},{1},{2},{3}",
        "id", "FirstName", "LastName", "DOB");
    sb.Append("\r\n");

    foreach (var all in get)
    {

        sb.AppendFormat(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\"",
            all.id, all.FirstName, all.LastName, all.DOB));
        sb.Append("\r\n");
    }
    StreamWriter File = new StreamWriter(@"C:\New folder\pqr.csv");

    File.WriteLine(sb.ToString());

    File.Close();
}

A: Use  Google Drive API , more details here


text:
Q: Unable to get Bake Console working and all answers are outdated I have a CakePHP project in

C:/xampp/htdocs/cms2

I'm trying to use bake console, but when I run "bin/cake" in the command prompt it says that 'bin' is not recognized as an internal or external command, operable program or batch file. I followed this and It got installed and I restarted my PC.
So, I 'cd' my way from the console to my project's directory and I type in composer require --dev cakephp/bake:"^2.0" for a second time just to make sure:

This means bake is installed, right? When I first ran this command, I had some files downloaded and installed, this picture is after running the command for a second time. I have PHP set up correctly in my Environment Variables. I've been doing my research and I still can't find my answer.
Things I've done:

*

*I followed this article here, but it lead to nowhere. I have no cake\console folder.
This is what my File Explorer of my project looks like, so there's no cake/console

*Then I followed this stackoverflow thread
However it was for WAMP, so I couldn't find anything similar. When I search for "Console" in my project folder, I find about 30 "Console" files and folders. When I do php -v I get: PHP 7.3.27

*I follow this thread and I add C:\xampp\htdocs\cms2\bin to my "Path" System Environmental Variables, but still nothing happens.
I'm out of ideas and I don't know what I'm doing wrong. I need to bake my models and controllers and what not and I am unable. I also took a picture of my SYSTEM Environmental Variables, just in case it could help someone help me.

A: Seems like I was following the documentation in the cakePHP cookbook and they had it typed:

Turns out, I had to use
bin\cake bake model users


text:
Q: Where are the events for the video element in GWT I'm trying to use HTML5 and the "Video" element. I'm would like to implement some kind of simple player using GWT and I'm looking for playback events. More specifically when a video has finished.
From the GWT documentation, there is no events (not in Video or VideoElement). So, do I have to implement my own timer and check the status (VideoElement.hasEnded) and fire my own event?
The closer I found to what I'm looking for is:
HTML 5 video or audio playlist
Also, I found this interesting library as well that does some of the stuff I'm interested in:
http://code.google.com/p/gwt-html5-video/.
thanks.

A: You "just" have to wait a bit: http://gwt-code-reviews.appspot.com/1385804/


text:
Q: Drop down menu's python Hello I have started a program to display my school time table this is my code so far:
from tkinter import *

master = Tk()
master2 = Tk()
var = StringVar(master)
var2 = StringVar(master2)
var.set("Day")
var2.set("Week")

option = OptionMenu(master, var, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
option2 = OptionMenu(master2, var, "A", "B")
option.pack()
option2.pack()

Week = var2.get()
Day = var.get()
def ok():
    if Day == "Monday" and Week == "A":
        print("You have: \n P.S.E with Mrs Smith \n W.B.Q with Mrs Smith \n Science with Mr Martin \n Media wirh Mr Kelleher \n English with Mrs Jenkins (of mice and men)")
        input("Press enter to close")
    if Day == "Tuesday" and Week == "A":
        print("You have: \n R.M with Mr Arnold/Mr Heywood \n English with Mrs Jenkins \n I.C.T with Mr Davies \n Maths with Mr Tucker \n I.T programing with Mr Arnold ")
        input("Press enter to close")
    if Day == "Wednesday" and Week == "A":
        print("You have: \n English with Mrs Jenkins \n Science with Mr Martin \n Re with Mr Davies \n Media with Mr Kelleher \n R.M with Mr Arnold/Mr Heywood ")
        input("Press enter to close")
    if Day == "Thursday" and Week == "A":
        print("You have: \n Games With Mr Davies \n I.C.T with Mr Davies \n I.T programing with Mr Arnold \n Science with Mr Martin \n Maths with Mr Tucker")
        input("Press enter to close")
    if Day == "Friday" and Week == "A":
        print("You have: \n Maths with Mr Tucker \n English with Mrs Jenkins \n Media with Mr Kelleher \n I.T programing with Mr Arnold \n Science with Dr Burton")
        input("Press enter to close")
    if Day == "Monday" and Week == "B":
        print("You have: \n Science with Dr Burton \n Re with Mr Davies \n Welsh with Mr Kedward \n English with Mrs Jenkins (of mice and men) \n Media with Mr Kelleher")
        input("Press enter to close")
    if Day == "Tuesday" and Week == "B":
        print("You have: \n Maths with Mr Tucker \n R.M with Mr Arnold/Mr Heywood \n I.T programing with Mr Arnold \n I.C.T with Mr Davies \n Science with Dr Burton")
        input("Press enter to close")
    if Day == "Wednesday" and Week == "B":
        print("You have: \n R.M with Mr Arnold/Mr Heywood \n Media with Mr Kelleher \n English with Mrs Jenkins \n Science with Miss Fair \n I.C.T with Mr Davies")
        input("Press enter to close")
    if Day == "Thursday" and Week == "B":
        print("You have: \n Games With Mr Davies \n I.C.T with Mr Davies \n I.T programing with Mr Arnold \n Maths with Mr Tucker \n Science with Miss fair")
        input("Press enter to close")
    if Day == "Friday" and Week == "B":
        print("You have: \n Welsh with Mr Kedward \n Science with Miss Fair \n English With Mrs Jenkins \n Maths with Mr Tucker an R.M with Mr Arnold/Mr Heywood")
        input("Press enter to close")
    else:
        print("Error invalid choice")
        input("Press enter to close")

button = Button(master, text="OK", command=ok)
button2 = Button(master2, text="OK", command=ok)
button.pack()
button2.pack()
mainloop()

I am wondering how can I display the two options in the same Tkinter window also it does not set the value to the correct ones e.g: Day does not = Monday and Week does not = A instead they = "day week" and I am wondering how to fix this thanks. I am new too tkinter

A: There's three things here to address. I'll do them in the order I found them
Multiple instances of Tk
master = Tk()
master2 = Tk() # DON'T DO THIS

Never have two instances of Tk running at once. If you need a second window, use tkinter.Toplevel. You don't need a second window for this, however, so let's move on.
Change everything to be inherited by master
That includes var2, option2, and button2. In fact since we're dropping master2 completely, just delete button2.
Make your StringVar update when the button is pressed
This is why your function isn't receiving the right info. You only assign Day and Week to var.get() and var2.get() once, and you do so right after you create the OptionMenus when they're still on their default values. When you change the OptionMenu item, Day and Week never actually change. Instead do something like:
def ok():
    global var, var2
    Day = var.get()
    Week = var2.get()
    if Day == ...
    ...

Afterword
By the way, your mainloop call should be master.mainloop(). You always run mainloop from your instance of Tk, which is part of the reason why you shouldn't have more than one instance! There's also a good deal of inconsistency in variable naming schemes, to which I'll refer you to PEP8 since it's a bit outside of the scope of this answer. Just know that things like var for a variable name are vague and terrible, and Day and Week should be classes if they're capitalized like that. I'd also STRONGLY recommend removing your "Press Enter to Continue" lines. You don't need them. In fact remove your console interaction from the user: make a Toplevel and write to a Label on it.
All in all though, good work! This is one of the most correct beginning forays into Tkinter I've seen in a long time.


text:
Q: i can not connect to tightvnc with my public IP, only with localhost When attempting to connect to my TightVNC with my public IP 192.168.0.32 the noVNC page does not show up however if I try with localhost 127.0.0.1 I can connect
I am on windows 10


text:
Q: How can I remove the color of underlines/strike through style in Libreoffice Writer In a document like this I have underlined and strike through text. Originally, the document was created by Microsoft word. Currently this text is also colored - either blue or some yellow, depending on how I call Libreoffice.
When printed to a PDF, the blue color remains.
How can I change the document such that the color is removed? Not only for one printing, but generally in the document such that this document can be printed without colors by anyone.
Help suggested to select "Print black", but I cannot find this.
(I am using 3.5.7.2 - which is the latest on 12.04.5 LTS)

A: Go to Tools -> Options -> LibreOffice Writer -> Changes and set all colors to black.

A: Well, in your document, the underlined text and the strike through text are both Reviews of the document. So, if you want to see them as a normal text you must either accept or reject them (for example, if you accept every strike through text will be removed and every underlined text will be added).

A: At the moment, there is no way to completely remove colour from your document in LibreOffice.  That is to say, there is no way that whatever you add into the document, it will always show up in black.  You do have a couple options, however:
1. Change all text color to black.
Begin by selecting all the text in the document. (Ctrl + a) On your toolbar, you should have an icon that looks something like this:

Click on it, and it gives you a drop down that looks something like this:

Select the black colour.  This will turn all the text in your document black, however, as I said above, it will not prevent new text from having another colour: you will have to repeat the process every time you add something with another colour.
2. Eliminate colour when exporting to pdf.
Go to your menus: Tools > Options.  In the window that pops up, go to LibreOffice Writer/Web > Print.  You should see something like this:

Check the Print text in Black box, and you're done.  Now when you export as PDF, it should export it all in black.
Hope it helps!


text:
Q: Artifact feed python twine doesnt find it I am using Artifacts feeds of Dev Ops for python package distribution, I used my default feed precrated inside artifacts of my own "Organization" and I can upload by "twine" python tool (a package) but not in the feed created by me ( not default). I have to create the feed because I want to do it the same in my employer organization and there is no default feed bacuase there are a lot projects and so. when I try to upload to created feed (Not deafult) to Dev Ops through twine function tells me that it doesnt exist. I am absolutely sure it exist and you can see it in the images, and if I try to do it in my employer dev ops organization it happen the same.
Twine error
Exisitig Feed

A:
Artifact feed python twine doesnt find it

This is a know issue about the Project-scoped feed.
Microsoft recently changed the default scope level for new feeds to Project instead of Organization, which broke several Azure Pipeline tasks. Older feeds don't to be affected by this issue.
Check this thread:

New feeds are now by default project-scoped and a required fix for the
  pipeline tasks failed to get deployed. We are pushing out a hotfix to
  update to the newest pipeline task versions and it should be out by
  the end of the day.

So, the easiest solution is to use the old feed.
Hope this helps.


text:
Q: Search M2M fields by names not by id in django I need have a search box, one of fields of the model has a M2M field. I got to put it works but only works when i look for the id of the M2M field, not for the name. my models:
class Specialities(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

 class Profile(models.Model):
        user = models.OneToOneField(User)
        name = models.CharField(max_length=200)
        specialities = models.ManyToManyField(Specialities)

        def __str__(self):
            return self.name

And my view:
class SearchView(TemplateView):
    template_name = 'contadores/search.html'

    def post(self,request,*args,**kwargs):
        buscar = request.POST['buscar']
        contadores = Profile.objects.filter(specialities=buscar)
        ctx = {'contadores':contadores}
        return render_to_response('contadores/resultados.html',ctx,context_instance=RequestContext(request))

The queryset in "contadores" works fine, but as i told before, the search box only receive the id of the M2M field, if i look for the word in the search box django says: invalid literal for int() with base 10: 'niif' I know the reason, but how can i pass to the search box the word of the M2M field associated to the Specialities model instead the id?

A: Try like this:
 buscar = Specialities.objects.filter(name__iexact = request.POST['buscar'])
 if buscar.exists():
     contadores = Profile.objects.filter(specialities=buscar[0])

A: What you can do is search by related table, like this:
contadores = Profile.objects.filter(specialities__name__iexact = request.POST['buscar'])


text:
Q: To pay or To paying? In Arnel's Everday English Youtube video there is the following exchange:

A: The client is refusing to pay. She owes us 1500

B: Maybe she'll agree to paying in installment

why does B is using "to paying" rather than "to pay" to answer A's question?

A: "agree to pay" would be a normal way of expressing this.  (agree to pay in installments)
But it is grammatically valid to have "agree to (something)"  For example

He agreed to a short lunch break.

The structure here is "Agree + prepositional phrase"
A prepostional phrase can also be formed from "to(preposition) + gerund/participle phrase".
Gerunds are verbs ending in -ing.
However the meaning is pretty much the same as "agree + to-infinitive"

A: Here's why paying is used in the second sentence:

*

*Maybe she'll agree to ||paying in installments.||

Using another form of this to clarify the structure:
Paying an installment is maybe something she'll agree to.
paying is a gerund form of the verb that behaves like a noun. Here, in fact, a noun phrase using the gerund.
The verb+ING + [direct object] is the subject of the sentence.
One can agree to paying some sum of money.
In this case, the to is not a to-infinitive.
Please note: It could also be said as: She agreed to pay in installments. But there, it is a to-infinitive.
She agrees to pay in installments. [to-infinitive, shows finality or purpose.
She agrees to paying in installments. [gerund, she agrees to performing that action.
You can agree to pay in installments and not be doing any paying at all at a particular time.

A: "Paying" is the continuous form. Since there are instalments, the paint won't be instantly, but over some range of time, therefore the continuous form.
(The difference is quite small, so nobody will take much notice if you say "I agree to pay in instalments".)


text: Q: SSH IP address resolving I just enabled ssh on my ubuntu pc. I had a doubt. Suppose I have two ubuntu PCs(say PC1 and PC2) configured as SSH server, both connected to the same router (lets say R1) through wifi. What will happen if I tried to connect to the public address of router R1 through ssh client from a third PC while both PCs have sshd up and running on the same port. Will I get connected to PC1 or PC2? How will ssh know where to forward the request?


text:
Q: Neo4j Cypher - FOREACH silently failing on a no-op 'case trick' In cypher, there isn't an 'official' conditional update. This is emulated using a 'case trick' IF, which is a CASE inside a FOREACH as demonstrated here and here.
Here's the query I'm working with:
MATCH (reaper:REAPER)-[:TO_REAP]->(doomed)
WHERE reaper <> doomed
WITH reaper, doomed
LIMIT 1
OPTIONAL MATCH (doomed)-[x]-(doomed)
DELETE x
WITH reaper, doomed
OPTIONAL MATCH (doomed)-[r]-(related)
DELETE r, doomed
WITH related, reaper
WHERE related <> reaper
FOREACH(ignore_me IN CASE WHEN
    related IS NOT NULL
            THEN [1] ELSE [] END | MERGE (reaper)-[:TO_REAP]->(related))
RETURN 1

The purpose of this REAPER is to delete nodes (subgraphs). We do this by deleting nodes directly connected to it ('doomed' nodes), then connecting all of the children of 'doomed' nodes directly to the REAPER (related) using the MERGE. Of course, if there are no children, we don't have anything to connect, which is where the FOREACH and CASE come in. If there are no children (related), then one would expect the FOREACH to NO-OP and move on to the RETURN.
The issue is when related IS null, the query craps out, and doesn't return ANYTHING, but also DOES NOT FAIL. This is a problem, because we cannot determine when there is nothing to delete VS. a 'leaf' (single node without children) node was deleted, due to this issue.
When trying to diagnose the issue, I removed the 'if' statement (FOREACH and CASE), and when related is null, it throws an error 'Other node is null'.
I am suspecting that the FOREACH loop is somehow eating this error, even though the MERGE shouldn't be executing at all in that condition.
I'm suggesting that there's a possible neo4j/cypher bug, so I would like someone to come in and tell me how wrong and inefficient my query is XD
edit: I forgot to talk about data staging, if you wanted to test this query yourself.
This will set you up to experience my issue:
CREATE (r:REAPER)
CREATE (r)-[:TO_REAP]->(n)-[:doesntmatter]->(m)
CREATE (r)-[:TO_REAP]->(p)

When you run the delete query, you'll notice that for the 'n' node, it will return a 1. But for the other 2 nodes, m and p (which are leaf nodes), they will get deleted, but nothing will be returned.

A: This info might help.
Cypher handles the following 2 contrived snippets differently. Let's assume that there is no Foo node.
Snippet 1. (The WHERE clause aborts the query, which returns nothing):
OPTIONAL MATCH (n:Foo)
WITH n
WHERE NULL = 123
RETURN 1;

Snippet 2. (The query completes and returns 1):
OPTIONAL MATCH (n:Foo)
WHERE NULL = 123
RETURN 1;

This difference in behavior may be what is causing your issue.
However, Cypher requires that you use a WITH to separate a DELETE from a subsequent MATCH or WHERE clause.
One way to work around this might be to just move the last WITH clause up by 2 lines (right after its corresponding OPTIONAL MATCH), so that it will not abort the query:
MATCH (reaper:REAPER)-[:TO_REAP]->(doomed)
WHERE reaper <> doomed
WITH reaper, doomed
LIMIT 1
OPTIONAL MATCH (doomed)-[x]-(doomed)
DELETE x
WITH reaper, doomed
OPTIONAL MATCH (doomed)-[r]-(related)
WHERE related <> reaper
DELETE r, doomed
WITH related, reaper
FOREACH(ignore_me IN CASE WHEN
    related IS NOT NULL
            THEN [1] ELSE [] END | MERGE (reaper)-[:TO_REAP]->(related))
RETURN 1


text:
Q: Ubuntu and HTPC related questions? I just built myself a 5th gen Intel nuc system to run Ubuntu(14.10) and Kodi. Right now the problem is I will be sitting at about 12 feet away from my tv screen, which is a recent-ish 32in 1080p Sony TV. The problem is from that distance I can't read anything at all. I scaled it up 2x, but that messed a few things up, so I had to move scaling down to 1.8x(or what ever is after 1.75x) scaling. I also increased font size to large. Problem is that many things are still pretty small, like Chromes and Firefox's toolbars and certain apps. So, what I would like to know is how can I setup Ubuntu so I can comfortably view things on the setup I have at the distance I am at? Is there a theme that can improve my experience? Or am I forced to sit closer?
On a side note, I have a 5.1 audio setup hooked up to my TV(via composite since it's and older speaker setup) and my pc hooked up via hdmi to the tv. Can I just run the edit mentioned here to get 5.1 audio to work, or am I stuck using 2 channel audio(not the biggest deal, but it would be nice to use it as my previous device a roku 2 was able to. Thank you.


text:
Q: strange behavior in event page: TypeError I try to do this in an event page.
// When the browser action is clicked, call the
// getBm function.
chrome.browserAction.onClicked.addListener(getBm);

function getBm () {
    var url = 'test.html';
    dumpBookmarks();
    chrome.tabs.create({ url: url });
}

function dumpBookmarks() {
    var b = chrome.bookmarks.getTree(
        function(bookmarkTreeNodes) {
            console.log(bookmarkTreeNodes); --------(1)
        });
}

function dumpTreeNodes(bookmarkNodes) {
   //do something here
}

This works fine but if I try to do
console.log(dumpTreeNodes(bookmarkTreeNodes));

at (1) it throws error,
Error in response to bookmarks.getTree: TypeError: undefined is not a function


text:
Q: Wrong format of JSON Array after a successful POST using Apex Class I've been trying to create a List from the Account object, filtered by their record type, to be sent to our website using the Apex Class. I managed to create the query correctly and it returned the organisations that I wanted, and I managed to send the result of that query to our endpoint using the below code:
public class WPPost {
public static HttpResponse WPPost() {
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('the_endpoint');
    request.setMethod('POST');
    request.setHeader('Content-Type', 'application/json;charset=UTF-8');
    request.setBody(JSON.serialize(Query.findAll()));
    HttpResponse response = http.send(request);
    System.debug(response);
    return response;
}

The below is the query code itself in Apex Class.
public class Query {
public static List<Account> findAll(){
        List<Account> results = (List<Account>) [SELECT Id,Name,Public_Description__c,Website,ShippingCountry, FROM Account WHERE RecordTypeId='0120I000000ygO6QAI'];
return results;
}

Despite the POST itself being successful, the format of the result that I got in the endpoint wasn't what I expected:
(
[0] => [{"attributes":{"type":"Account","url":"/services/data/v45.0/sobjects/Account/0010w000005QkRNAA0"},"Id":"0010w000005QkRNAA0","Name":"Member 2","Public_Description__c":"
Lorem Ipsum Dolor si amet Numero 2

","Website":"www.membernumber2.asia","ShippingCountry":"Indonesia","RecordTypeId":"0120I000000ygO6QAI","CurrencyIsoCode":"USD"},{"attributes":{"type":"Account","url":"/services/data/v45.0/sobjects/Account/0010w000005QvtqAAC"},"Id":"0010w000005QvtqAAC","Name":"Member 4","Website":"www.membernumero4.asia","ShippingCountry":"Philippines","RecordTypeId":"0120I000000ygO6QAI","CurrencyIsoCode":"USD"},{"attributes":{"type":"Account","url":"/services/data/v45.0/sobjects/Account/0010w000005Qki9AAC"},"Id":"0010w000005Qki9AAC","Name":"Member 3","Public_Description__c":"
Lorem Ipsum Dolor si amet Numero 3

","Website":"www.membernumber3.asia","ShippingCountry":"Cambodia","RecordTypeId":"0120I000000ygO6QAI","CurrencyIsoCode":"USD"},{"attributes":{"type":"Account","url":"/services/data/v45.0/sobjects/Account/0010w000005QkIHAA0"},"Id":"0010w000005QkIHAA0","Name":"Member 1","Public_Description__c":"
Lorem Ipsum Dolor si met Numero 1

","Website":"www.membernumber1.asia","ShippingCountry":"Singapore","RecordTypeId":"0120I000000ygO6QAI","CurrencyIsoCode":"USD"}]
)

I'm really unsure what else to change since I thought using JSON.serialize would help me get the format that I need, which is something like:
{
   "Id":"0010w000005QkIHAA0"
   "Name":"Member 1"
   "Public_Description__c":"Lorem Ipsum Dolor si met Numero 1"
   "Website":"www.membernumber1.asia"
   "ShippingCountry":"Singapore"
   "RecordTypeId":"0120I000000ygO6QAI"
}

I wonder if anyone can help me realise if the wrong part was my Apex code or something else...?

A: What you're seeing is normal when serializing an SObject.
The only difference between what you're seeing, and what you want is that the serialization is including "attributes":{...}. This extra information helps Salesforce determine what kind of SObject you're working with (in case you ever want to deserialize back into an SObject).
It's been a while since I did any work in PHP, but I suspect the [0] => <JSON string> is just PHP sticking the entirety of your JSON into the $_POST superglobal array. PHP isn't auto-deserializing (which sounds like a terrible idea from a security standpoint), so you only have the one item in the array.
Honestly, I don't think there's anything that you really need to do here. PHP's json_decode() should be able to take what you have here, and you can just simply pretend that deserialized[0]->attributes can't be used.
If you just can't bring yourself to ignore the attributes, then the easiest route to go would probably be to make a simple inner class to hold your data as Strings.


text:
Q: Как получать координаты движущегося объекта в реальном времени? Добрый день! Есть элемент который анимируется с помощью css (transform: translateY). Нужно получать его координаты x и y на странице в реальном времени. Пробывал реализовать через getBoundingClientRect() , но он отображает только начальные координаты. Нужно реализовать на чистом JS, без библиотек. Для удобства: пример на jsfiddle

.container {
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

.rec {
  position: absolute;
  left: 220px;
  top: 260px;
  width: 70px;
  height: 30px;
  background-color: red;
}

.animate {
  animation-name: moveup;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

}

@keyframes moveup{
  0% {
    transform: translateY(0px);
  }

  100% {
    transform: translateY(-250px);
  }

}

22

A: Если правильно понял какой ожидается результат:

.container {
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

.rec {
  position: absolute;
  left: 220px;
  top: 260px;
  width: 70px;
  height: 30px;
  background-color: red;
}

.animate {
  animation-name: moveup;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

}

@keyframes moveup{
  0% {
    transform: translateY(0px);
  }

  100% {
    transform: translateY(-250px);
  }

}

22


text:
Q: Multiple Definition на C++ не даёт покоя Делаю небольшой проект в Qt Creator. Есть три файла и 2 из них конфликтуют между собой и линковщику становится плохо - выдает мне Multiple Definition.
Вот код:
Game.h:
#pragma once

#include <iostream>
#include <X11/Xlib.h> // Нужное подключение

// Тут небольшой пропуск...

using namespace std;

// Инициализация функций
void menu(); // Для меню
void start(); // Для инициализации
void customize(); // Для отдельной кастомизации

// Переменные из Xlib для определения ширины и высоты монитора
Display *d;
Screen *s;

// Если что все структуры описаны, и описаны правильно
struct main_character character;
vector<struct location*> locations;
struct save _save;

// И остальное...

Game.cpp:
#include "Game.h"

void start()
{
    d = XOpenDisplay(NULL);
    s = DefaultScreenOfDisplay(d);

  // С остальным проблем нет
}

void menu()
{
    // Тут проблем нет..
}

void customize()
{
   character.life = bool;
   character.health = 100;
   // И остальное настраивание
}

main.cpp
#include "Game.h" // Просто подключаю

int main()
{
       start(); // Просто начинаю программу
}

Вообщем за такое мне линковщик сказал, что с переменными d, s, character, location, _save (притом, что 2 последних я даже не использовал) произошел Multiple Definition, first define here. Я подумал-подумал и добавил к ним extern
Линковщик таких финтов не понял, и поэтому выдал мне что в функции start() у меня undefined reference to 'd' и to 's', а в customize у меня undefined reference to 'character' (скорее всего если я буду использовать location и _save, то мне тоже влетит, а так пока что норм).
Вообщем я хз почему так, но скорее всего, я криво подключил файлы, хотя всё вроде логично: Game.cpp(описание функций) -> Game.h <- main.cpp
p.s.: если в main.cpp подключить Game.cpp, то всё равно не запустится(

A: Вот такие вещи -
Display *d;
Screen *s;

надо в заголовочных файлах делать либо inline (в последних версиях С++), либо
extern Display *d;
extern Screen *s;

а затем определять их в .cpp-файле.
Так, как у вас - в каждом .cpp-файле имеются переменные с одинаковыми именами - то самое множественное определение...
Да, на всякий случай - если вам предложат написать вместо extern - static, ошибки компиляции не будет, но переменная в одном .cpp-файле не будет иметь никакого отношения к той же переменной в другом - это будут разные переменные, несмотря на одинаковое имя.

A: Почему нельзя организовать переменные и методы в рамках одного класса. Зачем этот глобализм?
Game.h

    #pragma once

    #include <iostream>
    #include <X11/Xlib.h> // Нужное подключение

    // Тут небольшой пропуск...

    using namespace std;
    class game
    {
    public:
    // Инициализация функций
    void menu(); // Для меню
    void start(); // Для инициализации
    void customize(); // Для отдельной кастомизации
    private:
    // Переменные из Xlib для определения ширины и высоты монитора
    Display *d;
    Screen *s;

    // Если что все структуры описаны, и описаны правильно
    struct main_character character;
    vector<struct location*> locations;
    struct save _save;

    // И остальное...
    }

Game.cpp
#include "game.h"

void game::start()
{
    d = XOpenDisplay(NULL);
    s = DefaultScreenOfDisplay(d);

  // С остальным проблем нет
}

void game::menu()
{
    // Тут проблем нет..
}

void game::customize()
{
   character.life = bool;
   character.health = 100;
   // И остальное настраивание
}

Ну а в main создать экземпляр и вызвать метод start


text:
Q: Find probability based on cumulative functions I have a CDF:
$F(x) = \begin{cases} 0, & x\le-2 \\ \frac 18, & -2< x\le -1 \\ \frac 38, &-1< x\le 0 \\ \frac 58,& 0 < x \le 1 \\ \frac 78,& 1 < x \le 2 \\ 1, &x> 2\end{cases}$
Find $P(-1\le X \le1)$, $P(X \le -1$ or $X = 2)$.
I'm not sure whether $P(-1\le X \le1) = F(1)-F(-1)=\frac 12$ or $P(-1\le X \le1) =F(2)-F(-1)=\frac 78 - \frac 18=\frac 68$
Please help me, I have been searching all sources and found no positive results.

A: Remark:

*

*The proposed CDF is not a valid cdf, a cdf should be right-continous, which is not the case here.

If we subtract $F(-1)$, we would not have included $P(X=-1)$.
Assuming that the typos are just with the inequality that is rather than $(-2<x\le -1)$, it should be $(-2 \le x < -1)$.
The answer should be \begin{align}Pr(-1 \le X \le 1) &= Pr(X \le 1) - Pr(X < -1) \\
&= F(1) - F(-2)\\
&=\frac78 - \frac18\\
&= \frac68\end{align}


text:
Q: Server to server authentication basics While I understand the various options available for server to server authentication between REST services, I could use some clarification on the security implications of each approach.
I want a service to verify that a request received does originate from a legitimate calling remote service. No interactive users involved, assume the request happens as the calling service starts up. The three approaches usually mentioned are:

*

*Use a fake user account and authenticate the client against the existing auth system

*Use a shared secret / API key and sign the request

*Use a client certificate (verifying the server is not a priority) 3.

The part I am missing is that it seems that all three methods depend entirely on the calling service's host (the client in the call) not being compromised. In the first approach this would give away the fake user password, but in the two other approaches an attacker could obtain the shared secret or the client certificate and impersonate the calling server just as easily as with approach number 1... so in what respect are 2 & 3 considered more secure?

A: If the host is compromised, the game is already over. You cannot hope to use network security techniques to provide guarantees about the end systems, that is not what they're meant for.  Consider passwords, for example. When a user types in a password, the guarantee you have is that the entity that entered the password knows the password, that's all. Designing to be secure against compromised hosts is like trying to build a password scheme that only authorizes you if you're the real person - you're expecting a guarantee that the mechanism is not built to provide.

A: If you want to check the calling server is not compromised you might want to use TPM based verification of the calling server in case the machines have TPMs on them. Once it has been verified that it is not compromised any of the above 3 methods would be secure.(ref: http://en.wikipedia.org/wiki/Trusted_Platform_Module)


text:
Q: Matching a file with table in postgres and identify the match level I have a table with 4 columns and is loaded with data. The data can range from 1000 to maximum of 2Million.
I get a file (lets say tab separated) as part of daily process with the data for 4 columns. I should prepare a report where for each column match i should increase the Match level.
eg:
file.col1 data exists in db.col1 ; then matchlevel = 1
file.col2 data exists in db.col2 ; then matchlevel = 2
file.col3 data exists in db.col3 ; then matchlevel = 3
file.col4 data exists in db.col4 ; then matchlevel = 4
Example Data in DB: (all fields are strings)
1367    37991   11111   sometext1
1365    37993   11112   sometext2
1369    34521   sample1 sometext1
1359    76583   sample2 sometext2

Example Data in File: (all fields are strings)
1367    37991   11111   sometext1
1365    8993    sample3  sometext5
1369    34521   sample4 sometext6
1359    76583   sample2 sometext7
1651    875637  notpresentindb    notpresentindb

The output should be
id from file    Match Level

1367            Max  (all fields match in db)
1365            Low  (only column1 matches
1369            Med  (column1 and 2 match)
1359            High (First 3 columns match)
1651            No Match (no columns match)

Currently, I am doing this Java. Declared 4 arraylists and copied all the data in the columns to arraylists and using apache collections to find if the each column data exists in each of the 4 arraylists for test purposes.
But this is redflagged because we need to load 4 columns of data with 1 million records and server memory may be all consumed.
Sample code below:
    Arraylist1,Arraylist2,Arraylist3,Arraylist4 are defined
before below code and loaded with data from db.
while ((sCurrentLine = br.readLine()) != null) {

                String[] temp;
                temp = sCurrentLine.split("\\t");
                value = "no match";
                valueInt = 0;
                if(arraylist1.contains(temp[0])){
                    value = "low";
                    int retval=arraylist1.indexOf(temp[0]);
                    if (arraylist2.get(retval).equals(temp[1]))  {
                        value = "med";

                        if (arraylist3.get(retval).equals(temp[2])){
                            value = "High";

                            if (arraylist4.get(retval).equals(temp[3])) {
                                value = "Max";

                            }
                        }
                    }
                }

A: If you want to do the processing in the database, you need to get the file content into it first. I can think of two ways of doing that:

*

*create another table and import the file content into it, e.g. using the copy command

*use a foreign data wrapper to access the file content directly

Once you are able to access the file content through SQL, what you want can be done using a simple outer join:
select fc.col1,
       case
         when fc.col1 = bt.col1 and fc.col2 = bt.col2 and fc.col3 = bt.col3 and fc.col4 = bt.col4 then 'Max'
         when fc.col1 = bt.col1 and fc.col2 = bt.col2 and fc.col3 = bt.col3 then 'High'
         when fc.col1 = bt.col1 and fc.col2 = bt.col2 then 'Med'
         when fc.col1 = bt.col1 then 'Low'
         else 'No Match'
       end as match_level
from file_content fc
  left join base_table bt on fc.col1 = bt.col1;

If you also need to identify rows that are in the base_table but not contained in the file, you need a full outer join rather than a left join:
select fc.col1,
       case
         when fc.col1 = bt.col1 and fc.col2 = bt.col2 and fc.col3 = bt.col3 and fc.col4 = bt.col4 then 'Max'
         when fc.col1 = bt.col1 and fc.col2 = bt.col2 and fc.col3 = bt.col3 then 'High'
         when fc.col1 = bt.col1 and fc.col2 = bt.col2 then 'Med'
         when fc.col1 = bt.col1 then 'Low'
         else
           case when bt.col1 is null then 'Not in database'
           else 'Not in file'
         end
       end as match_level
from file_content fc
  full join base_table bt on fc.col1 = bt.col1;

SQLFiddle example: http://sqlfiddle.com/#!15/1ff38/2

A: Since Postgresql 9.1 you can use foreign data wrappers to view files as tables. http://www.postgresql.org/docs/9.4/static/file-fdw.html
Once you can see your Csv as a table, you can use SQL power to generate your report.
CREATE TABLE t (
    id SERIAL PRIMARY KEY,
    c1 text,
    c2 text,
    c3 text
) ;

CREATE EXTENSION file_fdw;
CREATE SERVER my_csv_server FOREIGN DATA WRAPPER file_fdw;

CREATE TABLE csv (
    id integer,
    c1 text,
    c2 text,
    c3 text
)
SERVER my_csv_server
OPTIONS ( filename '/home/me/data.csv', format 'csv' );

SELECT
     id,
     CASE
         WHEN t.c1 = csv.c1 AND t.c2 = csv.c2 AND t.c3 = csv.c3 THEN
             'Max'
         WHEN t.c1 = csv.c1 AND t.c2 = csv.c2 THEN
             'High'
         WHEN t.c1 = csv.c1 THEN
             'Mid'
         ELSE
             'Low' -- only id match
    END as report
FROM
    t JOIN csv USING (id)


text:
Q: TypeScript копирование массива Столкнулся с интересным (для меня) примером:
  archive(): void {
    var oldTodos = this.todos;
    console.log(this.todos);
    console.log(oldTodos);
    this.todos = [];
    console.log(oldTodos);
    console.log(this.todos);
    oldTodos.forEach((todo: Todo) => {
      if (!todo.done) this.todos.push(todo);
    });
  }

Масив ведь имеет ссылочный тип, верно? И вроде бы, this.todos = []; должен просто перетереть массив и по всем ссылкам теперь будет пустой массив, но это не так и он ведет себя не как ссылочный тип. В чем тут дело и где я ошибаюсь?
Весь код: http://plnkr.co/edit/x0aeMXEwYo67pAWYXzfA?p=preview

A: Не совсем понял вопрос:

*

*была ссылка на массив: this.todos

*сохранили эту ссылку в переменную  var oldTodos = this.todos;
теперь на один массив две ссылки: this.todos и oldTodos

*присвоили this.todos ссылку на новый массив this.todos = [];
теперь this.todos ссылается на [], а oldTodos продолжает ссылаться на старый массив

*бежим по старому массиву и копируем ссылки на его элементы в новый.
Массив тут вполне себе ведет себя как ссылочный тип.
Возможно, если бы использовался метод filter было бы понятнее
archive(): void {
    this.todos = this.todos.filter((todo: Todo)=> !todo.done);
}


text:
Q: Changing text in EditText glitch In my activity, I have a multi-line EditText so the user can store some notes:
<EditText
    android:id="@+id/notesTV"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="30dp"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="30dp"
    android:layout_marginEnd="30dp"
    android:layout_marginRight="30dp"
    android:background="@android:color/transparent"
    android:hint="Enter notes here..."
    android:inputType="textMultiLine"
    android:scrollbars="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">>
</EditText>

In code, I create an outlet to this EditText. I then go to my database to fetch any notes the user may have taken previously and set these notes to the EditText's text.
package org1hnvc.httpshbssup.hbsnewventurecompetition;

import ...

public class Notes extends AppCompatActivity {

    private EditText notesTV;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Notes");

        notesTV = findViewById(R.id.notesTV);

        fetchNotes();
    }

    private void fetchNotes(){
        FirebaseManager.manager.fetchNotes(companyID, new FirebaseManager.NotesCallback() {
            @Override
            public void onSuccess(String notes) {
                notesTV.setText(notes);
            }

            @Override
            public void onError(String error) {
                Toast.makeText(getApplicationContext(), "An error occurred while fetching your notes",
                        Toast.LENGTH_LONG).show();
            }
        });
    }

}

When I do this, the application goes crazy. It exits out of the activity and goes to the previous activity (from which I segued). No error is thrown, but clearly the code is not properly executed. At first, I believed it may have something to do with my fetchNotes method. However, when I remove this method and just simply set the EditText's text to "test" in the onCreate method, the same thing happened. Somebody please help.

A: Your Activity is crashing because of this line:
notesTV = findViewById(R.id.notesTV);

You're asking the Activity to 'find' a View by Id, except you never told it which layout to inflate.
Make a change like this:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.the_layout_file_of_your_activity);

    setTitle("Notes");

    notesTV = findViewById(R.id.notesTV);

    fetchNotes();
}

In particular, the setContentView() part.
This way, the Activity will inflate the layout and make it possible for it to find your notesTV EditText.


text:
Q: dplyr error with summarise_ and n() I plan to use a loop to go through a few 100 columns and calculate a median and count against a set of variables.
Code :
grp_var <- "Species"
voi <- "Sepal.Length"
dmp <- iris%>%
      select_(grp_var,voi)%>%
      group_by_(grp_var)%>%
      summarise_(Median_Value = median(voi),Count = n())

Error :

Error in n() : This function should not be called directly

I face this error when i use summarise_ and don't face any issues at all when i use summarise.
I know that the function call to n() is just the error message but when called within a dplyr function it should return the row count.
Am i just being dumb about this or is this a bug ?
Edit : I don't have any conflicts for the summarise function , plyr isn't loaded.

A: First, as explained in the comments, you mixed standard evaluation and non-standard evaluation. n() is not found because you can't use it like that in *_ functions. In dplyr before 0.7.0, you would use ~n() in summarise_.
However things have changed in the tidyverse world.
Since version 0.7.0, dplyr uses now a new system for programming with dplyr, called tidy evaluation, or tidy eval for short. All function with *_ are now deprecated and should not be used in new code, unless you want to keep a dependency on an old dplyr version. I'll advice to use tidy eval now. I will not explained it here, you could see the  Programming vignette
For example, now you would do something like this with dplyr (>= 0.7.0):

library(dplyr)
# quo is a tidy eval concept for quoting
grp_var <-quo(Species)
voi <- quo(Sepal.Length)
# use !! another tidy eval concept to unquote
dmp <- iris %>%
  select(!! grp_var, !! voi) %>%
  group_by(!! grp_var) %>%
  summarise(Median_Value = median( !! voi ), Count = n())
dmp
#> # A tibble: 3 x 3
#>      Species Median_Value Count
#>       <fctr>        <dbl> <int>
#> 1     setosa          5.0    50
#> 2 versicolor          5.9    50
#> 3  virginica          6.5    50


text:
Q: Angular2 : having multiple output on a component I am currently trying to have a component in Angular2, but trying to implement it with multiple Outputs.
I have a parent component and a navbar component
Parent component :
@Component({
    selector:"personal-dashboard",
    directives:[NavBar],
    template:`
        <navbar [hidden]= "!loggedIn" (loggingOut) ="unlogSuccess($event)" (changedTab)="changingTab($event)"></navbar>
    `
})

export class PersonalDashboard{
    tabNumber:number =0; //0 is for the default Courses tab

    unlogSuccess(event){
        this.loggedIn = false;
    }

    changingTab(event){
        if(event == 'courses-tab'){
            this.tabNumber = 0;
        }
        else if (event == 'activities-tab'){
            this.tabNumber = 1;
        }
    }
}

Navbar Component :
@Component({
    selector:"navbar",
    template:`

Courses

Activity

Logout

    `
})

export class NavBar{
    @Output() loggingOut = new EventEmitter();
    @Output() changedTab = new EventEmitter();

    logout(){
        Cookies.remove("oauth_token");
        Cookies.remove("coursesData");
        this.loggingOut.emit(true);
    }

    changingTab(tabName){
        (<any>$("li.principal-navbar")).each(function(index){
            if ((<any>$(this)).attr('id') == tabName){
                (<any>$(this)).addClass("active");
                this.changedTab.emit(tabName);
            }
            else{
                (<any>$(this)).removeClass("active");
            }
        });
    }
}

I simplified the files so it looks clearer. What I am trying to do is have two possible outputs from the navbar that are triggered by clicks on different parts of the navbar. One is a changing tab action and the other is a logout action.
So I tried to write in the parent component that the navbar component should have two different outputs and I handle them in two different methods in the parent component (unlogSuccess and changingTab methods).
I also created in the navbar component two outputs with the @Output decorator. Then, on different part of the template I trigger different function of the navbar class that emit events to the two different Output that I created.
I have no problem when I compile. However when I try to trigger the second Output I created, it says that 'this.changedTab' is undefined. It works perfectly for the loggingOut output, that I create first.
So I thought that maybe angular2 doesn't let you create multiple outputs on a simple component.
As I described my problem, can you confirm this ? Is it impossible to have multiple outputs in a single component ? If so, what is the good way to do what I am trying to achieve ?

A: You need to use an arrow function to be able to use the lexical this:
(<any>$("li.principal-navbar")).each((index) => { // <-------
        if ((<any>$(this)).attr('id') == tabName){
            (<any>$(this)).addClass("active");
            this.changedTab.emit(tabName);
        }
        else{
            (<any>$(this)).removeClass("active");
        }
    });
}


text:
Q: Getting errors when trying to 'next build && next export' I'm trying to build and export my Next.js app. However, the build is failing, producing the following error below, which is repeated for every page.
[  ==] info  - Generating static pages (0/30)
Error occurred prerendering page "/". Read more:
https://nextjs.org/docs/messages/prerender-error
Error: Cannot find module for page: /
    at pageNotFoundError

This is the final error output:
> Build error occurred
Error: Export encountered errors on following paths:
    /
    /about-meadowvalefoods
    /careers
    /case-studies
    /case-studies/[id]
    /contact-us
    /export
    /find-a-supplier
    /industry-news
    /industry-news/[id]
    /my-account/dashboard
    /our-companies
    /our-products
    /our-products/1
    /our-products/10
    /our-products/11
    /our-products/12
    /our-products/13
    /our-products/14
    /our-products/15
    /our-products/2
    /our-products/3
    /our-products/4
    /our-products/5
    /our-products/6
    /our-products/7
    /our-products/8
    /our-products/9
    /point-of-sale
    /point-of-sale/images

info  - Using webpack 5 and
"next": "11.0.1",
Does anyone know what the problem is?


text:
Q: Functions in main() are executing before the previous function is complete (c++ Xcode) As the title says, I'm having problems where functions are executing before the function before them has finished. This is a problem because it's messing up the flow of my program. My main() function looks like this:
int main()
{
    FilePath1();
    FilePath2();

    VideoConfig1();
    VideoConfig2();

    VideoRecord();

    return 0;
}

and the FilePath functions look like this:
void FilePath1()
{
    cout << "Please enter the full filepath for where you want to save the first video: ";
    cin >> filepath1;
    cin.ignore();

}

The problem is that VideoConfig1() is starting directly after FilePath1(), at the same time as FilePath2(). Does anyone know why this would be happening?
I've tried using waitKey() as the initialisation of VideoConfig1(), but it had no effect.
EDIT:
The program is supposed to work as follows:

*

*Run FilePath1()

*

*get the user to enter the filepath for video1 to be saved

*Run Filepath2()

*

*get the user to enter the filepath for video2 to be saved

*Run VideoConfig1()

*Run VideoConfig2()

*Run VideoRecord()

The two FilePath programs are run in the terminal, whilst the others open up their respective video windows. What the program is currently doing is this:

*

*Run FilePath1()

*

*get the user to enter the filepath for video1 to be saved

*Run Filepath2() AND VideoConfig1()

*

*get the user to enter the filepath for video2 to be saved

*if FilePath2 hasn't been completed by the time VideoConfig1 has, crash entire program

*Run VideoConfig2()

*Run VideoRecord()

A: Since you said you are entering file paths with spaces, this is what I believe is happening:
FilePath1();
FilePath2();
...

void FilePath1()
{
    cout << "Please enter the full filepath for where you want to save the first video: ";
    cin >> filepath1;

    // user enters the following sans quotes: "c:\my files\file.ext"
    // filepath1 becomes "c:\my"

    cin.ignore();
    // cin.ignore() with no params will clear ONE character from the stream
    // the space is removed from the input stream

}

void FilePath2()
{
    cout << "Please enter the full filepath for where you want to save the first video: ";
    cin >> filepath2;

    // at this point, there is still data in the input buffer,
    // so filepath2 becomes: "files\file.ext" and execution continues
    // without waiting on user input

    cin.ignore();
    // the return is removed from the input stream, input stream is now empty

}

As you suggested, you want to use getline since you are expecting spaces in your input. Here's a good reference to clear up the cin vs getline: http://www.cplusplus.com/doc/tutorial/basic_io/


text:
Q: SQL Server Query to get latest items I have the following information in a table. Assume that we have various fruits where each crate of fruit can have one of the three quality level (Good, bad, and average).
I want to query the table to get the latest quality status of a fruit.

Fruit   Quality  Timestamp

Orange   Good       Nov 10, 11:20 AM
Apple    Bad       Nov 10, 11:10 AM
Banana   Good       Nov 10, 10 AM
Apple   Average       Nov 10, 8 AM
Grapes   Bad       Nov 10, 7 AM
Grapes   Average       Nov 10, 6:45 AM
Apple   Good       Nov 10, 6:20 AM
Banana   Good       Nov 10, 5 AM
Orange   Average       Nov 9, 11 AM
Orange   Bad       Nov 9, 10:20 AM
Apple   Good       Nov 9, 8:20 AM
Grapes   Good       Nov 9, 5 AM
Mango   Bad       Nov 9, 4 AM

Result of query should be:
Orange Good
Apple Bad
Banana Good
Grapes Bad
Mango Bad
I am a newbie and struggling with this query. Any help would be appreciated. Thanks!

A: Have you considered using a window aggregate function along with the QUALIFY clause?
SELECT Fruit
     , Grade
  FROM MyTable
 QUALIFY MAX(Timestamp) OVER (PARTITION BY Fruit) = Timestamp

You should also be able to accomplish it this way:
SELECT Fruit
     , Grade
  FROM MyTable T1
 INNER JOIN
      (SELECT Fruit
            , MAX(Timestamp) AS MaxTimeStamp
         FROM MyTable
        GROUP BY 1) DT1
    ON T1.Fruit = DT1.Fruit
   AND T1.TimeStamp = DT1.MaxTimeStamp;

A: WITH fruitStatus
AS
(
    SELECT fruit, quality, [timestamp],
            ROW_NUMBER() OVER (Partition BY Fruit ORDER BY [TimeStamp] DESC) rn
    FROM    tableName
)
SELECT fruit, quality
FROM fruitStatus
WHERE rn = 1


text:
Q: How do I modify an oracle.sql.ARRAY argument in a Java stored procedure? When writing Java stored procedures, I often receive values via oracle.sql.ARRAY parameters. However, how do I export values via oracle.sql.ARRAY parameters? For example:
public static void fetchFavoriteFoods(oracle.sql.ARRAY favoriteFoods) {
    // What must be done here to add "pizza" and "cheese burger" to favoriteFoods?
}

A: Simply put, you don't.
java.sql.Array and its implementations (like oracle.sql.ARRAY) are

a logical pointer to the data in the
  SQL ARRAY value rather than containing
  the ARRAY value's data.

Needless to say, this means that they are read-only values.

A: This should be along the lines of what you are looking for:
Oracle ARRAY type usage
Basically, you can create an object of your own oracle.sql.ARRAY and use it.


text:
Q: How to Save PDF file to disk or Open in Firefox using Selenium Webdriver I am trying to save pdf file to disk or open pdf in different tab in firefox browser. This is what I have tried but I am unable to save file to desk. And I am also not sure how to find url of the pdf.
firefoxProfile.setPreference("browser.download.defaultFolder", "C:\\Work");
        firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf,application/octet-stream, application/vnd.fdf, application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff");
        firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
        firefoxProfile.setPreference("pdfjs.disabled", true);

        //Use this to disable Acrobat plugin for previewing PDFs in Firefox (if you have Adobe reader installed on your computer)
        firefoxProfile.setPreference("plugin.scan.Acrobat", "99.0");
        firefoxProfile.setPreference("plugin.scan.plid.all", false);


text:
Q: Lifetime parameter in function call has conflicting requirements I have a Screen struct which holds two mutable slices for buffers and one for a canvas:
pub struct Screen<'a> {
    pub canvas: Canvas<'a>,
    pub buffers: [Vec<u32>; 2],
    pub index: usize,
}

Methods to borrow the buffers and a method do swap and write them:
impl<'a> Screen<'a> {
    pub fn get_buf(&'a self) -> &[u32] {
        self.buffers[self.index].as_slice()
    }
    pub fn get_mut_buf(&mut self) -> &mut [u32] {
        self.buffers[self.index].as_mut_slice()
    }
    pub fn swap_buffers(&mut self) {
        self.canvas.copy_from_slice(self.get_buf());
        self.bufnum += 1;
        if self.bufnum == self.buffers.len() {
            self.bufnum = 0;
        }
    }
}

The issue here is that, as answered in another thread (Cannot infer correct lifetime when borrowing index of slice and field of a struct at once), the compiler can't see self.buffers and self.canvas as different things, so I tried to assign a new 'b lifetime to buffers, but it resulted in it having conflicting requirements somehow:
struct Screen<'a, 'b> {
    pub canvas: &'a mut [u32],
    pub buffers: [&'b mut [u32]; 2],
    pub bufnum: usize,
}

impl<'a, 'b> Screen<'a, 'b> {
    pub fn get_buf(&self) -> &'b [u32] {
        self.buffers[self.bufnum]
    }
    pub fn get_mut_buf(&mut self) -> &'b mut [u32] {
        &mut self.buffers[self.bufnum]
    }
    pub fn swap_buffers(&mut self) {
        self.canvas.copy_from_slice(self.get_buf());
        self.bufnum += 1;
        if self.bufnum == self.buffers.len() {
            self.bufnum = 0;
        }
    }
}

How can I solve this problem and still be able to use get_but and get_mut_buf?

A: Use your original struct.
match self {
    Screen { index, buffers, index } => {
        // the parts are separate &mut references here
       ....
    }
}


text:
Q: What's the fastest query to get limited (but different) number of articles from multiple categories? For the homepage of a news portal (powered by PHP and MySQL), I need to get 9 articles from one category, 9 articles from  another category and 28 latest articles from any categories. Which is the fastest way to do it?
I found some solutions that deal with getting a specified number of articles from multiple categories in a single query, but they all return the same number of articles for every category, which doesn't fit my problem. And also they use an IF statement, which i have a feeling wouldn't be best speed-wise(?)
Should i just do 3 queries? Or use UNION ALL to put it all in one query?

A: I don't think you can achieve what you're trying to do in a (non UNION or subselect) query.
In terms of multiple queries vs a UNION or sub-select it depends on how fast the query is. Multiple small queries might incur repeated overhead in querying/fetching responses. In terms of concurrency and playing nicely with other queries more smaller queries generally tends to be nicer to a database in terms of contending against other queries.

A: When you do one query with union or union all, it will be faster than three separate queries, because you save the communication overhead.
Also consider union instead of union all, because union all retains duplicate rows.


text:
Q: Why does Processing use floats instead of doubles? The fact that Processing uses float rather than double has bothered me for a long time.
I found the actual code block in PdeEmitter.java, which is looping through an ANTLR generated AST:
// making floating point literals default to floats, not doubles
case NUM_DOUBLE:
  final String literalDouble = ast.getText().toLowerCase();
  out.print(literalDouble);
  if (Preferences.getBoolean("preproc.substitute_floats")
      && literalDouble.indexOf('d') == -1) { // permit literal doubles
    out.print("f");
  }
  dumpHiddenAfter(ast);
  break;

This leads to a frustrating amount of incompatibility when convert Processing code to standard java (all decimal literals need f added to the end, or all floats need to be renamed to double).
It looks like this can be disabled in the lib/preferences.txt:
# preprocessor: PdeEmitter.java
preproc.substitute_floats = true
#preproc.substitute_image = false
#preproc.substitute_font = false

Nevertheless, this breaks common uses of the API, since all Processing API functions were written for float.
So why is float used everywhere? I can't imagine there being a large incentive for memory usage optimization in this type of application.

A: Processing is mainly aimed at creating visual applications, rather than doing serious number crunching (which is admittedly ironic, given the name). As such, the developers don't think the precision of a double is necessary.
According to the documentation for the float datatype:

"Processing supports the 'double' datatype from Java as well, however it is not documented because none of the Processing functions use double values, which are overkill for nearly all work created in Processing and use more memory. We do not plan to support doubles, as it would require increasing the number of API functions significantly."


text:
Q: ArangoDB update action in .Net I am a .Net developer and is currently exploring on ArangoDB. I have played around with the arangod web user interface and arangod and like this NoSql very much until I delve into the detail of coding. I could not find the .Net driver working properly. Even for simple CRUD operation. Here's the problem.
ArangoClient.AddConnection("127.0.0.1", 8529, false, "Sample", "Sample");

var db = new ArangoDatabase("Sample");

string collectionName = "MyTestCollection";
var collection = new ArangoCollection();
collection.Name = collectionName;
collection.Type = ArangoCollectionType.Document;

if (db.Collection.Get(collectionName) == null)
{
    db.Collection.Create(collection);
}

var employee = new Employee();

employee.Id = "1234";
employee.Name = "My Name";
employee.Salary = 33333;
employee.DateOfBirth = new DateTime(1979, 7, 22);

db.Document.Create<Employee>("MyTestCollection", employee);

employee.Name = "Tan";
db.Document.Update(employee);

It thrown the error for db.Document.Update(employee). Here's the error message:  Field '_id' does not exist.
Then I tried to add the field _id though I think it is weird, it prompted me another error message.
Arango.Client.ArangoException : ArangoDB responded with error code BadRequest:
expecting PATCH /_api/document/<document-handle> [error number 400]
   at Arango.Client.Protocol.DocumentOperation.Patch(Document document, Boolean waitForSync, String revision)
   at Arango.Client.ArangoDocumentOperation.Update[T](T genericObject, Boolean waitForSync, String revision) ...

I have no clues at all and do not know how to to proceed further. Any help will be much appreciated. Thanks.

A: This is likely due to the definition of the Employee class, which is not contained in the above snippet.
To identify a document in a collection, documents have special system attributes, such as _id, _key and _rev. These attributes should be mapped to properties in .NET classes, even if not used explicitly. So one property in the class should be tagged with "Identity", one with "Key", and one with "Revision". Here is an example class definition that should work:
public class Employee
{
    /* this will map the _id attribute from the database to ThisIsId property */
    [ArangoProperty(Identity = true)]
    public string ThisIsId { get; set; }

    /* this will map the _key attribute from the database to the Id property */
    [ArangoProperty(Key = true)]
    public string Id { get; set; }

    /* here is _rev */
    [ArangoProperty(Revision = true)]
    public string ThisIsRevision { get; set; }

    public DateTime DateOfBirth { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }

    public Employee()
    {
    }
}

The ThisIsId property will contain the automatically assigned _id value, and can also be used to retrieve the document easily later:
var employeeFromDatabase = db.Document.Get<Employee>(employee.ThisIsId);

You can of course rename the properties to your like.