text:
Q: zsh: How to declare associative array programmatically? To declare associative array programmatically, I tried this:
foo=bar
typeset -A "${foo}"=(
  [key1]="hello world"
  [key2]=baz
)

Whatever I try, I'm getting:

zsh: unknown sort specifier

How to declare an associative array using a variable to set its name ?

A: This might not be the best way, but you can use indirect parameter expansion  after declaring the name to be an associative array.
foo=bar
typeset -A "${(p)foo}"
typeset "${(p)foo}[hello]=world"

You can also use set -A
foo=bar
set -A $foo hello world


text:
Q: jQuery Accordion Icons Not Showing I've never used the icon feature in jQuery before, but I assumed they would be part of the linked UI style sheet. Do I need to download the icon pack or something before they show up? Here's my project and everything is working, just no icons.
In the Header:

And in the footer:

And the actual html structure of the accordion elements:

Header Text

Words and stuff

Oh hello, I'm the second header

SO MANY WORDS!

Thanks.

A: You need to include some CSS files by the looks of it.
I've created a fiddle with your code, including the CSS file, and everything works fine.
http://jsfiddle.net/MaWsm/
<link href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve number of views in a scrollview I am currently trying to write some automated tests within instruments and am having a bit of an issue, is it possible to retrieve the number of views/panes in a scrollView so that I can say, if more than one view, scrollRight() for example?

A: int count = scrollview.subviews.count;

if ( count > 1 )
{
.....
}

??
EDIT:
You will need to get a reference to the view you are looking for. This will be done by iterating through your windows subview collection. In objective-C it would be something like this:
 NSInteger count = 0;
 for ( UIView *view in self.window.subviews )
 {
     if([view isKindOfClass:[UIScrollView class]])
     {
          count = (UIScrollView *) view.subviews.count;
     }

 }


text:
Q: VB .NET Parse XML to Linq Im trying to parse the XML using Linq Query but im not able to parse. Please help me
responseXMLstring = "<?xml version='1.0' encoding='UTF-8'?>
                <Student>
                <StudentId>00000</StudentId>
                <FirstName>Tuan</FirstName>
                <LastName>xxx</LastName>
                <Email>xxxxx</Email>
                <AccBalance>350.64</AccBalance>
                <Bak>
                <AcPeriod>2022U</AcPeriod>
                <Amount>340.32</Amount>
                <Ac>2022S</AcPeriod>
                <Amount>10.32</Amount>
                </Bak>
                </Student>"

Code
       Dim query = From termviseSum In reportEntryXML.Descendants("Student").Elements("Bak").Elements("Amount") Group CDec(termviseSum) By GroupKey = CStr(termviseSum.Parent.Element("AcPeriod").ElementsAfterSelf.Value) Into g = Group
                            Select New With {Key .TermCode = GroupKey, Key .Balance = g.Sum()}

Above linq query is not returning proper result
below screenshot is my expected result.

Thanks in advance


text:
Q: Facebook login with Laravel 5 I'm trying to create a login via facebook to a laravel 5 based application.
I read This social authentication explanation.
  [1]: http://laravel.com/docs/5.0/authentication#social-authentication

I added this to my routes:
   Route::get('facebook-login', 'FacebookLogin@redirectToProvider');

I added this to the controllers folder, file name :FacebookLogin.php
 <?php namespace App\Http\Controllers;
    class FacebookLogin{
    public function redirectToProvider()
{
    return Socialize::with('facebook')->redirect();
}

public function handleProviderCallback()
{
    $user = Socialize::with('facebook')->user();

    // $user->token;

dd($user);
}

}

Now when i go to:
http://localhost:8000/facebook-login

This is the message that i get:
FatalErrorException in ControllerDispatcher.php line 201:
Call to undefined method App\Http\Controllers\FacebookLogin::getAfterFilters()

Does anyone have any insight?
Thanks in advance!

A: The problem is your FacebookLogin does not extend Controller (or BaseController in laravel 4).
Try
use App\Http\Controllers\Controller;
class FacebookLogin extends Controller
{
//Your code
}


text:
Q: How to pass scalar parameters in EF6 raw sql function? I am adding scalar parameters in my SQLquery, but whenever the query executes I am getting an exception for the follwoing piece of code:
IEnumerable<ICRDocumentComplete> results = saturnContext
                .Set<ICRDocumentComplete>()
                .SqlQuery(query,
                    new SqlParameter("@StartDate", startDate),
                    new SqlParameter("@EndDate", endDate.AddDays(1)),
                    new SqlParameter("@SubmissionId", submissionId));

I have my query saved inside the query variable. I am getting a null reference, but I am assuming it is just because I didn't add the scalar variables correctly. Can someone shed some light on this matter?

A: make sure that saturnContext, query, endDate is not null at the time of execution.


text:
Q: How do I concatenation two strings in Bash without using variables? I'm trying to tar a large directory, and I'd like the output file to contain the date. Here's what I have so far.
tar -zcvf "mywebsite website backup" $(date "+%Y-%m-%d %T") public_html

This doesn't quite work though. As an example, I'm trying to get the single string below to be the file name. The call to date is working fine and I don't need help with that, but I'm not sure how to concatenate the "my website backup" with the output from date without first storing them in variables (which seems ham fisted).
mywebsite website backup 2001-12-01 12:04:03

A: Variables and such are interpreted within double quotes (but not within single quotes):
tar -zcvf "mywebsite website backup $(date '+%Y-%m-%d %T').tgz" public_html

(I added the .tgz suffix, you apparently forgot.)
If you had no white space in your file name, you could do it without quotes:
tar -zcvf foo_backup_$(date '+%Y-%m-%d_%T').tgz foo/

Or you could turn it around and use the fact that date already accepts a format string:
tar -zcvf $(date +'foo_backup_%Y-%m-%d_%T.tgz') foo/

(Still needs double quotes around $() if the file name contains white space.)
NB: For various reasons it is usually not a good idea to include colons in file names.

A: You can also try syntax:
tar -zcvf "mywebsite website backup `date \"+%Y-%m-%d %T\"`.tgz" public_html


text:
Q: Looking for Case Studies of How TDD Improved Quality and/or Speed of Development At my company I am trying to make a case for why we should be doing TDD. Currently most developers just do whatever they can to get the project done, then go add unit tests after the fact in order to meet manager metrics. Any examples from reputable companies doing TDD and seeing the benefits would be greatly appreciated.

A: A study of 4 projects in IBM and Microsoft. Published in Emperical Software Engineering journal.
Empirical Studies Show Test Driven Development Improves Quality

A paper first published in the Empirical Software Engineering journal reports: "TDD seems to be applicable in various domains and can significantly reduce the defect density of developed software without significant productivity reduction of the development team." The study compared 4 projects, at Microsoft and IBM that used TDD with similar projects that did not use TDD...
The paper includes 1 case study at IBM and 3 from Microsoft. Each of the case studies compare two teams working on the same product, using the same development languages and technologies, under the same higher-level manager, only one of which was using test-driven development (TDD). None of the teams knew that they would be part of the study during their development cycles. The IBM case study followed teams doing device driver development. The Microsoft cases followed teams working on Windows, MSN, and Visual Studio.
The paper describes the TDD practices used by the teams as minute-to-minute workflows, as well as task-level workflows...

A: There is a chapter about TDD with a case study in the recent book, "Making Software: What works and why we believe it". But you may be disappointed, since if I recall correctly the study did not uncover any real benefits to TDD. The case study was interesting anyway, and the book in general is one of the best software books I'v read recently. It contains many case studies of things like pair programming, code review, etc.

A: look at how much time you and the client spent manually testing the software; compare that to an estimate of how long TDD-style automated tests would have taken. Pocket the difference
in my experience, TDD's automated tests are gold because they provide insurance and eliminate enormous amounts of manual testing
as Andres F pointed out, you can get these benefits merely from automated testing, not necessarily TDD - however, TDD requires automated tests instead of it being an afterthought or nice-to-have
Being forced to think about testing first also forces you to think about quality-related issues - such as modularity, interface design, and so on - before you start writing code.
Personally, I believe one of the biggest benefits of TDD is that writing the test first keeps the specification of what the code actually has to do fresh in your mind while you are writing the code, rather than sort-of-figuring-it-out-as-you-code.

A: Definitely check out this: TDD Proven Effective! Or is it?

...when Phil Haack announced that Research Supports the Effectiveness of TDD I was more than a little interested in seeing what the linked report actually contained. Phil quotes from the abstract.

We found that test-first students on average wrote more tests and, in turn, students who wrote more tests tended to be more productive. We also observed that the minimum quality increased linearly with the number of programmer tests, independent of the development strategy employed.

Phil has obviously read the rest of the report and provides his favorite pieces that seem to do as his title suggests. One of the things I worry about when I see things supporting the latest and greatest software development practices, however, is a strong tendency towards confirmation bias — of looking for confirmation of current theories and overlooking counter-indicators.
So, being the curious type and since TDD is something I'm keeping an eye on to see if its something I might want to adopt myself some day, I went into the report...
...without question, testing first leads to having more tests per functional unit. The question is if this is valuable. This study would seem to indicate that this is probably not the case, at least if quality is your intended gain. But then, I'm not that surprised that number of tests doesn't correspond to quality just as I'm not surprised that the number of lines of code doesn't correspond to productivity.

The author has a lot of good points about TDD not being all that effective (imo despite being hyped to death)

A: you want to make the case for it: suggest you do it for the next project, and then learn from it. If it turns out it works great for you, then I hope you'll continue to use it and if it took longer to do the project and/or spend all your time writing tests instead of coding, then you'll surely dump it as a failure.
I think the real-world solution is (like most things) a mid-way, you want tests but you don't want the tests to be more important than the project.
(personally I think TDD is a fad, sounds good in theory, but in practice... not so good. I find integration testing is far more important, but that could be just the kind of complex projects I work on).

A: I have been working using TDD for 2 years and where I worked at the time ,we were all reluctant to use including managers.However it soon turned to be the right thing todo.The benefits that we soon noticed were

*

*Discovering bugs at an early stage.

*Writing Better code without even realising.

*Your code is now more maintainable as due to your testing
is all in small chunks (we hadfunctions that were 300-400lines)silly. Now max 30 and all
indenpendently tested.

The managers would not know as they are all interested in one thing "Have you finished".
But then they complain when the software keeps breaking without realising.
With a good coverage and sensible tests.It's not the quantity but quality you can really see when somebody breaks a functionality.
Also unfortunately it's difficult if you are on your own.I had the same problem,as you might need to change code eg base classes etc so that you can make parts of the software testable.
I give you an example.I wanted to mock the repository but there was no interface and i need to inject the repository into my service layer and therefore add/modify a constructor all over the shop,this turned out to be a big deal but in the end i have more than 200 tests just testing one area of the system and they were impressed.
I usually do the following:

*

*I keep my unittests very short

*Only 1 assert .No russian roulette.

*I test a positive -negative and exception scenario

Regarding case studies I am afraid ,I am not sure I have seen any. You need to build your project and become your case studies.They might be impressed too.
I hope it helps


text:
Q: UIViewController! Does not conform to protocol "LogicValue" I am trying to convert the following objective-c code to swift:
- (UIViewController *)currentViewController
{
    UIViewController *viewController = self.rootViewController;
    while (viewController.presentedViewController) {
        viewController = viewController.presentedViewController;
    }
    return viewController;
}

#ifdef __IPHONE_7_0

- (UIViewController *)viewControllerForStatusBarStyle
{
    UIViewController *currentViewController = [self currentViewController];

    while ([currentViewController childViewControllerForStatusBarStyle]) {
        currentViewController = [currentViewController childViewControllerForStatusBarStyle];
    }
    return currentViewController;
}

- (UIViewController *)viewControllerForStatusBarHidden
{
    UIViewController *currentViewController = [self currentViewController];

    while ([currentViewController childViewControllerForStatusBarHidden]) {
        currentViewController = [currentViewController childViewControllerForStatusBarHidden];
    }
    return currentViewController;
}

#endif

//SWIFT

func currentViewController() -> UIViewController {

    var viewController = self.rootViewController

    while (viewController.presentedViewController) {
        viewController = viewController.presentedViewController
    }
    return viewController

}

func viewControllerForStatusBarStyle() -> UIViewController {

    var cViewController = currentViewController()

    while (cViewController.childViewControllerForStatusBarStyle) {
        cViewController = cViewController.childViewControllerForStatusBarStyle
    }
    return cViewController

}

func viewControllerForStatusBarHidden() -> UIViewController {

   var cViewController = currentViewController()

        while (cViewController.childViewControllerForStatusBarHidden) {
            cViewController = cVC.childViewControllerForStatusBarHidden
        }

        return cViewController

}

But I get some errors saying that UIViewController! Does not conform to protocol "LogicValue" at the following line " while (cViewController.childViewControllerForStatusBarStyle)"
How can I fix this issue?

A: childViewControllerForStatusBarStyle() is a method not a property
   while (cViewController.childViewControllerForStatusBarStyle()) {
        cViewController = cViewController.childViewControllerForStatusBarStyle()
}


text:
Q: Split array by percentage I have some powershell code that returns a load of computers to an array from a SQL query.
The query return vary in the total number of members. I shuffle the array also.
I want to take that array and split it into four or five smaller arrays by percentage. I want to define the percentages beforehand. For example, I might want to see 25%, 25%, 25%, 25%. Another time I want to see 10%, 30%, 30%, 40% or another 5%, 35%, 30%, 30%.
$phasepercents = 0.1,0.2,0.2,0.25,0.25 #Percentage of machines in each
group

# AD groups to be created, Group5 is not needed as all EUC machines will be
# added in the final round
$Phase0group = @()
$Phase1group = @()
$Phase2group = @()
$Phase3group = @()
$Phase4group = @()
$computers = my sql query with returned computers

$totalmachines = $computers.count #Total No of machine in the collection

$Machinesineachgroup = @()
$phasestartnumbers  = @()

# work out the percentages
$counter = 0
foreach ($phasepercent in $phasepercents)
{
$value =  $phasepercent *= $totalmachines
$value =  [Math]::floor($value)
$Machinesineachgroup += $value
#WriteToLog "[INFO]`t,Machines in Phase$counter is $value"
$counter +=1
}
WriteToLog "[INFO-S]`t Total Machines in each phases $Machinesineachgroup"

A: this will break your collection into batch sizes based on the % in the $PercentageList and then store those batches into an array of arrays. you could also modify it to store the arrays in properties of a custom object OR into a hashtable if desired. [grin]
$MasterList = 1..100
$PercentageList = 10, 30, 20, 40

$Index = 0
$BatchList = foreach ($PL_Item in $PercentageList)
    {
    $BatchSize = [math]::Round($MasterList.Count * $PL_Item / 100, 0)

    # the leading comma forces PoSh to NOT unroll the array
    #    instead, it is stored as whole
    ,$MasterList[$Index..($Index + $BatchSize - 1)]

    $Index = $Index + $BatchSize
    }

$BatchList[0] -join ', '
'=' * 30
$BatchList.ForEach({$_ -join ', '})

output ...
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
==============================
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100


text:
Q: Android ImageView , image gets cut off at the top Left corner, how to avoid id? I have an imageView with
scaleType="centerCrop"

The images are showing inside ViewPager with sliding functionality.
I am using picasso to load images, but the image gets cut off on the top left corner like below :

Here is the xml code :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<ImageView
    android:id="@+id/img_sliding"
    android:scaleType="centerCrop"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

And the code to load images is :
 if (imgList!=null && imgList.size()>0)
        Picasso.with(getActivity())
                .load(imgList.get(position))
                .placeholder(drawable)
                .into(imgView);

So, I can't figure out why this is happening, and also the cut of part is covered sometime by blue color and sometimes by green color.
Any help is appreciated.
Thanks

A: Seems like you've enabled Picasso's debug indicators.
Try the following:
Picasso picasso = Picasso.with(getApplicationContext());
picasso.setIndicatorsEnabled(false); // disabling the indicators

picasso
    .load(imgList.get(position))
    .placeholder(drawable)
    .into(imgView);

Or look for setIndicatorsEnabled(true) in your code and remove it.

A: Yes, above answers are write for the cut of adge is the reason is you are using android:scaleType as a center crop so its try to adjust image with your image container (ImageView) or remove extra area after fill image with image container,For resolve it you can use android:scaleType as  android:scaleType="fitXY".
And about the color is the reason of Picaso library if you are setting following property in your code then you can't get color again,
Picasso.with(getApplicationContext()).setIndicatorsEnabled(false);

A: use android:scaleType="fitXY" on your ImageView
<ImageView
    android:id="@+id/img_sliding"
    android:scaleType="fitXY"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />


text:
Q: How to display period class from lubridate in datatable from DT? I have runtime data for various devices that can be widely different, ranging from a few minutes to several months that I would like to display in a datatable. So I thought the seconds_to_period function from lubridate provides a neat format to print this data. However, I seem unable to display it within a datatable from DT, which is what I want to do (within a shiny App).
Some example data:
library(lubridate)
library(DT)

names <- c("A","B","C","D","E","F")
timevec <- c(225,2250,22500,225000,2250000,22500000)
timevec <- seconds_to_period(timevec)

Writing this into a datatable without any formatting does not work as it only displays the seconds without considering the minutes/hours etc.:
##### This cuts off at the seconds -> useless
table <- data.frame(name = names, time = timevec)
my_table <- datatable(table)

Formatting the time column with formatDate also doesn't work since it is not a date or POSIXct object. I can print the desired format by typecasting it as a string, but then the sorting of the column doesn't work as it is sorted alphabetically:
##### This prints the period format, but sorting does not work
table <- data.frame(name = names, time = as.character(timevec))
my_table <- datatable(table)

and of course I could just print the total time in seconds, but as I said I find this very unintuitive to read:
##### This prints the seconds -> unintuitive to read
table <- data.frame(name = names, time = as.duration(timevec))
my_table <- datatable(table)

Any Ideas on how to achieve this or alternative suggestions how to intuitively display duration data?

A: solution by programming DT to sort a shown character column by a hidden numeric column via columnDefs
library(tidyverse)
library(lubridate)
library(DT)

names <- c("A", "B", "C", "D", "E", "F")
timevec_raw <- c(225, 2250, 22500, 225000, 2250000, 22500000)
timevec_period <- seconds_to_period(timevec_raw)

(table <- tibble(
  name = names,
  timenum = timevec_raw,
  timechar = as.character(timevec_period)
)
)

my_table <- datatable(table,
  options = list(
    columnDefs = list(
      list(
        visible = FALSE, targets = 2
      ), # hide column 2 the numeric one
      list(
        orderData = c(2), # the ordering of column 3 comes from hidden column 2
        targets = c(3)
      )
    )
  )
)


text:
Q: iMac very slow wifi while macbook is fine I currently have a MacBook Pro (Lion) and my iMac (Leopard) sitting side by side. The MacBook  Pro connects to a wifi network and speeds are as they should be. The iMac has serious problems: it doesn't find the same networks, it gets connection timeouts when trying to connect to the wifi network, when it finally connects the speed is so slow that it's unusable. When I ping yahoo.com I get results of between 100 - 1500ms and sites take minutes to load.
How can I start debugging this problem?

A: Here is a general plan to start debugging this problem.  Post your results and we'll help you figure this out.  I'm running an iMac with Snow Leopard and these steps have helped me.
Write down key data for each machine for each wifi connection.  I've included my data below.
Go to the iMac and hold down the option key while clicking the Airport icon in the menu bar.  Write down the PHY, BSSID, Channel, RSSI and Transmit Rate.
Move over to the MBP and gather the same information.
Phy Mode this tells you if you joined the network as a B, G or N connection.  I'm on an Airport Extreme N network using the 2.4 Ghz frequency.
BSSID - This is the access point you are logged into.  They are likely the same on each machine.  If they are different, your machines are logged into different access points.
Channel - This is the channel each machine is using.  In my case, my neighbor and I were both on channel 1.  I changed over to 11 and my speed improved since I was no longer fighting his interference.
RSSI - Received signal strength.  Mine is -43 while my neighbor's is -88.
Transmit Rate - The higher the better.  Mine is 130.  I can't view the neighbor's rate but it's like less due to his lower RSSI.
If you see other nearby networks, you can view some information about their signal by moving your cursor over the other network and a small dialog box will pop up with their PHY, BSSID, Channel, and RSSI.  This is how I found my neighbor was using the same channel as me.
You can also view this data in System Profiler under Network>Airport.


text:
Q: How to create 1 forest plot for multi- and univariable (factor variables) Cox regression results I have browsed multiple similar questions here but always get stuck by different problems, probably because I am not good at R.
I need to create a forest plot with several variables made of various levels of factors that includes its uni- and multivariable HR estimates. The HR lines of each factor level should be on top of each other and grouped by the main variables.
I have tried the code below, but I would like to have the main variable names on the left of the plot, next or above each factor (Not on the right as from the code). Also, the factor levels need to be ordered specifically, for example: General childhood condition levels: Poor, Fair, Good, Very good, Excellent. Any help would be very much appreciated!
Here is a snippet of my dataset & ggplot script:
df <- data.frame(
  label = c("Low", "Middle", "High", "Good", "Fair", "Poor", "Very  good", "Excellent", "Low", "Middle", "High", "Good", "Fair", "Poor", "Very good", "Excellent"),
  var_label = c("Education", "Education", "Education", "General health", "General health", "General health", "General health", "General health", "Education", "Education", "Education", "General health", "General health", "General health", "General health", "General health"),
  reference = c("TRUE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE", "FALSE"),
  estimate = c(1.00, 1.34, 1.67, 1.00, 0.82, 1.11, 0.85, 1.48, 1.00, 2.67, 3.49, 0.83, 1.00, 0.95, 1.34),
  std.error = c(NA, 0.16, 0.20, NA, 0.16, 0.24, 0.18, 0.24, NA, 0.14, 0.18, NA, 0.16, 0.23, 0.18, 0.24),
  conf.low = c(NA, 0.95, 1.10, NA, 0.60, 0.69, 0.60, 0.92, NA, 2.01, 2.45, NA, 0.61, 0.63, 0.66, 0.83),
  conf.high = c(NA, 1.87, 2.52, NA, 1.11, 1.80, 1.21, 2.39, NA, 3.55, 4.98, NA, 1.13, 1.58, 1.35, 2.16),
  p.value = c(NA, 0.09, 0.02, NA, 0.20, 0.67, 0.38, 0.11, NA, 0.00, 0.00, NA, 0.24, 1.00, 0.76, 0.23),
  model = c("m", "m", "m", "m", "m", "m", "m", "m", "u", "u", "u", "u", "u", "u", "u", "u")
)

dotCOLS = c("#a6d8f0","#f9b282")
barCOLS = c("#008fd5","#de6b35")
forest <- ggplot(df, aes(x = estimate, xmax= conf.high, xmin = conf.low, y = label, color = model, fill = model)) +
  geom_point(size = 3, shape = 18, position = position_dodge(width = 0.5)) +
  geom_linerange(position = position_dodge(width = 0.5), size = 1) +
  geom_vline(xintercept = 1, size = 1) +
  geom_hline(yintercept = 0, size = 1) +
  facet_grid(var_label~., scales = "free_y", space = "free_y") +
  scale_alpha_identity() +
  scale_fill_manual(values=barCOLS)+
  scale_color_manual(values=dotCOLS)+
  scale_y_discrete(name="Variable groups") +
  scale_x_continuous(name="Hazard ratio", limits = c(0, 5)) +
  geom_text(aes(label = var_label), x = Inf, y = Inf, hjust = 1, vjust = 4.5, check_overlap = TRUE, color = "darkgreen") +
  theme(panel.background = element_blank(),
        panel.spacing = unit(0, "pt"),
        axis.line.x.bottom = element_line(size = 1),
        strip.background = element_blank(), strip.text = element_blank())

And here is a picture of the result:

A: As you want the labels on the left use x=-Inf in geom_text. Also, instead of shifting via vjust you could IMHO simply use vjust=1 to align at the top. Additionally use coord_cartesian(clip = "off") to prevent the labels from being clipped off and make some room for the labels by adding some margin to the y axis text. Finally, if you want your labels in a specific order than convert to a factor with the levels set in your desired order.
Note: I fixed your data which had only 15 values for the estimate variable while all other columns had a length of 16. Additionally I removed the geom_hline which IMHO is not necessary (at least for your example data).
dotCOLS <- c("#a6d8f0", "#f9b282")
barCOLS <- c("#008fd5", "#de6b35")

library(ggplot2)

df$label <- factor(df$label, levels = c("Low", "Middle", "High", "Good", "Fair", "Poor", "Very  good",
                                        "Excellent", "Very good"))

ggplot(df, aes(x = estimate, xmax = conf.high, xmin = conf.low, y = label, color = model, fill = model)) +
  geom_point(size = 3, shape = 18, position = position_dodge(width = 0.5)) +
  geom_linerange(position = position_dodge(width = 0.5), size = 1) +
  geom_vline(xintercept = 1, size = 1) +
  #geom_hline(yintercept = 0, size = 1) +
  facet_grid(var_label ~ ., scales = "free_y", space = "free_y") +
  scale_alpha_identity() +
  scale_fill_manual(values = barCOLS) +
  scale_color_manual(values = dotCOLS) +
  scale_y_discrete(name = "Variable groups") +
  scale_x_continuous(name = "Hazard ratio", limits = c(0, 5)) +
  geom_text(aes(label = var_label), x = -Inf, y = Inf, hjust = 1, vjust = 1, check_overlap = TRUE, color = "darkgreen") +
  coord_cartesian(clip = "off") +
  theme(
    panel.background = element_blank(),
    panel.spacing = unit(0, "pt"),
    axis.line.x.bottom = element_line(size = 1),
    axis.text.y.left =  element_text(margin = margin(l = 20, unit = "pt")),
    strip.background = element_blank(),
    strip.text = element_blank()
  )
#> Warning: Removed 2 rows containing missing values (geom_segment).
#> Removed 2 rows containing missing values (geom_segment).

DATA
df <- data.frame(
  label = c("Low", "Middle", "High", "Good", "Fair", "Poor", "Very  good", "Excellent", "Low", "Middle", "High", "Good", "Fair", "Poor", "Very good", "Excellent"),
  var_label = c("Education", "Education", "Education", "General health", "General health", "General health", "General health", "General health", "Education", "Education", "Education", "General health", "General health", "General health", "General health", "General health"),
  reference = c("TRUE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "TRUE", "FALSE", "FALSE", "FALSE", "FALSE"),
  estimate = c(1.00, 1.34, 1.67, 1.00, 0.82, 1.11, 0.85, 1.48, 1.00, 2.67, 3.49, 0.83, 1.00, 0.95, 1.34, 1),
  std.error = c(NA, 0.16, 0.20, NA, 0.16, 0.24, 0.18, 0.24, NA, 0.14, 0.18, NA, 0.16, 0.23, 0.18, 0.24),
  conf.low = c(NA, 0.95, 1.10, NA, 0.60, 0.69, 0.60, 0.92, NA, 2.01, 2.45, NA, 0.61, 0.63, 0.66, 0.83),
  conf.high = c(NA, 1.87, 2.52, NA, 1.11, 1.80, 1.21, 2.39, NA, 3.55, 4.98, NA, 1.13, 1.58, 1.35, 2.16),
  p.value = c(NA, 0.09, 0.02, NA, 0.20, 0.67, 0.38, 0.11, NA, 0.00, 0.00, NA, 0.24, 1.00, 0.76, 0.23),
  model = c("m", "m", "m", "m", "m", "m", "m", "m", "u", "u", "u", "u", "u", "u", "u", "u")
)


text:
Q: Bootstrap 3.3.5 disable prev next buttons in product carousel I am working on a small project and also new to bootstrap. I am stuck at product carousel controls to be disabled (not hide) when on item:first & item:last class has active state. It is similar to E-commerce site slider.
Here is my code: http://www.bootply.com/T7KihOPj2R

A: You can either set data-wrap="false" on the carousel
or
just put it in the options when you initialize the carousel.
For refrence you can go through the Demo


text:
Q: Problem with opening hyperlinks in Excel directing to webpages with SSO cookies I am looking for a workaround in Excel that lets hyperlinks use the SSO cookies.
The problem
I have a hyperlink in Excel that links to a page that requires a login.
Even though I am already logged in (there is a session cookie) on the new tab opened by the hyperlink, the page asks for my credentials again.
Making things worse, after manually logging again, it directs to the landing page, and not the original hyperlinked page.
The cause
From what I understand when looking around here, it works something like this:
When clicking the hyperlink Excel is going to a program behind the scenes (some user agent stuff? I have no idea what that means, i'm a programmer noob.)
There is checks if the URL is valid. It runs some checks, and that program tells Excel: "yup, this is good, go to this page."
As a result, it misses the already existing session cookie.
My suggested solution
What should solve the problem is: Click on hyperlink --> make new tab in browser --> just put the damn hyperlink into the URL. (Like how it should work? Why doesn't it work like this in the first place?)
Can someone help me to write a VBA file that does just that? (or come up with a different solution)
I can somewhat write my idea, I just don't know how the VBA in Excel works, and what the valid commands are.
Because this obviously doesn't work:
Sub WorkingHyperlink()
    When ClickOnCell(columnA)
    'Maybe this needs some i++ recursion so it works on every cell in column A, no clue.
    Do Open "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
    Add URL, URL = hyperlink text

End Sub

Looking forward to learn from you.


text:
Q: How can I delete the n-th element in a list with javascsript I know how to delete all elements from a list. I don't know how to delete just one item. Let's say I want to delete the 3th list item
* of an unorder list . lets say I have the following:

      this is the fist item

      this is the second item

       this is the third item

        this is the fourth item

its eassy to delete the fist child or the last child. The list I am building gets built dynamicaly and it will be nice if I can delete the n-th child. It will be nice if I could do something like   document.getElementById("someElemet").delete

A: Example code to remove the 3rd item (index number 2):
document.getElementById("parent").removeChild(document.getElementById("parent").children[2]);

A: var ul = document.getElementById('parent');
var liToKill = ul.childNodes[2];
liToKill.parentNode.removeChild( liToKill );
// or ul.removeChild( ... )


text:
Q: How to calculate Real World Object Size? I am taking image from camera. So i want to get  object original  width and height.For that I am using UIImagePickerController.
e.g If 15 inch monitor is placed on table.  so when I took image from camera  then i
    want orginal size i.e. 15 inch. Does anyone have idea ? how can i achieve this ?.
EDIT
I dont't want image size. I want actual object size....
EDIT 2
 I want this type of app:-https://itunes.apple.com/us/app/easymeasure-measure-your-camera!/id349530105?mt=8
Thanks In Advance....

A: what you are asking for is not possible to determine with only a picture from a camera, acquiring the actual size of an object through a picture cannot be done without some other information telling you how far away the object is (which the camera cannot tell you).
edit: well actually not impossible to determine, bad choice of words... just very difficult. (vuforia augmented reality for example can determine the distance away an object is from the camera, but the object recognition is done as a preprocess and not just any old object)

A: in ImagePickerController delegate method pick original image
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];

Where info is dictionary of ImagePickerController delegate.
 NSLog(@"ImageSize = %@", image.size);

It will provide original image size.


text:
Q: how to remove first and last \n from string? PHP I have a problem in a variable in PHP that I want to remove the first and last \n from a string but not the \n in the text.
eg:
<--------------\n //I want to remove this (if exists)
some text \n
some text \n
<--------------\n //I want to remove this (if exists)

Any ideas?

A: Trim PHP function makes what you want to do : All whitespaces before and after string are removed.
$someText = "   bulbul   ";
echo trim($sometext); // "bulbul"

A: trim() strips whitespace from the beginning and end of a string. I believe this is what you need. More on the trim() function: http://php.net/manual/en/function.trim.php


text:
Q: dpkg "missing version" for libcgns2-dbg in /var/lib/dpkg/available — can't do update - how can I fix this? dpkg: warning: parsing file '/var/lib/dpkg/available' near line 839085 package 'libcgns2-dbg':
 missing description
dpkg: error: parsing file '/var/lib/dpkg/available' near line 839085 package 'libcgns2-dbg':
 missing version
Error in function:
SystemError: E:Sub-process /usr/bin/dpkg returned an error code (2)

This message I got after failure of installation of updates. What should I do?

A: dpkg: warning: parsing file '/var/lib/dpkg/available' near line 839085 package 'libcgns2-dbg':
missing description

From the above error report, it was clearly shown that description for a specific package is missing in the file /var/lib/dpkg/available. So delete the current available file and move or copy the backup file to it's location.
sudo rm /var/lib/dpkg/available
sudo cp /var/lib/dpkg/available-old /var/lib/dpkg/available

A: I'm not sure there's any merit in going back to an old available file. It's a very temporary file (unlike status) so we can just rebuild it:
sudo dpkg --clear-avail
sudo apt-get update

If you're still getting issues after that, there's something wrong in your repositories. I can only find this in 12.04 and my 12.04 machines seem to be fine... That suggests you might have it coming in from another repository... Check and get back to us.


text:
Q: Maxwell Stress Tensor and Equations in Mathematician's Language In my language, a differential two-form on $\mathbb{R}^4$ (viewed as a differentiable manifold with coordinates $t,x,y,z$) is a differentiable choice at each point of an alternating bilinear function from the tangent space at that point to $\mathbb{R}$, or equivalently something of the form $a_{xy} dx \wedge dy + a_{yz} dy \wedge dz + a_{zx} dz \wedge dx + a_{tx} dt \wedge dx + a_{ty} dt \wedge dy + a_{tz} dt \wedge dy$. A one-form just gives a cotangent vector. The most natural operation on a two-form is to take two tangent vectors at a given point and to apply the function to them to get a number. Another natural operation is to integrate this over an oriented surface in $\mathbb{R}^4$. As well, divergence is a natural operation on two-forms, whereas curl is a natural operation on one-forms, even though physicists often take the curl or the divergence of the same type of quantity, which they call a "vector field" (which at least seems bad from a mathematician's perspective).
We also have a metric on $\mathbb{R}^4$ (known by the name Lorentz), meaning a symmetric bilinear function on the tangent space at each point (that varies differentiably). Since $\mathbb{R}^4$ is a linear and homogenous space, we can actually think of that form as a form on space (manifold) as a whole. This means that there is a natural identification between tangent and cotangent vectors at each point, implying an identification between two-forms on the $T_p(\mathbb{R}^4)$ and elements of $T_p(\mathbb{R}^4) \otimes_{\mathbb{R}} T_p(\mathbb{R}^4)$ at each point $p$, and this identification extends differentiably to differential two-forms. Well, okay, it isn't really "natural" in the purely categorical sense, but because we have specified a metric, it kind of is.
This means that Lorentz transformations, ones which preserve the metric, commute with the identification between two-forms and elements of $T_p(\mathbb{R}^4) \otimes_{\mathbb{R}} T_p(\mathbb{R}^4)$ (equivalently, bilinear functions on the cotangent space). That is, if we have a Lorentz transformation sending $p$ to $q$, then we have a commutative diagram where the vertical arrows are the isomorphisms between the tangent and cotangent spaces (or more specifically their second tensor powers) at $p$ and $q$ respectively, and the horizontal arrows are the morphism and comorphism induced on the cotangent spaces of the Lorentz transformation (which is a diffeomorphism).
I think it also means something along the lines of the idea that a Lorentz transformation preserves the "form" of the equation, meaning that if you apply the Lorentz transformation as a change of coordinates, the coordinate-independent object (say the bilinear function) has another set of coordinates, but because we are using a Lorentz transformation, the coordinates are the same.
Diffeomorphisms which are not Lorentz transformations still send tangent and cotangent vectors at points to the same things at other points in a functorial way (specifically, a functor from the category of pointed differentiable manifolds to the category of vector spaces), but they don't necessarily satisfy this nice commutativity.
So could someone please explain electromagnetism in a simple way in this language? Also, how does it relate to the classical picture? E.g. does it look something like $E_x dy \wedge dz + \cdots + B_y dt \wedge dy + B_z dt \wedge dz$ or whatever? (This is wrong, but it's the kind of answer I'm looking for.)
Once we have, say, a two-tensor, what natural operations (in the mathematical sense) can we do to it to get the basic physical quantities? E.g., if we have a two-form, what two vectors (or vector fields) do we plug into it? (I mean, that's what a two-form is made for - it's a bilinear function that you can plug two tangent vectors into! That and you can also integrate it and take its divergence.) How do Maxwell's equations work in this context?

A: The current approach to this subject is to regard electromagnetism as a special cace (the abelian case) of a gauge field (aka a connection). I have written a book called "The Geometrization of Physics" that explains this (see in particular page xi of the introduction). It is freely available here:
http://www.e-booksdirectory.com/details.php?ebook=3623

A: This is only a rather partial (in all senses of the word) answer. The elctro-magnetic field is nothing but a closed $2$-form $\omega$ over $\mathbb R^4$. It cannot be split in a natural way into an electric and a magnetic parts, but once we choose space-time coordinates, then we may define $E$ and $B$ by
$$\omega=\sum_{j=1}^3E_jdx_j\times dt+\sum_{\epsilon(i,j,k)=1}B_idx_j\times dx_k.$$
The fact that $\omega$ is closed gives $\partial_tB+{\rm curl}E=0$ and ${\rm div}B=0$.
The rest of Maxwell's system comes from a variational principle
$$\delta{\mathcal L}[\omega]=0,\qquad{\mathcal L}[\omega]:=\int\int L(B,E)dxdt.$$
Special relativity tells us that the integrand $L$ must be invariant under Lorentz transformations. This means that there exists a function $L_0:\mathbb R^2\rightarrow\mathbb R$ such that
$$L(B,E)=L_0(E\cdot B,\frac12(|E|^2-|B|^2)).$$
If $L_0=\frac12(|E|^2-|B|^2)$, then you get the usual linear Maxwell's equations. But other choices have been made, in order to resolve the paradox of the infinite energy of a single particle. One of them,
$$L_0=-\sqrt{1+|B|^2-|E|^2-(E\cdot B)^2}$$
gives the Born-Infeld model. This is related to models in string and brane theory.


text:
Q: Need help highlighting our underlining active page in html/dreamweaver/css I have a website in which I want to highlight or underline the active page so viewers will know which page they are on at a glance. This is html and CSS.  My code looks like this:

HOME |
OUR TEAM |
PARTNERS |
CONTACT US

I'm a bit new to this and have a fair understanding of dreamweaver, html and CSS so I need to find a way to easily identify the pages for site visitors.  Any help is appreciated....

A: If you're making each HTML page by hand, then all you need to do is provide a CSS class for the highlighted  tag, then in your CSS sheet, specify rules for highlighting anchors with that class. Here's a simple example:
HTML
About me
Contact me

CSS
a.highlighted {
  font-weight: bold;
}

The alternative is to use JavaScript, which could get a little messy, or a server-side solution such as a content management system.

A: Maybe this JavaScript is helpful. It compares links on the page to the current page and makes the link text bold for matches.
You can place it in a function that loads when the body does or place it at the end of the HTML document.
var links=document.getElementsByTagName("A");
for(var i=0;i<links.length;i++)
{
    if(location==links[i].href)
    {
        links[i].style.fontWeight="bold";
    }
}


text:
Q: SOAPUI: Encrypt the date/time of the "Created" element, using OASIS Standard I'm a novice in SOAPUI.
I've already consulted some tutorials but I couldn't get the Header to look similar, and the error 1999 was returned.
Is it possible in SoapUI to configure WS-Security this way?
(OASIS Standard)


text:
Q: Windows ADFS User Certificate URL I have setup a window lab server based on windows server 2012 r2. I have an AD, ADFS and CS.
I have setup User certificate enrollment. Everything work fine but I have a litle issue.
I have setup ADFS SAML2 authentication and some of my server use it has SSO.
All URLs are: myserver1.mylab.lab, myserver2.mylab.lab, myserver3.mylab.lab
myserver1.mylab.lab is my ADFS server when I go on myserver2/3.mylab.lab I'm redirected to myserver1.mylab.lab set the authentication and be redirected to the requested server.
The problem is when I accessing myserver2/3.mylab.lab the web client (chrome/IE) propose the user certificate for authentication click on ok or cancel I'm redirected to adfs server the user certificate appear and I'm redirect to the initial server.
So my question is: can I generate the user certificate only for myserver1.mylab.lab ? As I use SAML2 authentication so I have every redirection implemented and everything work correctly?


text:
Q: Container Hierarchy I'm using Unity as a container and I'm wondering if it can help me solve an issue. I have 2 services, Service1 and Service2. They both depend on another object, lets call it IFoo. I want each service to get their own instance of IFoo but at the same time I don't want everybody else to. Essentially it should be a singleton but scoped. I thought about using a combination of child containers to achieve this but it doesn't work as I hoped. The idea is that IFoo contains some connection details that are specific to Service1 and Service2 and some other container resolved objects. Below is some code which hopefully makes it clearer.
The code that resolves ViewController would only ever know about the parentContainer.
var parentContainer = new UnityContainer();
parentContainer.RegisterType<IParentScope, ParentScoped>(
    new ContainerControlledLifetimeManager());

var childContainer1 = parentContainer.CreateChildContainer();
childContainer1.RegisterInstance<IFoo>(new Foo("Unique to Child Container 1"),
    new ContainerControlledLifetimeManager());
childContainer1.RegisterType<IService1, Service1>(
    new ContainerControlledLifetimeManager());

var childContainer2 = parentContainer.CreateChildContainer();
childContainer2.RegisterInstance<IFoo>(new Foo("Unique to Child Container 2"),
    new ContainerControlledLifetimeManager());
childContainer2.RegisterType<IService2, Service2>(
    new ContainerControlledLifetimeManager());

var viewController = parentContainer.Resolve<ViewController>();

public class ViewController
{
    public ViewController(IParentScope parentScope, IService1 service1, IService2 service2)
    {
        ParentScope = parentScope;
        Service1 = service1;
        Service2 = service2;
    }

    public IParentScope ParentScope { get; set; }
    public IService1 Service1 { get; set; }
    public IService2 Service2 { get; set; }
}

A: Thanks for your comments guys. I perhaps didn't explain it so well but I've realized I can make it work using named registrations like so.
var foo1 = new Foo("FOO 1");
        parentContainer.RegisterInstance<IFoo>("Foo1", foo1);

        var foo2 = new Foo("FOO 2");
        parentContainer.RegisterInstance<IFoo>("Foo2", foo2);

        parentContainer.RegisterType<IService1, Service1>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IFoo>("Foo1")));
        parentContainer.RegisterType<IService2, Service2>(new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IFoo>("Foo2")));

A better option I've now discovered it to use the [Dependency("Foo1")] attribute on the Service1 constructor. This allows me to specify a single named dependency.


text:
Q: How to access and mount an SMB Share via Command Line on Mac I want to extract dmg file from smb share drive and want to perform silent installation on mac machine .
I tried
$ mount_smbfs //'domain;username'@smb://a/b/c.dmg ~/local_folder
mount_smbfs: server connection failed: No route to host


text:
Q: Phonegap Screenshot plugin in Cordova 2.0.0 I have set up the screenshot plugin from github, located here:
https://github.com/phonegap/phonegap-plugins/tree/master/Android/Screenshot
I set it up as instructed and with 1.8.1 of cordova. It worked and the screenshot was saved to the phone. However it fails with cordova 2.0.0.
Screenshot.java code:
https://github.com/phonegap/phonegap-plugins/blob/master/Android/Screenshot/src/org/apache/cordova/Screenshot.java
Screenshot.js code:
https://github.com/phonegap/phonegap-plugins/blob/master/Android/Screenshot/www/Screenshot.js
Due to the advice of a very clever man called Simon MacDonald, I removed line 31 and 38 from the JS file shown above.
However when I try to use the screenshot plugin with cordova 2.0.0 I receive these errors:
ERROR: org.json.JSONException: Value undefined of type java.lang.String cannot be converted to JSONArray.
Error: Status=8 Message=JSON error
file:///android_asset/www/cordova-2.0.0.js: Line 938 :  Error: Status=8 Message=JSON error
Error: Status=8 Message=JSON error at file:///android_asset_/www/cordova-2.0.0.js:938

line 938 of the cordova.js is:
 // If error, then display error
    else {
        console.log("Error: Status="+v.status+" Message="+v.message);

but im almost certain this is a compatibility error. Does anyone know a fix for this, or even a reason. Im abit lost. Any help is appreciated.
I call the screenshot.js with this code:
function takeScreenShot() {
cordovaRef.exec("Screenshot.saveScreenshot");

}
Any help massively appreciated.

A: I just upgraded it to support v2.0.0:
https://github.com/phonegap/phonegap-plugins/commit/88a57e1c232f604f73be5bd82868d711ac235424


text:
Q: read document urls in a sharepoint library via pnp Js ver 3 I am using pnp.js ver 3 libary to read some images within a document library.
But the following two functions do not return the url/FileRef or even the Name of the stored document. Even if i explicitly specify the url column(s) in viewXml node of Came
Any idea how we can read the url via pnp ?
eg
await sp.web.lists.getByTitle(constants.visualsList).items.getAll()

 await sp.web.lists.getByTitle(constants.visualsList).getItemsByCAMLQuery({
       ViewXml: `<View><ViewFields>
       <FieldRef Name='Title' />
       <FieldRef Name='EncodedAbsUrl' />
       <FieldRef Name='FileRef' />
       </ViewFields>
       <Query><Where>....

A: This works for me:
await sp.web.lists.getByTitle(constants.visualsList).items.select('Title', 'EncodedAbsUrl', 'FileRef', 'FileLeafRef', 'ID').getAll()

Please if it does not work, write response from this call.


text:
Q: Assign and calculate by exponential notation Have you ever observed this phenomenon:
If I try to calculate the following calculation in ImmediateWindow of Visual Studio 2010 C# .Net, I get this weird solution.
1E-9 * 100 = 0.00000010000000000000001
1E-9 * 1E+2 = 0.00000010000000000000001

Even if I do the calculation this way:
double val = 1E-9;
0.000000001
val = val * 100;
0.00000010000000000000001

If I calculate the same calculation in Windows calc I get the expected result:
1E-9 * 100 = 0,0000001

If someone knows something about this behaviour I would be very pleased to get the info.

A: It doesn't matter if you use exponential notation or not, you're just running into floating-point accuracy.  If you want better accuracy, use decimal  e.g.:
decimal val = 1E-9;
0.000000001
val = val * 100;
0.0000001

See What Every Computer Scientist Should Know About Floating-Point Arithmetic


text:
Q: Date is not properly calculated in Java. Issue with zone I have a date format stored in DB, for example:
Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time)

I want to display the same date as output. Seems like I am missing something zone. It's evolving to be one day prior to this date.
I did the following:
DateTimeFormatter etFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma 'ET'");
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = ((Timestamp) date).toLocalDateTime().atZone(zoneId);
etFormat.format(zonedDateTime)

Output:
08/26/2020 at 08:00PM ET

What am I doing wrong?

A: In your database you have the date time with offset UTC-04:40 (which is 4 hr behind from UTC assuming America/New_York timezone). And when it converts into Timestamp it will be stores in UTC without offset which is 08/26/2020 at 08:00PM.
So first convert the Timestamp into Instant of UTC and then convert the Instant into ZonedDateTime with the zone information
 ZonedDateTime dateTime = timestamp.toInstant()
                           .atZone(ZoneOffset.UTC)
                           .withZoneSameInstant(ZoneId.of("America/New_York"));
 etFormat.format(dateTime);     //08/27/2020 at 00:00PM ET

A: The central issue is this:
java.sql.Timestamp, which is what e.g. resultSet.getTimestamp() returns, does not contain any timezone data. It is simply an instant in time, and it is stored as milliseconds since the epoch (jan 1st, 1970), UTC zone.
This does not match what most DBs store, because most DBs do in fact explicitly store the timezone with that. If your DB does not do this, or you picked a column type which does not do this, you should strongly consider changing that.
So, if the database has stored 'midnight in new york, aug 27th', and the database is forced by JDBC to put this in java.sql.Timestamp terms, there's nothing the DB engine can do about it, other than do its best, which is to return that exact time, in UTC terms. If you then print the UTC timestamp in human terms, you end up with '4 at night', and not 'midnight' (because new york is 4 hours earlier than UTC).
You then, with your code say: Okay, take the timestamp, turn it into a local date time (that'd be the notion of '27th of august, 4 o clock at night', without any inkling of in which czone that is in, and by itself not a thing that can ever be turned back into an epoch with more info), and then you put this at the new york zone, giving you '4 at night in new york', which is 4 hours later than where we started.
Okay, but how do I fix this?
Every other answer (so far) is just giving you silly ways to fight the symptoms.
I propose you fix the disease.
The actual error occurs when you ask the DB to transfer the fully timezoned information from its tables into the timezoneless java.sql.Timestamp object. Stop doing that.
Don't call (I assume your column is called 'mark', fill in whatever it might be):
resultSet.getTimestamp("mark").
Call:
resultSet.getObject("mark", ZonedDateTime.class);
or possibly try LocalDateTime.class, or possibly OffsetDateTime.class, but ZDT is preferred.
Then if that does not work, complain to your DB and/or JDBC driver because they're messing up and making it next to impossible to do timezone stuff properly when interacting with that DB from the java side.
Actually, the DB should store just a moment-in-time
If truly the time being stored represents the notion of an 'instant in time' and not so much 'as humans would ever talk to you about it', then there are data types for that too, but convert your java.sql.Timestamp object to a java.time.Instant asap (via .toInstant()), or straight up ask for it: resultSet.getObject("colName", Instant.class) and have java and the db line up the datatypes straight away.
Eh, whatever. Cures are for wussies, just work around it
Eh, well, the only thing you really need to do then is not to magically add 4 hours. This will do it:
ZonedDateTime dateTime = timestamp.toInstant()
                           .atZone(ZoneOffset.UTC)
                           .withZoneSameInstant(ZoneId.of("America/New_York"));

even if the tz stored in the DB is something else (it'll then give you that instant in time, but in new york, e.g. if the db has stored 'midnight in amsterdam', this will give you a time 6 hours earlier (or possibly 7 or 5, there are a few days in the year where things go ape due to US and europe having different shift days for daylight savings).

A: The format that you have used is not correct. I hope you will be able to understand the difference by comparing your pattern with mine. The reason why I've presented the parsing logic is that you have not made it clear the type of date-time. Whatever type it may be, it looks like you have a date-time string, Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time) which you want to parse into ZonedDateTime and display the same into the pattern of the date-time string you have. I guess, the main problem you are having is how to format the ZonedDateTime instance into the same form.
Do it as follows:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;

public class Main {
    public static void main(String[] args) {
        // Given date-time string
        String dateStr = "Thu Aug 27 2020 00:00:00 GMT-0400 (Eastern Daylight Time)";

        // Define the formatter for parsing
        DateTimeFormatter parsingFormat = new DateTimeFormatterBuilder()
                                            .appendPattern("EEE MMM dd uuuu HH:mm:ss zX")
                                            .appendLiteral(" (")
                                            .appendGenericZoneText(TextStyle.FULL)
                                            .appendLiteral(")")
                                            .toFormatter();

        // Parse the given date-time into ZonedDateTime
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateStr, parsingFormat);

        // Display in default format [i.e. zonedDateTime.toString()]
        System.out.println(zonedDateTime);

        // Define the formatter for output
        DateTimeFormatter outputFormat = new DateTimeFormatterBuilder()
                                            .appendPattern("EEE MMM dd uuuu HH:mm:ss z")
                                            .appendLiteral(" (")
                                            .appendPattern("zzzz")
                                            .appendLiteral(")")
                                            .toFormatter();

        // Get the string representation in the custom format
        String strDate = zonedDateTime.format(outputFormat);

        // Display the string representation in the custom format
        System.out.println(strDate);
    }
}

Output:
2020-08-27T00:00-04:00[America/New_York]
Thu Aug 27 2020 00:00:00 GMT-04:00 (Eastern Daylight Time)

Note: By any chance, if you also have difficulty to convert the timestamp into ZonedDateTime, you can refer other answers on this page and use this answer to solve the problem with formatting.

A: The date is converted with timezone set to GMT.
final static String datePattern = "EEE MM/dd/yyyy HH:mm:ss 'GMT'Z '('z')'";
DateFormat df = new SimpleDateFormat(datePattern, Locale.getDefault());
simpledateformat.setTimeZone(TimeZone.getTimeZone("GMT"))

simpleDateFormat.format(givenDate)

A: java.time
I recommend that you use java.time, the modern Java date and time API, exclusively for your date work. Instead of getting a Date or Timestamp from your database, since JDBC 4.2 (in the case of MySQL that's many years now) get a modern LocalDate from your result set. An example:
    PreparedStatement ps = yourDatabaseConnection.prepareStatement("select your_date from your_table;");
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        LocalDate date = rs.getObject("your_date", LocalDate.class);
        // Do something with date
    }

A LocalDate is a date without time of day and without time zone. So this will relieve you of all time zone trouble.
If you want to print the start of the day in North American Eastern time zone to the user in the format used in the question:
    DateTimeFormatter etFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mma v");
    ZoneId zoneId = ZoneId.of("America/New_York");

    LocalDate date = LocalDate.of(2020, Month.AUGUST, 27);
    ZonedDateTime startOfDay = date.atStartOfDay(zoneId);
    String result = startOfDay.format(etFormat);
    System.out.println(result);

Output from this example is:

08/27/2020 at 12:00AM ET

Do use pattern letter v for time zone in the format pattern rather than hard-coding ET. The latter will produce false and confusing results when one day a junior programmer feeds a ZonedDateTime in an other time zone into the code.
What went wrong in your code?
It's not clear to me how you got your date from your database. Apparently date even though declared a Date was really a Timestamp (a bad practice since the inheritance relationship between the two classes is really one of implementation, not a conceptual one) denoting the start of the day in UTC. toLocalDateTime() is a dangerous and often meaningless call: it uses the time zone of the JVM for converting the Timestamp to a LocalDateTime. At 0:00 UTC it is 8 PM the evening before in Eastern time zone, so your LocalDateTime becomes 2020-08-26T20:00. Next atZone(zoneId) only gives the correct time because zoneId happens to coincide with the JVM's time zone used in the previous step.
Link

*

*Oracle tutorial: Date Time explaining how to use java.time.


text:
Q: Using getResource with ProGuard results in null result Using ProGuard on my jar files has broken my calls to class.getResource(""). I have seen that in the ProGuard manual you need to specify the -keepdirectories mypackage (manual link). However, I have specified the -keepdirectories option and it doesn't seem to be working. I think there is something wrong with my ProGuard configuration. I have also looked at this related question, but I am having trouble getting the -keeppackagenames working as well.
In my code I have something similar to the following.
package com.example.mypackage;
public class MyClass{
    public static void main(String [] args){
        //url is always returned as null
        URL url = MyClass.class.getResource("");
        //do additional stuff including retrieving manifest file
    }
}

ProGuard Configuration
-injars ...
-outjars ...
-libraryjars ...

-dontoptimize
-keepattributes SourceFile,LineNumber,Table,LocalVariable*Table,*Annotation*
-renamesourcefileattribute SourceFile

-repackageclasses
-overloadaggressively

-keep public class com.example.mypackage.MyClass{
    public static void main(java.lang.String[]);
}
-keepdirectories com.example.mypackage,com.example.mypackage.MyClass
-keeppackagenames com.example.mypackage,com.example.mypackage.MyClass

A: ProGuard expects dots in packages names, and slashes in file names and directory names:
-keeppackagenames com.example.mypackage
-keepdirectories  com/example/mypackage

A: I found that I was able to get it working with the following modification to -keepdirectories
-keepdirectories **mypackage**

However, this feels sort of clunky, and while it works, I feel as if there is a better solution out there.


text:
Q: Will we soon have online IDE that is based on Skywriter? I saw that Skywriter is released and it looks promising for people that want to create online IDE for other programmers.
Will we soon have online IDE that is based on Skywriter you think?

A: Although not based on Skywriter online IDEs are already here.
One of the most complete ones I've played around with so far is CodeRun.  Palm's Ares IDE is also very impressive.
The cool part about Skywriter though is that since it's open source so you can integrate it into your own applications.  You don't need to wait for some new service to make the IDE.  Just throw it up on your own site and edit the pages on the fly.  This is particularly easy with PHP.


text:
Q: Checking permission for a path I need to code a file browser and want to implement it in a dynamic manner. (so theoretically every folder can be browsed)
To prevent access outside the root folder I thought of the following concept:

*

*Client never ever gets to see the absolute paths.

*The client always requests relative paths.

*Server appends root folder to relative path and converts the path with realpath.

*Server checks if the resulting path begins with the specified root directory.

Example:
Root folder is /var/www (always put through realpath first).

*

*Client requests /../

*Server appends root folder -> /var/www//../ and calls realpath -> /var/.

*Server checks if /var/ starts with /var/www -> false -> hence permission denied.

Here the implementation I thought of (crudely coded):
$rootFolder = realpath('/var/www/');

function to_absolute_path($relativePath) {
    global $rootFolder; // <- i know, globals are evil >:)

    $absolutePath = $rootFolder.'/'.$relativePath;

    return realpath($absolutePath);
}

function verify_permission($absolutePath) {
    global $rootFolder;

    if (!$absolutePath) return false;

    // strlen($rootFolder) is also cacheable, i'm aware
    return substr($absolutePath, 0, strlen($rootFolder)) === $rootFolder;
}

$absolutePath = to_absolute_path($clientRequestedFile);

if (!verify_permission($absolutePath)) {
   // Permission denied
}

It seems to work fine but I really want to get this right to prevent nasty bugs.
Can someone confirm my logic?
BTW:
In the case of symlinks, I thought I would just follow the symlink and apply verify_permission when I arrived at the destination.


text:
Q: Wordpress new setup old articles We run several installations of Wordpress without using MU. The whole thing got a little out of hand code wise as there are really old plugin versions, legacy files and lots of potentially insecure data on the server. The core installation is out of date as well as the plugins. Some of those plugins do not work anymore. What we want to do is make a clean cut, install a new version with all plugins needed. We also want to use a different theme. But we do not want to loose the articles, comments, tags aso.
I tried exporting everything with Wordpress' own functionality and then import it into the new system. Works fine, except that the routine changes article id, which is bad for permalinks and has side effects when it comes to tweaks where we worked with those ids to display special extra content.
I think the best way is to use the old database. However, I think I cannot just use a dump of the old version. Does anybody know which tables I need for the whole content thing without systems settings? Or is there any other way?

A: I would not suggest that aproach, but if You like to try, then:

*

*comments data:
wp_commentmeta,
wp_comments

*posts data, categories, custom menus etc:
wp_postmeta,
wp_posts,
wp_terms,
wp_term_relationships,
wp_term_taxonomy

*users:
wp_usermeta,
wp_users
As You can see, there are 10 mandatory tables and one more:
wp_options
which You dont want to copy.
All other tables are from plugins etc.


text:
Q: XmlWriter only escaping one kind of quote Here's some C# code:
var sb = new StringBuilder();
var w = XmlWriter.Create(sb);
w.WriteStartElement("hello");
w.WriteAttributeString("target", "world ' \" !");
w.WriteEndElement();
w.Flush();
// then look at sb.ToString()

I'm getting a string that looks like:
 <?xml version="1.0" encoding="utf-16"?><hello target="world ' " !" />

It's only escaping the double-quote, not the single-quote.  But the docs for XmlWriter.WriteAttributeString(String, String) say:

If the attribute value includes double or single quotes, they are
  replaced with " and ' respectively.

Is there some flag I need to set to make it do what the docs say it does?

A: If you use .Net Reflector to look at the code, you'll find that the System.Xml.XmlTextEncoder.Write(string) method is being called.  Here's the code of interest:
if (!this.inAttribute || (this.quoteChar != ch))
   this.textWriter.Write('\'');
else
   this.WriteEntityRefImpl("apos");

When writing an attribute value, a single quote is not escaped since it doesn't need to be.  It's only when writing a text element that "'" is used.

A: This isn't a bug in the XmlWriter, it's a bug in your legacy system.
If you look at the definition of AttValue in the XML 1.0 recommendation, you'll see that the XmlWriter is doing exactly what it's supposed to be doing:  if the attribute value is delimited with apostrophes, an attribute value can contain quotation marks, and if it's delimited with quotation marks, an attribute value can contain apostrophes.
You could, conceivably, derive a class from XmlTextWriter and override its WriteAttributes and WriteAttributeString methods.  That might work.  Watch out for namespaces and encoding if you do this, though.


text:
Q: how to upload file to users google drive account We have a scenario where we need to upload files from our website to user's google drive account once user approves to do. Out website is deployed in house so not sure how I could push the big file to users google drive account.
Could you please guide me on this.
Thank you


text:
Q: Try to find Angular DevTools Extension for Edge I want to install the Angular DevTools extension into Edge. It is not on the  Edge Web Store and Chrome Web Store won't allow me to install it into Edge. Is there another location where I can install the extension?

A: Have you allowed extensions from other stores in Edge? You can follow the steps below to install Angular DevTools extension in Edge:

*

*Navigate to edge://extensions/ in Edge.

*Turn on Allow extensions from other stores.

*Navigate to Angular DevTools extension page in Edge and click Add to Chrome to install the extension in Edge.

If you still can't add the extension successfully in Edge, you can provide if there's any error message when install and provide screenshots about the issue.


text:
Q: Firefox on Windows renders an image color incorrectly I've run into this issue before without ever really figuring out what the problem was, but I'm attempting to do the standard "drop-shadow" effect by using an image border on the main content of my page.  The content portion has a blue background (#3366ff) so the border image has one pixel of that color before the "drop-shadow".  Everything works great in Chrome (Windows & Mac), Safari (Mac), IE8 and Firefox (Mac) but it falls apart on Firefox for Windows.  The images are below, but instead of rendering the #3366ff color, Firefox renders #4e50fb.  Thoughts?  Could this be a color profile issue? And if so, how would I go about fixing it?
Thanks!
Bad Rendering:

Good Rendering:


text:
Q: node js - debugging the event loop In my express.js project everything works fine,  but having several routing files an other function files, I feel a bit like drowning in all the functions,  not knowing which functions run,  when, and by which caller.
For example,  I have two functions that may run too many times in event loop:  the router.use which I see as a constructor to all related routes (from which I want to filter out some),  and verify token function that should run only when certain conditions are met,  such as API calls,  or regular calls that detect admin cookie etc.
I'm trying to generate a log that can help me find which functions are called more than once and by which caller.
Sort of like a map per event.
I use console.log to see order and  current call url when firing an event,  and I also use node-inspector's breakpoints to see how many times functions like router.use are called,  but when manually following the functions in node-inspector,  many node core files are involved in the process,  which makes the task more tedious because I am interested to debug only my functions...  and it doesn't let me see the bigger picture,  more readable information on a zoomed out perspective.
What is the preferable method to generate such a log/report?


text:
Q: How can I make vim not follow links? I have a linux checkout directory with a module inside called learnldd
 ./linux/learnldd/hello/hello.c

I have a tags file called TAGS in my linux checkout
./linux/TAGS

When I open hello.c in vim, vim cannot find the tags file because learnldd is actually a link from
~/Repos/learnldd -> ~/Repos/linux/learnldd

So, when vim is searching for my tags file a la
:set tags=./TAGS;

it ends up looking in the actual directory and it's parents, rather than the linked one. If I
:cd ~/Repos/linux/learnldd
:pwd

vim follows the directory and reports that I'm in
cd ~/Repos/linux/learnldd

Is this a limitation on vim or is there some way around this without changing my link setup?

A: Use the environment variable $PWD, which does not follow links. In your ~/.vimrc:
set tags=$PWD/TAGS;


text:
Q: Transfer and arrange data in two lists using jquery

List A

    <select id="list1" multiple="multiple" rows=2>
       <option value=1>Chennai</option>
         <option value=2>Bangalore</option>
        <option value=3>Kolkata</option>
     <option value=4>Pune</option>
    </select>

    <input id="button1" type="button" value=">>" />
        <input id="button Up" type="button" value="Move Up" />
   <input id="button Down" type="button" value="Move Down" />

List B

    <select id="list2" multiple="multiple" rows=2>
       <option value=1>Jackfruit</option>
         <option value=2>Papaya</option>
        <option value=3>Water Melon</option>
     <option value=4>Banana</option>
    </select>

    <input id="button2" type="button" value="<<" />

Need help with this need to implement all of the functionality as individual functions .

A: Define your function outside document ready like below.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>ListBox</title>

//The first List Box

    <select id="lstFields" name="lstFields" style="width: 88px">
     <option value=1>America</option>
     <option value=2>London</option>
     <option value=3>Singapore</option>
     <option value=4>Malaysia</option>
     </select>

    <input type="button" value="Up" onclick="ReorderFields('up', 'lstFields');return false;" />
    <input type="button" value="Down" onclick="ReorderFields('down', 'lstFields');return false;" />

//The second List Box

List A

    <select id="list1" style="width: 88px">
       <option value=1>Chennai</option>
         <option value=2>Bangalore</option>
        <option value=3>Kolkata</option>
     <option value=4>Pune</option>
    </select>

//The Third List Box

List B

    <select id="list2" style="width: 88px">
       <option value=1>Jackfruit</option>
         <option value=2>Papaya</option>
        <option value=3>Water Melon</option>
     <option value=4>Banana</option>
    </select>

    <input id="button2" type="button" value="<<" />

values are swapping correctly your code is working just need to define outside of document ready.


text:
Q: Finding Visio Shapes Is there some way of printing out ALL Visio shapes - I used to manually do a screen shot of all the shapes and then print it out and bind it so I could flip through the pages and pick out shapes that I needed.  Was really handy when I didnt know the name of a shape I was looking for. This exercise is now way too time consuming and was hoping there was some sort of gallery that I could scroll through that had ALL the shapes.

A: See this related SuprtUser question: How do I browse all shapes in Visio (2010)
In summary, I wrote a tool that prints out all shapes for Visio 2010.

A: Check out the Visio PowerTools Addin.  It has the wonderful capability of Creating a Stencil Catalog.
Here's the link Visio Power Tools There are versions for Visio 2007 and 2010.


text:
Q: getting 0 for return value when using atoi Im taking a numerical input in my command line arguments and if there is a '+' or '-' character im trying to strip it away and only leave the numbers. Ive managed to strip the leading character but whenever i try assigning the value of the string with atoi without the leading character i keep getting a value of 0. Wondering what i could be doing wrong because whenever i print out the string its the same exact string except no leading character so shouldnt the atoi function convert that to a number? The ReadLine() function takes in a string and dynamically allocates memory depending on the size of the user input.
char *val = ReadLine();
  int i, size = strlen(val);
  int count = 0;
  int num = 10;
  char *newVal = (char*)malloc(sizeof(char) * 10);
  for(i = 0; i < size; i++) //checks once to make sure its proper formatting, if count == size then input is correct
  {
    if((val[0] == '+' && i == 0) || (val[0] == '-' && i == 0))
    {
      //printf("check\n");
      count++;
      i++;
    }
    if(val[i] >= '0' && val[i] <= '9')
    {
       count++;
    }
  }
  printf("the count is %d\n\nand the size is %d\n", count, size);
  while(count != size)    ///input check to make sure user is inputting correct values.
  {
    //repeat
    count = 0;
    val = ReadLine();
    size = strlen(val);
    for(i = 0; i < size; i++)
    {
      if((val[0] == '+' && i == 0 ) || (val[0] == '-' && i == 0)){
        //printf("check\n" );
        count++;
        i++;
      }
      if(val[i] >= '0' && val[i] <= '9')
      {
        //printf("%c\n", val[i]);
        count++;
      }
    }
    printf("count: %d\nsize: %d\n", count,size);
  }
  char numb[size-1];
  if(val[0] == '+')
  {
    //char *fin = (char*)malloc(sizeof(char) * size - 1);
    for(i = 1; i < 2; i++)
    {
      strcat(numb,&val[i]);
      count++;
      break;

    }
    printf("value of numb = %s\n", numb);
    newVal = (char*)realloc(newVal,sizeof(size-1));
    newVal = numb;
    printf("Value of newVal = %s\n", newVal);

    num = atoi(newVal);

    printf("The string is %s", newVal);
    return num;
  }
  else if (val[0] == '-')
  {
    for(i = 1; i < 2; i++)
    {
      strcat(numb,&val[i]);
      break;
      count++;
    }
    printf("value of numb = %s\n", numb);
    newVal = (char*)realloc(newVal,sizeof(size-1));
    newVal = numb;
    printf("Value of newVal = %s\n", newVal);
    num = -1 * atoi(newVal);
    printf("the num is%d\nstring is : %s",num, numb);
    return num;
  }
  //now convert that string to integer whether its plus or negative.
  num = atoi(val);
  return num;

This is the input that im using and this is what it prints back.
Please enter a value
-1248
the count is 5
and the size is 5
value of numb = 1248
Value of newVal = 1248
the num is 0
string is : 1248
The value you put was: 0


text:
Q: High explained variance but low p-value in output of factor analysis I'm trying to perform a factor analysis on some survey data (bit new to the subject) using R's built-in factanal function, but I'm failing to interpret its output. My approach was to first perform a PCA to estimate the number of significant axes of variation in the data and then to take this as the number of factors in the function call. However, I obtain a p-value of 0 for the chi-squared test (which probably means the value is below machine precision). If I'm not mistaken, this would mean that this number of factors is not sufficient.
However the SS of the loadings is high for this number (Cumulative Var is 0.886), and the p-value does not increase by adding more variables. What am I misunderstanding here?
Output:
Call:
factanal(x = ., factors = 2, scores = "Bartlett", rotation = "promax",     nstart = 100)

Uniquenesses:
     extInv      conseq       affin intrinsieke       focus    zelfExpl
      0.086       0.308       0.082       0.135       0.069       0.120
  explBrdte    explDpte     toewijd        tijd        afh1
      0.080       0.093       0.073       0.074       0.005

Loadings:
            Factor1 Factor2
extInv               0.921
conseq      -0.205  -0.723
affin        0.424   0.696
intrinsieke -0.451   1.031
focus        0.843   0.230
zelfExpl     1.039  -0.460
explBrdte    1.015  -0.153
explDpte     0.756   0.338
toewijd      0.831   0.247
tijd         0.913   0.105
afh1         1.002

               Factor1 Factor2
SS loadings      6.351   3.392
Proportion Var   0.577   0.308
Cumulative Var   0.577   0.886

Factor Correlations:
        Factor1 Factor2
Factor1    1.00   -0.43
Factor2   -0.43    1.00

Test of the hypothesis that 2 factors are sufficient.
The chi square statistic is 6376.64 on 34 degrees of freedom.
The p-value is 0


text:
Q: PHP Commenting System Has Fallen Apart I have a problem with my syntax. I don't know how to complete the following. I have built a member system that allows viewers to register and login and view my site. I wanted to make a commenting system so people can comment on stuff. I have built a test commenting system and it seems to run fine without the user information in place. However, if I try to build a page just like the other pages for my user system and include my commenting system it breaks down because of syntax error. I don't mean like the won't coexist, they are, but stuff conflicts with other stuff and posting a comment doesn't include retrieved user information from mysql database and I can't define ranks to where the user can edit his/her post or remove their post without modifying the other posts and the admin should be able to do it all. I have no idea on what went wrong or how to fix it. I am ready to send information your way, but I have no idea what you may need so I will post anything you need if you ask for it.
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
$person = $_SESSION['person'];
$rank = $_SESSION['rank'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guestbook 2 | Harley's Digital Portfolio</title>

<?php
//connect to member database and retrieve user information
require("./connect2.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username' ");
$numrows = mysql_num_rows($query);
if ($numrows == 1){
    $row = mysql_fetch_assoc($query);
    $username = $row['username'];
    $fullname = $row['fullname'];
    $fullname = $row['fullname'];
    $fullname = $row['fullname'];
    $rank = $row['rank'];

    if (!$fullname){
        $person = $username;
        $_SESSION['person'] = $person;
    }
    else
        $person = $fullname;
        $_SESSION['person'] = $person;
}

mysql_close();
?>
<?php
//Connect to the database
require("./connect.php");

//Page Header
echo "
Guestbook | Harley's Digital Portfolio
 Welcome $person, you are ranked as: $rank. Post Comment
";
$query = mysql_query("SELECT * FROM guestbook ORDER BY id DESC");
$numrows = mysql_num_rows($query);

if($numrows > 0){
    while ($row = mysql_fetch_assoc($query)){
        $dbid = $row['id'];
        $dbname = $row['name'];
        $dbemail = $row['email'];
        $dbmessage = $row['message'];
        $dbtime = $row['time'];
        $dbdate = $row['date'];
        $dbip = $row['ip'];

        $id = $dbid;
        $name = $dbname;
        $message = $dbmessage;
        $time = $dbtime;
        $date = $dbdate;
        $message = nl2br($message);

        $form = "<form action='./guestbook2.php' method='post'>

        By $id $name at $time on $date $removebutton

        $message

</form>";
        echo "$form";

    }
}
else
    echo "No posts found.";

    $removebutton = "<input type='submit' name='removebtn' value='X'/>";
    if ($_POST['removebtn']){
        mysql_query("SELECT * FROM guestbook WHERE id='$id'");
        mysql_query("DELETE FROM guestbook WHERE id='$id'");
        echo "Message Removed.";
    }

//Disconnect from database
mysql_close();
?>

The above is my guestbook2.php, the below is the postguestbook.php:
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username = $_SESSION['username'];
$person = $_SESSION['person'];
$rank = $_SESSION['rank'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Post to Guestbook | Harley's Digital Portfolio</title>

<?php
//connect to member database and retrieve user information
require("./connect2.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username' ");
$numrows = mysql_num_rows($query);
if ($numrows == 1){
    $row = mysql_fetch_assoc($query);
    $username = $row['username'];
    $rank = $row['rank'];

    if (!$fullname){
        $person = $username;
        $_SESSION['person'] = $person;
    }
    else
        $person = $fullname;
        $_SESSION['person'] = $person;
}

mysql_close();
?>
<?php
//Connect to the database
require("./connect.php");

//Page Header
echo "
Post to Guestbook | Harley's Digital Portfolio
";

if ($_POST['postbtn']){
    $name = strip_tags($_POST['name']);
    $email = strip_tags($_POST['email']);
    $message = strip_tags($_POST['message']);

    if ($name && $email && $message){
        if ( (strlen($email) >= 7) && (strstr($email, "@")) && (strstr($email, "."))){
            // add to the database
            $time = date("h:i A");
            $date = date("F d, Y");
            $ip = $_SERVER['REMOTE_ADDR'];

            mysql_query("INSERT INTO guestbook VALUES ('', '$name', '$email', '$message', '$time', '$date', '$ip')");
            echo "You message was posted successfully, Go back to Comments";
        }
        else
            echo "You did not enter a valid email address.";
    }
    else
        echo "You did not enter all the required info.";
}

echo    "<form name='postmessage' action='./postguestbook.php' method='post'>

    Name:
    <input type='text' name='name' style='width: 200px;'/>

    Email
    <input type='text' name='email' style='width: 200px;'/>

    Message:
    <textarea  name='message' style='width: 200px; height: 200px;'></textarea>

    <input type='submit' name='postbtn' value='Post'/>

</form>";

//Disconnect from database
mysql_close();
?>

There is no errors it just won't show up.. It worked separately before I tried to implement my user system and now I can't get it to where the user can edit or remove his post and the admin can do it all.
Thanks for looking at this post and answering.
Harley

A: Not sure about your problem exactly cause your description is a bit obscure. Here's some observations though:
guestbook2.php -
$removebutton is never defined. What is this?
echo "$form"; is unnecessary. Just echo $form; if you MUST echo html in php. In your case since you are running all php inline    you should break out of php ?> and place normal html in the    conditional. It is just more readable this way and you won't have to    escape slashes.
if ($_POST['removebtn']){
    mysql_query("SELECT * FROM guestbook WHERE id='$id'");
    mysql_query("DELETE FROM guestbook WHERE id='$id'");
    echo "Message Removed.";
}

this doesn't make sense. You are querying guestbook, doing nothing with the results and then deleting? Why not just delete? In any case, you are not checking to see if $id is even defined, which it is not in this case unless $numrows is greater than zero. That alone could cause problems since you are supposed to be referencing $_POST['id'] at least so you don't just can whatever the last instance of $id was.
You shouldn't be running queries with blindly accepted session vars either. look into mysql_real_escape_string() to help prevent the horrible security holes in trusting $_SESSION vars, get post or any others the user can spoof as well.
Again, I don't know what your whole problem is cause I can't see the error myself and I don't know what you're getting back from the code, so these are just pointers that may be at least part of the problem.

A: I would first like to start off by thanking everyone who posted an answer or comment that was helpful, but I fixed my error. Here is what has been going on:
It wouldn't retrieve the user information from the database after I impletemented my member system into an already built comment system that was using just a name variable and not a user variable. That was mistake number one, see you type in your name and email and message then it would post. Nice and easy. Now when I changed the name variable to the username variable, the MYSQL database was not updating with the correct username information that should have been gathered when you first enter the comment page hence the if username and userid function.
Mistake number to was trying to include everything under one roof (). That didn't work so well because the while loop was interfering. What I did was rewrite the entire page starting with the member system content and then built off of it separating it into multiple  tags. That fixed the retrieval errors that I haven't been seeing because there was nothing to retrieve. Once that was completed then I created a separate page called delete.php that will connect to the database and when you press the remove button it will open $removelink = "Remove"; variable. Inside the delete.php is
<?php
require("./connect2.php");
$removeid = $_GET['id'];
mysql_query("DELETE FROM comments WHERE id='$removeid'");
header("location: comments.php");
?>

That will then delete the post from the database and go back to the main page. It all works and everything is okay. I have all the pages fixed and if anybody wants to know how I did it please don't hesitate to email me. I would be glad to help.


text:
Q: Use D3.js single line graph to display same date but different temperatures I have this simple d3.js single line graph that is displaying multiple dates across the x-axis:
<script>

// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;

// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);

// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom");

var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);

// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });

// Adds the svg canvas
var svg = d3.select("#air_temp_chart")
.append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
.append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// Get the data
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
    d.date = parseDate(d.date);
    d.close = +d.close;
});

var tickValues = data.map(function(d) { return d.date; });

xAxis
.tickValues(tickValues)
.tickFormat(d3.time.format('%H:%M'));

// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);

// Add the valueline path.
svg.append("path")
    .attr("class", "line")
    .attr("d", valueline(data));

// Add the X Axis
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

// Add the Y Axis
svg.append("g")
    .attr("class", "y axis")
    .call(yAxis);

});

data.csv:
date,close
1-May-12,58.13
30-Apr-12,53.98
27-Apr-12,67.00

I'd like to change the data so that the date is the same for all, but the times and temperature readings are different values.
I changed the time.format line to:
var parseDate = d3.time.format("%d-%b-%y %H").parse;

to include the times with the readings, but the graph breaks when I do this.
I'd like to use this data with the same date but different times and temperature readings:
1-May-12 06:00,58.13
1-May-12 06:30,53.98
1-May-12 07:00,67.00

How do I modify the x-axis code to work with the values above?

A: You can provide specific tick values to be displayed on a d3 chart.
Firstly, correct your date parser:
var parseDate = d3.time.format("%e-%b-%y %H:%M").parse;  // %e instead of %d

First, you need to get the list of tick values you want to display. After you've loaded the csv and processed it, extract the tick values and assign them to your xAxis:
d3.csv("data.csv", function(error, data) {
    data.forEach(function(d) {
        d.date = parseDate(d.date);
        d.close = +d.close;
    });
    var tickValues = data.map(function(d) { return d.date; });

    xAxis
        .tickValues(tickValues)
        .tickFormat(d3.time.format('%H:%M'));

Do not forget to remove the ticks on your current xAxis definition.