text:
Q: Not able to bind src attribute in embed tag using attr binding The textbox binds fine, but the src attribute in the embed tag doesn't bind at all. Why?
http://jsfiddle.net/pscr43sc/1/
<input type='text' data-bind='value: 123'/>
<embed data-bind="attr: {src: 'http://google.com'}" />

A: The problem is not that the src attribute is not being bound by Knockout: that bit is working perfectly, as you can tell from this screenshot of your fiddle with the dev tools open:

The src attribute gets set correctly by KnockoutJS.
You are experiencing (a variant of) this issue where the browser doesn't like the fact that src is dynamically changed on such elements. Mentioned workarounds mostly come down to re-creating the entire element, which is pretty easy to do with KnockoutJS.
Here's a "naive" example that allows for some "dirty" KnockoutJS code, as in that it contains some DOM manipulation inside the view:

function RootViewModel() {
  var self = this;
  self.link = ko.observable("//placehold.it/50");
  self.embedHtml = ko.computed(function() {
    return "<embed src='" + self.link() + "' />"; // Might need some sanitation on "link()"
  });
}

ko.applyBindings(new RootViewModel());
pre { background: white; padding: 10px; color: #333; font: 11px consolas; border: 1px solid #ddd; }

Change link: <input data-bind="value: link">

Debug info:

If you change the link (e.g. change "50" to "200") and blur the input field, you'll see the change on the embed tag.
Note that the above is actually remixed from (and the solution should be attributed to @RPNiemeyer) another SO answer, which also goes on to suggest an alternative. With that alternative you'd create a custom binding handler that clones the embed node on view model updates, changes the src attribute, and then replaces the original node with the clone in the DOM. The upside there is that you have no DOM code inside your view model. The answer links to this jsfiddle for an example.


text:
Q: Contact Form 7 embedded in Wordpress theme page using do_shortcode is displaying everything except the inputs I am trying to embed a Contact Form 7 form in a custom theme page in Wordpress.
My custom theme page is located in /wordpress/wp-content/themes/theme-name/.
All of the HTML markup in the Contact Form 7 form is outputting correctly, including the form tag and all of the hidden inputs generated by CF7.  The only elements that are not displaying are the form fields themselves.  Is there some setting or something else I need to do to get this to work?
PHP code in theme file:
<?php echo do_shortcode( '[contact-form-7 id="503" title="landing-page-1"]' ); ?>

Contact Form 7 form template:

Get your free quote

      [text* requester-name placeholder "Your name" class:form-control class:form-control-lg class:py-3]

      [email* requester-email placeholder "Your email" class:form-control class:form-control-lg class:py-3]

      [tel requester-phone placeholder "Phone (optional but helpful)" class:form-control class:form-control-lg class:py-3]

      [text* property-address placeholder "Property address + zip code" class:form-control class:form-control-lg class:py-3]

          [submit class:btn class:btn-primary class:green-btn class:py-3 "Click here"]

Here is the resulting output (note that the inputs are missing):

<form action="/493-2#wpcf7-f503-o1" method="post" class="wpcf7-form" novalidate="novalidate">

<input type="hidden" name="_wpcf7" value="503" />
<input type="hidden" name="_wpcf7_version" value="5.1" />
<input type="hidden" name="_wpcf7_locale" value="en_US" />
<input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f503-o1" />
<input type="hidden" name="_wpcf7_container_post" value="0" />
<input type="hidden" name="g-recaptcha-response" value="" />

Get your free lawn care quote

    <input type="submit" value="Click here" class="wpcf7-form-control wpcf7-submit btn btn-primary green-btn py-3" />

</form>

A: The answer is... the order of the class attributes matters.
I moved the class attributes to before the placeholder attribute and it worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show retweets and like counts in iOS TwitterKit? In twitterKit, there is a tweetView for displaying the Tweet from tweet model object, but there is no field for showing retweets and likes counts in the tweetView.
cell.tweetView.showActionButtons = true;

This allow us to show action buttons for favorite and share. But I want to show the retweet/likes counts in each tweets. How can I achieve?

A: Just subclass a regular UITableViewCell and use a TWTRTweetView inside of it. Which is basically what TWTRTweetTableViewCell does, it has a tweetView property which is essentially an IBOutlet of type TWTRTweetView and use that in the tableview cell instead.
Place the custom label for like and retweets counts in proper position on top of the TWTRTweetView.
- (void)configureCell:(TWTRTweet *)tweet{
  self.customTweetView.showActionButtons = true;
  [self.customTweetView configureWithTweet:tweet];
  self.likesCount.text = [NSString stringWithFormat:@"%lld", tweet.likeCount];
  self.retweetsCount.text = [NSString stringWithFormat:@"%lld", tweet.retweetCount];
}

For more info: check this SO post


text:
Q: CSS not working in mobile browsers http://mpkosis28.com/28cup
The site looks perfect when viewed from a laptop or a desktop. But when I tried to access it through my phone, it doesn't recognize the css file from the site and only loads the html portion. Read through other similar questions but they don't seem to have the same problem as I do. Any advice on how to fix it?
BTW, If you guys need the codes:
Here is a sample css file
EDIT: I use an android 4.2 phone, native browser

A: You need to make sure that you're telling the browser to set the viewport to the device width. Just define the meta content in your document head as such:
<meta name="viewport" content="width=device-width; initial-scale=1.0;">

A: You should use the following structure
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pruebas</title>
    <meta name="viewport" content="width=device-width; initial-scale=1.0;">
    <link rel="stylesheet" href="styleslocation/style.css">

</head>
<body>

    <!--Content here-->

</body>
</html>

A: I think you are hitting this issue:
http://css-tricks.com/css-tricks-chronicle-vol-iv/
Some mobile browsers need this format for imports:
@import url("css/style.css");

A: If you have not solved this problem I was experiencing the same issue and the problem is the @media query isnt closed properly so it applies to all the styles below it and will only show on the screen resolution that isn't closed so you gotta close the tag properly, just do a cross check.

A: I just cleared my cache, and it worked.


text:
Q: press F1 to open sub menuitem in wpf C# Instead of using Alt + F to open the menu "File", I want to change the holy key F1, how do I do that? Thanks!
 <Grid>
    <Menu Background="Transparent">
        <MenuItem x:Name="asd" Header="_File">
            <MenuItem x:Name="a"  Header="1. _New" InputGestureText="ALT-N" Margin="0,18,0,0"/>
            <MenuItem Header="2. _Open" InputGestureText="Alt+O"/>
            <MenuItem Header="3. _Close"/>
            <MenuItem Header="4. Save"/>
            <Separator/>
            <MenuItem Header="5. Delete" Margin="0,8,0,0"/>
            <MenuItem Header="6. Rename"/>
            <Separator/>
            <MenuItem Header="7. Print" Margin="0,8,0,8"/>
            <Separator/>
            <MenuItem Header="8. Format Disk" Margin="0,8,0,8"/>
            <Separator/>
            <MenuItem Header="9. MINE(Decode)" Margin="0,8,0,8"/>
        </MenuItem>
    </Menu>
</Grid>

A: One way of getting the behaviour you desire would be to add an PreviewKeyDown event listener to your Grid or the parent.
<Grid PreviewKeyDown="Grid_PreviewKeyDown">
    <Menu Background="Transparent">
        <MenuItem x:Name="asd" Header="_File">
            <MenuItem x:Name="a"  Header="1. _New" InputGestureText="ALT-N" Margin="0,18,0,0"/>
            <MenuItem Header="2. _Open" InputGestureText="Alt+O"/>
            <MenuItem Header="3. _Close"/>
            <MenuItem Header="4. Save"/>
            <Separator/>
            <MenuItem Header="5. Delete" Margin="0,8,0,0"/>
            <MenuItem Header="6. Rename"/>
            <Separator/>
            <MenuItem Header="7. Print" Margin="0,8,0,8"/>
            <Separator/>
            <MenuItem Header="8. Format Disk" Margin="0,8,0,8"/>
            <Separator/>
            <MenuItem Header="9. MINE(Decode)" Margin="0,8,0,8"/>
        </MenuItem>
    </Menu>
</Grid>

Then in the underlying C# code add the following action event
private void Grid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.F1) // This filters what key was pressed
    {
        asd.IsSubmenuOpen = true; // This opens the menu
        e.Handled = true; // Setting this to true prevents the any other events from occurring due to the key press
    }
}


text:
Q: meaning of the phrase "name over"? It is from Crash Course Biology. It is at 1 minute and 37 second. Here is the context:

Because coal is made out of carbon, so they named the epoch of geological history over how face-meltingly intense and productive these forests were.

Does it mean the same as name after? Could you please rephrase the sentence for me?

A: I think that "name after" is slightly different from "name over" because when I hear "name after" I tend to think that the two things share the same name. For instance,

I named my son after Freddie Mercury.

In this example, you could not use "name over".
So, "name over" shows not exactly the thing by which it was named, but more the idea by which it was named.
It's also worth noting that "name over" can be used interchangeably with "name for."

A: "Named over" isn't a fixed phrase in English, the way "named after" and "named for" are.
"Over" means "pertaining to [some subject]", so you see uses like

There was a scandal over Trump's alleged use of the n-word.

The writer is using "over" in that sense, but it's not idiomatic.

A: This "named...over" is a mistake for "named after"/"named for".
British English prefers "named after"; American English prefers "named for".
https://books.google.com/ngrams/graph?content=was+named+after%2Cwas+named+for%2Cwas+named+over&year_start=1800&year_end=2000&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cwas%20named%20after%3B%2Cc0%3B.t1%3B%2Cwas%20named%20for%3B%2Cc0%3B.t1%3B%2Cwas%20named%20over%3B%2Cc0


text:
Q: Comments in a programming code On Stack Overflow, many people are asking questions with the following type of programming code:
a = 123;
b = 345;
// g = funGet(a,b); // COMMENT
g = a + b;

When editing the question (for improving the question), should we remove such comments? Are there any guidelines for it?

A: I don't really see any reason to do so, and I'd generally avoid it just in case. If you are absolutely, 100% sure that the commented line has absolutely nothing to do with the question, go ahead and edit it out. But you have to be 100% sure, not 99.99999%.
Keep in mind that if you suggest an edit like that, it's very, very likely to get rejected, simply because changes to a user's code tend to be incorrect, and people don't usually look past that. Combine that with the fact that it's very minor.
So, to summarize: you probably should just let it go. Most people won't even include random comments like that unless they're relevant to the question. If not, it's one line; no big deal.

A: I don't think there are any strict rules about this or that we could realistically come up with some.
My personal guideline is that if there's a lot of commented out code and it makes it harder to read what's going on, I remove it. If it's just one or two lines? Meh.
Either way, you gotta be careful, because sometimes folks will leave commented out code in their samples to show what other things they've tried. Clearing those out could hurt. So, it really depends and I look at each case individually.


text:
Q: How to insert oracle database string with /n /r? I have a string with /n and /r characters. I want to insert them to Oracle database but it inserts with no /n or /r characters. Here is my code:
public static void SaveToDB(string body)
    {
        string connectionString = "bla bla";
        using (OracleConnection oraConn = new OracleConnection(connectionString))
        {
            oraConn.Open();
            OracleCommand oraCmd = new OracleCommand("CTI_DBA.CTI_DOCUMENT_PACK_TEST.CREATE_DOCUMENT");
            oraCmd.CommandType = CommandType.StoredProcedure;
            oraCmd.Connection = oraConn;
            OracleParameter oraParam;

            oraParam = new OracleParameter("IN_DOC_BODY", body);
            oraParam.OracleType = OracleType.VarChar;
            oraParam.Direction = ParameterDirection.Input;
            oraCmd.Parameters.Add(oraParam);

            oraCmd.ExecuteNonQuery();
        }

IN_DOC_BODY datatype is VARCHAR2(1000). I also tried to insert with OracleType.NVarChar, OracleType.Char, OracleType.NChar but nothing changed.
Where is my problem? Any suggestions?
I


text:
Q: Question followed by an explanation / clarification etc of the question in the sentence ... how to punctuate? Is there a standard or preferred way to punctuate this sentence?

Would you prefer that or the status quo, which is ...

The first half is definitely a question, while the second half is definitely a statement. I'm conflicted as to whether to end the sentence with a question mark or period, or whether to use a question mark mid sentence (which intuitively seems quite odd).

A: If you use actual parentheses, the use of the question mark becomes apparent:

Would you like to eat an apple?
  Would you like to eat an apple (which is a kind of round fruit)?

The same is true of the nonessential, appositive information provided in the question after the comma:

Would you prefer that or the status quo?
  Would you prefer that or the status quo, which is . . .?

But as with anything that looks strange, even if it's correct, it may not be useful to keep it phrased as it's been written.
For instance, the sentence could be rephrased:

This is x. The status quo is y. Which would you prefer?
  Knowing that the status quo is x, which would you prefer?

You could use actual or a dash:

Would you prefer that or the status quo (which is x)?
  Would you prefer that or the status quo—which is x?

Or it could be broken into two parts:

Would you prefer that or the status quo? (The status quo is x.)

Last, depending on the nature of the missing information from the question, it could be used adjectivally:

Would you prefer that or the x status quo?


text:
Q: Is my public IP really unique? I'm asking about if the IP address of my router (my "public" IP address) is actually unique, i.e. it is not shared with other routers/hosts over the Internet.
If it is the case, I imagine that there will be some NAT policies applied by my ISP, which translates my "public" IP address and the port of my connection in some other IP:port pair (just like happens in local NAT).

A: Many operators use a version of NAT which is called by several names: Carrier Grade NAT, NAT 44, Large Scale NAT.
Essentially the operators use private addressing between the network core and the edge devices (i.e. your router) and then translate the private addresses to public addresses at the core of their network before traffic goes to another network.
There is not a one to one mapping between the private addresses and the public addresses, and even port numbers can be reused over time.
So to identify a given private address and hence user from the operator logs, you need to look at the public IP address, the public port and the timestamp (as the same public IP and port may be mapped to a different private IP at a different time).
Things start to get even more complex when you try to make the network devices as optimised as possible - there are mechanisms to try to assign to same public IP and port to a private IP that it has used previously for efficiency. This can give the impression to an end device that it has a static IP mapping in the NAT, but often this is not actually the case.
Finally, all the above is independent of any locate NAT you may have in your home or business - i.e. you can and probably will have a NAT translation on you local router for your locals devices also.

A: Unlike IP addresses, public IP addresses are not used in a local network but only on the internet. The routers (iphone: your box) IP address to internet, it that rent your box visible on the internet (it will respond to the ping). But also, when you use a website you use the public address of the web server.
A public IP address is unique in the world, which is not the case for private addresses which must be unique in the same local network but not at the global level since these addresses can not be routed on the internet.
Public IP addresses that list all IP addresses of classes A, B, and C that are part of the list of private addresses for those classes or class A exceptions.


text:
Q: How can I make my markerclusters show an average value instead of the number of samples in a cluster I'm doing research into water quality along some beaches and I have repeatedly been taking samples on set locations. I am now trying to make an interactive map that shows my results but keep running into this issue.
My current code is:
    #create range to define the type as follows
CountsLoc$CFU_Range = cut(CountsLoc$CFU_TOTAL,
                       breaks = c(0, 20, 35, 50, 1000 ), right=FALSE,
                       labels = c("Good[0-20)", "Moderate[20-35)", "Problematic[35-50)", "bad[50-400)"))

#Define a color palette corresponding to the magnitude ranges
pal = colorFactor(palette = c("Green","yellow", "orange", "red"), domain=CountsLoc$CFU_Range)

# Create the map object & add circle marker
leaflet(data=CountsLoc) %>%
  addProviderTiles("Esri.WorldImagery") %>%
  addCircleMarkers(lng = ~Lon,
                   lat= ~Lat,
                   color = ~ pal(CFU_Range),popup = ~CountsLoc$CFU_TOTAL, #use the palette
                   label = paste("Magnitude=", CountsLoc$CFU_TOTAL, "Type=", CountsLoc$CFU_Range),
                   clusterOptions = markerClusterOptions(showCoverageOnHover = TRUE,
                                                         zoomToBoundsOnClick = TRUE,
                                                         spiderfyOnMaxZoom = TRUE,
                                                         removeOutsideVisibleBounds = TRUE,
                                                         spiderLegPolylineOptions = list(weight = 1.5, color = "#222",
                                                                                opacity = 0.5)))

This is now giving me markers that are colored and numbered based on the amount of samples that have been taken from a location instead of the average CFU(contamination) found on a location. Anyone knows how to customize this? thanks for reading


text:
Q: How to send a username between web service requests? Basically the problem is this:
There is a stored database procedure that takes a username as an argument and produces some XML data depending on it. It is called by a method with no arguments in an unsecured web service (let's call that web service WSA). There is also another web service (let's call it WSB) which is supposed to call WSA. In this setup, WSA should only ever be called by WSB and never by anyone else. WSB is what users call and it is the way they get the required XML data. The web services are deployed on OC4J, and they have security enabled on them. WSB is secured by OC4J and is accessed by providing the username and password of an OC4J user.
When testing a web service, OC4J provides you with a form where you can enter login information prior to invoking a web service. If you select to include security info in the header and preview the message before invoking the service, the username and password are in the message.
My problem is that I can't get the security information (or at least the username) to reach the endpoint implementation and invocation of the stored procedure.
So far I have created WSA, made a web service proxy that refers to it, and created WSB based on the proxy.
What I have tried so far to get the username (and why it doesn't work):

*

*Had WSA implement javax.xml.rpc.server.ServiceLifecycle. This provides WSA with an instance of javax.xml.rpc.server.ServletEndpointContext, which provides me with a java.security.Principal. However, that Principal is null if I call WSB (which in turn calls WSA). If I secure WSA and call it directly, the Pricipal is not null and contains the user (but it doesn't solve the problem, because I need to call WSB, not WSA).

*Created handlers (extending javax.xml.rpc.handler.GenericHandler) for both services, which were supposed to be able to process the message. One thing really baffled me here. The handler methods get called correctly - the WSB handler handles the request, then the WSA handler handles the request, then the WSA handler handles the response and finally the WSB handler handles the response. But when I tried printing the messages to a file on each step, I found out that even at the first step (when WSB handles the request) there is no security information in the message. No username, no nothing. The message is in fact quite different from what is shown on the invocation page when previewing the request message before invoking the service.

*Tried injecting an instance of WebServiceContext by using the @Resource annotation, but apparently OC4J doesn't support this.
If anyone can shed some light on where I might be doing something wrong, I would be very thankful.

A: The problem is that "WSA is called by a method with no arguments in an unsecured web service".  So, there is no security context for WSA to pick-up the user id from...
The simplest fix might be to change the WSA API to accept a user id in the request parameters.
HTH
Tom


text:
Q: Create stripe brush in WPF How can I create a brush (DrawingBrush) for stripes as shown in the blog:
http://blog.pixelingene.com/2008/09/quick-tip-to-get-a-striped-background/
I can't use it because it uses scale transform, which means if the UI element is small, the stripes are pretty much not visible or too close together.
I can't use image brush because I need to bind the colors.

A: Just use MappingMode="Absolute":
<LinearGradientBrush MappingMode="Absolute" x:Key="HatchBrush"  StartPoint="0,0" EndPoint="4,4" SpreadMethod="Repeat">
  <GradientStop Offset="0" Color="LightCoral"/>
  <GradientStop Offset="0.75" Color="LightCoral"/>
  <GradientStop Offset="0.75" Color="Gray"/>
  <GradientStop Offset="1" Color="Gray"/>
</LinearGradientBrush>

A: Creates downward 45 degree angle stripe pattern.
Alter viewport to change size of stripes
<DrawingBrush Stretch="UniformToFill" ViewportUnits="Absolute" Viewport="0,0,10,10" TileMode="Tile">
    <DrawingBrush.Drawing>
        <DrawingGroup>
            <DrawingGroup.Children>
                <GeometryDrawing Brush="Black">
                    <GeometryDrawing.Geometry>
                        <GeometryGroup FillRule="Nonzero">
                            <PathGeometry>
                                <PathFigure StartPoint="0,0">
                                    <LineSegment  Point="100,0"/>
                                    <LineSegment  Point="100,100"/>
                                    <LineSegment  Point="0,100"/>
                                </PathFigure>
                            </PathGeometry>
                        </GeometryGroup>
                    </GeometryDrawing.Geometry>
                </GeometryDrawing>
                <GeometryDrawing Brush="#FF404040">
                    <GeometryDrawing.Geometry>
                        <GeometryGroup FillRule="Nonzero">
                            <PathGeometry>
                                <PathFigure StartPoint="0,0">
                                    <LineSegment  Point="25,0"/>
                                    <LineSegment  Point="100,75"/>
                                    <LineSegment  Point="100,100"/>
                                    <LineSegment  Point="75,100"/>
                                    <LineSegment  Point="0,25"/>
                                    <LineSegment  Point="0,0"/>
                                </PathFigure>
                                <PathFigure StartPoint="75,0">
                                    <LineSegment  Point="100,25"/>
                                    <LineSegment  Point="100,0"/>
                                </PathFigure>
                                <PathFigure StartPoint="0,75">
                                    <LineSegment  Point="25,100"/>
                                    <LineSegment  Point="0,100"/>
                                </PathFigure>
                            </PathGeometry>
                        </GeometryGroup>
                    </GeometryDrawing.Geometry>
                </GeometryDrawing>
            </DrawingGroup.Children>
        </DrawingGroup>
    </DrawingBrush.Drawing>
</DrawingBrush>

Alternatively you could bind the scale transform to the height and width of the control using multibinding. Then with a converter, you alter the scale to the max of height or width, then the stripes will remain the same size.


text:
Q: Copy data from Office 365 BasicDataSet_v0.Message_v0 into Azure using Azure Data Factory Problem: I am trying to load data from Office 365 by using Azure Data Factory. When I test connection of the linked service I am getting error:

Office365 data loading failed to get OAuth token. Operation returned an invalid status code 'InternalServerError'

Screenshot of the error:

Tried: I have created linked service (Data store - Office 365). By following steps from this link: Microsoft - Getting started with Microsoft Graph Data Connect
I have registered Application via Azure AD-App Registration for generating Application (client) ID/Service principal ID and Client secrete/Service principle Key.
Two permission are there under API permission page in Application with Granted admin consent.

Please help me I am unable to find the reason , I can't find the missing gear to drive.

A: this is Guosen from ADF dev team.
Can you double check the service principal id and key? Making sure they are all correct.


text:
Q: Open QGIS project files in exclusive mode / alert if project file already in use I have QGIS-Project-Files saved to a network drive and was wondering if it is possible to warn users that a project file is already opened by an other user to prevent concurrent editing of the same project file.
I was thinking of showing an alert like this:

Does anyone have a clue how this could be done?
I found some information on stackexchange but I am not sure if these could be implemented in QGIS in some generic way(not a manually added 'openProject' macro):
https://stackoverflow.com/questions/21126108/ensuring-that-my-program-is-not-doing-a-concurrent-file-write/21149744#21149744
https://stackoverflow.com/questions/11114492/check-if-a-file-is-not-open-not-used-by-other-process-in-python
I know that QGIS shows a warning if I try to save a project file another user has changed since I opened it....
But it would be even better if I got the information in the moment when I open the project that someone else has opened the project, too.
The best option would be to implement this in QGIS core (C++) but a pythonic solution would be also interesting.
A generic C++ solution is probably harder as it has to check the exclusive file access on different OS's (windows, linux, mac).

A: Took me a while to find: a long while ago I had a naive lock file implementation in place, using Python Macros (activate and alter in <QGIS>|Project|Properties...|Macros).
I updated the code to use the QGIS 3.x classes and syntax:
import os
import socket
from qgis.core import QgsProject
from PyQt5.QtWidgets import QMessageBox

### utility functions ###

# get the executing machine and process id #
def _getId():
    return socket.getfqdn()+'.'+str(os.getpid())

# read machine and process id holding lock from lock file #
def _getLockerId(file):
    try:
        with open(file) as _file:
            return _file.readline()
    except:
        return

# create lock file path #
def _getLockFile():
    _path, _file = __getProjectPath()
    return os.path.join(_path,'.'+_file+'.lock')

# create current project file path root and name #
def __getProjectPath():
    return os.path.split(QgsProject.instance().absoluteFilePath())

### QGIS macros ###

def openProject():
    lockfile = _getLockFile()

    try:
        with open(lockfile, "x") as _file:
            _file.write(_getId())
    except OSError:
        _path, _file = __getProjectPath()
        copyfile = os.path.join(_path, _getId() + "__" + _file)

        QMessageBox.information(
            None,
            "Project locked",
            "Cannot open project with write access: "+
              "the following user (user.PID)\n\n"+_getLockerId(lockfile)+
              "\n\nhas already aquired a lock on the project!"+
              "\nCopying project and switching context to\n\n"+copyfile
        )

        QgsProject.instance().write(copyfile)
        QgsProject.instance().read()
        QgsProject.instance().setDirty()

def saveProject():
    pass

def closeProject():
    lockfile = _getLockFile()

    if _getId() == _getLockerId(lockfile):
        os.remove(lockfile)

This will make QGIS check for the existence of a (hidden) lock file (naming schema: .<project_name>.lock) at the project location (needs write access!), and

*

*if present, opens a notification window, copies the project to the same location (naming schema:
<socket_user.PID>__<project_name>) and reads the copy into QGIS

*if not present, one is created holding the current machine and
process id, and the original project is opened as usual

The lock holder will delete the file after closing the project.

This worked well enough for a small team, when I had to come up with a quick and dirty solution since no proper DB/versioning system had been at hand. I haven't done extensive testing; things that may be an issue:

*

*no safety against stale locks due to killed QGIS instances or whatever; deleting the lock file manually is the way to go then

*no error handling whatsoever; with write access at the path location, I haven't encountered any issue, but I'm sure there are

*you'll get a note that "The loaded project file on disk was meanwhile changed.", which refers to the original project file as per the date, but overwrites the copy, so you can safely ignore it

An implementation using the lockfile module may be better; I haven't done any idiomatic, cosmetic or performance updates to the code since I've first written it. Feel free to improve and post as answers.


text:
Q: jquery get object value How do I get get the value url from this string:
[{
    "url": "https://www.filepicker.io/api/file/WGS4Wmkk",
    "filename": "4827889.jpg",
    "mimetype": "image/jpeg",
    "size": 53113,
    "key": "be7BxONVHe_48278891840.jpg",
    "isWriteable": false
}]

With jquery or regular javascript

A: If str is the string you posted above, you can use JSON to parse it:
var data = JSON.parse(str);
console.log(data[0].url); // the url value


text:
Q: How can a scalar be passed to a vector (1D array) to a Fortran subroutine? There is this program:
INTEGER i,k
REAL*8  mp(15,48)
REAL*8  sp(15)
k=0
do i=1,12
   k=k+1
   call Equaltensors(sp,mp(1,k),15)
enddo
end

c=====================

subroutine Equaltensors(tensA,tensB,n)
REAL*8 tensA(n),tensB(n)
INTEGER i
do   i=1,n
     tensB(i)=tensA(i)
enddo
return
end

So basically the value of mp(1,1) and so on is passed to the subroutine as a vector tensB(15) with n=15. What I don't understand is how a real number can be stored in a one-dimension array in a subroutine.

A: The title of your question is a bit misleading. Fortran doesn't allow you to pass a scalar to an array. But what it DOES allow is passing a single element of an array to a routine's array dummy argument - this is called "sequence association" in Fortran. As IanH and others have said, the following elements are automatically associated with the elements of the dummy array, up to the last element in the called routine's actual array.
There are some restrictions on this feature, though. If the element is of a POINTER array,you can't do this.
Going back to your title, I have seen many programs pass, say, the constant 3 to a routine where the dummy is an array. The routine only uses the first element, but this is not legal and newer compilers may detect the error and complain. One workaround for this is to turn the argument into an array by using an array constructor - for example, CALL FOO ([3]), but this works only if the value is to be read, not written.
I've written some blog posts on this general issue - see Doctor Fortran in "I've Come Here For An Argument" and Doctor Fortran in "I've Come Here For An Argument, Side 2"

A: EDIT: corrected per the comment by IanH, who points out that the behavior is guaranteed without making assumptions about the argument passing convention.
This approach started in early FORTRAN, by assuming that the argument is being passed as an address, typically called "call by reference".    The address of scaler mp(1,k) is the address of the first element of this column k.  Since Fortran stores arrays in column major format (http://en.wikipedia.org/wiki/Row-major_order#Column-major_order), the 15 values of the kth column will be sequential in memory.  So if the called subroutine interprets this address as that of a 1-D array tensB of length 15, it will access the elements of the kth column.
In modern Fortran one could write the argument in a clearer manner by selecting a column with an array slice: mp (:,k).


text:
Q: Aure Function App returns 'The credentials supplied to the package were not recognized' when using pfx file I have a Azure Function app on a shared app service plan and I don't want to import my certificates through the Azure portal. That is because this app service plan is shared within the organisation and these certificates are client certificates that I want to be sure of that I am the only one able to access them.
So I import them using Function app settings (and I am moving them to the Vault for even more security).
byte[] bytearray; // PFX file, imported from settings using base64 encoding
string password; // Imported from settings
certificates = new X509Certificate2Collection();
certificates.Import(bytearray, password, X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.PersistKeySet);

Using them goes like this
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
foreach (var cert in certificates)
handler.ClientCertificates.Add(cert);

But the connection is refusing with the error 'The credentials supplied to the package were not recognized'.
I tried a few things

*

*I am sure the PFX is inserted correctly because I can read the 3 certificates that are in them.

*Only one of the certificates has an EKU with Client Authentication, the others are there because this is a privately generated certificate and they represent the chain.

*I tried saving the PFX to local filestorage first. I thought that might be an option because I understand that all certificates go trough the local certificate storage first because of security implications of shielding the private key, and this store keeps a handle open to the PFX file (that might or not exist on disk). That didn't work.

*I know the certificates are OK because I can use them on my Function App when doing this 'the intended way' with uploading on Azure, routing them to the app using WEBSITE_LOAD_CERTIFICATES, and then in-code selecting them from the store (using the X509Store class).

A: If you are setting up X509Certificate2 instance from a pfx file or cert encoded containing private key, you may run into CryptographicException: The system cannot find the file specified..
The reason is Windows stores private key as a file under a user profile directory. By default, Azure Web App (AppService) does not load user profile (avoid overhead for majority scenarios where it is not needed). Hence, the The system cannot find the file specified. issue. To work around, set the below appSetting to enable User Profile.

WEBSITE_LOAD_USER_PROFILE=1

By setting the App Setting WEBSITE_LOAD_USER_PROFILE = 1, Azure Websites will load user profiles for the given application, and thus applications can load certificates from PFX files.
References:
https://azure.microsoft.com/en-in/blog/pdf-generation-and-loading-file-based-certificates-in-azure-websites/
https://github.com/projectkudu/kudu/wiki/Configurable-settings#the-system-cannot-find-the-file-specified-issue-with-x509certificate2


text:
Q: View resets after scrolling in RecyclerView I am implemeting multiple selection on GridManager using RecyclerView.
Here is my code inside adapter
imgStamps.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    //First setting up isSelected() or not

                    if (imageList.get(getAdapterPosition()).isSelected()) {
                        imageList.get(getAdapterPosition()).setSelected(false);
                    } else {
                        imageList.get(getAdapterPosition()).setSelected(true);
                    }

                   //Setting blur image on Imageview onLongclick and resting on again press.
                    if (imageList.get(getAdapterPosition()).isSelected()) {
                        mCount++;
                        imgBlurr.setVisibility(View.VISIBLE);
                    } else {
                        mCount--;
                        imgBlurr.setVisibility(View.GONE);
                    }
                    mCommunicator.clicked(mCount, getAdapterPosition());
                    return true;
                }
            });

The above code is inside ViewHolder not onBindViewHolder.
If I am selectimg first image and scrolls down and then up the view gets reset.
Can the mistake or behaviour can be pointed out?

A: RecyclerView reuses your layout. Put your logic on onBindViewHolder method.
For more information explore this question
How to properly highlight selected item on RecyclerView?

A: RecyclerView will reused your item view when you scroll. To manager multi select you must have an array of selected position (or selected model). And onBindViewHolder, check position in this array to check item selected or not. For more details implement, please refer to : Multi selection in RecyclerView?


text:
Q: NSArray in Objective C - what does it contain When I have such code:
Fruit *fruit= [[Fruit alloc] init];

// This is effectively two different things right, one is "fruit" - the pointer, and another thing is the object it is pointing to (the one that was allocated using alloc/init) - though not directly visible

When I add this to NSArray:
[myArray addObject: fruit];

What gets added to the array is actually a pointer to the Fruit class object, right?

A: Yes, a copy of the pointer, which points to a valid initialized object, so the following won't cause an issue (under ARC, at least):
Fruit *fruit= [[Fruit alloc] init];
[myArray addObject: fruit];
fruit = nil;     // OK, array still contains a valid Fruit object

A: Yes it adds a strong pointer to your object.
Using ARC remember that an object is automatically dealloc'd when there are no strong pointers to them. This means that by design if you use ARC you need to set any pointer to an object that you have to "nil" in order to deallocate it. This includes for instance a pointer stored in an NSArray.

A: As you know if *var is the value at the pointer then var is pointer (as in c language)
which means if *fruit  is the object then you are adding the pointer fruit to the array like [myArray addObject: fruit];


text:
Q: PHP - How to capture only one string between delimiters from multiline strings based on defined position I have a little web sql editor but when user writes a query like:
SELECT * FROM users;
SELECT * FROM references;|  <-- here is the caret, i want to run only this query
SELECT * FROM settings

and submit that string, only the first query is executed. I want to run only that query where the users caret is positioned.
Obviously that example looks easy, but consider more realistic querys used in a real environment, something like:
SELECT col1,col2,col3
FROM users
WHERE id IN (1,2,3,4);
SELECT * FROM references WHERE status = 1
;
SELECT
    a.col1
    , a.col2
    , b.col1
FROM table_a a |                            <--- Here is the caret, run this query
    INNER JOIN table_b b ON b.id_table_a = a.id
WHERE a.id = 5
;
UPDATE table_a SET col1 = 'demo' WHERE id = 3;
-- etc, etc, etc

Until now I have the carets position: row & column, and cut the string in two parts: before the caret and after the caret.
Then I get the substring after last semicolon occurrence at first string, and the substring before de first occurrence at second string.
But i want to know if there are another ways to solve this with more efficiency.

A: Try a regex statement like this:
/(?<=;)(.*)(?=\|)/

A: You can use a regex or non-regex approach for this.  If your queries are going to contain | (pipes) in them then it would be more suitable to nominate a different/unique marker.
Code: (Demo)
$queries="
SELECT col1,col2,col3
FROM users
WHERE id IN (1,2,3,4);
SELECT * FROM references WHERE status = 1
;
SELECT
    a.col1
    , a.col2
    , b.col1
FROM table_a a |                            <--- Here is the caret, run this query
    INNER JOIN table_b b ON b.id_table_a = a.id
WHERE a.id = 5
;
UPDATE table_a SET col1 = 'demo' WHERE id = 3;
-- etc, etc, etc";

$rtrimmed=substr($queries,0,strpos($queries,'|'));     // remove substr following pipe
$ltrimmed=substr($rtrimmed,strrpos($rtrimmed,';')+1);  // remove substr upto latest semicolon
echo trim($ltrimmed);                                  // remove whitespace on either side

echo "\n---\n";

echo preg_match('~;\s*\K[^;|]*?(?= *\|)~',$queries,$out) ? $out[0] : '';

Output:
SELECT
    a.col1
    , a.col2
    , b.col1
FROM table_a a
---
SELECT
    a.col1
    , a.col2
    , b.col1
FROM table_a a

Pattern Demo
Pattern Breakdown:
~         #pattern delimiter
;\s*      #match semicolon followed by zero or more whitespace characters
\K        #restart the fullstring match (release previous matched characters)
[^;|]*?   #match zero or more (lazily) non-semicolon and non-pipe characters
(?= *\|)  #look ahead for zero or more spaces followed by a pipe (so that the output is trimmed)
~         #pattern delimiter


text:
Q: String replace replacing all occurrences of sub string in java I have this java code
    String s3="10100111001";
    String s4="1001";
    String s5="0";
    System.out.println(s3);
    int last_index=3; //To replace only the last

    while(last_index>=0) {
        last_index=s3.indexOf(s4,last_index);
        System.out.println("B:" +last_index);
        if(last_index>=0)
        {

            s3=s3.replace(s3.substring(last_index,(last_index+s4.length())),s5);
            last_index=last_index+s4.length();
            System.out.println("L:"+last_index);
            continue;
        }

        else
        {
            continue;
        }

    }
    System.out.println(s3);

Ideally, this code should replace only the last occurence of 1001 but its replacing both the occurrences of 1001
My output is 10010 but it should be 10100110. where I am going wrong?

A: The expression
s3.substring(last_index,(last_index+s4.length()))

returns "1001" string. Calling replace with that string as the argument will perform the replacement throughout the entire string, so it would replace both occurrences.
To fix your solution, you can replace the call of replace with a composition of three substrings:

*

*from zero to last_index

*s5

*from last_index+4 to the end.

Like this:
s3=s3.substring(0, last_index) + s5 + s3.substring(last_index+s4.length());


text:
Q: mouse up javascript event not firing over image control I have an asp.net image control and am trying to simulate a drag event over it(I don't want the image to move). I just need the co-ordinates of the initial and final position. the mousedown event gets fired but the mouse up event doesn't get fired. Could you help me out ??
var t;

    function set_coordinates_up(event) {
        pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("divScreenshot").offsetLeft;
        pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("divScreenshot").offsetTop;
        var hdf = document.getElementById('HiddenField1')
        if (hdf != null) hdf.value = t + " " + pos_x + " " + pos_y

    }
    function set_coordinates_down(event) {

        pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementById("divScreenshot").offsetLeft;
        pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementById("divScreenshot").offsetTop;
        t = "4" + " " + pos_x + " " + pos_y

    }
<div id="divScreenshot" onclick="set_coordinates(event)" onmousedown="set_coordinates_down(event) " onmouseup="set_coordinates_up(event) " >
                <asp:Image ID="imgScreenshot" runat="server"  />
            </div>

A: Have you considered using jQuery UI? There might be a little bit of a learning curve but they already did the Draggable plugin to make pretty much any object draggable. Its nice to do it yourself, but why reinvent the wheel?
JQuery UI - Draggable

A: Try binding the events on the image rather than the container div.


text:
Q: How to imitate Python 3's raise ... from in Python 2? Python 3 has the neat
try:
    raise OneException('sorry')
except OneException as e:
    # after a failed attempt of mitigation:
    raise AnotherException('I give up') from e

syntax which allows raising a followup exception without loosing context. The best analogy I could come up with in Python 2 is
raise AnotherException((e,'I give up')), None, sys.exc_info()[2]

where the (e,'') is an ugly hack to have the original exception's name included in the message. But isn't there a better way?

A: Instead of using six.raise_from, try to use six.reraise, as explained in this page:
http://python-future.org/compatible_idioms.html
from six import reraise as raise_
# or from future.utils import raise_

traceback = sys.exc_info()[2]
raise_(ValueError, "dodgy value", traceback)

A: There's a raise_from in python-future; simply install it
pip install future

and import to use
from future.utils import raise_from
# or: from six import reraise as raise_from

class FileDatabase:
    def __init__(self, filename):
        try:
            self.file = open(filename)
        except IOError as exc:
            raise_from(DatabaseError('failed to open'), exc)

UPDATE
The compatibility package six also supports raise_from, from version 1.9 (released in 2015). It is used in the same manner as above.


text:
Q: Storyboard - refer to ViewController in AppDelegate consider the following scenario: I have a storyboard-based app. I add a ViewController object to the storyboard, add the class files for this ViewController into the project and specify the name of the new class in the IB identity inspector. Now how am I going to refer to this ViewController programmatically from the AppDelegate? I've made a variable with the relevant class and turned it into an IBOutlet property, but I don't see any way of being able to refer to the new ViewController in code - any attempt to ctrl-drag a connection doesn't work.
i.e. within the AppDelegate I can get to the base ViewController like this
(MyViewController*) self.window.rootViewController

but how about any other ViewController contained within the storyboard?

A: Generally, the system should be handling view controller instantiation with a storyboard. What you want is to traverse the viewController hierarchy by grabbing a reference to the self.window.rootViewController as opposed to initializing view controllers, which should already be initialized correctly if you've setup your storyboard properly.
So, let's say your rootViewController is a UINavigationController and then you want to send something to its top view controller, you would do it like this in your AppDelegate's didFinishLaunchingWithOptions:
UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
MyViewController *myVC = (MyViewController *)nav.topViewController;
myVC.data = self.data;

In Swift if would be very similar:
let nav = self.window.rootViewController as! UINavigationController;
let myVC = nav.topViewController as! MyViewController
myVc.data = self.data

You really shouldn't be initializing view controllers using storyboard id's from the app delegate unless you want to bypass the normal way storyboard is loaded and load the whole storyboard yourself. If you're having to initialize scenes from the AppDelegate you're most likely doing something wrong. I mean imagine you, for some reason, want to send data to a view controller way down the stack, the AppDelegate shouldn't be reaching way into the view controller stack to set data. That's not its business. It's business is the rootViewController. Let the rootViewController handle its own children! So, if I were bypassing the normal storyboard loading process by the system by removing references to it in the info.plist file, I would at most instantiate the rootViewController using instantiateViewControllerWithIdentifier:, and possibly its root if it is a container, like a UINavigationController. What you want to avoid is instantiating view controllers that have already been instantiated by the storyboard. This is a problem I see a lot. In short, I disagree with the accepted answer. It is incorrect unless the posters means to remove loading of the storyboard from the info.plist since you will have loaded 2 storyboards otherwise, which makes no sense. It's probably not a memory leak because the system initialized the root scene and assigned it to the window, but then you came along and instantiated it again and assigned it again. Your app is off to a pretty bad start!

A: If you use XCode 5 you should do it in a different way.

*

*Select your UIViewController in UIStoryboard

*Go to the Identity Inspector on the right top pane

*Check the Use Storyboard ID checkbox

*Write a unique id to the Storyboard ID field

Then write your code.
// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

A: Have a look at the documentation for -[UIStoryboard instantiateViewControllerWithIdentifier:]. This allows you to instantiate a view controller from your storyboard using the identifier that you set in the IB Attributes Inspector:

EDITED to add example code:
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                         bundle: nil];

MyViewController *controller = (MyViewController*)[mainStoryboard
                    instantiateViewControllerWithIdentifier: @"<Controller ID>"];

A:     UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
    self.window.rootViewController = [storyboard instantiateInitialViewController];

A: For iOS 13+
in SceneDelegate:
var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options
connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window = UIWindow(windowScene: windowScene)
    let storyboard = UIStoryboard(name: "Main", bundle: nil) // Where "Main" is the storyboard file name
    let vc = storyboard.instantiateViewController(withIdentifier: "ViewController") // Where "ViewController" is the ID of your viewController
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
}


text:
Q: Python Flask app is not running on heroku servers I am trying to deploy my flask app on heroku but it shows a runtime error on the heroku server, but when i test it on my end, AKA localhost, it seems to work fine
My Code:
import flask
from flask import request
from flask import jsonify
from GoogleNews import GoogleNews
from apscheduler.schedulers.background import BackgroundScheduler
import multiprocessing
googlenews = GoogleNews()
news_latest = []
googlenews.set_lang('en')
googlenews.set_period('1d')
googlenews.set_encode('utf-8')
def get_latest_news():
    global news_latest
    googlenews.get_news('TECHNOLOGY')
    news_latest = googlenews.result()
my_scheduler = BackgroundScheduler()
my_scheduler.add_job(func=get_latest_news, trigger="interval", seconds=5)
my_scheduler.start()
app=flask.Flask(__name__)
@app.route('/', methods=["GET"])
def home():
    return jsonify(news_latest[0: 3])
app.run()

requirements.txt:
gunicorn
GoogleNews
APScheduler

PROCFILE:
web: gunicorn app:appweb: gunicorn app:app

runtime.txt:
python-3.9.4

But the server seems to crash when you open it,
And what is remarkable is in the logs, Flask says it is running on a DEVELOPMENT server. It prints the location where it has started the app as 127.0.0.0.5000

A: On localhost is fine to use the default 5000 port but on Heroku you need to use the one provided by the platform in the $PORT env variable
server_port = int(os.environ.get("PORT", 5000))
app.run(debug=False, port=server_port, host='0.0.0.0')

A: I was able to overcome this problem, The right way of doing this is:
import flask
from flask import request
from flask import jsonify
from GoogleNews import GoogleNews
from apscheduler.schedulers.background import BackgroundScheduler
import multiprocessing
googlenews = GoogleNews()
news_latest = []
googlenews.set_lang('en')
googlenews.set_period('1d')
googlenews.set_encode('utf-8')
def get_latest_news():
    global news_latest
    googlenews.get_news('TECHNOLOGY')
    news_latest = googlenews.result()
my_scheduler = BackgroundScheduler()
my_scheduler.add_job(func=get_latest_news, trigger="interval", seconds=5)
my_scheduler.start()
app=flask.Flask(__name__)
@app.route('/', methods=["GET"])
def home():
    return jsonify(news_latest[0: 3])

The change was to remove app.run() since heroku servers will already be running your code, if you put the app.run() heroku will consider this as default code and will run that too, hence the interpretation process will stop at app.run() and will never complete the interpretation. Hence the app will crash with no return response.


text:
Q: twitter bootsrap modal appears on top of menu (unclickable links) I am working at this site http://www.digiruptiva.com/site/
If you scroll to "Serviços" section at the home page you will see a row of icons and a blue button with the text "saber mais". When you click in the button, a modal opens containing more information.
The problem is: Some links in the top menu like (Quem Somos and Serviços) arent clickable becuase the hidden modal is getting in the way.
I tried moved the modals before the close body tag but still the same problem. I found a topic here an S.0 saying that adding data-backdrop="false" to the modal element solves the problem but I want to have the backdrop.
How can I fix this?
Thank you.

A: Well, i think I solved it by adding .modal { display: none; } to my css ile.


text:
Q: Cannot Obeserve LiveData I am trying to update the values in an EditText by observing a LiveData from a ViewModel.
Here is the FRAGMENT in which I am trying to update the values of my EditText:
private var qnaQuestionData: String = "TEST VALUE"

private val communicationViewModel by lazy {
        ViewModelProvider(this).get(
            MyProfileEditSharedViewModel::class.java
        )
    }

override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        communicationViewModel.question.observe(viewLifecycleOwner, Observer {data ->
                data.let { qnaQuestionData = it }
        })

        et_question.setText(qnaQuestionData)

}

Here is my ViewModel:
class MyProfileEditSharedViewModel : ViewModel() {
    val question: MutableLiveData<String> by lazy { MutableLiveData<String>() }
}

When I run this code, the value of my EditText is set to "TEST VALUE" which means that the LiveData was never observed. How can I fix this??
Thank you!

A: Move the call et_question.setText(qnaQuestionData) to the observer:
communicationViewModel.question.observe(viewLifecycleOwner, Observer { data ->
    qnaQuestionData = data
    et_question.setText(qnaQuestionData)
})

et_question.setText(qnaQuestionData)

A:
I would change your MyProfileEditSharedViewModel  to be like this

class MyProfileEditSharedViewModel : ViewModel() {
    val question: MutableLiveData<String>  = MutableLiveData()
}

and your fragment should be like this

class someFragment(): Fragment() {

    private var qnaQuestionData: String = "TEST VALUE"
    private val communicationViewModel
        get() = ViewModelProviders.of(activity!!).get(MyProfileEditSharedViewModel::class.java)

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        et_question.setText(qnaQuestionData)

        communicationViewModel.question.postValue("This Message will Show") //<------- for testing
        communicationViewModel.question.observe(this, Observer {
            qnaQuestionData = it
            et_question.setText(qnaQuestionData)
        })
    }
}

A: Changing
private val communicationViewModel by lazy {
        ViewModelProvider(this).get(
            MyProfileEditSharedViewModel::class.java
        )
    }

to
private val communicationViewModel by lazy {
        ViewModelProvider(requireActivity()).get(
            MyProfileEditSharedViewModel::class.java
        )
    }

Solved the problem.
The official docs told me to change this to requireActivity()


text:
Q: test is not executed - nightwatch with standard mocha and phantomjs so i have a nodejs server and I want to start on some functional tests with nightwatch.
If I start selenium manually and I run it with mocha ( command: mocha ./test/functional/*.spec.js --compilers js:babel-register) it starts the node server and runs fine in firefox(default - by the way using standard mocha how can it be changed from default firefox to other browser?):
import nightwatch from 'nightwatch';

require('../../server');

describe('Functional', function wrapIt() {
  const client = nightwatch.initClient({
    silent: true,
  });

  const browser = client.api();

  this.timeout(99999999);

  beforeEach((done) => {
    client.start(done);
  });

  it('should login', (done) => {
    browser
      .url('http://localhost:8441/')
      .waitForElementVisible('button[name=login]', 1000)
      .click('button[name=login]')
      .pause(1000);

    browser.expect.element('button').to.have.attribute('class').which.contains('theme__button');
    browser.end();
    client.start(done);
  });

  after((done) => {
    browser.end();
    client.start(done);
  });
});

Now i want to put it on Bamboo and use phantomjs, selenium server starts, nodejs server starts but the test is not executed.
I have nightwatch.json:
{
  "src_folders" : ["test/night"],
  "output_folder": "reports",
  "test_runner" : "mocha",

  "selenium" : {
    "start_process": true,
    "server_path": ".//bin/selenium-server-standalone-2.53.1.jar",
    "log_path": "./reports",
    "host": "127.0.0.1",
    "port": 4444
  },

  "test_settings" : {
    "default" : {
      "desiredCapabilities": {
        "browserName": "phantomjs",
        "phantomjs.cli.args" : ["--ignore-ssl-errors=true"],
        "version":"latest",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    }
  }
}

,nightwatch.conf.js is:
require('babel-core/register');

module.exports = require('./nightwatch.json');

and the test script in night folder:
require('../../server');

describe('Functional', function wrapIt() {
  const client = this.client;
  const browser = client.api();

  this.timeout(99999999);

  beforeEach((done) => {
    client.start(done);
  });

  it('should login', (done) => {
    browser
      .url('http://localhost:8441/')
      .waitForElementVisible('button[name=login]', 1000)
      .click('button[name=login]')
      .pause(1000);

    browser.expect.element('button').to.have.attribute('class').which.contains('theme__button');
    browser.end();
    client.start(done);
  });

  after((done) => {
    browser.end();
    client.start(done);
  });
});

So running it with nightwatch it starts the selenium server, also the nodejs server starts ok but then nothing happens.

A: I changed it using webdriver:
export const client = require('webdriverjs').remote({ // eslint-disable-line
  // Settings
  desiredCapabilities: {
    // You may choose other browsers
    // http://code.google.com/p/selenium/wiki/DesiredCapabilities
    browserName: 'phantomjs',
  },
  // webdriverjs has a lot of output which is generally useless
  // However, if anything goes wrong, remove this to see more details
  logLevel: 'silent',
});

client.init();

and:
require('../../server');

const client = require('./client').client;

describe('Functional testing', function wrapIt() {
  this.timeout(99999999);

  before((done) => {
    client.init().url('http://localhost:8441/', done);
  });

  describe('Check homepage', () => {
    it('should login', (done) => {
      client.waitFor('button[name=login]', 100, () => {
        client.click('button[name=login]', () => {
          client.element('.theme__button*');
          client.waitForVisible(1000);
          client.end();
        });
      });
      done();
    });
  });

  after((done) => {
    client.end();
    done();
  });
});

and it works running mocha './test/funcTest.js' --compilers js:babel-register -t 10000
PS: selenium is already started local and on bamboo I added a commmand to start it


text:
Q: tibco BW http reciever not triggering with get method and with request parameters In TIBCO BusinessWorks, in a stater process with a HTTP Receiver process starter:

*

*If I configure no request parameters in the receiver, then I'm able to receive the request.

*If I configure request parameters in the receiver, then I'm not able to receive the request.

How do I receive the request with request parameters?
I am using TIBCO BusinessWorks 5.9

A: Your configuration seems incorrect to me. Please check that you have created HTTP receiver parameters what you have in your request url (Your request url should be in following format: http://localhost:portNumber/?Parameter1&Paramter2). There are twon ways to read the parameters: Query string and paramters.
Please let me know if you are able to resolve the issue


text:
Q: How to find duplicated field values and delete them in MySQL Consider we have a field named (username) in our table named (tpl_users), now this table has lots of duplicated rows
I wrote this code to delete duplicated usernames:
Delete FROM tpl_users WHERE username = username;

How is it possible to delete duplicated usernames?

A: Your query deletes all the rows where the user name is not NULL.
If you want to identify the user names which are associated with more than one row:
SELECT username
  FROM tpl_users
 GROUP BY username
HAVING COUNT(*) > 1;

Before converting that into a DELETE, you need to be aware that the majority of queries will delete all the records associated with a duplicated name, rather than retaining just one of the duplicates.

A: What you want to do is delete duplicate rows.
You'll do this by finding all non-duplicate rows, and replacing the table with those rows:
create table tpl_users_new as select distinct * from tpl_users;

alter table tpl_users rename to tpl_users_old;

alter table tpl_users_new rename to tpl_users;

A: If you want to keep the users with the lowest id, first make sure this query has what you want to remove (and backup your database):
SELECT u1.id, u1.username FROM tpl_users u1 LEFT JOIN tpl_users u2 ON u1.username = u2.username WHERE u1.id > u2.id;

Then, if your database is backed up, and you're sure the above statement represents what you want to remove.
DELETE u1 FROM tpl_users u1 LEFT JOIN tpl_users u2 ON u1.username = u2.username WHERE u1.id > u2.id

A: Assuming you have a primary key column in the table, you can do this:
DELETE
FROM tpl_uers
USING tpl_users, tpl_users AS vtable
WHERE vtable.id > tpl_users.id
AND tpl_users.username = vtable.username


text:
Q: CSS image appearing on navigation bar on hover acting weird? So down below you see an image of the problem im currently experiencing. I have some classes in lists and on hover i make it so their background image change to a specific image. Basically its acting really weird when it fades in, in a way it kinda jumps into the box instead of fading in which is the problem. I want the image to fade in, not jump in like on the image you can see down below. Anyways, here is my code, thanks in advance for help:

#NavBar ul {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
#NavBar li {
  width: 100px;
  float: left;
}
#NavBar li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  -o-transition: .5s;
  -ms-transition: .5s;
  -moz-transition: .5s;
  -webkit-transition: .5s;
  transition: .5s;
}
#NavBar .hjem:hover {
  background-color: #111;
}
#NavBar .olie:hover {
  background-color: #111;
  background-image: url("billeder/olie_navbar.png");
  background-size: 30px;
  background-repeat: no-repeat;
  background-position: center;
}
#NavBar .kul:hover {
  background-color: #111;
  background-image: url("billeder/kul_navbar.png");
  background-size: 45px;
  background-repeat: no-repeat;
  background-position: center;
}
#NavBar .naturgas:hover {
  background-color: #111;
  background-image: url("billeder/naturgas_navbar.png");
  background-size: 25px;
  background-repeat: no-repeat;
  background-position: center;
}

Hjem

Olie

Kul

Naturgas

A: Add the property which needs to be transitioned, like transition: background ease-in .5s;

#NavBar ul {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}
#NavBar li {
  width: 100px;
  float: left;
}
#NavBar li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  -o-transition: background ease-in .5s;
  -ms-transition: background ease-in .5s;
  -moz-transition: background ease-in .5s;
  -webkit-transition: background ease-in .5s;
  transition: background ease-in .5s;
}
#NavBar .hjem:hover {
  background-color: #111;
}
#NavBar .olie:hover {
  background-color: #111;
  background-image: url("billeder/olie_navbar.png");
  background-size: 30px;
  background-repeat: no-repeat;
  background-position: center;
}
#NavBar .kul:hover {
  background-color: #111;
  background-image: url("billeder/kul_navbar.png");
  background-size: 45px;
  background-repeat: no-repeat;
  background-position: center;
}
#NavBar .naturgas:hover {
  background-color: #111;
  background-image: url("billeder/naturgas_navbar.png");
  background-size: 25px;
  background-repeat: no-repeat;
  background-position: center;
}

Hjem

Olie

Kul

Naturgas

A: It's because you have to specify their width before doing the :hover effect.
Like this
#NavBar .olie, #NavBar .hjem, #NavBar .naturgas, #NavBar .kul {
  background-size: 30px;
}


text:
Q: Animating an expanding textarea with jQuery Objective
I want to animate all of my textareas in various forms. Currently I can only animate one because I am using an ID selector.
Javascript
$(function() {
    $("#content").focus(function(){
        $(this).animate({"height": "85px",}, "fast" );
        $("#button_block").slideDown("fast");
        return false;
    });

    $("#cancel").click(function(){
        $("#content").animate({"height": "30px",}, "fast" );
        $("#button_block").slideUp("fast");
        return false;
    });
});

HTML
<form method="post" action="">
    <textarea  id="content"></textarea>

        <input type="submit" id="button" value=" Share "/>
        <input type="submit" id='cancel' value=" cancel" />

</form>

A: Try this.Use class and select the closest textarea to animate.
A sample demo

$(function() {

  $(".content").focus(function() {
    $(this).animate({
      "height": "85px",
    }, "fast");
    $(this).closest('form').find(".button_block").slideDown("fast");
    return false;
  });

  $(".cancel").click(function(event) {
    $(this).closest('form').find('.content').animate({
      "height": "30px",
    }, "fast");
    $(this).closest('form').find(".button_block").slideUp("fast");
    return false;
  });

});

<form method="post" action="">
  <textarea class="content"></textarea>

    <input type="submit" class="button" value=" Share " />
    <input type="submit" class='cancel' value=" cancel" />

</form>
<form method="post" action="">
  <textarea class="content"></textarea>

    <input type="submit" class="button" value=" Share " />
    <input type="submit" class='cancel' value=" cancel" />

</form>
<form method="post" action="">
  <textarea class="content"></textarea>

    <input type="submit" class="button" value=" Share " />
    <input type="submit" class='cancel' value=" cancel" />

</form>

A: Here you go with a solution https://jsfiddle.net/d71g96cx/

$(function() {
  $(".content").focus(function(){
    $(this).animate({"height": "85px",}, "fast" )
      .siblings('div.button_block')
      .slideDown("fast");
    return false;
  });

  $('input[value="Cancel"]').click(function(){
    $(this).parent('div.button_block')
      .slideUp()
      .siblings('textarea.content')
      .animate({"height": "30px"}, "fast" );
    return false;
  });
});

<form method="post" action="">
    <textarea  class="content"></textarea>

        <input type="submit" id="button" value="Share "/>
        <input type="submit" id='cancel' value="Cancel" />

</form>

<form method="post" action="">
    <textarea  class="content"></textarea>

        <input type="submit" id="button" value="Share "/>
        <input type="submit" id='cancel' value="Cancel" />

</form>

<form method="post" action="">
    <textarea  class="content"></textarea>

        <input type="submit" id="button" value="Share "/>
        <input type="submit" id='cancel' value="Cancel" />

</form>

Hope this will help you.


text:
Q: '<' not supported between instances of 'str' and 'Node'? I'm trying to implement the Huffman coding algorithm but keep getting this error due to the comparisons for the priority queue.
My code:
class Node(object):
    def __init__(self, left=None, right=None):
        self.left = left
        self.right = right
    def children(self):
        return(self.left, self.right)
    def __lt__(self,other):
        return 0

def create_tree(count):
    print(count)
    priority = queue.PriorityQueue()
    for value in count:
        priority.put(value)
    while priority.qsize() > 1:
        one, two = priority.get(), priority.get()
        node = Node(one, two)
        priority.put((one[0]+two[0], node))
    return priority.get()

I've tried multiple attempts of using _lt_ in my HuffmanNode class but always end up with can't compare 'str' to 'Node', 'int' or 'tuple'. I'm wondering if it's possible to do this and any suggestions would be appreciated.
Edit: Also count for create_tree is a list of tuples that looks like:
[(1, 'a'), (1, 'b'), (2, 'c')]
Code that should produce error:
[(1, 113), (1, 107), (1, 98), (1, 120), (1, 106), (1, 118), (1, 108), (1, 122), (1, 121), (1, 100), (1, 87), (1, 70), (1, 10), (2, 84), (2, 117), (2, 99), (2, 119), (2, 102), (2, 109), (2, 97), (2, 46), (3, 110), (3, 112), (4, 114), (4, 115), (4, 116), (4, 103), (5, 104), (5, 101), (7, 105), (8, 111), (18, 32)]

Also realized I changed my code so it uses ASCII values rather than strings but I get the same error whether it's 'int' or 'str'

A: This is lifted straight out of the docs for PriorityQueue:

The lowest valued entries are retrieved first (the lowest valued entry
  is the one returned by sorted(list(entries))[0]). A typical pattern
  for entries is a tuple in the form: (priority_number, data).
If the data elements are not comparable, the data can be wrapped in a
  class that ignores the data item and only compares the priority
  number.

The example code they give is:
from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)

Using the example that you provided for count = [(1, 'a'), (1, 'b'), (2, 'c')]:
def create_tree(count):
    print(count)
    priority = queue.PriorityQueue()
    for value in count:
        priority.put(value)
    while priority.qsize() > 1:
        one, two = priority.get(), priority.get()  # one == (1, 'a'); two == (1, 'b')
        node = Node(one, two)  # node == Node(left=(1, 'a'), right=(1, 'b'))
        priority.put((one[0]+two[0], node))  #  (2, Node(left=(1, 'a'), right=(1, 'b'))  <== error here
    return priority.get()

When your code adds (2, Node(left=(1, 'a'), right=(1, 'b')) to the PriorityQueue the other element in the queue, (2, 'c') has the same priority, so the data element is used to sort.
So, you need to either explicitly ignore sorting by data (see the docs example above for some guidance), or define how 'c' should sort relative to Node(left=(1, 'a'), right=(1, 'b')) and implement it. For example if you always want Node to sort last relative to some other data type:
def __lt__(self, other):
    return True

def __gt__(self, other):
    return False

Or vice versa:
def __lt__(self, other):
    return False

def __gt__(self, other):
    return True

Or something more complicated?

A: When you implement __lt__(), you create the comparison for Node < int, but not int < Node.
To get this, we need to reverse the operation:

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other's reflection, __le__() and __ge__() are each other's reflection, and __eq__() and __ne__() are their own reflection.
Python data model documentation

In other words, when evaluating B < A i.e. B.__lt__(A) and B does not define a suitable __lt__() method, it uses A.__gt__(B) instead.
To fix this, add the following to your Node class:
def __gt__(self,other):
    return 0 # or something else intelligent


text:
Q: Jquery: slideToggle() multiple divs independently using one function Markup:

Heading 1

Line One

Line Two

Line Three

Heading 2

Line One

Line Two

Line Three

and the JQuery:
$(".toggle").slideUp();
$(".trigger").click(function(){
    $(".toggle").slideToggle("slow");
  });

I'd like to be able to toggle these
s independently. Currently, when either
 title is clicked both divs toggle...
code is at: http://jsfiddle.net/CPvCZ/4/

A: The solution is quite simple:
$(".toggle").slideUp();
$(".trigger").click(function(){
    $(this).next(".toggle").slideToggle("slow");
  });

http://jsfiddle.net/CkTRa/


text:
Q: Knockout foreach is not creating child elements The binding below works in that it creates the li and a elements as expected, but for some reason the i element nested inside the a element is not created. How do I tell knockout to create nested i element?
The fiddle: http://jsfiddle.net/TJdhW/3/ illustrates this. The li items are created without icons.

ePM

http://jsfiddle.net/TJdhW/3/

A: The problem is with your data-bind="text: property" an the a element which replaces the whole content of the link so it removes the icon and only displays the value of the property property.
In order to have both the text and the icon inside your anchor move the data-bind="text: property" inside the a (for example on a span element):

Demo JSFiddle.


text:
Q: check if IsNumeric using Me.Controls() I have a userform with dozens of text boxes where the user should input only numbers from 1 to 6. When the form is completed the user clicks Save and the numbers are added to an Excel table.
As the text boxes are quite a lot I used the following code to read their value:
' Text boxes name are: txt_a01, txt_a02, txt_a03...
For i = 1 To 5
    ws.Cells(iRow, i).Value = Me.Controls("txt_a0" & i).Value
Next

' Here text boxes name are: txt_b01, txt_b02, txt_b03...
For i = 6 To 10
    ws.Cells(iRow, i).Value = Me.Controls("txt_b0" & i - 5).Value
Next

etc.

rather than write dozens of times:
ws.Cells(iRow, 1).Value = Me.txt_a01.Value
ws.Cells(iRow, 2).Value = Me.txt_a02.Value
ws.Cells(iRow, 3).Value = Me.txt_a03.Value
ws.Cells(iRow, 4).Value = Me.txt_a04.Value
ws.Cells(iRow, 5).Value = Me.txt_a05.Value

Now I would like to check - during input - if the user has really added a number and if its between 1 and 6. Normally I would do it like this:
Private Sub txt_a01_AfterUpdate()
    If Not IsNumeric(txt_a01.Value) Then
        MsgBox ("Only numbers accepted")
    End If
End Sub

But as I use a FOR - LOOP and Me.Controls() to read the text box values I don't understand how to write down the _AfterUpdate Sub.

A: You could attach dynamically an event handler on form load or you could create a custom control with an event.
Personally I prefer use custom control and KeyPressEventHandler to refuse all not allowed chars.
You may create a class to handle the event :
Private WithEvents m_oTextBox as TextBox

Public Property Set TextBox(ByVal oTextBox as TextBox)
Set m_oTextBox = oTextBox
End Property

Private Sub m_oTextBox_Change()
' Do something
End Sub

then, for each control:
Dim myEventHandler As TextBoxEventHandler
        Set myEventHandler = New TextBoxEventHandler

        Set myEventHandler.TextBox = oControl

        m_oCollectionOfEventHandlers.Add myEventHandler


text:
Q: How To Add Row Dynamic with Rowspan in Table with JavaScript I have 2 add button. First add button on header, click this button will add 1 new row. Second add button in table (such as image on my post), click this button will add new row such as image my post. I want add row in table such as below image, but i haven't thought of a solution yet. Hope to be got your helps!
View Image Here

A: The insertRow() method allows you to add rows to a
 and returns a reference to a new row. Adding that to an onClick() function should be easy! :)
Here's the relevant information on Mozilla's site .

A: To solve this, you have to add a new table inside td, like this

function addNewRow() {
    let table = document.getElementById("add");
    table.innerHTML  += '

This is a test

';
}

          <button onclick="addNewRow()">Add</button>

                  This is one td
                  This is another td


text:
Q: JDBC CLASSPATH Not Working I'm setting up a simple JDBC connection to my working MySQL database on my server. I'm using the Connector-J provided by MySQL. According to their documentation, I'm suppose to create the CLASSPATH variable to point to the directory where the mysql-connector-java-5.0.8-bin.jar is located. I used export set CLASSPATH=/path/mysql-connector-java-5.0.8-bin.jar:$CLASSPATH. When I type echo $CLASSPATH to see if it exists, everything seems fine. But then when I open a new terminal and type echo $CLASSPATH it's no longer there. I think this is the main reason why my Java server won't connect to the JDBC, because it isn't saving the CLASSPATH variable I set.
Anyone got suggestions or fixes on how to set up JDBC in the first place?

A: Forget the CLASSPATH environment variable. It's a big joke. It's ignored by pretty much everything else than a low-level java com.example.Foo command. It's ignored when you add the -jar argument. It's ignored when you add the -cp or -classpath argument. It's ignored by IDE's and web/application servers. That environment variable was intented as a convenience for starters. But beyond that, it's useless.
It boils down to that the JAR file has got to be placed in any of the existing/default paths of the runtime classpath of the Java application in question, or that at least the path to the JAR file is to be added to the runtime classpath of the Java application in question.
Since you're talking about a server and considering the fact that the CLASSPATH environment variable doesn't work, I'll assume that it's actually a webserver/appserver such as Apache Tomcat. If that's indeed true, you've got to either drop the JAR file in Tomcat/lib folder (if you use the container managed DataSource approach for a fast connection pool), or in webapp's WEB-INF/lib folder (if you use the poor man's Class#forName() approach to load the driver).
If it's not and it's actually a Java application which is to be executed as a JAR, then you've got to specify the classpath in MANIFEST.MF file of the JAR in question. But if it's also not that and it is a loose .class file, then you've got to specify the classpath in -cp or -classpath argument of java command. To save yourself from typing it again and again when executing it, just create a .sh file with the command.

A: Try to do :
Class.forName("com.mysql.jdbc.Driver");

before getting your connection
You might also want to get a more recent version of the mysql jdbc driver. 5.0.8 is pretty old.
Take a look at JDBC Basics it will give you some tips.
This tutorial might help you as well.

A: You seem to be working on a linux box. Make sure that your terminal launches a login shell. For example the gnome-terminal application (probably what you are using if you are using a ubuntu or fedora box for development) has a checkbox under the profile preferences > Title and command menu called "run command as a login shell". Check that and make sure you also put this code in the ~/.bash_profile file at the end.
export CLASSPATH=/path/mysql-connector-java-5.0.8-bin.jar:$CLASSPATH

But i would argue against doing this and doing a simple launch script for your application. Something similar to this:
#!/bin/bash

Set CLASSPATH=CLASSPATH=/path/mysql-connector-java-5.0.8-bin.jar:$CLASSPATH

java -cp "$CLASSPATH" <your.main.application.Class>

make executable and use that to launch your application.

A: I know this is an old thread but it might help someone.
I have succeeded connecting to SQLite3 on Windows 7 with the proper CLASSPATH
I use the JDBC driver sqlite-jdbc-3.7.2.
First I tried to copy the driver under the directory c:\Program Files\java\jre7\lib and then set the CLASSPATH variable, but that failed to recognize the line :
Class.forName("org.sqlite.JDBC");

I think that's due to the Windows bug to have spaces in a folder name like "Program Files".
So I copied the JAR file under C:\jbmorla and set the CLASSPATH to:
.;c:\jbmorla\sqlite-jdbc-3.7.2.jar

Hope this helps

A: For MAVENS project solution. You can directly modify the pom.xml file.
Add the mysql-connector dependency to the pom.xml project file:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.40</version>
</dependency>

A: In Ubuntu 20.04: Set permanent class path of jdbc driver
Install Mariadb driver
sudo apt install libmariadb-java

Put the class path in .bashrc file
export CLASSPATH=/usr/share/java/mariadb-java-client-2.5.3.jar:$CLASSPATH

Save the file


text:
Q: Repartition to avoid large number of small files Currently I have a ETL job that reads few tables, performs certain transformations and writes them back to the daily table.
I use the following query in spark sql
     "INSERT INTO dbname.tablename PARTITION(year_month)
            SELECT * from Spark_temp_table "
The target table in which all these records are being inserted is partitioned at a year X month level. Records which are generated on a daily basis are not that much hence I am partitioning on year X month level.
However, when I check the partition, it has small ~50MB files for each day my code runs (code has to run daily) and eventually I will end up having around 30 files in my partition totalling ~1500MB
I want to know if there is way for me to just create one (or maybe 2-3 files as per  block size restrictions) in one partition while I append my records on a daily basis
The way I think I can do it is to just read everything from the concerned partition   in my spark dataframe, append it with the latest record and repartition it before writing back. How do I ensure I only read data from the concerned partition and only that partition is over written with lesser number of files?

A: you can use DISTRIBUTE BY clause to control how the records will be distributed in files inside each partition.
to have a single file per partition, you can use DISTRIBUTE BY year, month
and to have 3 file per partition, you can use DISTRIBUTE BY year, month, day % 3
the full query:
INSERT INTO dbname.tablename
PARTITION(year_month)
SELECT * from Spark_temp_table
DISTRIBUTE BY year, month, day % 3


text:
Q: Accessing MenuDrawerNavigator Header from the Java Class I am trying to modify the Menu Drawer that is suggested from the wizard.
when  creating the Drawer Menu. It generates the followings Files:
MainActivity2.java
the Layouts :
1-activity_main2
2-app_bar_main2
3-content_main2
4- nav_header_main2
activity_main2 layout as the followings :
  <?xml version="1.0" encoding="utf-8"?>
  <android.support.v4.widget.DrawerLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/drawer_layout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  tools:openDrawer="start">

<include layout="@layout/app_bar_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main2"
    app:menu="@menu/activity_main2_drawer" />

  </android.support.v4.widget.DrawerLayout>

THe Nav_Header_main2 as the followings :
     <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom">

<ImageView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:src="@mipmap/hadir_ic"
    android:id="@+id/imageView" />

<TextView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:id="@+id/USERNAME"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    />

 </LinearLayout>

My Main2Activiy as the followings :
   public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private String USERNAME ;
private TextView UserName ;

private Intent intent  ;
Bundle bundle = new Bundle();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    //UserName = (TextView) findViewById(R.id.USERNAME) ;
    setSupportActionBar(toolbar);
    intent = getIntent();

    USERNAME = intent.getStringExtra("USERNAME");
    //UserName.setText(USERNAME);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle =
            new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    /*if (id == R.id.action_settings) {
        return true;
    }
   */
           return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camara) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
 }

I want to access The USERNAME ViewText that is in the nav_header_main2 layout from this Activity.
The Error :
     11-28 18:26:23.367 28297-28323/hadirfinalversion.amjad.hadirfinal  W/EGL_emulation: eglSurfaceAttrib not implemented
     11-28 18:26:23.367 28297-28323/hadirfinalversion.amjad.hadirfinal W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad74cd80, error=EGL_SUCCESS
     11-28 18:26:23.988 28297-28323/hadirfinalversion.amjad.hadirfinal E/Surface: getSlotFromBufferLocked: unknown buffer: 0xabe943e0
     11-28 18:26:24.185 28297-28297/hadirfinalversion.amjad.hadirfinal D/AndroidRuntime: Shutting down VM
     11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime: FATAL EXCEPTION: main
     11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime: Process: hadirfinalversion.amjad.hadirfinal, PID: 28297
     11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{hadirfinalversion.amjad.hadirfinal/hadirfinalversion.amjad.hadirfinal.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at hadirfinalversion.amjad.hadirfinal.Main2Activity.onCreate(Main2Activity.java:51)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6237)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
      11-28 18:26:24.186 28297-28297/hadirfinalversion.amjad.hadirfinal E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: You can access the particular TextView from your MainActivity2.java like you do for any other other view in main_activity2
TextView userName = (TextView) findViewById(R.id.USERNAME);

and then set it to whatever you want using like
userName.setText(R.string.app_name);

Since main_activity2 got design.widget.NavigationView with headerLayout set to
app:headerLayout="@layout/nav_header_main2"

and your USERNAME TextView is inside that nav_header_main2 layout, you can access that ID from MainActivity2. Hope it helps :)
EDIT :
Okay the only difference I can spot between your code and mine is that I initialized the TextView after I initialized the DrawerLayout and NavigationView
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//UserName = (TextView) findViewById(R.id.USERNAME) ; REMOVE
setSupportActionBar(toolbar);
intent = getIntent();

USERNAME = intent.getStringExtra("USERNAME");
//UserName.setText(USERNAME); REMOVE

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle =
        new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
UserName = (TextView) findViewById(R.id.USERNAME) ; // add here
UserName.setText(USERNAME); // add here