Stripe connect with Auth and Capture retrieving Charge in Php

Stripe connect with Auth and Capture retrieving Charge in Php

I am implementing Stripe Connect with auth and Capture and so far I am succeeded in it but when I am trying to Capture the authenticated amount I am not able to do so. because stripe does not allow us to pass multiple parameters to Stripe:: Retrieve function but its working on curl request which I have developed. which as follow.

curl https://api.stripe.com/v1/charges/ch_1CfTe5Dye6RVcYtHp*****/capture

-u sk_test_C5uYX8juNRT9kTj******:
-d application_fee=1000
-H "Stripe-Account: acct_1CNbqaDy*****"
-X POST

this is working fine but when I try to do the same thing it is giving me an error on an unknown parameter which I can understand bcoz Stripe:: Retrieve does not accept extra parameter I am trying to do it in PHP like this

$stripe = array(
"secret_key" => "sk_test_C5uYX8juNRT9k********",
"publishable_key" => "pk_test_b2gp9tSHK9iP******"
);

$keystripe = StripeStripe::setApiKey($stripe['secret_key']);
$res = StripeCharge::retrieve(array(
"id" =>"ch_1CfTe5Dye6RVcYtHp********",
"application_fee" => 1000),
array("stripe_account" => "acct_1CNbqaDy*****"));

$re = $res->capture();

Can someone suggest me how can I archive this in PHP?

2 Answers
2

I have found the solution which is like this.

$keystripe = StripeStripe::setApiKey('sk_test_C5uYX8juNRT9kTj9wj******');
$res = StripeCharge::retrieve('ch_1CjkyXDye6RVcYt******', ["stripe_account" => "acct_xxx"]);
$re = $res->capture(["application_fee" =>1000]);

by using this I have resolved my problem

As per the docs on this, you should pass the arguments for capturing to the capture function, not the retrieve function. It’s a two step process, you get the charge object by calling retrieve, and then capture it, passing arguments. The code would look like this :

capture

retrieve

retrieve

$charge = StripeCharge::retrieve("ch_xxx", array("stripe_account" => "acct_xxx"));
$charge->capture(array(
"application_fee" => 1000
),array("stripe_account" => "acct_xxx"));

Thanks for trying to help me out but I found a solution I am answering it below.
– Priyank lohan
Jul 3 at 10:30

Cool, but I think we have the exact same answer 🙂
– karllekko
Jul 3 at 10:41

yes maybe …:-)
– Priyank lohan
Jul 3 at 10:49

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Convert Datetime column from UTC to local time in select statement

Convert Datetime column from UTC to local time in select statement

I’m doing a few SQL select queries and would like to convert my UTC datetime column into local time to be displayed as local time in my query results. Note, I am NOT looking to do this conversion via code but rather when I am doing manual and random SQL queries against my databases.

Does this question seem similar to your circumstances? stackoverflow.com/questions/3404646/…
– Taryn East
Nov 7 ’11 at 15:46

possible duplicate of TSQL: How to convert local time to UTC? (SQL Server 2008)
– BroSlow
Mar 6 ’15 at 2:12

17 Answers
17

You can do this as follows on SQL Server 2008 or greater:

SELECT CONVERT(datetime,
SWITCHOFFSET(CONVERT(datetimeoffset,
MyTable.UtcColumn),
DATENAME(TzOffset, SYSDATETIMEOFFSET())))
AS ColumnInLocalTime
FROM MyTable

You can also do the less verbose:

SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), GETDATE()), MyTable.UtcColumn)
AS ColumnInLocalTime
FROM MyTable

Whatever you do, do not use - to subtract dates, because the operation is not atomic, and you will on occasion get indeterminate results due to race conditions between the system datetime and the local datetime being checked at different times (i.e., non-atomically).

-

Please note that this answer does not take DST into account. If you want to include a DST adjustment, please also see the following SO question:

How to create Daylight Savings time Start and End function in SQL Server

Is there a way to make this account for day light savings?
– Steve
Mar 30 ’12 at 18:53

I don’t see the name of a time zone here so this is incorrect. It’s a really bad idea to assume you can convert to local time by doing arithmetic
– Jonny Leeds
Sep 3 ’14 at 16:33

@MichaelGoldshteyn if you have a timezone offset you still dont know what logical timezone a time is in. Timezones are social things and can be changed by governments at different points. The offset for a timezone can be different at different points in time/history (summer time being a common one). You are offsetting a time by the current offset from UTC… a further point is that this will give the timezone of the server and not the client, which could be a further problem if you are hosting in a different country.
– Jonny Leeds
Apr 17 ’15 at 14:15

@Niloofar The simple answer is that you don’t, and shouldn’t. Datetimes should always be stored in UTC (preferably based on the database server’s clock, not the webserver’s, the application server’s, and definitely not the client’s clock). Displaying that datetime is a function for the UI layer, and it is responsible for converting the datetime into the format you want (including a timezone if necessary).
– Robert McKee
Jun 9 ’16 at 17:42

For anyone using sql azure this approach won’t work because the date/time functions all return UTC, so comparing GETDATE() to GETUTCDATE() doesn’t give you anything to work with and your result is the same as you started with.
– Brian Surowiec
Nov 9 ’16 at 20:55

I didn’t find any of these example helpful in getting a datetime stored as UTC to a datetime in a specified timezone (NOT the timezone of the server because Azure SQL databases run as UTC). This is how I handled it. It’s not elegant but it’s simple and gives you the right answer without maintaining other tables:

select CONVERT(datetime, SWITCHOFFSET(dateTimeField, DATEPART(TZOFFSET,
dateTimeField AT TIME ZONE 'Eastern Standard Time')))

So far this is the only one that seems to work for the Azure issue
– Jeff Davis
Jun 29 ’17 at 15:36

This doesn’t work for me in SQL Server 2014
– Jeff Orris
Jun 30 ’17 at 17:10

Works for 2016 only and uses system registry. But great solution for Azure.
– Dan Cundy
Sep 20 ’17 at 9:03

This one works for azure times stored in UTC, thanks guys
– Null
Dec 20 ’17 at 10:44

Here’s a list of the strings you can use for the time zones: stackoverflow.com/a/7908482/631277
– Matt Kemp
Feb 19 at 5:46

If you need a conversion other than your server’s location, here is a function that allows you to pass a standard offset and accounts for US Daylight Savings Times:

-- =============================================
-- Author: Ron Smith
-- Create date: 2013-10-23
-- Description: Converts UTC to DST
-- based on passed Standard offset
-- =============================================
CREATE FUNCTION [dbo].[fn_UTC_to_DST]
(
@UTC datetime,
@StandardOffset int
)
RETURNS datetime
AS
BEGIN

declare
@DST datetime,
@SSM datetime, -- Second Sunday in March
@FSN datetime -- First Sunday in November

-- get DST Range
set @SSM = datename(year,@UTC) + '0314'
set @SSM = dateadd(hour,2,dateadd(day,datepart(dw,@SSM)*-1+1,@SSM))
set @FSN = datename(year,@UTC) + '1107'
set @FSN = dateadd(second,-1,dateadd(hour,2,dateadd(day,datepart(dw,@FSN)*-1+1,@FSN)))

-- add an hour to @StandardOffset if @UTC is in DST range
if @UTC between @SSM and @FSN
set @StandardOffset = @StandardOffset + 1

-- convert to DST
set @DST = dateadd(hour,@StandardOffset,@UTC)

-- return converted datetime
return @DST

END

GO

Ron Smith I know this is an old post but I was curious what the hard coded ‘0314’ and ‘1107’ represent in the getting of DST range. It appears to be hard coded days which change due to DTS. Why would you hard code this when it should be a calculated date because the days change based on where on the calendar the second Sunday of march and the first Sunday of November falls. The hard coded days would make this code fundamentally flawed.
– Mike
Aug 16 ’17 at 17:40

Good question 🙂 Those are the max dates where the second Sunday in March and the first Sunday in November can occur. The following lines set the variables to the actual date.
– Ron Smith
Aug 18 ’17 at 0:25

If enabling CLR on your database is an option as well as using the sql server’s timezone, it can be written in .Net quite easily.

public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime fn_GetLocalFromUTC(SqlDateTime UTC)
{
if (UTC.IsNull)
return UTC;

return new SqlDateTime(UTC.Value.ToLocalTime());
}
}

A UTC datetime value goes in and the local datetime value relative to the server comes out. Null values return null.

Here’s a version that accounts for daylight savings, UTC offset, and is not locked into a particular year.

---------------------------------------------------------------------------------------------------
--Name: udfToLocalTime.sql
--Purpose: To convert UTC to local US time accounting for DST
--Author: Patrick Slesicki
--Date: 3/25/2014
--Notes: Works on SQL Server 2008R2 and later, maybe SQL Server 2008 as well.
-- Good only for US States observing the Energy Policy Act of 2005.
-- Function doesn't apply for years prior to 2007.
-- Function assumes that the 1st day of the week is Sunday.
--Tests:
-- SELECT dbo.udfToLocalTime('2014-03-09 9:00', DEFAULT)
-- SELECT dbo.udfToLocalTime('2014-03-09 10:00', DEFAULT)
-- SELECT dbo.udfToLocalTime('2014-11-02 8:00', DEFAULT)
-- SELECT dbo.udfToLocalTime('2014-11-02 9:00', DEFAULT)
---------------------------------------------------------------------------------------------------
ALTER FUNCTION udfToLocalTime
(
@UtcDateTime AS DATETIME
,@UtcOffset AS INT = -8 --PST
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@PstDateTime AS DATETIME
,@Year AS CHAR(4)
,@DstStart AS DATETIME
,@DstEnd AS DATETIME
,@Mar1 AS DATETIME
,@Nov1 AS DATETIME
,@MarTime AS TIME
,@NovTime AS TIME
,@Mar1Day AS INT
,@Nov1Day AS INT
,@MarDiff AS INT
,@NovDiff AS INT

SELECT
@Year = YEAR(@UtcDateTime)
,@MarTime = CONVERT(TIME, DATEADD(HOUR, -@UtcOffset, '1900-01-01 02:00'))
,@NovTime = CONVERT(TIME, DATEADD(HOUR, -@UtcOffset - 1, '1900-01-01 02:00'))
,@Mar1 = CONVERT(CHAR(16), @Year + '-03-01 ' + CONVERT(CHAR(5), @MarTime), 126)
,@Nov1 = CONVERT(CHAR(16), @Year + '-11-01 ' + CONVERT(CHAR(5), @NovTime), 126)
,@Mar1Day = DATEPART(WEEKDAY, @Mar1)
,@Nov1Day = DATEPART(WEEKDAY, @Nov1)

--Get number of days between Mar 1 and DST start date
IF @Mar1Day = 1 SET @MarDiff = 7
ELSE SET @MarDiff = 15 - @Mar1Day

--Get number of days between Nov 1 and DST end date
IF @Nov1Day = 1 SET @NovDiff = 0
ELSE SET @NovDiff = 8 - @Nov1Day

--Get DST start and end dates
SELECT
@DstStart = DATEADD(DAY, @MarDiff, @Mar1)
,@DstEnd = DATEADD(DAY, @NovDiff, @Nov1)

--Change UTC offset if @UtcDateTime is in DST Range
IF @UtcDateTime >= @DstStart AND @UtcDateTime < @DstEnd SET @UtcOffset = @UtcOffset + 1

--Get Conversion
SET @PstDateTime = DATEADD(HOUR, @UtcOffset, @UtcDateTime)
RETURN @PstDateTime
END
GO

I found the one off function way to be too slow when there is a lot of data. So I did it through joining to a table function that would allow for a calculation of the hour diff. It is basically datetime segments with the hour offset. A year would be 4 rows. So the table function

dbo.fn_getTimeZoneOffsets('3/1/2007 7:00am', '11/5/2007 9:00am', 'EPT')

would return this table:

startTime endTime offset isHr2
3/1/07 7:00 3/11/07 6:59 -5 0
3/11/07 7:00 11/4/07 6:59 -4 0
11/4/07 7:00 11/4/07 7:59 -5 1
11/4/07 8:00 11/5/07 9:00 -5 0

It does account for daylight savings. A sample of how it is uses is below and the full blog post is here.

select mt.startTime as startUTC,
dateadd(hh, tzStart.offset, mt.startTime) as startLocal,
tzStart.isHr2
from MyTable mt
inner join dbo.fn_getTimeZoneOffsets(@startViewUTC, @endViewUTC, @timeZone) tzStart
on mt.startTime between tzStart.startTime and tzStart.endTime

It does not appear to consider DST in a correct way. Not sure if you assume only US exists and that DST rules never change.
– vikjon0
Jul 23 ’17 at 6:07

@vikjon0 yes, the project I built this for had only US time zones.
– JBrooks
Jul 23 ’17 at 12:55

Using new SQL Server 2016 opportunities:

CREATE FUNCTION ToLocalTime(@dtUtc datetime, @timezoneId nvarchar(256))
RETURNS datetime
AS BEGIN

return @dtUtc AT TIME ZONE 'UTC' AT TIME ZONE @timezoneId

/* -- second way, faster

return SWITCHOFFSET(@dtUtc , DATENAME(tz, @dtUtc AT TIME ZONE @timezoneId))

*/

/* -- third way

declare @dtLocal datetimeoffset
set @dtLocal = @dtUtc AT TIME ZONE @timezoneId
return dateadd(minute, DATEPART (TZoffset, @dtLocal), @dtUtc)

*/

END
GO

But clr procedure works in 5 times faster :’-(

Pay attention that Offset for one TimeZone can change to winter or summer time. For example

select cast('2017-02-08 09:00:00.000' as datetime) AT TIME ZONE 'Eastern Standard Time'
select cast('2017-08-08 09:00:00.000' as datetime) AT TIME ZONE 'Eastern Standard Time'

results:

2017-02-08 09:00:00.000 -05:00
2017-08-08 09:00:00.000 -04:00

You can’t just add constant offset.

There is no simple way to do this in a correct AND generic way.

First of all it must be understood that the offset depends on the date in question, the Time Zone AND DST.
GetDate()-GetUTCDate only gives you the offset today at the server’s TZ, which is not relevant.

GetDate()-GetUTCDate

I have seen only two working solution and I have search a lot.

1) A custom SQL function with a a couple of tables of base data such as Time Zones and DST rules per TZ.
Working but not very elegant. I can’t post it since I don’t own the code.

EDIT: Here is an example of this method
https://gist.github.com/drumsta/16b79cee6bc195cd89c8

2) Add a .net assembly to the db, .Net can do this very easily. This is working very well but the downside is that you need to configure several parameters on server level and the config is easily broken e.g. if you restore the database.
I use this method but I cant post it since I don’t own the code.

declare @mydate2 datetime
set @mydate2=Getdate()
select @mydate2 as mydate,
dateadd(minute, datediff(minute,getdate(),@mydate2),getutcdate())

Ron’s answer contains an error. It uses 2:00 AM local time where the UTC equivalent is required. I don’t have enough reputation points to comment on Ron’s answer so a corrected version appears below:

-- =============================================
-- Author: Ron Smith
-- Create date: 2013-10-23
-- Description: Converts UTC to DST
-- based on passed Standard offset
-- =============================================
CREATE FUNCTION [dbo].[fn_UTC_to_DST]
(
@UTC datetime,
@StandardOffset int
)
RETURNS datetime
AS
BEGIN

declare
@DST datetime,
@SSM datetime, -- Second Sunday in March
@FSN datetime -- First Sunday in November
-- get DST Range
set @SSM = datename(year,@UTC) + '0314'
set @SSM = dateadd(hour,2 - @StandardOffset,dateadd(day,datepart(dw,@SSM)*-1+1,@SSM))
set @FSN = datename(year,@UTC) + '1107'
set @FSN = dateadd(second,-1,dateadd(hour,2 - (@StandardOffset + 1),dateadd(day,datepart(dw,@FSN)*-1+1,@FSN)))

-- add an hour to @StandardOffset if @UTC is in DST range
if @UTC between @SSM and @FSN
set @StandardOffset = @StandardOffset + 1

-- convert to DST
set @DST = dateadd(hour,@StandardOffset,@UTC)

-- return converted datetime
return @DST

END

It’s a feature, not a bug 🙂 Most of the United States begins Daylight Saving Time at 2:00 a.m en.wikipedia.org/wiki/Daylight_saving_time
– Ron Smith
Aug 18 ’17 at 0:36

@RonSmith Yes, at 2:00 a.m. local time, which we have to convert to UTC to detect if the given UTC time is in the DST range.
– jlspublic
Nov 18 ’17 at 21:15

The UNIX timestamp is merely the number of seconds between a particular date and the Unix Epoch,

SELECT DATEDIFF(SECOND,{d ‘1970-01-01’},GETDATE()) // This Will Return the UNIX timestamp In SQL server

you can create a function for local date time to Unix UTC conversion using Country Offset
Function to Unix Time Stamp In SQL server

As a warning – if you’re going to use the following (note the milliseconds instead of minutes):

SELECT DATEADD(ms, DATEDIFF(ms, GETUTCDATE(), GETDATE()), MyTable.UtcColumn)
AS ColumnInLocalTime
FROM MyTable

Keep in mind that the DATEDIFF part will not always return the same number. So don’t use it to compare DateTimes down to milliseconds.

I’ve found that this function is faster than other solutions using a separate table or loops. It’s just a basic case statement. Given that all months between April and October have a -4-hour offset (Eastern Time) we just need to add a few more case lines for the fringe days. Otherwise, the offset is -5 hours.

This is specific to a conversion from UTC to Eastern time, but additional time zone functions can be added as needed.

USE [YourDatabaseName]
GO

/****** Object: UserDefinedFunction [dbo].[ConvertUTCtoEastern] Script Date: 11/2/2016 5:21:52 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[ConvertUTCtoEastern]
(
@dtStartDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE @Working DATETIME
DECLARE @Returned DATETIME

SET @Working = @dtStartDate
SET @Working =
case when month(@Working) between 4 and 10 then dateadd(HH,-4,@Working)
when @Working between '2017-03-12' and '2017-11-05' then dateadd(HH,-4,@Working)
when @Working between '2016-03-13' and '2016-11-06' then dateadd(HH,-4,@Working)
when @Working between '2015-03-08' and '2015-11-01' then dateadd(HH,-4,@Working)
when @Working between '2014-03-09' and '2014-11-02' then dateadd(HH,-4,@Working)
when @Working between '2013-03-10' and '2013-11-03' then dateadd(HH,-4,@Working)
when @Working between '2012-03-11' and '2012-11-04' then dateadd(HH,-4,@Working)
else dateadd(HH,-5,@Working) end

SET @Returned = @Working

RETURN @Returned

END

GO

None of these worked for me but this below worked 100%. Hope this can help others trying to convert it like I was.

CREATE FUNCTION [dbo].[fn_UTC_to_EST]
(
@UTC datetime,
@StandardOffset int
)
RETURNS datetime
AS
BEGIN

declare
@DST datetime,
@SSM datetime, -- Second Sunday in March
@FSN datetime -- First Sunday in November
-- get DST Range
set @SSM = DATEADD(dd,7 + (6-(DATEDIFF(dd,0,DATEADD(mm,(YEAR(GETDATE())-1900) * 12 + 2,0))%7)),DATEADD(mm,(YEAR(GETDATE())-1900) * 12 + 2,0))+'02:00:00'
set @FSN = DATEADD(dd, (6-(DATEDIFF(dd,0,DATEADD(mm,(YEAR(GETDATE())-1900) * 12 + 10,0))%7)),DATEADD(mm,(YEAR(GETDATE())-1900) * 12 + 10,0)) +'02:00:00'

-- add an hour to @StandardOffset if @UTC is in DST range
if @UTC between @SSM and @FSN
set @StandardOffset = @StandardOffset + 1

-- convert to DST
set @DST = dateadd(hour,@StandardOffset,@UTC)

-- return converted datetime
return @DST

END

This should be able to get server time with DST

declare @dt datetime
set @dt = getutcdate() -- GMT equivalent

sysdatetimeoffset takes DST into account

select [InputTime] = @dt
, [LocalTime2] = dateadd(mi, datediff(mi, sysdatetimeoffset(),getdate()), @dt)

First function: configured for italian time zone (+1, +2), switch dates: last sunday of march and october, return the difference between the current time zone and the datetime as parameter.

Returns:
current timezone < parameter timezone ==> +1
current timezone > parameter timezone ==> -1
else 0

The code is:

CREATE FUNCTION [dbo].[UF_ADJUST_OFFSET]
(
@dt_utc datetime2(7)
)
RETURNS INT
AS
BEGIN

declare @month int,
@year int,
@current_offset int,
@offset_since int,
@offset int,
@yearmonth varchar(8),
@changeoffsetdate datetime2(7)

declare @lastweek table(giorno datetime2(7))

select @current_offset = DATEDIFF(hh, GETUTCDATE(), GETDATE())

select @month = datepart(month, @dt_utc)

if @month < 3 or @month > 10 Begin Set @offset_since = 1 Goto JMP End

if @month > 3 and @month < 10 Begin Set @offset_since = 2 Goto JMP End

--If i'm here is march or october
select @year = datepart(yyyy, @dt_utc)

if @month = 3
Begin

Set @yearmonth = cast(@year as varchar) + '-03-'

Insert Into @lastweek Values(@yearmonth + '31 03:00:00.000000'),(@yearmonth + '30 03:00:00.000000'),(@yearmonth + '29 03:00:00.000000'),(@yearmonth + '28 03:00:00.000000'),
(@yearmonth + '27 03:00:00.000000'),(@yearmonth + '26 03:00:00.000000'),(@yearmonth + '25 03:00:00.000000')

--Last week of march
Select @changeoffsetdate = giorno From @lastweek Where datepart(weekday, giorno) = 1

if @dt_utc < @changeoffsetdate
Begin
Set @offset_since = 1
End Else Begin
Set @offset_since = 2
End
End

if @month = 10
Begin

Set @yearmonth = cast(@year as varchar) + '-10-'

Insert Into @lastweek Values(@yearmonth + '31 03:00:00.000000'),(@yearmonth + '30 03:00:00.000000'),(@yearmonth + '29 03:00:00.000000'),(@yearmonth + '28 03:00:00.000000'),
(@yearmonth + '27 03:00:00.000000'),(@yearmonth + '26 03:00:00.000000'),(@yearmonth + '25 03:00:00.000000')

--Last week of october
Select @changeoffsetdate = giorno From @lastweek Where datepart(weekday, giorno) = 1

if @dt_utc > @changeoffsetdate
Begin
Set @offset_since = 1
End Else Begin
Set @offset_since = 2
End
End

JMP:

if @current_offset < @offset_since Begin
Set @offset = 1
End Else if @current_offset > @offset_since Set @offset = -1 Else Set @offset = 0

Return @offset

END

Then the function that convert date

CREATE FUNCTION [dbo].[UF_CONVERT]
(
@dt_utc datetime2(7)
)
RETURNS datetime
AS
BEGIN

declare @offset int

Select @offset = dbo.UF_ADJUST_OFFSET(@dt_utc)

if @dt_utc >= '9999-12-31 22:59:59.9999999'
set @dt_utc = '9999-12-31 23:59:59.9999999'
Else
set @dt_utc = (SELECT DATEADD(mi, DATEDIFF(mi, GETUTCDATE(), GETDATE()), @dt_utc) )

if @offset <> 0
Set @dt_utc = dateadd(hh, @offset, @dt_utc)

RETURN @dt_utc

END

Here’s a simpler one that takes dst in to account

CREATE FUNCTION [dbo].[UtcToLocal]
(
@p_utcDatetime DATETIME
)
RETURNS DATETIME
AS
BEGIN
RETURN DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), @p_utcDatetime), GETDATE())
END

This doesn’t actually take DST into account. Just try it: SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), '20150101'), GETDATE()). I’m currently in CEST (UTC+2), but DST will not be in effect on New Year’s day, so the correct answer for me would be 1 January 2015 01:00. Your answer, like the accepted answer, returns 1 January 2015 02:00.
– hvd
Aug 26 ’14 at 10:13

SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, GETUTCDATE(), '20150101'), GETDATE())

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Protractor e2e tests are running very fast in AngularJS/Anuglar 6 Hybrid application

Protractor e2e tests are running very fast in AngularJS/Anuglar 6 Hybrid application

I have migrated our Angular JS(1.5) app to a Hybrid app. I am using Angular6/AngularJS (1.6) both. I am trying to run protractor e2e of the existing e2e tests for angular js pages.

My all the existing tests are running very fast. and Most of e2e tests are now failing with reasons like “Element not visible", or “Element not enabled", so now I have add wait for elements at multiple places to get them fixed. Any reasons why they are running too fast ? I have hundreds of test cases, and to put the wait in the test cases is a time consuming task.

Any other setting which I use to make them passing, since those were working fine in Angular JS only app.

In the Angular JS application my protractor version was “4.0.9″ and “webdriver-manager “: “10.2.3″. and that now after moving to a angular hybrid app here updated version

My protractor version : protractor": “^5.3.2
“webdriver-manager": “12.0.6″,
“selenium-webdriver": “4.0.0-alpha.1″,

Node Version: `8.11.3
Protractor Version: 5.3.2
Angular Version: 6.0.4
AngularJS Version: 1.6.4
Browser(s): Chrome, firefix

1 Answer
1

You don’t need add waiters before each action in your tests. You can implement wrapper with some common actions. Take a look at this idea:

public async clickOn(): Promise<void> {
try {
await this.waitForClickable();
} catch (e) {
throw new Error(`Can not click on fragment of not clickable fragment. ${e}`);
}
await this.click();
}

public async type(text: string): Promise<void> {
await this.clearInput();
await this.sendKeys(text);
}

public async clearInput(): Promise<void> {
try {
await this.waitForVisible();
} catch (e) {
throw new Error(`Can not clear the input of not visible fragment. ${e}`);
}
await this.clear();
}

I hope you get the idea.

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Javascript Slider with Multiple Allowed sections/timeslots

Javascript Slider with Multiple Allowed sections/timeslots

I want to implement a time-slot selector in jquery/javascript slider form.

There are a few slider libraries out there such as Ion Slider, jQRangeSlider etc. but I don’t know how I would be going about this. It doesn’t look like they support multiple “dead-zones".

I want the user to be able to select a timeslot (from and to) during a particular day. To select the day, I have implemented a date picker, then for the date, I retrieve the already occupied slots for instance:

07h00 - Available
07h30 - Available
08h00 - Occupied
08h30 - Occupied
09h00 - Occupied
09h30 - Available
...
18h30 - Available
19h00 - Available

So the range picker must look like this:
enter image description here

The user should only be able to select a time zone in the available sections (blue) and drag the start slider between the “available" section, and the end selector will move along with it. There might be multiple unavailable zones (Red).

Is this possible with the libraries already out there or is this a case of roll my own?

I have thought about using a bunch of check boxes then check all the boxes between the start and end time-slots, and disable the already occupied slots, but I think a slider like this would be much more user friendly to use, functionally and visually.

2 Answers
2

A double slider can be made with very little effort by overlaying two sliders on top of each other using CSS. You need to listen to the onchange events of these two and reset the slider to previous value or closet non dead region when set to a dead region.

var deadZones = [[2,3], [6,7]];
function showVal(input) {
deadZones.forEach(([from, to]) => {
// reset to old value if in dead zone
if(from <= input.value && input.value <= to)
input.value = input.oldValue;
});
input.oldValue = input.value;
//console.log(input.id, input.value);
displayValues();
}

function displayValues() {
var a = $('#a').val();
var b = $('#b').val();
$('#slider-values').text(`Min: ${Math.min(a,b)} Max: ${Math.max(a,b)}`);
}
displayValues();

html,body{
margin: 0; padding: 0;
}
#a, #b{
position: absolute;
top: 30px;
display: block;
z-index: 100;
}
#b {
top: 60px;
}

/* from: https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/ */
input[type=range] {
-webkit-appearance: none; /* Hides the slider so that custom slider can be made */
width: 90%; /* Specific width is required for Firefox. */
background: transparent; /* Otherwise white in Chrome */
margin-left: 5%;
}

input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: 1px solid #000000;
height: 36px;
width: 16px;
border-radius: 3px;
background: #ffffff;
cursor: pointer;
automatic */
box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d; /* Add cool effects to your sliders! */
position: relative;
}
input[type=range]#a::-webkit-slider-thumb {
top: 100px;
}
input[type=range]#b::-webkit-slider-thumb {
top: 70px;
}

.slider-bg {
width: 100%;
margin: 0; padding: 0;
margin-left: 2.5%;
position: relative;
z-index: 1;
top: 135px;
}
.slider-bg div {
display: inline-block;
width: 9%;
margin: 0; padding: 0;
text-align: center;
border-top: 1px solid green;
padding-top: 20px;
}
.slider-bg div.disabled {
border-top: 1px solid red;
}

https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js

<input id="a" type="range" min="1" max="10" value="1" oninput="showVal(this)" onchange="showVal(this)" />
<input id="b" type="range" min="1" max="10" value="9" oninput="showVal(this)" onchange="showVal(this)"/>
<hr />

1
2
3
4
5
6
7
8
9
10

</div>

I have decided to implement an ionRangeSlider with custom slots from 05h30 to 19h30. A separate array of used time-slots to which I compare in the onChange event.

05h30

19h30

used

onChange

var slider = $("#timeslotSlider").ionRangeSlider({
type: "double",
grid: true,
from: 1,
from_value: "06h00",
to: 2,
to_value: "06h30",
values: timeslotvalues,
onChange: function (data) {
timeslotSetSelectedText(data);
}
});

var sliderdata = slider.data("ionRangeSlider");
var dt = sliderdata.result.from_value != null ? sliderdata.result : sliderdata.options;

timeslotSetSelectedText(dt);

The timeslotSetSelectedText function compares the selected range to the used slots then display a message "Available" or "Overlaps Existing time-slot"

timeslotSetSelectedText

used

"Available"

"Overlaps Existing time-slot"

The same function is used to Validate the selected slot before sending it to the server.

Validate

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Reading two columns in two files and outputting them to another file

Reading two columns in two files and outputting them to another file

I recently posted this question – paste -d " " command outputting a return separated file

paste -d " "

However I am concerned there is formatting in the text files that is causing it to error. For this reason I am attempting to do it with awk.

awk

I am not very experienced with awk but currently I have the following:

awk

awk {print $1} file1 | {print $1} file2 > file 3

Is this the kind of syntax I should be using? It gives an error saying missing } Each file contains a single column of numbers and the same number of rows.

}

Please do not post links which have another data, post all details with in same post itself, kindly post sample of input and sample of output too in your post and let us know then.
– RavinderSingh13
Jul 3 at 10:36

Read the first couple of pages of any awk book or tutorial or even look at some examples on this forum to get an idea of awk syntax, there’s no need to just guess wildly. I highly recommend the book Effective Awk Programming, 4th Edition, by Arnold Robbins.
– Ed Morton
Jul 3 at 12:01

2 Answers
2

By seeing your OLD post seems to be you could have control M characters in your files. To remove control M characters in your files either use dos2unix utility or use following command(s).

dos2unix

1st: To remove junk chars everywhere.

tr -d 'r' < Input_file > temp_file && mv temp_file Input_file

2nd: To remove them only at last of lines use following.

awk '{sub(/r$/,"")} 1' Input_file > temp_file && mv temp_file Input_file

I believe once you remove junk chars your paste command should work properly too. Run following after you fix the control M chars in your Input_file(s).

paste

paste -d " " Input_file1 Input_file2 > Output_file

OR to concatenate 2 files simply use:(considering that your Input_files have either 1 column or you want full lines to be there in output)

cat Input_file1 Input_file2 > output_file

You beautiful human being
– Jt246
Jul 3 at 10:48

awk to the rescue:

awk

awk 'FNR==NR{a[FNR]=$1;next}{print a[FNR],$1}' a.txt b.txt > output.txt

a.txt:

1
2
3
4
5

b.txt:

A
B
C
D
E

output.txt:

1 A
2 B
3 C
4 D
5 E

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Working with special characters in VBScript and XMLHTTP

Working with special characters in VBScript and XMLHTTP

With this VB Script code execute download the XLSX file from autorized remote share to my client server.

The name of XLSX file is

TB-àdemain20180703.xlsx

For the special character à on the file name TB-àdemain20180703.xlsx the download is failed because on the client server the XLSX File is saved with this name :

TB-Ã demain20180703.xlsx

How to do resolve this ?

My code below.

Set File = WScript.CreateObject("Microsoft.XMLHTTP")

File.Open "GET", "https://share.xxx.com/Report/TB-àdemain20180703.xlsx", False

File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send

Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile "D:ReportTB-àdemain20180703.xlsx", 2

1 Answer
1

Try this in your link.

Please replace this :

File.Open "GET", "https://share.xxx.com/Report/TB-àdemain20180703.xlsx", False

With

File.Open "GET", "https://share.xxx.com/Report/TB-%C3%A0demain20180703.xlsx", False

I hope I was helpful.

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Parse error: syntax error, unexpected ‘{‘, expecting function (T_FUNCTION) or const (T_CONST) in session.php on line 37 [duplicate]

Parse error: syntax error, unexpected ‘{‘, expecting function (T_FUNCTION) or const (T_CONST) in session.php on line 37 [duplicate]

This question already has an answer here:

I don’t know why but all of the sudden I started getting this error.
I marked the line 37 in it. I am using xampp server. and below the full error line which I am getting.
“Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in C:xampphtdocsgalleryadminincludesfunctions.php on line 19″.

Please help me out in this.

<?php

class Session {

private $signed_in = false;
public $user_id;

function __construct(){

session_start();
$this->check_the_login();
}

public function is_signed_in() {

return $this->signed_in;

}

public function login($user){

$this->user_id = $_SESSION["user_id"] = $user->id;
$this->signed_in = true;
}

public function logout(){

unser($_SESSION["user_id"]);
unser($this->user_id);
$this->signed_in = false;

}

private function check_the_login(); { // This is line 37

if (isset($_SESSION["user_id"])) {
$this->user_id = $_SESSION["user_id"];
$this->signed_in = true;
}else {

unset($this->user_id);
$this->signed_in = false;
}
}

}

$session = new Session();

?>

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

There is an extra semicolon (;) in line 37. Remove it and the error will disappear. Read about the syntax of user-defined functions in PHP.
– axiac
Jul 3 at 10:37

;

You have typo in this line. unser($_SESSION["user_id"]);unser($this->user_id); It should be unset($_SESSION["user_id"]);unset($this->user_id);
– Virb
Jul 3 at 10:37

unser($_SESSION["user_id"]);unser($this->user_id);

unset($_SESSION["user_id"]);unset($this->user_id);

1 Answer
1

try this

Remove ; after function name

;

private function check_the_login(); // remove ;

also error in logout() function

error

logout()

write unset instead of unser

unset

unser

unset($_SESSION["user_id"]);
unset($this->user_id);

What a shameless mistake I had done. That’s form helping me Dr, Strange 🙂
– Karan Khandekar
Jul 4 at 5:06

Set RTF text into WPF RichTextBox control

Set RTF text into WPF RichTextBox control

I have this RTF text:

{rtf1ansiansicpg1252deff0deflang1033{fonttbl{f0fnilfcharset0 Arial;}}
{colortbl ;red0green0blue0;red255green0blue0;}
viewkind4uc1pardqccf1fs16 test b bold cf2b0i italiccf0i0fs17
par }

How to set this text into WPF RichTextBox?

Solution:

public void SetRTFText(string text)
{
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(text));
this.mainRTB.Selection.Load(stream, DataFormats.Rtf);
}

Thanks for help from Henk Holterman.

Just 1 remark, are you sure you want ASCII encoding? It could be but UTF8 or default usually make more sense.
– Henk Holterman
Sep 2 ’09 at 16:35

Yes, in case that I have, ASCII Encoding is what I need to use. Thanks for the tip 🙂
– Andrija Cacanovic
Sep 2 ’09 at 17:12

Actually, you’re not using ASCII encoding with this code… Default actually refers to Encoding.Default, so it’s the system’s default ANSI codepage. Beware of accessing static members through derived classes, it is often misleading.
– Thomas Levesque
Dec 31 ’13 at 10:42

Default

Encoding.Default

5 Answers
5

Do you really have to start with a string?

One method to load RTF is this:

rtfBox.Selection.Load(myStream, DataFormats.Rtf);

You probably should call SelectAll() before that if you want to replace existing text.

So, worst case, you’ll have to write your string to a MemoryStream and then feed that stream to the Load() method. Don’t forget to Position=0 in between.

But I’m waiting to see somebody to come up with something more elegant.

rtfBox.Selection.Load is what I needed. Thank you 🙂
– Andrija Cacanovic
Sep 2 ’09 at 15:27

Instead of using the Selection property and worrying about calling SelectAll, you can probably use new TextRange( rtfBox.Document.ContentStart, rtfBox.Document.ContentEnd ) and then call Load on the TextRange (Selection is itself a TextRange).
– devios1
Jun 1 ’10 at 1:51

Selection

new TextRange( rtfBox.Document.ContentStart, rtfBox.Document.ContentEnd )

with devios’s snippet, this works: TextRange textRange = new TextRange( rtfBox.Document.ContentStart, rtfBox.Document.ContentEnd ); MemoryStream ms = new MemoryStream( ASCIIEncoding.ASCII.GetBytes( rtfText ) ); textRange.Load( ms, DataFormats.Rtf );
– Tom Sirgedas
Feb 2 ’16 at 16:05

TextRange textRange = new TextRange( rtfBox.Document.ContentStart, rtfBox.Document.ContentEnd ); MemoryStream ms = new MemoryStream( ASCIIEncoding.ASCII.GetBytes( rtfText ) ); textRange.Load( ms, DataFormats.Rtf );

Create an Extension method

public static void SetRtf(this RichTextBox rtb, string document)
{
var documentBytes = Encoding.UTF8.GetBytes(document);
using (var reader = new MemoryStream(documentBytes))
{
reader.Position = 0;
rtb.SelectAll();
rtb.Selection.Load(reader, DataFormats.Rtf);
}
}

Then you can do WinForm-esque style

richTextBox1.SetRtf(rtf);

richTextBox1.SetRtf(rtf);

You can’t use extension method as property.
– Andrija Cacanovic
Dec 9 ’12 at 19:23

I wrote a really slick solution by extending the RichTextBox class to allow Binding to an actual rich text file.

I came across this question/answer but didn’t really get what I was looking for, so hopefully what I have learned will help out those who read this in the future.

Loading a RichTextBox from an RTF file using binding or a RichTextFile control

string rtf = @"{rtf1ansiansicpg1252deff0deflang1033{fonttbl{f0fnilfcharset0 Arial;}} {colortbl ;red0green0blue0;red255green0blue0;} viewkind4uc1pardqccf1fs16 test b bold cf2b0i italiccf0i0fs17 par } ";
richTextBox1.Rtf = rtf;

It’s working fine

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don’t require clarification from the asker. – From Review
– David
Jul 3 at 16:40

That’s for Windows Forms, the question specifies WPF.
– Marty
Jul 6 at 0:07

Simply use RichTextBox.Rtf:

string rtf = @"{rtf1ansiansicpg1252deff0deflang1033{fonttbl{f0fnilfcharset0 Arial;}} {colortbl ;red0green0blue0;red255green0blue0;} viewkind4uc1pardqccf1fs16 test b bold cf2b0i italiccf0i0fs17 par } ";
richTextBox1.Rtf = rtf;

That works for the WinForms RichTextBox
– Henk Holterman
Sep 2 ’09 at 12:11

Oh my bad. I missed you where using WPF.
– J. Random Coder
Sep 2 ’09 at 12:22

you’re answer helped me, so vote up.
– juanjo.arana
Sep 13 ’11 at 8:48

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Decompose grid into rows and columns

Decompose grid into rows and columns

Currently I’m working on an algorithm for laying out plots and widgets on a grid. The underlying library I’m using has two primitives for building up a grid, rows and a columns. The idea is that I feed it with a grid spec which defines how many grid cells each plot takes up. The individual plots and widgets can take up one or more grid cells but must be rectangular. To make this problem a bit more concrete I will draw a simple 4×4 grid, where each number represents a separate plot or widget:

---------------------
| 1 | 2 | 3 | 3 |
|____|____|____|____|
| 4 | 2 | 5 | 5 |
|____|____|____|____|
| 4 | 6 | 7 | 7 |
|____|____|____|____|
| 4 | 6 | 7 | 7 |
|____|____|____|____|

By breaking up each part of the grid we can be decompose it into a number of nested rows and columns, e.g. in this example this might look something like this:

col1 = column(1, 4)
col2 = column(3, 5)
row1 = row(2, col2)
row2 = row(6, 7)
col3 = column(row1, row2)
grid = row(col1, col3)

Is there an algorithm we can use that will let us decompose this grid into rows and columns like this? I’ve been playing around with it but anything I’ve tried starts getting very complex quickly and I suspect I’ve simply not found a good way to represent and think about the problem.

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How to store data offline in andoid database after parsing it from json through URL?

How to store data offline in andoid database after parsing it from json through URL?

I want to store data locally in the phone after parsing it from JSON API and then make a button to synchronize that data whenever I need to so that the content can be used offline.

2 Answers
2

If you want to store data object locally, then you can make use of Realm DB. Below link explains how to use Realm DB https://www.androidhive.info/2016/05/android-working-with-realm-database-replacing-sqlite-core-data/

Right now, the best option to store bunch of data locally is using sqlite. You can search for it. There is a bunch of tutorials for it. Also, you can also use Room library which makes it really easy to create sqlite databases and interact with it.

Room

By clicking “Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.