text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Fixed container positioned on top of the body's scroll We are experencing Fixed container positioned on top of the body's scroll ( even with: box-sizing: border-box;), with those styles:
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
z-index: 100;
width: 100%;
height: 71px;
background-color: #115191;
box-shadow: 0 0px 20px 0 rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 0 0px 20px 0 rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 0px 20px 0 rgba(0, 0, 0, 0.1);
font-family: 'Lato', sans-serif;
position: fixed;
top: 0;
box-sizing: border-box;
but if I set the width, like this:
width: calc(100% - 17px )
then is what we expect ( at least in chrome, other browsers/versions must have a different scroll width)
The styles of html tag:
height: 100%;
overflow-y: auto;
body:
padding: 0;
margin: 0;
background-color: #f7f7f7;
min-height: 100%;
any idea wha'ts causing this and how to prevent it?
thanks
A: We need to see all your code, but you probably have margin:0 at the html/body. Without it, it works
html,
body {
height: 100%;
overflow-y: auto;
}
.fixed {
position: fixed;
height: 70px;
background-color: blue;
top: 0;
width: 100%
}
.content{
height: 2000px
}
<div class="fixed"></div>
<div class="content">
</div>
When I add the margin I got the same problem you experience
html,
body {
height: 100%;
overflow-y: auto;
margin: 0;
}
.fixed {
position: fixed;
height: 70px;
background-color: blue;
top: 0;
width: 100%
}
.content{
height: 2000px
}
<div class="fixed"></div>
<div class="content">
</div>
A: You can remove scroll from html, body elements and add it to content wrapper. In this example it is main element.
Html example
<body>
<header>Header</header>
<main>
<!--All page content goes here-->
</main>
</body>
Remove dafault page scroll
body, html {
height: 100%;
overflow: hidden;
}
Add scroll and height for content wrapper
main {
margin-top: 40px;
height: calc(100% - 40px);
overflow: auto;
}
40px here is the height of the fixed header.
header {
...
height: 40px;
...
}
body, html {
height: 100%;
overflow: hidden;
/*Some reset styles*/
margin: 0;
font-family: sans-serif;
}
header {
position: fixed;
top: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
height: 40px;
background-color: gainsboro;
}
main {
margin-top: 40px;
height: calc(100% - 40px);
overflow: auto;
}
header, main {
padding-left: 15px;
padding-right: 15px;
}
<header>Header</header>
<main>
<h1>Title</h1>
<h2>Title 2</h2>
<h3>Title 3</h3>
<p>The Lost World is a novel released in 1912 by Sir Arthur Conan Doyle concerning an expedition to a plateau in the Amazon basin of South America where prehistoric animals (dinosaurs and other extinct creatures) still survive. It was originally published serially in the popular Strand Magazine and illustrated by New-Zealand-born artist Harry Rountree during the months of April–November 1912. The character of Professor Challenger was in thrusting book. The novel also describes a war between indigenous people and a vicious tribe of ape-like creatures.</p>
<p>The Lost World is a novel released in 1912 by Sir Arthur Conan Doyle concerning an expedition to a plateau in the Amazon basin of South America where prehistoric animals (dinosaurs and other extinct creatures) still survive. It was originally published serially in the popular Strand Magazine and illustrated by New-Zealand-born artist Harry Rountree during the months of April–November 1912. The character of Professor Challenger was in thrusting book. The novel also describes a war between indigenous people and a vicious tribe of ape-like creatures.</p>
</main>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52813451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to draw very specific annular sectors using visual basic .NET 2 This question furthers a previous question. In that question valter provided me with a very good answer that used two lines of code to perform all the math. I'm hoping he would like to try his hand at this problem also. Even though it looks similar I have not been able to get any math to work.
I need to now draw exactly the same annular sectors accept that the OuterRadius in that question becomes a Rectangle. I include this image to explain what I mean. You will notice the red line that represents the Rectangle plugged into the function. The image is actually a screen capture of what the code I tried up to now produces. Naturally most them are is wrong, but the top left annular sector for instance is correct. All the annular sectors should terminate on the rectangle edge, whilst compensating for the gap. Corner cases would probably need 3 points.
I have decided to post the code I have so far, so the puritans must please close their eyes, because it is pretty brutal:
<Extension()> Friend Sub AddAnnularSector(
ByVal aGraphicsPath As GraphicsPath,
ByVal aCenterPoint As PointR,
ByVal aInnerRadius As Double,
ByVal aOuterRectangle As RectangleF,
ByVal aStartAngle As Double,
ByVal aSweepAngle As Double,
ByVal aStartGap As Double,
ByVal aEndGap As Double)
'Declare local variables...
Dim tInnerStartOffset As Double = (Math.Asin(aStartGap / aInnerRadius) * 180.0R) / Math.PI
Dim tInnerEndOffset As Double = (Math.Asin(aEndGap / aInnerRadius) * 180.0R) / Math.PI
Dim tTestAngle1 As Double = aStartAngle + aSweepAngle - tInnerEndOffset
If tTestAngle1 > 360.0R Then tTestAngle1 -= 360.0R
If tTestAngle1 > 270.0R Then tTestAngle1 = 360.0R - tTestAngle1
If tTestAngle1 > 180.0R Then tTestAngle1 -= 180.0R
If tTestAngle1 > 90.0R Then tTestAngle1 = 180.0R - tTestAngle1
Dim tOuterEndLength As Double = (Math.Min(aOuterRectangle.Width, aOuterRectangle.Height) / 2) / Math.Sin(tTestAngle1.ToRadians)
Dim tTestAngle2 As Double = aStartAngle + tInnerStartOffset
If tTestAngle2 > 360.0R Then tTestAngle2 -= 360.0R
If tTestAngle2 > 270.0R Then tTestAngle2 = 360.0R - tTestAngle2
If tTestAngle2 > 180.0R Then tTestAngle2 -= 180.0R
If tTestAngle2 > 90.0R Then tTestAngle2 = 180.0R - tTestAngle2
Dim tOuterStartLength As Double = (Math.Min(aOuterRectangle.Width, aOuterRectangle.Height) / 2) / Math.Sin(tTestAngle2.ToRadians)
'Add the annular sector to the figure...
aGraphicsPath.StartFigure()
aGraphicsPath.AddArc(CSng(aCenterPoint.X - aInnerRadius), CSng(aCenterPoint.Y - aInnerRadius), CSng(aInnerRadius * 2.0R), CSng(aInnerRadius * 2.0R), CSng(aStartAngle + tInnerStartOffset), CSng(aSweepAngle - (tInnerStartOffset + tInnerEndOffset)))
aGraphicsPath.AddLines(New PointF() {
New PointF(CSng((aCenterPoint.X) + (Math.Cos((aStartAngle + aSweepAngle - tInnerEndOffset).ToRadians) * tOuterEndLength)), CSng((aCenterPoint.Y) + (Math.Sin((aStartAngle + aSweepAngle - tInnerEndOffset).ToRadians) * tOuterEndLength))),
New PointF(CSng((aCenterPoint.X) + (Math.Cos((aStartAngle + tInnerStartOffset).ToRadians) * tOuterStartLength)), CSng((aCenterPoint.Y) + (Math.Sin((aStartAngle + tInnerStartOffset).ToRadians) * tOuterStartLength)))
})
aGraphicsPath.CloseFigure()
Return
End Sub
You will notice how OuterRadius of the previous question changed to aOuterRectangle. Also the inner arc is drawn exactly like the previous outer arc was drawn.
EDIT 1: Just chopped the code off a bit to make it more legible.
EDIT 2: Here is an image of what is actually required unlike the above image that just shows the current result.
*
*Light Cyan - Figure that will actually be added to the GraphicsPath.
*Dark Cyan - The part of the figure that is cut away by the OuterRectangle.
*Green - The OuterRectangle's dimensions including its center point.
*Yellow - The InnerRadius's dimensions including its center point.
*Pink - Figure added in a previous call to the function with different inputs just for reference.
EDIT 3: This image shows what I thought would be a quick mathematical solution.
Thanks
drifter
A: For wdthRect = 250, hgtRect = 200, innerR = 65, startA = 280.0, angle = 30.0, gap = 10.0R
Private Sub DrawAnnular2(ByVal pntC As Point, ByVal wdthRect As Integer, ByVal hgtRect As Integer, ByVal innerR As Integer, ByVal startA As Single, ByVal angle As Single, ByVal gap As Double)
Dim g As Graphics
Dim pth As New GraphicsPath
Dim pthRct As New GraphicsPath
Dim pthCrclIn As New GraphicsPath
Dim pthCrclOut As New GraphicsPath
Dim fe, theta, dbl As Double
Dim outerR, wdth As Integer
Dim rect As Rectangle
wdth = Math.Min(wdthRect, hgtRect)
outerR = CInt(Math.Sqrt(2.0R * (CDbl(wdth) / 2.0R) * (CDbl(wdth) / 2.0R))) 'πυθαγόρειο θεώρημα
rect.X = CInt(CDbl(pntC.X) - CDbl(wdth) / 2.0R)
rect.Y = CInt(CDbl(pntC.Y) - CDbl(wdth) / 2.0R)
rect.Width = wdth
rect.Height = wdth
pthCrclOut.AddEllipse(pntC.X - outerR, pntC.Y - outerR, 2 * outerR, 2 * outerR)
pthCrclIn.AddEllipse(rect)
pthRct.AddRectangle(rect)
'////// The same as annular 1 //////////////////////////////////////////////////
g = Me.CreateGraphics
g.SmoothingMode = SmoothingMode.AntiAlias
gap /= 2.0R
dbl = gap / CDbl(outerR)
theta = Math.Asin(dbl) * 180.0R / Math.PI
fe = theta
pth.AddArc(pntC.X - outerR, pntC.Y - outerR, 2 * outerR, 2 * outerR, startA + CSng(fe), angle - CSng(2.0R * fe)) 'Outer
dbl = gap / CDbl(innerR)
theta = Math.Asin(dbl) * 180.0R / Math.PI
fe = theta
pth.AddArc(pntC.X - innerR, pntC.Y - innerR, 2 * innerR, 2 * innerR, startA + angle - CSng(fe), -(angle - CSng(2.0R * fe))) 'Inner
'////////////////////////////////////////////////////////////
Dim Reg1 As New Region(pth)
Dim Reg2 As New Region(pthRct)
Reg2.Intersect(Reg1)
g.FillRegion(Brushes.Aqua, Reg2) 'This is the actual annular 2.
g.DrawPath(Pens.Green, pthCrclIn)
g.DrawPath(Pens.Green, pthCrclOut)
g.DrawPath(Pens.Red, pthRct)
Reg1.Dispose()
Reg2.Dispose()
pthRct.Dispose()
pthCrclOut.Dispose()
pthCrclIn.Dispose()
pth.Dispose()
g.Dispose()
End Sub
This line of code:
Reg2.Intersect(Reg1)
is actually the intersect between the blue and the red
EDIT
Private Function DrawAnnular2(ByVal pntC As Point, ByVal wdthRect As Integer, ByVal hgtRect As Integer, ByVal innerR As Integer, ByVal startA As Single, ByVal angle As Single, ByVal gap As Double) As GraphicsPath
Dim g As Graphics
Dim pth As New GraphicsPath
Dim pthRct As New GraphicsPath
Dim pthFinal As New GraphicsPath
Dim fe, theta, dbl As Double
Dim outerR, wdth As Integer
Dim rect As Rectangle
Dim lst1 As New List(Of Integer)
Dim lst2 As New List(Of Integer)
Dim lst3 As New List(Of Integer)
Dim lst4 As New List(Of Integer)
Dim i As Integer
Dim lstBl(3) As Boolean
Dim position As Integer
lstBl(0) = False
lstBl(1) = False
lstBl(2) = False
lstBl(3) = False
wdth = Math.Min(wdthRect, hgtRect)
outerR = CInt(Math.Sqrt(2.0R * (CDbl(wdth) / 2.0R) * (CDbl(wdth) / 2.0R))) 'πυθαγόρειο θεώρημα
rect.X = CInt(CDbl(pntC.X) - CDbl(wdth) / 2.0R)
rect.Y = CInt(CDbl(pntC.Y) - CDbl(wdth) / 2.0R)
rect.Width = wdth
rect.Height = wdth
pthRct.AddRectangle(rect)
'////////////////////////////////////////////////////////
g = Me.CreateGraphics
g.SmoothingMode = SmoothingMode.AntiAlias
gap /= 2.0R
dbl = gap / CDbl(outerR)
theta = Math.Asin(dbl) * 180.0R / Math.PI
fe = theta
If CDbl(angle) - 2.0R * fe >= 360.0R Then
pthFinal.AddEllipse(pntC.X - innerR, pntC.Y - innerR, 2 * innerR, 2 * innerR)
pthFinal.AddRectangle(rect)
g.FillPath(Brushes.Aqua, pthFinal)
g.DrawPath(Pens.Red, pthRct)
pthRct.Dispose()
pth.Dispose()
g.Dispose()
Return pthFinal
End If
pth.AddArc(pntC.X - outerR, pntC.Y - outerR, 2 * outerR, 2 * outerR, startA + CSng(fe), angle - CSng(2.0R * fe)) 'Outer
dbl = gap / CDbl(innerR)
theta = Math.Asin(dbl) * 180.0R / Math.PI
fe = theta
pth.AddArc(pntC.X - innerR, pntC.Y - innerR, 2 * innerR, 2 * innerR, startA + angle - CSng(fe), -(angle - CSng(2.0R * fe))) 'Inner
'////////////////////////////////////////////////////////////
For i = rect.X To rect.X + wdth
If pth.IsVisible(i, rect.Y) Then
If lst1.Count <> 0 Then
If i <> lst1(lst1.Count - 1) + 1 Then
lstBl(0) = True
position = lst1.Count
End If
End If
lst1.Add(i)
End If
Next
For i = rect.Y To rect.Y + wdth
If pth.IsVisible(rect.X + wdth, i) Then
If lst2.Count <> 0 Then
If i <> lst2(lst2.Count - 1) + 1 Then
lstBl(1) = True
position = lst2.Count
End If
End If
lst2.Add(i)
End If
Next
For i = rect.X To rect.X + wdth
If pth.IsVisible(i, rect.Y + wdth) Then
If lst3.Count <> 0 Then
If i <> lst3(lst3.Count - 1) + 1 Then
lstBl(2) = True
position = lst3.Count
End If
End If
lst3.Add(i)
End If
Next
For i = rect.Y To rect.Y + wdth
If pth.IsVisible(rect.X, i) Then
If lst4.Count <> 0 Then
If i <> lst4(lst4.Count - 1) + 1 Then
lstBl(3) = True
position = lst4.Count
End If
End If
lst4.Add(i)
End If
Next
'If lstBl(0) = True Or lstBl(1) = True Or lstBl(2) = True Or lstBl(3) = True Then
'It is a rare case that i have to work on, when angle is too large
'MsgBox(lstBl(0).ToString + " " + lstBl(1).ToString + " " + lstBl(2).ToString + " " + lstBl(3).ToString + " ")
'Application.Exit()
'End If
'TextBox1.Text = lst1.Count.ToString + " " + lst2.Count.ToString + " " + lst3.Count.ToString + " " + " " + lst4.Count.ToString
pthFinal.AddArc(pntC.X - innerR, pntC.Y - innerR, 2 * innerR, 2 * innerR, startA + angle - CSng(fe), -(angle - CSng(2.0R * fe))) 'Inner
If CDbl(startA) + fe >= 225.0R And CDbl(startA) + fe <= 315.0R Then '1
If lst1.Count <> 0 Then
If lstBl(0) = True Then
pthFinal.AddLine(lst1(position), rect.Y, lst1(lst1.Count - 1), rect.Y)
Else
pthFinal.AddLine(lst1(0), rect.Y, lst1(lst1.Count - 1), rect.Y)
End If
End If
If lst2.Count <> 0 Then
pthFinal.AddLine(lst1(lst1.Count - 1), rect.Y, rect.X + wdth, lst2(lst2.Count - 1))
End If
If lst3.Count <> 0 Then
pthFinal.AddLine(rect.X + wdth, lst2(lst2.Count - 1), lst3(0), rect.Y + wdth)
End If
If lst4.Count <> 0 Then
pthFinal.AddLine(lst3(0), rect.Y + wdth, rect.X, lst4(0))
End If
If lstBl(0) = True Then
pthFinal.AddLine(rect.X, lst4(0), lst1(position - 1), rect.Y)
End If
ElseIf (CDbl(startA) + fe > 315.0R And CDbl(startA) + fe <= 360.0R) Or _
(CDbl(startA) + fe >= 0.0R And CDbl(startA) + fe <= 45.0R) Then '2
If lst2.Count <> 0 Then
If lstBl(1) = True Then
pthFinal.AddLine(rect.X + wdth, lst2(position), rect.X + wdth, lst2(lst2.Count - 1))
Else
pthFinal.AddLine(rect.X + wdth, lst2(0), rect.X + wdth, lst2(lst2.Count - 1))
End If
End If
If lst3.Count <> 0 Then
pthFinal.AddLine(rect.X + wdth, lst2(lst2.Count - 1), lst3(0), rect.Y + wdth)
End If
If lst4.Count <> 0 Then
pthFinal.AddLine(lst3(0), rect.Y + wdth, rect.X, lst4(0))
End If
If lst1.Count <> 0 Then
pthFinal.AddLine(rect.X, lst4(0), lst1(lst1.Count - 1), rect.Y)
End If
If lstBl(1) = True Then
pthFinal.AddLine(lst1(lst1.Count - 1), rect.Y, rect.X + wdth, lst2(position - 1))
End If
ElseIf CDbl(startA) + fe > 45.0R And CDbl(startA) + fe <= 135.0R Then '3
If lst3.Count <> 0 Then
If lstBl(2) = True Then
pthFinal.AddLine(lst3(position - 1), rect.Y + wdth, lst3(0), rect.Y + wdth)
Else
pthFinal.AddLine(lst3(lst3.Count - 1), rect.Y + wdth, lst3(0), rect.Y + wdth)
End If
End If
If lst4.Count <> 0 Then
pthFinal.AddLine(lst3(0), rect.Y + wdth, rect.X, lst3(0))
End If
If lst1.Count <> 0 Then
pthFinal.AddLine(rect.X, lst3(0), lst1(lst1.Count - 1), rect.Y)
End If
If lst2.Count <> 0 Then
pthFinal.AddLine(lst1(lst1.Count - 1), rect.Y, rect.X + wdth, lst2(lst2.Count - 1))
End If
If lstBl(2) = True Then
pthFinal.AddLine(rect.X + wdth, lst2(lst2.Count - 1), lst3(position), rect.Y + wdth)
End If
Else '4
If lst4.Count <> 0 Then
If lstBl(3) = True Then
pthFinal.AddLine(rect.X, lst4(position - 1), rect.X, lst4(0))
Else
pthFinal.AddLine(rect.X, lst4(lst4.Count - 1), rect.X, lst4(0))
End If
End If
If lst1.Count <> 0 Then
pthFinal.AddLine(rect.X, lst4(0), lst1(lst1.Count - 1), rect.Y)
End If
If lst2.Count <> 0 Then
pthFinal.AddLine(lst1(lst1.Count - 1), rect.Y, rect.X + wdth, lst2(lst2.Count - 1))
End If
If lst3.Count <> 0 Then
pthFinal.AddLine(rect.X + wdth, lst2(lst2.Count - 1), lst3(0), rect.Y + wdth)
End If
If lstBl(3) = True Then
pthFinal.AddLine(lst3(0), rect.Y + wdth, rect.X, lst4(position))
End If
End If
'g.FillPath(Brushes.Blue, pth)
g.FillPath(Brushes.Aqua, pthFinal)
g.DrawPath(Pens.Red, pthRct)
pthRct.Dispose()
pth.Dispose()
g.Dispose()
Return pthFinal
End Function
Your values:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25886948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RegisterClientScriptBlock within AJAX method call I am trying to RegisterClientScriptBlock in a method that is only called via an AJAX call. It doesn't appear to actually register the script on the page and I'm guessing this is because it's not actually reloading the entire page. Is there any way to register javascript on a page from within an ajax method call?
protected void MyMethod(object sender, EventArgs e)
{
// This method only called via AJAX call
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "resize", "alert('here');", true);
}
A: With AJAX enabled pages, you should use the ScriptManager to register scripts:
ScriptManager.RegisterClientScriptBlock(Page, typeof(MyPage),
"MyScript", "GoStuff()", true)
You can use this to register all your scripts (Original load, postback, AJAX postback).
A: It works if you specify the UpdatePanel being updated on the AJAX call back. For example:
ScriptManager.RegisterClientScriptBlock(UpdatePanelMain, typeof(UpdatePanel),
UpdatePanelMain.ClientID,
"document.getElementById('imgLoading').style.display = 'none';" +
"document.getElementById('divMultiView').style.display = 'inline';",
true);
The control in the first argument must be inside the update panel or the update panel itself that triggers the update.
A: As far as I know for this you would be forced to be calling this method via a PostBack and not an ajax call. There may be OTHER ways of doing this, but it is not possible with Page.ClientScript....
A: In general, when loading external javascript after appending an element innerHTML with a block containing such script, one needs to evaluate (eval) the script in order for it to work properly and render itself into the current loaded document.
I'd suggest doing on of the following:
Use an external tool such as YUI get utility which is supposed to enable such behavior or do some evaluation for scripts yourself like this
A: If there's anyone else out there like myself, and the accepted answer STILL won't work for you, then look no further.
Check out this link - a simple class that pops a Javascript alert no matter if you're on page load, unload, AJAX request, etc:
WebMsgBox.Show("Your message here");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/297081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Passing model property expression to view I want to have a way of getting a view to focus on a particular model property from a controller in a generic way.
What i have so far is:
Controller:
// To become an extension/base class method
private void FocusOnField<TModel, TProperty>(Expression<Func<TModel, TProperty>> fieldExpression)
{
ViewData["FieldToFocus"] = fieldExpression;
}
...
FocusOnField((ConcreteModelClass m) => m.MyProperty);
View
public static class ViewPageExtensions
{
public static MvcHtmlString FocusScript<TModel>(this ViewPage<TModel> viewPage)
{
if (viewPage.ViewData["FieldToFocus"] != null)
{
return MvcHtmlString.Create(
@"<script type=""text/javascript"" language=""javascript"">
$(document).ready(function() {
setTimeout(function() {
$('#" + viewPage.Html.IdFor((System.Linq.Expressions.Expression<Func<TModel, object>>)viewPage.ViewData["FieldToFocus"]) + @"').focus();
}, 500);
});
</script>");
}
else
{
return MvcHtmlString.Empty;
}
}
}
The problem I'm faced with now, is that in the view's FocusScript method I don't know the return type of the property to focus on, and casting to (System.Linq.Expressions.Expression<Func<TModel, object>>) fails for any property that doesn't return an object.
I can't just add a second generic parameter for the property because I don't know what the return type of the property the controller wants me to focus on is.
How can I write my view extension method FocusScript in a generic way so it can be used with properties of varying return types?
Why is there a problem?
I know I could just pass the Id of the control i want to focus on in the controller and have javascript read that id, find the control and focus on it. However, I don't like having something that belongs in the view (the Id of a control) hard-coded in the controller. I want to tell the method what property I want and it should know the Id to use in the same way the view normally gets/creates the Id for a control.
Lets say I have a model:
class MyModel
{
public int IntProperty { get; set; }
public string StringProperty { get; set; }
}
In different places in the controller I want to focus one different fields:
FocusOnField((MyModel m) => m.IntProperty);
...
FocusOnField((MyModel m) => m.StringProperty);
Now, in the first case the expression is a function returning an integer, in the second case it's returning a string. As a result I don't know what to cast my ViewData["FieldToFocus"] to (to pass it to IdFor<>()) as it varies based on the property..
A: I think I've come up with a solution to your problem - it works in my environment but then I've had to guess how your code probably looks.
public static class ViewPageExtensions
{
public static MvcHtmlString GetIdFor<TViewModel, TProperty>(ViewPage<TViewModel> viewPage, Expression<Func<TViewModel, TProperty>> expression)
{
return viewPage.Html.IdFor(expression);
}
public static MvcHtmlString FocusScript<TViewModel>(this ViewPage<TViewModel> viewPage)
{
if (viewPage.ViewData["FieldToFocus"] == null)
return MvcHtmlString.Empty;
object expression = viewPage.ViewData["FieldToFocus"];
Type expressionType = expression.GetType(); // expressionType = Expression<Func<TViewModel, TProperty>>
Type functionType = expressionType.GetGenericArguments()[0]; // functionType = Func<TViewModel, TProperty>
Type[] functionGenericArguments = functionType.GetGenericArguments(); // functionGenericArguments = [TViewModel, TProperty]
System.Reflection.MethodInfo method = typeof(ViewPageExtensions).GetMethod("GetIdFor").MakeGenericMethod(functionGenericArguments); // method = GetIdFor<TViewModel, TProperty>
MvcHtmlString id = (MvcHtmlString)method.Invoke(null, new[] { viewPage, expression }); // Call GetIdFor<TViewModel, TProperty>(viewPage, expression);
return MvcHtmlString.Create(
@"<script type=""text/javascript"" language=""javascript"">
$(document).ready(function() {
setTimeout(function() {
$('#" + id + @"').focus();
}, 500);
});
</script>");
}
}
Perhaps there's a more elegant way to do, but I think what it boils down to is you're trying to cast an object (ie return type of ViewData["FieldToFocus"]) to the correct expression tree Expression<Func<TViewModel, TProperty>> but like you've said you don't know what TProperty should be.
Also to make this work I had to add another static method to GetIdFor because at the moment I'm not too sure how to invoke an extension method. Its just a wrapper to call the IdFor extension method.
You could make it less verbose (but probably less readable).
object expression = viewPage.ViewData["FieldToFocus"];
MethodInfo method = typeof(ViewPageExtensions).GetMethod("GetIdFor")
.MakeGenericMethod(expression.GetType().GetGenericArguments()[0].GetGenericArguments());
MvcHtmlString id = (MvcHtmlString)method.Invoke(null, new[] { viewPage, expression });
One final thought, would the output of HtmlHelper.IdFor ever differ from ExpressionHelper.GetExpressionText? I don't fully understand IdFor, and wonder if it will always give you a string that matches the property name.
ViewData["FieldToFocus"] = ExpressionHelper.GetExpressionText(fieldExpression);
A: It's as simple as using a LambdaExpression. No need to go the Expression<Func<TModel, TProperty>> way.
public static class HtmlExtensions
{
public static string IdFor(
this HtmlHelper htmlHelper,
LambdaExpression expression
)
{
var id = ExpressionHelper.GetExpressionText(expression);
return htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldId(id);
}
public static MvcHtmlString FocusScript(
this HtmlHelper htmlHelper
)
{
if (htmlHelper.ViewData["FieldToFocus"] != null)
{
return MvcHtmlString.Create(
@"<script type=""text/javascript"">
$(document).ready(function() {
setTimeout(function() {
$('#" + htmlHelper.IdFor((LambdaExpression)htmlHelper.ViewData["FieldToFocus"]) + @"').focus();
}, 500);
});
</script>");
}
else
{
return MvcHtmlString.Empty;
}
}
}
then in your controller:
public ActionResult Index()
{
FocusOnField((MyModel m) => m.IntProperty);
return View(new MyModel());
}
and in your view:
@model MyModel
@Html.FocusScript()
This being said I am leaving without comment the fact that a controller action is setting a focus.
A: You can take advantage of your out of the box Metadata to provide you the property Id etc..
And then in your Extensions:
public static MvcHtmlString FocusFieldFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var fullPropertyName = html.ViewData.TemplateInfo.GetFullHtmlFieldId(metadata.PropertyName);
var jsonData =
@"<script type=""text/javascript"">
$(document).ready(function() {
setTimeout(function() {
$('#" + fullPropertyName + @"').focus();
}, 500);
});
</script>";
return MvcHtmlString.Create(jsonData);
}
A: Maybe I'm missing something, but since you're passing in the field name to your FocusOnField function, could you not also just pass the string of the field name as well which will be the default ID in the view then set a ViewData value? Then your javascript could do something like...
<script type="text/javascript">
onload = focusonme;
function focusonme() {
var element = document.getElementById(@ViewData["FieldToFocus"]);
element.focus();
}
</script>
Maybe this isn't exactly what you're after, but the JS will definitely work this way...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11450774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Regex removing anything that is not a 14-digit number followed with space I'm trying to invert this expression: ([0-9]{14} ),
so all 14 digit numbers followed by a space.
I looked everywhere, and it seems that the best way should be using negative lookahead.
But when I try apply q(?!u) to my case >> (?!([0-9]{14} )), it doesn't work.
What am I doing wrong?
I will appreaciate any advice, thank you.
The point is to remove everything that is not a 14-digit chunk of text while preserving those 14-digit chunks.
A: If you want to delete text other than 14 digits followed with a space, use (\b\d{14} )|. and replace with $1.
The pattern matches and captures (we can refer to the text captured with a backreference in the replacement pattern) the 14-digit chunks and then a space as whole word due to \b (a word boundary). If this text is not found, any character other than a newline is matched with . and is not captured (we cannot refer to it with a backreference).
Thus, when we replace with a backreference $1, we just restore the matched 14 digit chunk with a space.
See the regex demo at regex101.com.
To get the cleaner view, remove all empty lines: Edit > Line Operations > Remove Empty Lines.
A: You can use this negative lookahead:
^(?!.*[0-9]{14} )
*
*Make sure you use start anchor ^
*Also important to use .* before your pattern to disallow this anywhere in input
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36696455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: semaphore/multiple pool locks in asyncio for 1 proxy - aiohttp I have 5,00,000 urls. and want to get response of each asynchronously.
import aiohttp
import asyncio
@asyncio.coroutine
def worker(url):
response = yield from aiohttp.request('GET', url, connector=aiohttp.TCPConnector(share_cookies=True, verify_ssl=False))
body = yield from response.read_and_close()
print(url)
def main():
url_list = [] # lacs of urls, extracting from a file
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([worker(u) for u in url_list]))
main()
I want 200 connections at a time(concurrent 200), not more than this because
when I run this program for 50 urls it works fine, i.e url_list[:50]
but if I pass whole list, i get this error
aiohttp.errors.ClientOSError: Cannot connect to host www.example.com:443 ssl:True Future/Task exception was never retrieved future: Task()
may be frequency is too much and server is denying to respond after a limit?
A: Yes, one can expect a server to stop responding after causing too much traffic (whatever the definition of "too much traffic") to it.
One way to limit number of concurrent requests (throttle them) in such cases is to use asyncio.Semaphore, similar in use to these used in multithreading: just like there, you create a semaphore and make sure the operation you want to throttle is aquiring that semaphore prior to doing actual work and releasing it afterwards.
For your convenience, asyncio.Semaphore implements context manager to make it even easier.
Most basic approach:
CONCURRENT_REQUESTS = 200
@asyncio.coroutine
def worker(url, semaphore):
# Aquiring/releasing semaphore using context manager.
with (yield from semaphore):
response = yield from aiohttp.request(
'GET',
url,
connector=aiohttp.TCPConnector(share_cookies=True,
verify_ssl=False))
body = yield from response.read_and_close()
print(url)
def main():
url_list = [] # lacs of urls, extracting from a file
semaphore = asyncio.Semaphore(CONCURRENT_REQUESTS)
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([worker(u, semaphore) for u in url_list]))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28406124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL Server Stress Test Tools? I am looking for a stress tool for SQL Server. I've seen a lot of suggestions on Google. But nothing of what I really need.
I am really looking for a tool that could run a list of stored procedures in parallel to see how much contention on resources. The collect and reporting feature is not that important. But I also want something server-side base for our enterprise build server.
I am not looking for a replay feature (Yes it could do the trick but it would be difficult to program a lot of different scenarios)
I've look at the following tools:
*
*RML Utilities from Microsoft
*DTM DB Stress (this is the closest to what I'm looking for)
*SQL Stress
A: I created a simple test tool for this scenario, check it out to see if it will be of any use to you. It's free, no licensing of any sort required. No guarantees on any performance or quality either ;-)
Usage: StressDb.exe <No. of instances> <Tot. Runtime (mins)> <Interval (secs)>
Connection string should reside in the configuration file.
All command line arguments are required. Use integers.
The stored proc to use is also in the config file.
You need to have .NET framework 3.5 installed. You can also run it from multiple workstations for additional load, or from multiple folders on same machine if trying to run additional stored procedures. You also need a SQL user Id, as currently it doesn't use a trusted connection.
This code was actually super simple, the only clever bit was making sure that the connections are not pooled.
http://......com/..../stressdb.zip
Let me know if you find it useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3391002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I solve multicollinearity? I constructed a linear model and tried to calculate the VIF of the variables but I get the following error:
vif(lm_model3101)
Error in vif.default(lm_model3101) :
there are aliased coefficients in the model
To check which numeric variables are corelated, i calculated the correlation of the used numeric variables and there is no perfect or nearly perfect correlation between any variables:
cor(multi)
mydata..CRU.Index. mydata..GDP.per.capita. mydata.price_per_unit mydata.price_discount mydata..AC..Volume.
mydata..CRU.Index. 1.000000000 0.006036169 0.1646463 -0.097077238 -0.006590327
mydata..GDP.per.capita. 0.006036169 1.000000000 0.1526220 0.008135387 -0.137733119
mydata.price_per_unit 0.164646319 0.152621974 1.0000000 -0.100344865 -0.310770525
mydata.price_discount -0.097077238 0.008135387 -0.1003449 1.000000000 0.339961760
mydata..AC..Volume. -0.006590327 -0.137733119 -0.3107705 0.339961760 1.000000000
What could the problem be? any help or suggestions? The rest of our explanatory variables are factorial so they can not be correlated
A: Having aliased coefficients doesn't necessarily mean two predictors are perfectly correlated. It means that they are linearly dependent, that is at least one terms is a linear combination of the others. They could be factors or continuous variables. To find them, use the alias function. For example:
y <- runif(10)
x1 <- runif(10)
x2 <- runif(10)
x3 <- x1 + x2
alias(y~x1+x2+x3)
Model :
y ~ x1 + x2 + x3
Complete :
(Intercept) x1 x2
x3 0 1 1
This identifies x3 as being the sum of x1 and x2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71690598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Live changes Wordpress I'm looking for something like npm live-server, that refreshes my webbrowser every time I make changes to a document. Npm live-server doesn't work with PHP files.
Currently using XAMPP Apache/MySQL to run WP locally.
Any ideas?
A: For the one's that are interested: here is the final solution.
(Big thanks to @Kintamasis )
*
*Install Gulp / Gulp BrowserSync
*Create a gulpfile.js in your themes' folder.
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('browser-sync', function() {
browserSync.init({
proxy: "YOUR PROXY HERE"
});
gulp.watch("*").on('change', browserSync.reload);
});
*Run gulp browser-sync in your WP theme folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63068397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Access macOS Photo Library using Electron I am trying to write an Electron application that lets users select photos from their photo library on macOS. My assumption is that the only way to access the photos without exporting them is by going into ~/Pictures/Photos Library.photoslibrary. However, when passing the file path of a photo to an <img> tag, I get net::ERR_ACCESS_DENIED error.
Is there a way to grant Electron application access to the user's photo library?
A: I've been writing code recently that accesses the PhotosLibrary. I did this by writing a native module that calls the PhotoKit API. If you go that direction there's going to be a steep learning curve as you'll likely be using Objective-C++ with the features and quirks of both C++ and Objective-C while trying to write something in JavaScript.
https://github.com/nodejs/node-addon-api
https://developer.apple.com/documentation/photokit?language=objc
With Apple's recent security features, you'll also need to somehow run your code inside of an app with the correct entitlements and values set in its Info.plist that will allow access to APIs.
In build/entitlements.mac.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- https://github.com/electron/electron-notarize#prerequisites -->
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<!-- https://github.com/electron-userland/electron-builder/issues/3940 -->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<!-- Allow app to access Photos Library using PhotoKit API -->
<key>com.apple.security.personal-information.photos-library</key>
<true/>
</dict>
</plist>
The following will be needed in your App's Info.plist:
<plist version="1.0">
<dict>
...
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs access to the photos library</string>
</dict>
</plist>
This can be done using electron-builder by adding the following value to the extendInfo extendInfo of your mac build settings in package.json.
{
...
"build": {
...
"mac": {
...
"extendInfo": {
...
"NSPhotoLibraryUsageDescription": "This app needs access to the photos library"
}
}
}
}
I hope this is gives you something to start with. Like I said above, this will come with a steep learning curve unless you're already familiar with JavaScript, native module development, Objective-C, C++ and Apple's APIs.
A: If you just need to read data from it for a one-off project, the photolibrary is really just a directory-like container around your photos, and an sqlite database for the metadata (faces, places and albums/folders). Right click-the photolibrary, show package contents, orig photos are under Masters/YYYY/MM/DD/IMG_XXXX.JPG format, and metadata is in database/photos.db, some tables you can query are RKMaster (filename/uuid of master files), RKAlbum, RKFace, RKMemory, RKPlace, RKFolder, RKVersion, RKKeyword, etc., get any free sqlite browser and you can figure out the rest.
You can also copy the .photolibrary file to Linux and scan its folder/sqlite file using pure node, you don't need any native modules to read it. Writing to it may try to fire some sqlite triggers that seem to belong to some macosx-proprietary extensions, so make backups first, try writes with extensions disabled, or just read and extract the images and metadata to some other format (raw jpeg/json files in a bucket somewhere) that are easy to collate and then (if you have to), reverse the process and write out to another photolibrary file once you get the relation between the tables and filesystem paths inside its container.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62944967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Only create Perl hash key/value pair if value is defined I wish to create a key/value pair in a hash only if I have a defined value to assign.
I am currently doing this:
$hash{key1} = $val1 if defined $val1;
which is OK - but can become annoying when $val1 is complicated. Is there a way that I can neatly get the same outcome without having to say $val1 twice? The test script below might help clarify what I am trying to achieve.
use strict;
use warnings;
use Test::More tests => 1;
my %hash;
my $val1 = undef; # Explicitly undef
my $val2 = 10;
$hash{key1} = $val1 if defined $val1;
$hash{key2} = $val2 if defined $val2;
my %expected = ('key2', 10);
is_deeply(\%hash, \%expected, 'Hashes compare');
A: If you have many such values to check you can use grep/list:
use strict;
use warnings;
my %hash;
my $val1 = undef;
my $val2 = 10;
$hash{$_->[0]} = $_->[1] for grep { defined $_->[1] }
['key1', $val1], ['key2', $val2];
Or you can filter the hash after populating it blindly:
$hash{key1} = $val1;
$hash{key2} = $val2;
%hash = map { $_, $hash{$_} } grep { defined $hash{$_} } keys %hash;
A: Write a subroutine.
set( \%hash, $key1, $val1 );
set( \&hash, $key2, $val2 );
sub set {
my $hash = shift;
my $key = shift;
my $val = shift;
$hash->{$key} = $val if defined $val;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16849830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get an attribute value with lxml on html I have some HTML that I want to parse with lxml using Python. There are a number of elements on the page that each represent a poster. I want to grab each poster's ID, so that I can then scrape a piece of information off the poster's page. Currently the poster's id is stored in the id attribute, so I want to use lxml to get the value of that attribute.
For example:
<div onclick="showDetail(9202)">
<div class="maincard narrower Poster" id="maincard_9202"> </div>
</div>
I want to grab the "maincard_9202" from the id attribute, so that I can then use regex to get the 9202. From there, I can use this value to get directly to the poster's page, since I know that the url redirect pattern goes from
https://nips.cc/Conferences/2017/Schedule?type=Poster (current page) to
https://nips.cc/Conferences/2017/Schedule?showEvent=9202 (poster page)
I was trying to use the following code:
from lxml import html
import requests
page = requests.get('https://nips.cc/Conferences/2017/Schedule?type=Poster')
tree = html.fromstring(page.content)
paper_numbers = tree.xpath('//div[@onclick]/id/')
but this returns an empty list.
How can I get the attribute value in this case?
A: paper_numbers = tree.xpath('//div[@onclick]/div/@id')
print(paper_numbers)
would give you
['maincard_9202']
It selects the id attributes of all divs inside a div with the onclick attribute...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47766150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you run a portion of a python script that requires superuser privileges, while the rest does not? I'm trying to make a script that will detect the color of a pixel, and have a keybind (say F5) to trigger this action.
The pixel scan portion can be done with something like this (put together from what I've found):
from Xlib import display, X
from PIL import Image
dsp = display.Display()
root = dsp.screen().root
def getPixelColor(x, y):
raw = root.get_image(x, y, 1, 1, X.ZPixmap, 0xffffff)
if isinstance(raw.data,str):
bytes=raw.data.encode()
else:
bytes=raw.data
image = Image.frombytes("RGB", (1, 1), bytes, "raw", "BGRX")
color = '%02x%02x%02x' % image.getpixel((0,0))
return color
This works, however when I want to combine it with the keyboard capturing portion of it:
import keyboard
def detect_key(event):
color = getPixelColor(100,100)
# Code that will do something with the color would go here
return False
keyboard.on_press_key("F5", detect_key)
keyboard.wait()
... it complains that keyboard requires root. If I run it as a superuser, then Xlib cannot connect to the x11 display.
How can I run the script to use both parts?
I'm using Ubuntu 22.04, with Gnome and X11.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75266027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamic update for different colums using between two date like calendar date CREATE PROCEDURE [dbo].[CalendarMonthly]
(
@FROMDATE VARCHAR(25)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE @ADate DATETIME
DECLARE @MonthCount INT
SET @ADate = @FROMDATE
SET @MonthCount = (SELECT DAY(EOMONTH(@ADate)))
DECLARE @tmpTable TABLE
(
TRoomID INT, DAY1 INT, DAY2 INT, DAY3 INT, DAY4 INT, DAY5 INT, DAY6 INT, DAY7 INT
)
INSERT INTO @tmpTable
SELECT RM.ROOMID,
0,0,0,0,0,0,0
FROM RoomMaster AS RM
LEFT JOIN RoomTypes AS RT ON RM.RoomTypeID = RT.RoomTypeID
WHERE RM.RoomMasterStatus <> 99
DECLARE @RoomID INT
DECLARE @ForDate DATE
DECLARE @dtFromDate DATE
DECLARE @dtToDate DATE
SET @dtFromDate = CONVERT(DATE,@FromDate)
SET @ForDate = @dtFromDate
SET @dtToDate = CONVERT(DATE,CONVERT(VARCHAR,YEAR(@dtFromDate)) +'-'+ CONVERT(VARCHAR,MONTH(DATEADD(M,1,@dtFromDate)))+'-1')
SET @dtToDate = DATEADD(D,-1,@dtToDate)
DECLARE @DayCount INT
WHILE @ForDate <= @dtToDate
BEGIN
SET @DayCount = DAY(@ForDate)
IF @DayCount = 1
BEGIN
-- Checkin
UPDATE @tmpTable SET DAY1 = 1
FROM @tmpTable TT
JOIN RoomCheckinDetails AS RCD ON RCD.RoomID = TT.TRoomID
JOIN RoomCheckinMaster AS RCM ON RCM.CheckinID = RCD.CheckinID
WHERE CONVERT(DATE,RCD.CheckinDate) = @ForDate
AND RCD.RoomID = TT.TRoomID
-- Expected Checkin
UPDATE @tmpTable SET DAY1 = 8
FROM @tmpTable TT
JOIN RoomBookingDetails AS RBD ON RBD.RoomID = TT.TRoomID
JOIN RoomBookingMaster AS RBM ON RBM.ReservationID = RBD.ReservationID
WHERE CONVERT(DATE,RBD.ExpectedCheckinDate) = @ForDate
AND RBD.RoomID = TT.TRoomID
END
ELSE IF @DayCount = 2
.
.
.
.
.
.
---upto Day count 7
SET @ForDate = DATEADD(Day,1,@ForDate)
END
SELECT * FROM @tmpTable
END
My question is:
ex: checkindate = 04/06/2017, checoutdate = 9/06/2017 in compare two date I have update to columns day1 to columns day6 values is 0.
A: Instead of creating a temporary table and using a cursor to update each set of columns, this is a set based solution that avoids all of that.
For the first part, if you just need 7 days then you can use a simple values tally table with a common table expression and the Table Value Constructor (Transact-SQL):
declare @fromdate date = '20170605';
;with dates as (
select
[Date]=convert(date,dateadd(day,rn-1,@fromdate))
, rn
from (values (1),(2),(3),(4),(5),(6),(7)) t(rn)
)
Otherwise, you can generate an adhoc table of dates using stacked ctes in a common table expression like this:
declare @fromdate date = '20170605';
declare @thrudate date = dateadd(day,6,@fromdate)
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
select top (datediff(day, @fromdate, @thrudate)+1)
[Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
, rn = row_number() over(order by (select 1))
from n as deka cross join n as hecto cross join n as kilo
cross join n as tenK cross join n as hundredK
order by [Date]
)
Then cross join the dates with roommaster, and left join both the checkin and booking tables to see if a room has a reservation or is currently occupied:
, cte as (
select
rm.roomid
, d.rn
, Value = case
when rcd.roomid is not null then 1
when rbd.roomid is not null then 8
else 0
end
from dates d
cross join roommaster rm
left join roomcheckindetails rcd
on rm.roomid = rcd.roomid
and d.date >= rcd.checkindate
and d.date <= rcd.checkoutdate
left join roombookingdetails rbd
on rm.roomid = rbd.roomid
and d.date >= rbd.expectedcheckindate
and d.date <= rbd.expectedcheckoutdate
where rm.roommasterstatus <> 99
)
Then for the last piece, you can use conditional aggregation or pivot() (pick one) like so:
select
roomid
, Day1 = min(case when rn = 1 then value end)
, Day2 = min(case when rn = 2 then value end)
, Day3 = min(case when rn = 3 then value end)
, Day4 = min(case when rn = 4 then value end)
, Day5 = min(case when rn = 5 then value end)
, Day6 = min(case when rn = 6 then value end)
, Day7 = min(case when rn = 7 then value end)
from cte
group by roomid
select
roomid
, Day1 = [1]
, Day2 = [2]
, Day3 = [3]
, Day4 = [4]
, Day5 = [5]
, Day6 = [6]
, Day7 = [7]
from cte
pivot (min(value) for rn in ([1],[2],[3],[4],[5],[6],[7]))p
rextester demo with conditional aggregation: http://rextester.com/RUJ98491
rextester demo with pivot(): http://rextester.com/YNKU89188
both return the same results for my demo data:
+--------+------+------+------+------+------+------+------+
| roomid | Day1 | Day2 | Day3 | Day4 | Day5 | Day6 | Day7 |
+--------+------+------+------+------+------+------+------+
| 2 | 1 | 1 | 1 | 1 | 0 | 0 | 0 |
| 3 | 0 | 8 | 8 | 8 | 8 | 0 | 0 |
+--------+------+------+------+------+------+------+------+
Number and Calendar table reference:
*
*Generate a set or sequence without loops - 2 - Aaron Bertrand
*The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden
*Creating a Date Table/Dimension in sql Server 2008 - David Stein
*Calendar Tables - Why You Need One - David Stein
*Creating a date dimension or calendar table in sql Server - Aaron Bertrand
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44366906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to copy parts of string in another strings? I want to send multi attach in email, but have problem with those. When I put all files what want to send in one string always get error, but when put one file in one attach inside of loop thing work.
Now I have problem with copying one part of string in to another strings, don't know how to do that, do you have some solution?
Example:
txtattach.Text = "d:\\folder\\file1,d:\\folder\\file2,d:\\folder\\file3";
want to get 3 strings with context of location without "," that I can easy put it in loop.
A: use the split function:
string[] paths = txtattach.Text.Split(',');
A: One way to do this is using the Split method so you easily can iterate over the items in a loop:
foreach(var filename in txtAttach.Text.Split(','))
{
// Do something with filename
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10810972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MS-Access 2007: Query for names that have two or more different values in another field Hello & thank you in advance.
I have an access db that has the following information about mammals we captured. Each capture has a unique ID, which is the capture table's primary key: "capture_id". The mammals (depending on species) have ear tags that we use to track them from year to year and day to day. These are in a field called "id_code". I have the sex of the mammal as it was recorded at capture time in another field called sex.
I want a query that will return all instances of an id_code IF the sex changes even once for that id.
Example: Animal E555 was caught 4 times, 3 times someone recorded this animal as a F and once as a M.
I've managed to get it to display this info by stacking about 5 queries on top of each other (Query for recaptured animals -> Query for all records of animals from 1st query -> Query for unique combo of id & sex (via just using those two columns & requiring "Unique Values") -> Query that pulls only duplicate id values from that last one and pulls back up all capture records of those ids). HOwever, this is clearly not the right way to do this, it is then not updateable (which I need since this is for data quality control) and for some reason it also returns duplicates of each of those records...
I realize that this could be solved two other ways:
*
*Using R to pull up these records (I want none of this data to have to leave the database though, because we're working on getting it into one place after 35 years of collecting! And my boss can't use R and I'm seasonal, so I want him to just have to open a query)
*Creating a table that tracks all animal id's as an animal index. However, this would make entering the data more difficult and also require someone to go back through 20,000 records and create a brand new animal id for every one because you can't give ear tags to voles & things so they don't get a unique identifier in the field.
Help!
A: It is quite simple to do with a single query. As a bonus, the query will be updatable, not duplicated, and simple to use:
SELECT mammals.ID, mammals.Sex, mammals.id_code, mammals.date_recorded
FROM mammals
WHERE mammals.id_code In
(select id_code from
(select distinct id_code, sex from [mammals]) a
group by id_code
having count(*)>1
);
The reason why you see a sub-query inside a sub-query is because Access does not support COUNT(DISTINCT). With any other "normal" database you would write:
SELECT mammals.ID, mammals.Sex, mammals.id_code, mammals.date_recorded
FROM mammals
WHERE mammals.id_code In
(select id_code
from [mammals]
group by id_code
having count(DISTINCT Sex)>1
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35932043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Array range I find my self using _.range a lot, and sometimes I don't want to drag with me lodash just for that reason.
What is the best way to do this without lodash?
My best solution is:
export function range(n) {
return new Array(n).fill(0).map((a, i) => i);
}
A: return Array.from({length: n}, (_, i) => i);
...saves a few bytes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48892536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disposing Camera before initialization is ready In WP7.1, If I dispose camera before it is ready, I got the following exception:
ExceptionObject {"Initialization canceled by .Dispose().\r\nObject name: 'Camera'."} System.Exception {System.ObjectDisposedException}
How camera should be Disposed in the case I need to shutdown the page before it gets ready. I would not like to wait till cam.Initialized is called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10617831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a way to specify Character Spacing in SSRS/BIDS? I am trying to create a SSRS report. The report is essentially as certificate which will be printed on Custom Stationary (Some arty paper like certificates).
The system we are migrating from used Word mail merge to specify the Certificate holder's name, certification date etc. Now we are creating an SSRS report which would essentially generate the Certificate. The font used in the legacy system was Lucida Calligraphy with a Character spacing of 66%. (Attached comparison image)
I could not locate a setting in BIDS to specify character spacing for fonts. Without the spacing things look a little weird and I'd rather not go and tell the client to change their stationary and/or printer because it'll be a logistics havoc.
So the question is, is it possible to specify character spacing in SSRS/BIDS? If yes how? If no what are the alternatives?
A: I was able to have correct character spacing by adding a space between each character and makeing that space to have a size of 8pt (because my text has a size of 16).
It looks good in my report.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the meaning of the : in Swift function signatures and why is there no comma when it seems there should be one? Here's an example of what I'm talking about: https://developer.apple.com/documentation/foundation/nsmutableorderedset/1410287-insert
The insert function is shown as insert(_:at:)
When it's actually used, the insert function looks more like:
namesArray.insert("John", at: 3)
There's no : after "John" (though I suppose it could be "John":String -- is that what it's there for?), and the , that actually needs to go there is not mentioned in the function signature in the documentation. Am I just supposed to know/assume that the comma goes there when I actually use it? Is this the case for all Swift functions?
Please note that this is not a question about the underscore, _ -- I understand why it's there and what it's for. I'm specifically asking about the reasons for including : and not including , in the function signature.
A: A : in the function signature always means an input argument to the function. The function signature contains the argument label followed by a :. The _ means there's no argument label, in which case you can omit the : as well when supplying that specific input argument to the function call.
This is exactly what you see with the insert(_:at:) function. You supply two input arguments to it, "John" and 3, but it only needs an argument label for the second input argument, hence you only need one :. It's also important to note that at call time, you separate the input arguments using ,, not :.
A: The convention, frequently seen in documentation, is a concise way of referring to a function, using only the function name and argument labels.
So consider this function declaration:
func insert(_ objects: [Any], at indexes: IndexSet)
This is
*
*a method called insert;
*the first parameter name is called objects, this parameter has no argument label (designated with the _) and has a type of [Any]; and
*the second parameter name is indexes, its argument label is at and has a type of IndexSet.
So you call it like so:
insert(someObjects, at: someIndex)
When you call it, you don’t care what the parameter names that are used inside that function, but rather just what the argument labels are. So, the convention when referring to that method in documentation is to omit the parameter names and types and just use the function name and the argument labels, but no comma:
insert(_:at:)
Note, you’d never actually use this syntax in your code. This is just a documentation convention employed to distill long function declarations down to something more manageable and concise:
For more information about argument labels and parameter names, see Function Argument Labels and Parameter Names
A: Swift functions have a unique way of specifying the signature, which is a carry over pattern from Objective C. There are 3 parts to specifying each input argument to the function signature. The signature for the function you mentioned is as follows:
func insert(_ objects: [Any],
at indexes: IndexSet)
Let's look at the second argument first:
*
*at indicates the argument label, which is how the caller specifies the parameter.
*indexes indicates the function's parameter name to the object. This means that in the body of the function, whatever was passed as at: would be referred to as indexes.
*IndexSet is the type of the argument.
Part 1 can be something besides a name, too:
*
*if it is not specified, the argument name and parameter label are the same. For example, if the signature were func insert(objects: [Any], indexes: IndexSet), the function would be called as o.insert(objects: ['a','b'], at: [1,2]).
*If it is an underscore (_), then the argument has no label for the caller. This allows the caller to use the simpler, intuitive call o.insert(['a','b'], at: [1,2]).
A: In a signature, the colon separates the name of a parameter from its value. Functions have this anatomy:
func functionName(label1 parameter1: Type1, label2 paramter2: Type2) -> ReturnType {
...
}
where labels are the names seen when calling the function and parameters are the names of the values as used in the body of the function. A label of _ removes the label from the parameter when calling it.
When calling a function, the colon simply separates parameter labels from the values passed to the function. Commas separate different parameters. A parameter with no label requires no colon. The following function would have no colons at all:
func myFunc(_ par1: Int, _ par2: String) {
print(par1, par2)
}
myFunc(3, "what") // 3 "what"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54537403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What should I install to query SQL Server DB from Powershell - could not load file or assembly Microsoft.SqlServer.Types? On my computer I have only SQL Server Management Studio installed.
I use runas.exe /netonly /user:myDomain\myUser powershell.exe to open Powershell console (I need to authenticate to SQL Server using Windows Authentication).
Then I connect to SQL Server DB using following code:
$myConnectionString = "Server=$($serverName);Database=$($dbName);Trusted_Connection=True;"
$SQLConnection = New-Object System.Data.SQLClient.SQLConnection
$SQLConnection.ConnectionString = $myConnectionString
$SQLConnection.Open()
$SQLCommand = New-Object System.Data.SqlClient.SqlCommand
$SQLCommand.CommandText = "SELECT top 2 * FROM [myTable]"
$SQLCommand.Connection = $SQLConnection
Unfortunately when I type:
$SQLCommand.ExecuteReader()
I receive an error:
An error occurred while enumerating through a collection: Could not
load file or assembly 'Microsoft.SqlServer.Types, V ersion=10.0.0.0,
Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its
dependencies. The system cannot find t he file specified.. At line:1
char:1
+ $SQLCommand.ExecuteReader()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Data.Common.DbEnumerator:DbEnumerator) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
After searching the Internet, I thought that I should install 'SQLSysClrTypes' (from SQL Server Feature Pack).
Thus I downloaded it, but it seems that I have this component installed on my local computer (installer allows me to repair or remove this component only).
What should I install to be able to query the DB from Powershell? On which computer should I install that computer?
EDIT:
When I log into the server through RDP (mstsc), and use following connection string:
$myConnectionString = "Server=.;Database=$($dbName);Trusted_Connection=True;"
I do not experience such issues - ExecuteReader() returns results.
A: You don't need to install any additional tools or libraries to query MS SQL Server from PowerShell, assuming you are running Windows 7 or newer.
The installed .NET framework has all ADO.NET components required to do this.
If you get an error, something is wrong with your script or your environment.
A: I am sure that there must be a better solution, thus I will not mark this response as an answer...
I checked the content of C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Types path and discovered that I have Microsoft.SqlServer.Types.dll for versions 12, 13 and 14.
Thus I just copy-paste mentioned file for version 10.0.0.0__89845dcd8080cc91 from the server to my computer...and it works
So, it seems that somewhere it's hardcoded to use this specific version of Assembly when connecting to SQL Server from Powershell (?)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48863821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery .outerHeight() after .append() Im trying to run .outerHeight() function on element that i just appended to html via .append()
$("#someid").append("<ul id='#otherid'><li>something</li></ul>");
var h = $("#otherid").outerHeight();
After this "h" has wrong value. I think that it is caused by "append" not applying css to created elements.
.outerHeight() runs correctly if i will put it in "setTimeout" but not right after "append".
Do you know how to get correct value of outerHeight after element was just appended?
A: The reason for that is probably due to the fact that the appended elements do not have their CSS rules applied yet and are not counting towards the total height. Try using a delay (like settimeout) to make things work right.
var h = $("#otherid").delay(300).outerHeight();
A: Instead: id='#otherid' try: id='otherid'
$("#someid").append("<ul id='otherid'><li>something</li></ul>");
var h = $("#otherid").outerHeight();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dynamically add, compile and link ng-class attribute from another directive In order give feedback on the validity in my input forms I'm using ng-class. These statements will look something like:
<div ng-class="{ 'has-error': !frmSomeName.vcHeader.$valid && frmSomeName.vcHeader.$dirty }">
<input type="text" name="vcHeader" ng-model="model.someText" ng-minlength="10" required />
</div>
I dislike the lengthiness of the statement, and would like to replace it with something alike:
<div validation-state="frmSomeName.vcHeader">
<input type="text" name="vcHeader" ng-model="model.someText" ng-minlength="10" required />
</div>
In order to avoid having to duplicate ngClass' behavior I'd like the the directive to add the ng-class directive.
This plnkr demonstrates my attempt at adding the attribute, and although it works in the simplest scenario, it is faulty and will not function with transclusion (or other more complex directives).
I know it doesn't work because of the misuse of the compile and link stages, however I'm not sure on how to actually make it work properly. Therefore my question: How do I add different directive-attribute from a directive-attribute?
A: The elements within the transclude directive aren't receiving the same scope. If you use the angualr $compile method and apply the scope of the transclude directive to the scope of the child directives it should work. The following should be added to your simpleTransclude directive:
link: function(scope, element) {
$compile( element.contents() )( scope )
}
remember to pass $compile into the directive.
I've forked your plnkr and applied the simpleTransclude scope to it's contents.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33759883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MATLAB non-linear optimization data set I am trying to write a non-linear optimization program using fmincon. I want MATLAB to read through a data set and compare those values to the constraints. (It is the size of an electrical generator based on electric and heat demand over a one month period).
How do I start this off?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5929388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to change the value of an int, and recover and use the new value? While attempting at creating some movement for a ball in a pong game, I have run into a most annoying problem. The value of the x and y coordinate do not want to change (for lack of better words). Maybe this is due to the immutable nature of strings in python, or a misconception I have of the way Python handles variables. Any help would be most welcome :)
x_coordinate = 100
y_coordinate = 100
NORTH_EAST = [x_coordinate + 1, y_coordinate - 1]
NORTH_WEST = [x_coordinate - 1, y_coordinate - 1]
SOUTH_EAST = [x_coordinate + 1, y_coordinate + 1]
SOUTH_WEST = [x_coordinate - 1, y_coordinate + 1]
direction = NORTH_EAST
while True:
print (direction)
x_coordinate = direction[0]
y_coordinate = direction[1]
A: The issue here is that when you say
NORTH_EAST = [x_coordinate + 1, y_coordinate - 1]
You construct a list of two values, which are computed and stored at the time. They will not update based on the values of x_coordinate and y_coordinate changing.
You will need to recalculate the values on each loop to get the behaviour you expect. The easiest way to do this is with a function:
directions = {
"north east": (+1, -1),
"north west": (-1, -1),
"south east": (+1, +1),
"south west": (-1, +1),
}
def new_position(old, direction):
x, y = old
dx, dy = directions[direction]
return x + dx, y + dy
position = 100, 100
direction = "north east"
while True:
print(position)
position = new_position(position, direction)
Note that where there are linked pieces of data, it's best to store them in a data structure. Here I use a tuple to store the x and y values together, and a dictionary for the directional data. This means less repetition in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15992746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Count the total number of times the sale was consecutive for a product - Sybase IQ I am using Sybase IQ, and from my data set, I need to count the total number of times the sale was consecutively 10 items.
Please review the data set.
Product Date Sale
Jams 2020-01-05 10
Jams 2020-01-06 10
Jams 2020-01-07 10
Jams 2020-01-08 10
Jams 2020-01-09 10
Jams 2020-01-10 1
Jams 2020-01-11 0
Jams 2020-01-12 4
Jams 2020-01-13 5
Candy 2020-01-14 3
Candy 2020-01-15 2
Candy 2020-01-16 0
Candy 2020-01-17 1
Candy 2020-01-18 0
Candy 2020-01-19 1
Candy 2020-01-20 1
Candy 2020-01-21 1
Candy 2020-01-22 4
Candy 2020-01-23 2
From my Data Set, I need the following output:
Product Count of Consecutive 10's
Jam 5
Candy 0
I have read the SybaseIQ help guide and tried to use ROW_NUMBER() OVER ([PARTITION BY window partition] ORDER BY window ordering) analytical function, but I keep getting a syntax error. I think the issue is that I am not able to understand the concept behind this calculation.
I would appreciate if someone can help me.
A: You can use window functions. For each product, you can identify groups of adjacent matching rows by counting the number of non-10s before that row. This identifies the groups.
select name, sum(case when sale = 10 then 1 else 0 end0 as cnt
from (select t.*,
sum(case when sale <> 10 then 1 else 0 end) over (partition by product order by date) as grp
from t
) t
group by name,
(case when sale <> 10 then 1 else 0 end),
grp;
This returns the value for all groups. I think you might want the longest, which would be:
select name, max(cnt)
from (select name, sum(case when sale = 10 then 1 else 0 end0 as cnt
from (select t.*,
sum(case when sale <> 10 then 1 else 0 end)
over (partition by product
order by date
rows between unbounded preceding and current row
) as grp
from t
) t
group by name,
(case when sale <> 10 then 1 else 0 end),
grp
) t
group by name;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59762887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xdebug 3 docker mac PhpStorm broken pipe I see There was a problem sending 179 bytes on socket 11: Broken pipe. in the xdebug.log and cannot see why. Have gone around in circles for days trying all sorts of stuff. What am I doing wrong?
*
*Xdebug 3.0.3,
*PhpStorm 2020.3.3,
*Mac OS X latest,
*Safari browser
[17] Log opened at 2021-03-24 02:49:43.184877
[17] [Step Debug] INFO: Checking remote connect back address.
[17] [Step Debug] INFO: Checking header 'HTTP_X_FORWARDED_FOR'.
[17] [Step Debug] INFO: Checking header 'REMOTE_ADDR'.
[17] [Step Debug] INFO: Client host discovered through HTTP header, connecting to 172.18.0.1:9003.
[17] [Step Debug] INFO: Connected to debugging client: 172.18.0.1:9003 (from REMOTE_ADDR HTTP header). :-)
[17] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/manawatech/public/index.php" language="PHP" xdebug:language_version="8.0.3" protocol_version="1.0" appid="17" idekey="19213"><engine version="3.0.3"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>
[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" status="stopping" reason="ok"></response>
[17] [Step Debug] WARN: 2021-03-24 02:49:43.851075: There was a problem sending 179 bytes on socket 11: Broken pipe.
[17] Log closed at 2021-03-24 02:49:43.851495
docker-compose.yml
version: "3.8"
services:
web:
container_name: web
build:
context: .
dockerfile: docker/php/Dockerfile
ports:
- "80:80"
- "443:443"
- "9003:9003"
volumes:
- .:/var/www/manawatech
extra_hosts: # <-- this is required for ray
- "host.docker.internal:host-gateway" # <-- this is required for ray
db:
container_name: db
image: mysql
command: --default-authentication-plugin=mysql_native_password
volumes:
- ./var/mysql:/var/lib/mysql
ports:
- "3306:3306"
environment:
MYSQL_RANDOM_ROOT_PASSWORD: "yes"
MYSQL_DATABASE: "${MYSQL_DATABASE}"
MYSQL_USER: "${MYSQL_USER}"
MYSQL_PASSWORD: "${MYSQL_PASSWORD}"
docker/php/Dockerfile
FROM php:8-apache-buster
RUN apt update \
&& apt install -y geoip-bin geoip-database libgeoip-dev libpng-dev libzip-dev
RUN pecl channel-update pecl.php.net \
&& pecl install redis apcu xdebug \
&& docker-php-ext-install pdo pdo_mysql gd zip \
&& docker-php-ext-enable redis apcu xdebug pdo pdo_mysql gd zip
# from https://github.com/nezhar/php-docker-ssl/blob/master/Dockerfile
RUN openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/ssl-cert-snakeoil.key -out /etc/ssl/certs/ssl-cert-snakeoil.pem -subj "/C=AT/ST=Vienna/L=Vienna/O=Security/OU=Development/CN=manawatech.local"
RUN a2dissite 000-default.conf \
&& a2enmod rewrite ssl expires headers
COPY docker/php/apache.conf /etc/apache2/sites-enabled/
COPY docker/php/98-production.ini /usr/local/etc/php/conf.d/
COPY docker/php/99-development.ini /usr/local/etc/php/conf.d/
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
EXPOSE 80
EXPOSE 443
EXPOSE 9003
/usr/local/etc/php/conf.d/99-development.ini
[xdebug]
xdebug.mode=debug
xdebug.discover_client_host=true
xdebug.client_host=host.docker.internal
xdebug.start_with_request=trigger
xdebug.force_display_errors=1
xdebug.log=/tmp/xdebug.log
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66774146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How i can create a Typescript interface that can take also a string? I need to create an interface that permit to have an array of objects and strings.
For example:
const array = [
'',
{id: '', labels: ['']}
]
I've tried with:
export interface Obj{
id: string;
label: string[];
}
export interface Objs extends Array<Obj> {
}
But this don't permit strings so this return an error:
const array: Objs = [
'',
{id: '', labels: ['']}
]
A: You have to use union types:
export type Objs = Array<Obj | string>;
A: If the entries in the array can be either strings or objects in the form {id: string; labels: string[]}, you can use a union type:
export type Obj = string | {id: string; labels: string[]};
const array: Obj[] = [
"",
{id: "", labels: [""]}
];
Playground Example
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61677779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove trailing slash in DNN I have an angular app on a page loaded in DotNetNuke.
As you know DNN puts a trailing slash at the end of URL like localhost/MyPage/, while I'm using Angular routing with html5mode(false) when opening the page the URL becomes like localhost/MyPage/#/ this cause a 404 Error for the templates I want to use.
when I remove the slash at the end (localhost/MyPage#/) the problem is solved. the question is How can I tell DNN to not to put slash after URL?
A: if you use dnn and routing, I have found usefull to use #
Usually I insert in Angular useHash: true:
imports: [RouterModule.forRoot(routes, { useHash: true })],
Let me know
Matteo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45125283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Django datetime not validating right I'm using the HTML5 datetime-local input type to try and get some datetime data into my database.
The ModelForm class Meta: looks like the following:
class Meta:
model = ScheduleEntry
fields = ['calendar', 'title', 'start', 'end', 'assets', 'users']
widgets = {
'calendar': forms.Select(attrs={
'class': 'fom-control chosen-select'
}),
'title': forms.TextInput(attrs={
'class': 'form-control'
}),
'start': forms.DateTimeInput(attrs={
'type':'datetime-local',
'class':'form-control'
}, format='%Y-%m-%dT%H:%M'),
'end': forms.DateTimeInput(attrs={
'type': 'datetime-local',
'class': 'form-control'
}, format='%Y-%m-%dT%H:%M'),
'assets': forms.SelectMultiple(attrs={
'class': 'form-control chosen-select'
}),
'users': forms.SelectMultiple(attrs={
'class': 'form-control chosen-select',
})
}
I keep failing on form validation and it's causing me to pull my hair out.This is the documentation page that shows it should work, but it looks like I'm missing something?
EDIT FOR CLARIFICATION:
The error message is for both start and end and it's Enter a valid date/time
A: The misconception:
To quote the docs:
Widgets should not be confused with the form fields. Form fields deal with the logic of input validation and are used directly in templates. Widgets deal with rendering of HTML form input elements on the web page and extraction of raw submitted data.
Widgets have no influence on validation. You gave your widgets a format argument, but that does not mean the form field validation will use it - it only sets the initial format the widget's content is rendered with:
format: The format in which this field’s initial value will be displayed.
The solutions
Two options:
*
*provide the form field (forms.DateTimeField) with the datetime format you would like to use by passing a input_formats argument
class MyIdealDateForm(forms.ModelForm):
start = forms.DateTimeField(
input_formats = ['%Y-%m-%dT%H:%M'],
widget = forms.DateTimeInput(
attrs={
'type': 'datetime-local',
'class': 'form-control'},
format='%Y-%m-%dT%H:%M')
)
This needs to be done for every form field (and probably by extension even their widgets). What you are doing here is effectively overwriting the settings (see the next point).
*Add your datetime format to the settings as the first item. This will apply globally to all formfields and widgets that use that setting.
A: you just have a typo. Make it 'form' instead of 'fom' in class value.
'calendar': forms.Select(attrs={
'class': 'fom-control chosen-select'
}),
A: Maybe you need to import datetime to ensure it's a valid date/time format for python, here you can see an aproach.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53180600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: from development to production - uploading a webpage First of all, I will excuse myself for possibly making vague questions.
I am a newby freelancer webdeveloper, and I recently created a webapplication which works fine on my own computer, running it on localhost.
More recently, using A2Hosting, i bought a domain and some server space, and my objective is to upload my application in order to make it online for anyone.
However, right now, I am having a few problems.
Specifically, I do not know how to upload my web application.
Basically, what I did was upload all the folders and files I had on my local machine into the server, and I was hoping that would work.
Unfortunatly, the server continues to display the "initial" site I uploaded. a simple, static, htlm file saying hello world. This file is the index.html that is inside the "www" folder.
The directory of the server is presented in the following figure.
My question is how do I make the server display the content of react/redux page, instead of the simple static html initialy uploaded.
A: I am not familiar with react however with Angular you would have to run through the same process on the server as you would to run the app locally but with the server variables in place of the local variables.
For example on angular I have to compile and run my front/back ends and ensure my database is also live for it to run at all otherwise nothing would work on the server .
Check what configs need changing to process the change from local to dev
Hopefully that is at least a little bit helpful, the below article should be useful to you.
https://medium.com/@baphemot/understanding-react-deployment-5a717d4378fd
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48627268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to use np.where while reading multiple columns I'm trying to create a new column called condition where it reads three different columns and fill it's rows based on given conditions. the dataset looks like this:
print(df)
IgG NC1 PCR
0 Neg Pos not_detec
1 Neg Neg not_detec
2 Pos Neg detec
What I'm trying to do is that if IgG is negative, NC1 is negative and PCR is not_detec it will give me negative else, positive.
So, my desired outcome is this
print(df)
IgG NC1 PCR condition
0 Neg Pos not_detec Pos
1 Neg Neg not_detec Neg
2 Pos Neg detec Pos
I tried doing by typing the following,
df['condition'] = np.where((df['IgM']=='Neg') & (df['NS1']=='Neg') & df['PCR']== 'not_detec'), 'Negative', 'Positive')
But, I got a syntax error.
SyntaxError: invalid syntax
A: As @jezrael commented, it was missing ( from df[PCR]=='not_detec'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61440568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using regex how do I stop identifiers matching strings Let's say I have this "code" I want to lex.
var text = 'hello'
Here's my regex.
*
*String: ([a-z\s]+)
*Identifier: [a-z]+
Now when I put my code into regexr.com and use the identifier regex, it matches the string as an identifier, how would I stop it from matching strings as identifiers?
A: What identifies a string? Quotation marks. In your case: single quotes.
Therefore, we want to match the content between quotes as a string. To do so, we can use the following lazy regex:
'.*?'
To allow both quotes, you could use: '.*?'|".*?" or the same with a backreference (['"]).*?\1.
If it is allowed to escape strings, it gets even more complicated. I suggest using a recursive regex to do so:
((['"])(?>[^'"\\]++|\\.|(?1))*+\2)
Samples matched:
a = "abc dsfsd", b= ' abc dsfsd'
c ="abc\" dsfsd"
d= "abc\\"
To match any identifiers but the strings you could use:
[a-z]+(?=([^']*['][^']*['])*[^']*$)
(Or here a version that matches both types of quotes: [a-z]+(?=([^'"]*(["'])[^"']*\2)*[^"']*$))
Again, it gets more involved if you want to account for escaped quotes:
[a-z]+(?=([^"'\\]*(\\.|(["'])([^"'\\]*\\.)*[^"'\\]*\3))*[^"']*$)
I hope, this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50653916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Friendly URLs remain with the old portion of the URL I started to use friendly URL but I have two problems.
I have a link pointing to www.mywebsite.com/articles.php/321312/some-text-here
When I click on this link, on the next page all my links remains with a portion of the url.
For example, the clickable logo image points to www.mywebsite.com/articles/321312/index.php instead of www.mywebsite.com/index.php
Another problem is that articles.php only works with the .php extension.
My htaccess here
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^ / [R=301,L]
RedirectMatch ^/$ /articles/
RewriteRule ^([^/\.]+)/?$ $1.php [L,QSA]
RewriteRule ^articles/([a-z0-9-]+)/([0-9]+)/?$ /articles.php?id=$2&desc=$1 [NC]
</IfModule>
Thanks in advance.
A: Replace your .htaccess code with this:
RewriteEngine On
RewriteRule ^$ /articles/ [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/.]+)/?$ $1.php [L]
RewriteRule ^articles/([a-z0-9-]+)/([0-9]+)/?$ articles.php?id=$2&desc=$1 [L,QSA,NC]
You must also add this just below <head> tag of your page's HTML:
<base href="/" />
so that every relative URL is resolved from that base URL and not from the current page's URL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57807439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Warning: Each child in an array or iterator should have a unique "key" prop G'Day.
I want to iterate over a bunch of JSON objects and turn them into React Elements. The objects look like this
"fields":
[
{
key: "testname",
"name": "testname",
"altName": "",
"visible": true,
"groupVisibility": "public",
"type": "text",
"component": "input",
"label": "Test Smart Input",
"placeholder": "Some default Value",
"required": "required",
"validated": false,
"data": []
},
{
key: "password",
"name": "password",
"altName": "",
"visible": true,
"groupVisibility": "public",
"type": "password",
"component": "input",
"label": "Test Smart Input",
"placeholder": "Password",
"required": "required",
"validated": false,
"data": []
}
]
And the code that iterates over them is quite simple. Such:
//--------------------
formFields(fieldsIn) {
const fieldsOut = []; // ARRAY of FORM ELEMENTS to return
console.log('doin fields');
for (var fieldIn in fieldsIn) { // array of FORM ELEMENT descriptions in JSON
console.log(fieldIn);
let field = React.createElement(SmartRender, // go build the React Element
fieldIn,
null); // lowest level, no children, data is in props
console.log('doin fields inside');
fieldsOut.push(field);
}
return(fieldsOut); // this ARRAY is the children of each PAGE
}
And I get the error
Warning: Each child in an array or iterator should have a unique "key" prop.
Any hints?
Cheers
I changed the code to do this.
//--------------------
formFields(fieldsIn) {
const fieldsOut = []; // ARRAY of FORM ELEMENTS to return
console.log('doin fields');
for (var fieldIn in fieldsIn) { // array of FORM ELEMENT descriptions in JSON
console.log(fieldIn);
let field = React.createElement(SmartRender, // go build the React Element
{key: fieldsIn[fieldIn].name, fieldIn},
null); // lowest level, no children, data is in props
console.log('doin fields inside');
fieldsOut.push(field);
}
return(fieldsOut); // this ARRAY is the children of each PAGE
}
And I get the same error. I don't understand why!
Fixed! Thanks for the help.
Here is the code.
//--------------------
formFields(fieldsIn) {
const fieldsOut = []; // ARRAY of FORM ELEMENTS to return
for (var fieldIn in fieldsIn) { // array of FORM ELEMENT descriptions in JSON
console.log(fieldIn);
let field = React.createElement(SmartRender, // go build the React Element
{key: fieldsIn[fieldIn].key, fieldIn},
null); // lowest level, no children, data is in props
fieldsOut.push(field);
}
return(fieldsOut); // this ARRAY is the children of each PAGE
}
//----------------------
pages(pagesIn, format) {
// I tried to do this in JSX, but no syntax I wrestled with would
// allow me to access the childred when building this with the
// BABEL transpiler. Same goes for the METHOD just above, items().
//
// This method returns an array of pages this are React elements
// this are treated as children by the smartForm.
const pagesOut = []; // array of pages to build and return
let Section = {}; // Component to fire in the build
switch(format) {
case 'accordion': {
Section = AccordionSection;
break;
}
case 'workflow': {
Section = null; // I haven't written this yet
break;
}
case 'simple': {
Section = null; // I haven't written this yet
break;
}
}
for (var pageIn in pagesIn) { // pages, any format, any number 1..N
let children = this.formFields(pagesIn[pageIn].fields); // 1..N fields, we don't know beforehand
let page = React.createElement( Section,
pagesIn[pageIn].props,
children);
pagesOut.push(page);
}
return(pagesOut); // this ARRAY is the children of each FORM
}
//--------
render() {
let formIn = this.props.form; // JSON description of FORM
let formOut = null; // contructed REACT/Javascript form
switch (formIn.format) { // what type of operation is this
case 'accordion': { // Accordion in a FORM, OK
let children = this.pages(formIn.pages,
formIn.format); // build the children
formOut = React.createElement(Accordion, // construct the parent with ALL nested CHILDREN after
{key: formIn.formName}, // just a unique key
children); // N ACCORDION pages, N2 input fields
break;
}
case 'workflow': {
let children = this.pages(formIn.pages, // build the children
formIn.format); // build the children
formOut = React.createElement(Workflow, // and create the complex sheet element
{ key: formIn.formName},
children); // N SLIDING pages, N2 input fields
break;
}
case 'simple': {
let children = this.pages(formIn.pages, // build the children
formIn.format); // build the children
formOut = React.createElement(Simple,
{ key: formIn.formName},
children); // One page, N input fields
break;
}
}
return(
<div>
<h2>SmartForm Parser</h2>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
{formOut}
</div>
);
}
}
//-------------------------------------------------------------------------
export default SmartForm;
//----------------- EOF -------------------------------------------------
A: You need to add a unique key prop to your React element.
According to the React docs:
Keys help React identify which items have changed, are added, or are
removed. Keys should be given to the elements inside the array to give
the elements a stable identity.
The best way to pick a key is to use a string that uniquely identifies
a list item among its siblings. Most often you would use IDs from your
data as keys
When you don’t have stable IDs for rendered items, you may use the
item index as a key as a last resort
You can do it like
for (var fieldIn in fieldsIn) { // array of FORM ELEMENT descriptions in JSON
console.log(fieldIn);
let field = React.createElement(SmartRender, // go build the React Element
{key: fieldsIn[fieldIn].key, fieldIn},
null); // lowest level, no children, data is in props
console.log('doin fields inside');
fieldsOut.push(field);
}
Why are keys necessary?
By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.
For example, when adding an element at the end of the children, converting between these two trees works well:
<ul>
<li>first</li>
<li>second</li>
</ul>
<ul>
<li>first</li>
<li>second</li>
<li>third</li>
</ul>
React will match the two <li>first</li> trees, match the two <li>second</li> trees, and then insert the <li>third</li> tree.
If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly.
<ul>
<li>first</li>
<li>second</li>
</ul>
<ul>
<li>third</li>
<li>first</li>
<li>second</li>
</ul>
That is where keys come in handy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47322401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error while updating SAP backend data using OData and SAP Gateway services I am trying to update SAP backend using OData and SAP Gateway services. while executing it throws an error and doesn't update data in backend. I am trying to update 'accounts' data in SAP CRM backend.
The error message contains this response:
The file {ServiceName}({BP_Number_of_that_Account}) has been successfully uploaded
This application has been deployed on to SAP Netweaver portal. I put the breakpoints in backend and found that it doesn't even reach the backend.
The code looks as follows:
OData.request(
{
headers: {'x-requested-with' : 'XMLHttpRequest','Content-Type': 'application/atom+xml', 'DataServiceVersion': '2.0'},
requestUri: "/sap/Gateway/PGY/SERVICEACCOUNTS/SERVICEACCOUNTSCollection("+recordToUpdate.data.BP_NUMBER+")?sap-client=100&$format=xml",
method: "PUT",
data: {
ACCOUNT_NAME: recordToUpdate.data.ACCOUNT_NAME,
BP_NUMBER: recordToUpdate.data.BP_NUMBER,
CITY: recordToUpdate.data.CITY,
COUNTRY: recordToUpdate.data.COUNTRY,
E_MAIL: recordToUpdate.data.E_MAIL,
HOUSE_NO: recordToUpdate.data.HOUSE_NO,
POSTL_COD1: recordToUpdate.data.POSTL_COD1,
REGION: recordToUpdate.data.REGION,
STREET: recordToUpdate.data.STREET,
TELEPHONE: recordToUpdate.data.TELEPHONE
},
user: "****",
password: "****"},
function (data, response) {
//success handler
console.log(response);
console.log('Successfully updated object');
},
function (err)
{
//error handler
console.log('error while updating');
console.log(err);
}
);
Any help will be appreciated, thank you.
A: *
*Login to the Gateway system and check the logs in transaction /IWFND/ERROR_LOG
*Always start transaction SRDEBUG and make sure that the breakpoints are set for the same user you are using for the request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10370749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Binding a Resource to a View Model How do you bind data from the view model into an object in the resources of the user control? Here is a very abstract example:
<UserControl ...
xmlns:local="clr-namespace:My.Local.Namespace"
Name="userControl">
<UserControl.Resources>
<local:GroupingProvider x:Key="groupingProvider" GroupValue="{Binding ???}" />
</UserControl.Resources>
<Grid>
<local:GroupingConsumer Name="groupingConsumer1" Provider={StaticResource groupingProvider"} />
<local:GroupingConsumer Name="groupingConsumer2" Provider={StaticResource groupingProvider"} />
</Grid>
</UserControl>
How do I bind GroupValue to a property in the view model behind this view. I've tried the following:
<local:GroupingProvider x:Key="groupingProvider" GroupValue="{Binding ElementName=userControl, Path=DataContext.Property}"/>
But this doesn't work.
Edit:
GroupProvider extends DependencyObject and GroupValue is the name of a DependencyProperty. I'm getting the following error:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DataContext.Property; DataItem=null; target element is 'GroupingProvider' (HashCode=47478197); target property is 'GroupValue' (type 'TimeSpan')
This seems to suggest that it cannot find userControl.
More Edit:
Nobody has an answer to my question? Is there not a way to do this?
A: I know its a bit late, but i had the same problem. Ricks answer is right, you need to inherit from Freezable.
The following Code gave me the same error as you got
Not working resource:
public class PrintBarcodesDocumentHelper : DependencyObject
{
public IEnumerable<BarcodeResult> Barcodes
{
get { return (IEnumerable<BarcodeResult>)GetValue(BarcodesProperty); }
set { SetValue(BarcodesProperty, value); }
}
public static readonly DependencyProperty BarcodesProperty =
DependencyProperty.Register("Barcodes", typeof(IEnumerable<BarcodeResult>), typeof(PrintBarcodesDocumentHelper), new PropertyMetadata(null, HandleBarcodesChanged));
private static void HandleBarcodesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Do stuff
}
}
Xaml:
<UserControl.Resources>
<Barcodes:PrintBarcodesDocumentHelper x:Key="docHelper" Barcodes="{Binding BarcodeResults}"/>
</UserControl.Resources>
My viewmodel is bound to the DataContext of the UserControl.
Error:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=BarcodeResults; DataItem=null; target element is 'PrintBarcodesDocumentHelper' (HashCode=55335902); target property is 'Barcodes' (type 'IEnumerable`1')
Working resource class:
public class PrintBarcodesDocumentHelper : Freezable
{
// Same properties
protected override Freezable CreateInstanceCore()
{
return new PrintBarcodesDocumentHelper();
}
}
Unfortunately i dont know why it have to be a Freezable.
A: In order to enable binding, GroupingProvider needs to be derived from Freezable or FrameworkElement or FrameworkContentElement and GroupValue needs to be a DependencyProperty.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5009935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's wrong with my Vigenere Cypher CS50 My code for CS50 pset2 Vigenere cypher is as follows. Please help me find the bug. This code basically does nothing when the key includes the letter 'a'. It says "Floating Point Exception". I don't know what that means. Please go through the code and tell me what the bug is.
#include<stdio.h>
#include<cs50.h>
#include<ctype.h>
#include<string.h>
int main(int argc, string argv[])
{
//check if there are only two command line arguments//
if (argc!=2)
{
printf("Please enter a valid input!\n");
return 1;
};
string key = argv[1];
for(int i=0, n=strlen(key); i < n; i++)
{
//check if there is any number in the key//
if(!isalpha(key[i]))
{
printf("Invalid Key!\n");
return 1;
};
//converting the key into ints.//
if(islower(key[i]))
{
key[i] = key[i] - 'a';
}
else if(isupper(key[i]))
{
key[i] = key[i] - 'A';
};
};
//prompt user for the string//
string s = GetString();
int c;
int k;
int stln = strlen(s);
int kyln = strlen(key);
for(int j = 0, m = strlen(s); j < m; j++)
{
if(islower(s[j]))
{
s[j] = s[j] - 'a';
//for wrapping around the key//
if(stln > kyln)
{
k = j % strlen(key);
c = (s[j] + key[k]) % 26;
s[j] = 'a' + c;
}
else
{
c = (s[j] + key[j]) % 26;
s[j] = 'a' + c;
};
}
else if (isupper(s[j]))
{
s[j] = s[j] - 'A';
//for wrapping around the key//
k = j % strlen(key);
if(stln > kyln)
{
c = (s[j] + key[k]) % 26;
s[j] = 'A' + c;
}
else
{
c = (s[j] + key[j]) % 26;
s[j] = 'A' + c;
};
};
};
printf("%s\n", s);
};
A: strlen(key) is invalid in later code as earlier code was injecting null characters in key[] whenever an 'a' or 'A' was used:
if(islower(key[i])) {
key[i] = key[i] - 'a';
Find the string length of key[] before changing its contents and use that
int n = strlen(key);
...
// k = j % strlen(key);
k = j % n;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38233381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: SceneKit: How can I position my 3D object from a 2D line obj? Scene: I have a 2 lines which is parallel to each other (on 2D) drawn on a UIImageView using UIBezierPath. Then I added a SceneView over the UIImageview to display my 3D object. Now I need to position my 3d object (which I created using SketchUp [.dae file]) according to the lines drawn using the UIBezierPath and this should be done programmatically.
I having trouble finding the right formula for the the SceneNode's position, rotation, eulerAngles, transform or pivot. Because I think these attributes needs to calculated based on my lines.
I am able to convert 2D x,y coordinates to 3D coordinates using the 3D object's max and min Bounding Box.
SCNVector3 min = SCNVector3Zero;
SCNVector3 max = SCNVector3Zero;
[mySceneView.scene.rootNode getBoundingBoxMin:&min max:&max];
float x = (pointA.x / CGRectGetMaxX(self.imageView.frame)) * max.x;
float y = ((CGRectGetMaxY(self.imageView.frame) - (CGRectGetMaxY(self.imageView.frame) - pointA.y)) / CGRectGetMaxY(self.imageView.frame)) * max.y;
However I am having trouble finding the z-axis.
Here is my current output.
and my expected output should be like this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31109244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: My test of whether a MySQL insertion was succesful doesn't work All,
I created a table with three fields - an autoincremented ID and 2 fields of data. The 2 fields of data are foreign keys and by mistake I set them to NON NULL. Then I run the following PHP code:
$inserted=false;
$insertQuery=$dbConnection->prepare("INSERT INTO $this->table () VALUES ()");
$inserted=$insertQuery->execute(); //Should be true if succesful, False if not.
echo $inserted;
exit;
That displays a 1 - so the value of $inserted is true. I use this variable as a control to make sure the query went fine.
However, if I then check the db, the query hasn't run. If I enter it manually, I get an error since the 2 data fields do not allow null values.
My question is: why is the value of $inserted switched to true in my code, given that the insert resulted in an error?
PS: To run the query manually in phpMyAdmin, I do:
INSERT INTO 'flashcards' () VALUES ()
and I get this:
#1452 - Cannot add or update a child row: a foreign key constraint fails ('project'.'table1', CONSTRAINT 'table1_ibfk_1' FOREIGN KEY ('data1') REFERENCES 'table2' ('data2') ON DELETE NO ACTION ON UPDATE NO ACTION)
PPS: If I add the vardump code suggested below:
var_dump("Result: ", $inserted);
var_dump("Affected: ", $insertQuery->rowCount());
var_dump("Warnings: ", $insertQuery->errorInfo());
Then I get the following:
string 'Result: ' (length=8)
boolean true
string 'Affected: ' (length=10)
int 1
string 'Warnings: ' (length=10)
array
0 => string '00000' (length=5)
1 => null
2 => null
A: I ran a test and here is what I found:
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
From the console:
INSERT INTO `test` () VALUES ();
// Result:
1 row(s) affected, 2 warning(s):
1364 Field 'name' doesn't have a default value
1364 Field 'email' doesn't have a default value
Then a select:
mysql> select * from test;
+----+------+-------+
| id | name | email |
+----+------+-------+
| 1 | 0 | |
+----+------+-------+
1 row in set (0.00 sec)
Another insert test:
mysql> INSERT INTO `test` () VALUES(NULL, NULL, NULL);
ERROR 1048 (23000): Column 'name' cannot be null
So it appears that if you bind no parameters and set no values, for some reason MySQL does not treal the missing values as NULL. It's interesting that the data still gets inserted even though no default values were set (so the defaults become specific to the column type).
Some PHP code to further illustrate the point:
$pdo = new PDO('mysql:host=10.1.1.37;dbname=testing', 'user', 'pw');
$query = $pdo->prepare("INSERT INTO `test` () VALUES ()");
$result = $query->execute();
var_dump("Result: ", $result);
var_dump("Affected: ", $query->rowCount());
var_dump("Warnings: ", $query->errorInfo());
/*
string(8) "Result: "
bool(true)
string(10) "Affected: "
int(1)
string(10) "Warnings: "
array(3) {
[0]=>
string(5) "00000"
[1]=>
NULL
[2]=>
NULL
}
*/
So, the reason you are getting a successful result from execute() is because I would guess the data is getting inserted into your table. Are you sure you weren't seeing anything in there? Hope that helps clear things up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11679093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JS get all URL parameters available for final form page I see a lot of ways and a number of them seem overly complicated.
i do plan on appending a program that will use these parameters to test based on the results.
But for now, I want a way to get all the URL parameters and post them using a p tag.
A: Does this answer your question? You can get the search params of a URL with the URL constructor and accessing the searchParams property.
const div = document.querySelector('div');
const appendParams = (url) => {
const params = Object.fromEntries(new URL(url).searchParams.entries());
for (const key in params) {
const p = document.createElement('p');
p.textContent = `${key}: ${params[key]}`;
div.appendChild(p);
}
};
window.addEventListener('DOMContentLoaded', () => {
appendParams('https://hello.world?foo=bar&fizz=buzz&abc=123&hello=world');
});
<div></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72765263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Check new day using Shared preferences I have created an app. I have Put a button in my app. When I click on the button the click time is saved to shared preferences.
private void saveClickTime() {
String str = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
SharedPreferences.Editor localEditor = this.sp.edit();
localEditor.putString("mTime", str);
localEditor.commit();
}
Now I want to create a method isTimeToClick() when a new day starts. Like today is 3rd October. On 12.00 Pm 4th October will starts. I want that when a new days starts the method will start.
private boolean isTimeToClick() {
SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
try
{
// here I have to call the method but I don't know what should I use. can anyone help me?
}
catch (Exception localException) {}
return false;
}
A: You can store time in milliseconds and retrieve it to create a date instance from shared preferences and compare the dates.
private void saveClickTime() {
sp.edit().putLong("mTime", System.currentTimeMillis()).apply();
}
private boolean isTimeToClick() {
Date oldDate = new Date(sp.getLong("mTime", System.currentTimeMillis()));
GregorianCalendar oldCalendar = new GregorianCalendar();
oldCalendar.setTime(oldDate);
Calendar newCalendar = new GregorianCalendar();
return newCalendar.get(Calendar.DATE) != oldCalendar.get(Calendar.DATE) ||
newCalendar.get(Calendar.MONTH) != oldCalendar.get(Calendar.MONTH) ||
newCalendar.get(Calendar.YEAR) != oldCalendar.get(Calendar.YEAR);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46537195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Html().replace() : RegExp : $1 and single quote I am faced with two problems. (with jQuery)
for (var i=0; i<len; i++) {
var e = arr[i], //<- strings
re = new RegExp(e,"ig");
target.html(
target.html().replace(
re, "<span class='rep'>" + e + "</span>"
)
);
}
*
*The original value cannot be called after replacing. (like a "$1")
*It cannot replace, if the candidate for substitution (property e) has a single quote.
A: You actually can use something similar to $1:
for (var i=0; i<len; i++) {
var e = arr[i], //<- strings
re = new RegExp(e,"ig");
target.html(
target.html().replace(
re, "<span class='rep'>$&</span>"
)
); //you could also have used $1 to refer to the first backreference, instead of the entire match
}
Your second problem is less clear to me. Single quotes are not special characters in regexes.
I could not replicate your other problem. Here is a working example: http://jsfiddle.net/Xsjt7/1/
A: if you want to use $1 and the arr is just an array of strings you could join it:
var arr = ["what","not make any sense","n't make any sense","it's"];
var target = $('#mydiv');
var re = new RegExp("(" + arr.join("|") +")","ig");
target.html(
target.html().replace(re, "<span class='rep'>$1</span>")
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13239009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dropdown not populating from MySQL I am trying to populate a dropdown list with PHP from a MySQL database. Right now nothing is populating in my dropdown. I have made sure I have the correct database name, server name, username, and password.
Here is my PHP file queryfunction.php:
<?php
function connect(){
$servername = "localhost";
$username = "root";
$password = "******";
$database = "lab4";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($database);
}
function close(){
mysqli_close();
}
function query(){
$mydata = mysqli_query("Select * from country");
while($record = mysqli_fetch_array($mydata)){
echo '<option value = "' . $record['CountryAbbreviation'] . '">' .$record['CountryAbbreviation'] . '"</option>';
}
}
?>
Here is is my PHP file where I call this:
<?php
include_once "queryfunction.php";
connect();
?>
<!DOCTYPE html/>
<html>
Further down in the doc within a table:
<tr>
<th>Country</th>
<td>
<select name="CountryDropDown">
<?php query() ?>
</select>
<?php close()?>
</td>
</tr>
A: Try with change this line while($record = mysqli_fetch_array($mydata)){ to this while($record = mysqli_fetch_array($mydata,MYSQLI_ASSOC)){
or show us your $record variable data
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35859958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom form input component I want to create a custom form input component, that will work reactively.
I created a component (TS)
import { Component, forwardRef, Input, OnInit } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
@Component({
selector: "app-new-input",
templateUrl: "./new-input.component.html",
styleUrls: ["./new-input.component.css"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NewInputComponent),
multi: true
}
]
})
export class NewInputComponent implements ControlValueAccessor, OnInit {
@Input() label: string = "";
@Input() placeholder: string = "";
@Input() type: string = "text";
propagateChange: any = () => {};
onTouch: any = () => {};
value: string = "";
constructor() {}
ngOnInit() {}
onChange(event: any) {
this.value = event.target.value;
this.propagateChange(this.value);
}
writeValue(value: string): void {
this.value = value ? value : "";
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
this.propagateChange = fn;
}
setDisabledState?(isDisabled: boolean): void {}
}
and the HTML
{{label}}
<input matInput [type]="type" [value]="value" [placeholder]="placeholder" (change)="onChange($event)" (keyup)="onChange($event)">
in my app component I have
searchForm: FormGroup = this.formBuilder.group({
name: [""]
});
constructor(private formBuilder: FormBuilder) {}
and in app component HTML
<form [formGroup]="searchForm">
<app-new-input formControlName="name"></app-new-input>
</form>
{{searchForm.value | json}}
All this can be found on STACKBLITZ
So, the problem I am having is that the changes from the component input do not propagate to the parent (app component) form
Could somebody tell me what am I doing wrong?
A: Your mistake is a simple one - you are setting propagateChange in both registerOnChange and registerOnTouched. Instead, assign to onTouch in registerOnTouched.
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
registerOnTouched is getting called after registerOnChange by the framework, so you are emitting touch events when you are intending to emit change events.
DEMO https://stackblitz.com/edit/angular-ve8sri
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60845833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Server ALTER field NOT NULL takes forever I want to alter a field from a table which has about 4 million records. I ensured that all of these fields values are NOT NULL and want to ALTER this field to NOT NULL
ALTER TABLE dbo.MyTable
ALTER COLUMN myColumn int NOT NULL
... seems to take forever to do this update. Any ways to speed it up or am I stuck just doing it overnight during off-hours?
Also could this cause a table lock?
A: You can alter a field and make it not null without it checking the fields. If you are really concerned about not doing it off hours you can add a constraint to the field which checks to make sure it isn't null instead. This will allow you to use the with no check option, and not have it check each of the 4 million rows to see if it updates.
CREATE TABLE Test
(
T0 INT Not NULL,
T1 INT NUll
)
INSERT INTO Test VALUES(1, NULL) -- Works!
ALTER TABLE Test
WITH NOCHECK
ADD CONSTRAINT N_null_test CHECK (T1 IS NOT NULL)
ALTER COLUMN T1 int NOT NULL
INSERT INTO Test VALUES(1, NULL) -- Doesn't work now!
Really you have two options (added a third one see edit):
*
*Use the constraint which will prevent any new rows from being updated and leave the original ones unaltered.
*Update the rows which are null to something else and then apply the not null alter option. This really should be run in off hours, unless you don't mind processes being locked out of the table.
Depending on your specific scenario, either option might be better for you. I wouldn't pick the option because you have to run it in off hours though. In the long run, the time you spend updating in the middle of the night will be well spent compared the headaches you'll possibly face by taking a short cut to save a couple of hours.
This all being said, if you are going to go with option two you can minimize the amount of work you do in off hours. Since you have to make sure you update the rows to not null before altering the column, you can write a cursor to slowly (relative to doing it all at once)
*
*Go through each row
*Check to see if it is null
*Update it appropriately.
This will take a good while, but it won't lock the whole table block other programs from accessing it. (Don't forget the with(rowlock) table hint!)
EDIT: I just thought of a third option:
You can create a new table with the appropriate columns, and then export the data from the original table to the new one. When this is done, you can then drop the original table and change the name of the new one to be the old one. To do this you'll have to disable the dependencies on the original and set them back up on the new one when you are done, but this process will greatly reduce the amount of work you have to do in the off hours. This is the same approach that sql server uses when you make column ordering changes to tables through the management studio. For this approach, I would do the insert in chunks to make sure that you don't cause undo stress on the system and stop others from accessing it. Then on the off hours, you can drop the original, rename the second, and apply dependencies etc. You'll still have some off hours work, but it will be minuscule compared to the other approach.
Link to using sp_rename.
A: The only way to do this "quickly" (*) that I know of is by
*
*creating a 'shadow' table which has the required layout
*adding a trigger to the source-table so any insert/update/delete operations are copied to the shadow-table (mind to catch any NULL's that might popup!)
*copy all the data from the source to the shadow-table, potentially in smallish chunks (make sure you can handle the already copied data by the trigger(s), make sure the data will fit in the new structure (ISNULL(?) !)
*script out all dependencies from / to other tables
*when all is done, do the following inside an explicit transaction :
*
*get an exclusive table lock on the source-table and one on the shadowtable
*run the scripts to drop dependencies to the source-table
*rename the source-table to something else (eg suffix _old)
*rename the shadow table to the source-table's original name
*run the scripts to create all the dependencies again
You might want to do the last step outside of the transaction as it might take quite a bit of time depending on the amount and size of tables referencing this table, the first steps won't take much time at all
As always, it's probably best to do a test run on a test-server first =)
PS: please do not be tempted to recreate the FK's with NOCHECK, it renders them futile as the optimizer will not trust them nor consider them when building a query plan.
(*: where quickly comes down to : with the least possible downtime)
A: Sorry for the discouragement, but:
*
*Any ways to speed it up: No, not if you want to change the table structure itself
*or am I stuck just doing it overnight during off-hours? Yes, and that's probably for the best, as @HLGEM pointed out
*Also could this cause a table lock? Yes
Not directly relevant to you (because it's about going from NOT NULL to NULL), but interesting read on this topic: http://beyondrelational.com/blogs/sankarreddy/archive/2011/04/05/is-alter-table-alter-column-not-null-to-null-always-expensive.aspx
And finally some ancient history - on an equivalent question in a forum in 2005, the same suggestion was made as @Kevin offered above - using a constraint insteadof making the column itself non-nullable: http://www.sqlteam.com/Forums/topic.asp?TOPIC_ID=50671
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1153673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Where can I find the GCP cloud service ID's that is required to list down the sku's for each cloud service? I'm planning to create a table in bigquery which would categorize the SKU's of each cloud services in billing. Basically I'd like to replicate the strategy suggested in one of the presentation at last Cloud Next '19, specifically this one -> https://youtu.be/UocD6uY2-js
Since there's a lot of sku's available, i'm planning to fetch this data directly from the billing api ( GET https://cloudbilling.googleapis.com/v1/{parent=services/*}/skus ), but the problem is, it requires for me to provide the service id of the cloud service I'd like to list down the SKU's. Now I don't know where can I find those service id's.
Does anybody know where can I find the service id's for each of the cloud services in google cloud? let's say for GAE or GCE, etc. ?
Here's the link to the Cloud Billing API explorer, https://developers.google.com/apis-explorer/#search/%20billing/cloudbilling/v1/cloudbilling.services.skus.list
A: There appears to be a an API called services.list. This API returns the services as a JSON array of service objects. Each object instance includes a field called serviceId which appears to the identifier of the service (eg. DA34-426B-A397) and I believe that this is what you are looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58160449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Push was rejected due to missing or corrupt local objects I have a lfs local repo with its remote bitbucket. I work with Unity and Visual studio and my routine is assisted commit with visual studio. My current commits are not allowed to be push-ed.
Git throws missing files errors but when I follow the path the files are there and ok.
How do I resolve this issue?
A: As seen here, your error should be like:
(missing) code.tar.gz (f2b4bf22bcb011fef16f80532247665d15edbb9051***)
Uploading LFS objects: 0% (0/1), 0 B | 0 B/s, done.
hint: Your push was rejected due to missing or corrupt local objects.
hint: You can disable this check with: 'git config lfs.allowincompletepush true'
error: failed to push some refs to 'git@gitlab.example.com:group/project.git'
Following this issue, start with
git lfs fetch --all
See if the error persists then.
If it does, try it from a fresh cloned repo (git lfs clone my-repo)
From the discussion:
*
*git lfs fetch --all could not work, since what is missing was never pushed in the first place
*a new git lfs clone, followed by reporting the old repository local work did get added, committed and pushed successfully.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69867730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you duplicate a file in XCode? Anyone know a good solution?
So far I have not found a better way than using File>New file and then copying contents from old file to new.
You can probably duplicate in Finder and re-import but that's almost same amount of work: switching to finder, duplicate, import new files.
Doing this with one class is not so hard, but what to do if you need to generate 10+ similar Classes based on superclass.
In Eclipse you select file and then copy/paste it in same folder. In finder there's Duplicate.
There's a menu Edit > Duplicate. But it's ALWAYS disabled. I tried selecting various files, classes, methods. It's still disabled.
A: "Duplicate" is enabled for targets in XCode (pretty much nothing else that I know of).
If you have a substantial number of subclasses with the same starting point to replicate, why not make a class template from it? Then you can just use file->New to make new instances. It's fairly quick to do.
This is probably the simplest example:
http://www.macresearch.org/custom_xcode_templates
Otherwise, I'd simply duplicate the files in Finder as many times as you need, name them, and drag them into XCode en-masse.
A: In XCode 4.2 (I know this is an old question) there is Duplicate under the File menu.
Select the file (you can select multiple files but it doesn't appear to do anything useful) in the Project Navigator and then File->Duplicate. Hooray!
A: Careful!
When you use duplicate ( CMD + Shift + S ) - Xcode have a problem with indexing headers.
Also when u want to make a refactoring it can be next error window:
So there a couple of ways what to do, to fix that.
*
*Delete derived data from menu Window > Projects. Restart Xcode.
*Product > Clean
A: In Xcode 4.5 we can duplicate using File-> Duplicate or cmd + shift + S
A: You could use "Save As..."; you'd still have to go back and re-add the original files to the project, though.
It wouldn't be such a bad way to do a bunch of related classes, though: edit file, Save As "class2", edit file, Save As "class3", etc., then "Add Existing Files" and re-add all of the files but the last to your project.
A: I use the following perl script to duplicate a file pair in the Terminal. You give it the base name of the original and new file, and it copies the header and implementation (c/cpp/m/mm) file, then replaces all occurances of the base name with the new name, then adds them to subversion. You still have to add the new files in to Xcode and adjust the creation date in the comment (I've got a Keyboard Maestro macro for that), but its quicker than doing a lot of the steps manually. I operate with a Terminal window and four tabs pre-set to the Project, Source, Resources, and English.lproj directory which gives quick access for a lot of operations.
#!/usr/bin/perl
use lib "$ENV{HOME}/perl";
use warnings;
use strict;
our $cp = '/bin/cp';
our $svn = '/usr/bin/svn';
our $perl = '/usr/bin/perl';
our $source = shift;
our $add = 1;
if ( $source =~ m!^-! ) {
if ( $source eq '-a' || $source eq '--add' ) {
$add = 1;
$source = shift;
} elsif ( $source eq '-A' || $source eq '--noadd' ) {
$add = undef;
$source = shift;
} else {
die "Bad arg $source";
}
}
our $dest = shift;
die "Bad source $source" unless $source =~ m!^(.*/)?[A-Za-z0-9]+$!;
die "Bad dest $dest" unless $dest =~ m!^(.*/)?[A-Za-z0-9]+$!;
my $cpp;
$cpp = 'c' if ( -e "$source.c" );
$cpp = 'cpp' if ( -e "$source.cpp" );
$cpp = 'mm' if ( -e "$source.mm" );
$cpp = 'm' if ( -e "$source.m" );
die "Missing source $source" unless -e "$source.h" && -e "$source.$cpp";
die "Existing dest $dest" if -e "$dest.h" && -e "$dest.$cpp";
our $sourcename = $source; $sourcename =~ s!.*/!!;
our $destname = $dest; $destname =~ s!.*/!!;
print "cp $source.h $dest.h\n";
system( $cp, "$source.h", "$dest.h" );
print "s/$sourcename/$destname in $dest.h\n";
system( $perl, '-p', '-i', '-e', "s/$sourcename/$destname/g", "$dest.h" );
print "cp $source.$cpp $dest.$cpp\n";
system( $cp, "$source.$cpp", "$dest.$cpp" );
print "s/$sourcename/$destname in $dest.$cpp\n";
system( $perl, '-p', '-i', '-e', "s/$sourcename/$destname/g", "$dest.$cpp" );
if ( $add ) {
print "svn add $dest.$cpp $dest.h\n";
system( $svn, 'add', "$dest.$cpp", "$dest.h" );
}
A: In my case, one of my folder changed from one place to another place.
I have "Home" folder in Controller folder, but unfortunately it's moved from Controller folder to Manager folder.
I checked many times everything fine, but I'm getting Command PrecompileSwiftBridgingHeader failed with a nonzero exit code
But after 2 hours i realised, my folder structure changed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1093287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
}
|
Q: Python: Log pixel-intensity values from a video-file I read in a video as a grayscale. I mark a circular contour on each frame of the video and try to record the intensity of each pixel on this contour:
frameCount += 1
currentTimestamp = timestamp + frameCount/fps
file = open("myRecord.txt", "a+") #a+ to append to file
file.write(str(currentTimestamp))
circleSegment = get_circle_segment(center_pt, 60, 360) #this function returns a list of tuples, where each tuple (x,y) contains x- and y-coordinates of a point along the circular contour
for el in circleSegment:
pixel = gray_frame[el[1],el[0]]
#log information
file.write('\t' + str(pixel))
file.write('\n')
file.close()
This works perfectly for a circular arch of up to 180° and even beyond (I have tested with 181° as well). However, as soon as I go beyond a certain value, e.g. 270° or 359° or 360° (a complete circle, which is what I want), the data logged simply contains chinese characters.
I have no idea what may cause this issue! Can it be that as soon as my txt-file goes beyond 1,000 KB something goes wrong?
after comments, this code works:
frameCount += 1
currentTimestamp = timestamp + frameCount/fps
storeData = []
storeData.append(currentTimestamp)
circleSegment = get_circle_segment(center_pt, 60, 360)
for el in circleSegment:
pixel = gray_frame[el[1],el[0]]
storeData.append(pixel)
#log information
file = open("myRecord.txt", mode="a+") #a+ to append to file
for element in storeData:
file.write('\t' + str(element))
file.write('\n')
file.close ()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56377798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a maximum Time Stamp Validity Duration when a client is set to a future datetime vs the server We set our Security on our custom Binding as below:
var lSecurity = lCustomBinding.Elements.Find<TransportSecurityBindingElement>();
lSecurity.LocalClientSettings.DetectReplays = false;
lSecurity.LocalServiceSettings.DetectReplays = false;
lSecurity.LocalClientSettings.TimestampValidityDuration = TimeSpan.FromDays(7);
lSecurity.LocalServiceSettings.TimestampValidityDuration = TimeSpan.FromDays(7);
lSecurity.LocalClientSettings.MaxClockSkew = TimeSpan.FromDays(7);
lSecurity.LocalServiceSettings.MaxClockSkew = TimeSpan.FromDays(7);
Now we find that if we test the above by setting the client back anywhere from now to 7 days back, it works. However, the moment we set the client anything more than 9 hours into the future, we get an exception.
The only thing we found was some obscure reference at the end of another thread:
http://social.msdn.microsoft.com/Forums/en/wcf/thread/7c3a7a7e-b9a5-4198-9a29-c6d4e408d36d
Does anybody have any ideas?
UPDATE:
The Exception we get is now added below. It seems as though the server rejects the client message:
System.ServiceModel.Security.MessageSecurityException occurred
Message=An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.RenewTokenCore(TimeSpan timeout, SecurityToken tokenToBeRenewed)
at System.IdentityModel.Selectors.SecurityTokenProvider.RenewToken(TimeSpan timeout, SecurityToken tokenToBeRenewed)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.RenewKey(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.SecureOutgoingMessage(Message& message, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecurityDuplexSessionChannel.Send(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableChannelBinder`1.DuplexClientReliableChannelBinder`1.OnSend(TDuplexChannel channel, Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ReliableChannelBinder`1.Send(Message message, TimeSpan timeout, MaskingMode maskingMode)
at System.ServiceModel.Channels.SendReceiveReliableRequestor.OnRequest(Message request, TimeSpan timeout, Boolean last)
at System.ServiceModel.Channels.ReliableRequestor.Request(TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableSession.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ClientReliableDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at CompuLoan.Maintenance.IMaintenanceService.IsLicensed(String pHardwareId, Boolean pUseLicense)
at CompuLoan.Maintenance.MaintenanceServiceClient.IsLicensed(String pHardwareId, Boolean pUseLicense) in C:\Development\compuloan\Source\CompuLoan\Service References\Maintenance\Reference.cs:line 5156
at CompuLoan.App.IsLicensed(Boolean pUseLicense) in C:\Development\compuloan\Source\CompuLoan\App.xaml.cs:line 365
InnerException: System.ServiceModel.FaultException
Message=The security context token is expired or is not valid. The message was not processed.
InnerException:
A: This is expiration of the session key, which is different than timestamp. For example of you turn establishSecurityContext off (or not use CreateSecureConversationSecurity) you should not get this exception.
Otherwise try to increase additional values such as InactivityTimeout, IssuedCookieLifetime, NegotiationTimeout, SessionKeyRenewalInterval and SessionKeyRolloverInterval.
If you turn on WCF trace on the server and see the exact stack trace of the error maybe we can dril down to the exact property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10515093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In a makefile how do I make a variable within a rule become global? I have a makefile with separate rules that set a variable of the same name. How do I set this variable to become global from within the rule so that I can use it later.
rule1: test_var=/path/to/folder/
rule2: test_var=/path/to/another/folder/
$(info test_var is $(test_var))
When I call "make rule2" it says "test var is "
But I want "test var is /path/to/another/folder"
Thanks!
EDIT
I may have simplified my approach too much, I thought I had it with the global variable idea but make maybe shouldn't be used that way. Here is the problem below.
When I run this code I get the error *** No rule to make target '/file_i_want_compiled.c', needed by 'out/IceCream'. Stop
LINK:= -lpthread
C_SRCS =
C_SRCS += folder1/file1.c
C_FLAGS:= -stf=gnu11
OBJ_PATH= out/objects/
rule1: path = /path/to/rule1folder
.PHONY : rule1
rule2: path = /path/to/rule2folder
.PHONY : rule2
C_SRCS_NO_DIR := $(notdir $(C_SRCS))
C_OBJS := $(C_SRCS_NO_DIR:%.c=$(OBJ_PATH)%.o
C_OBJS += $(path)/file_i_want_compiled.o
out/IceCream: GEN_ICECREAM $(C_OBJS) $(OBJ_PATH)IceCream.o
$(CC) $(C_FLAGS) $(C_OBJS) %(OBJ_PATH)IceCream.o -o $@ $(LINK)
/path/to/rule1folder
&
/path/to/rule2folder
both have their own unique file_i_want_compiled.c
I call make with make rule1 for example
A: You're actually setting the variable correctly, but the info statement is not being evaluated in the context of the recipe. You can check this by looking at the very lengthy output of make -d rule1. Notice that the info statement is evaluated before any rules.
You can have it print out in the context of the rule by doing something like
rule1: test_var=/path/to/folder/
rule2: test_var=/path/to/another/folder/
rule%:
$(info test_var is $(test_var))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54131046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run sentiment So, that I can get result for every file separately I am working on Sentiment Analysis. I have 542 text files and have to get sentiment scores for each of the files separately But in 1 Loop. How can I add for loop that prints results separately?
Here is the code:
path = 'C:/Users/Hamza/OneDrive/Desktop/talha.R/Project 5/text.files'
setwd(path)
getwd()
fileslist = list.files(pattern = ",*.txt")
datalist = lapply(fileslist, function(x) readLines(x))
datafr = do.call("rbind", datalist)
view(datalist[1])
filename <- datalist
filename <- trimws(filename)
filetext <- glue(read_file(filename))
filetext <- gsub("\\$", "", filetext)
tokens <- tibble(text = filetext) %>% unnest_tokens(word, text)
tokens %>%
inner_join(get_sentiments("loughran")) %>%
count(sentiment) %>%
spread(sentiment, n, fill = 0) %>%
mutate(sentiment = positive - negative)
This is the sample of the result:
I want this same output for 542 files. Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71482530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I let my list return the list within a specific range So I'm trying to move every '1' in list board to the bottom list of lists. Here is what I mean,
If my input in this,
board = [[" "," ","1"," "],
[" "," ","1"," "],
["1","1"," "," "],
["1"," "," ","1"]]
my output should return
[[" "," "," "," "],
[" "," "," "," "],
["1"," ","1"," "],
["1","1","1","1"]]
If u do not understand, I basically have to move every '1' in the list to the lowest list in board in python.
Here is what I have so far,
board = [[" "," ","1"," "],
[" "," ","1"," "],
["1","1"," "," "],
["1"," "," ","1"]]
def summ(board: [list[str]]):
j = []
for x in board:
for i in x:
j.append(i.count('1'))
return sum(j)
def remove(board):
r = []
for x in board:
for i in x:
r.append(i.removesuffix('1'))
return r
def new(board):
s = list('1'* summ(board))
return [remove(board) + s]
print(new(board))
and the output I get is this
[[' ', ' ', '', ' ', ' ', ' ', '', ' ', '', '', ' ', ' ', '', ' ', ' ', '', '1', '1', '1', '1', '1', '1']]
What should I change??
A: It is simple. just transpose array, sort it and transpose back again.
board = [[" "," ","1"," "],
[" "," ","1"," "],
["1","1"," "," "],
["1"," "," ","1"]]
boardT=list((map(list, zip(*board))))
boardS=[sorted(L) for L in boardT]
boardR=list((map(list, zip(*boardS))))
print(boardR)
#ans=[[' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' '],
['1', ' ', '1', ' '],
['1', '1', '1', '1']]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69961094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the advantage of malloc? What is the advantage of allocating a memory for some data. Instead we could use an array of them.
Like
int *lis;
lis = (int*) malloc ( sizeof( int ) * n );
/* Initialize LIS values for all indexes */
for ( i = 0; i < n; i++ )
lis[i] = 1;
we could have used an ordinary array.
Well I don't understand exactly how malloc works, what is actually does. So explaining them would be more beneficial for me.
And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing? And is there a way to print the values stored in the variable directly from the memory allocated space, for example here it is lis?
A: Your question seems to rather compare dynamically allocated C-style arrays with variable-length arrays, which means that this might be what you are looking for: Why aren't variable-length arrays part of the C++ standard?
However the c++ tag yields the ultimate answer: use std::vector object instead.
As long as it is possible, avoid dynamic allocation and responsibility for ugly memory management ~> try to take advantage of objects with automatic storage duration instead. Another interesting reading might be: Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)
"And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing?"
- If you still consider n to be the amount of integers that it is possible to store in this array, you will most likely experience undefined behavior.
A: The answer is simple. Local1 arrays are allocated on your stack, which is a small pre-allocated memory for your program. Beyond a couple thousand data, you can't really do much on a stack. For higher amounts of data, you need to allocate memory out of your stack.
This is what malloc does.
malloc allocates a piece of memory as big as you ask it. It returns a pointer to the start of that memory, which could be treated similar to an array. If you write beyond the size of that memory, the result is undefined behavior. This means everything could work alright, or your computer may explode. Most likely though you'd get a segmentation fault error.
Reading values from the memory (for example for printing) is the same as reading from an array. For example printf("%d", list[5]);.
Before C99 (I know the question is tagged C++, but probably you're learning C-compiled-in-C++), there was another reason too. There was no way you could have an array of variable length on the stack. (Even now, variable length arrays on the stack are not so useful, since the stack is small). That's why for variable amount of memory, you needed the malloc function to allocate memory as large as you need, the size of which is determined at runtime.
Another important difference between local arrays, or any local variable for that matter, is the life duration of the object. Local variables are inaccessible as soon as their scope finishes. malloced objects live until they are freed. This is essential in practically all data structures that are not arrays, such as linked-lists, binary search trees (and variants), (most) heaps etc.
An example of malloced objects are FILEs. Once you call fopen, the structure that holds the data related to the opened file is dynamically allocated using malloc and returned as a pointer (FILE *).
1 Note: Non-local arrays (global or static) are allocated before execution, so they can't really have a length determined at runtime.
A: More fundamentally, I think, apart from the stack vs heap and variable vs constant issues (and apart from the fact that you shouldn't be using malloc() in C++ to begin with), is that a local array ceases to exist when the function exits. If you return a pointer to it, that pointer is going to be useless as soon as the caller receives it, whereas memory dynamically allocated with malloc() or new will still be valid. You couldn't implement a function like strdup() using a local array, for instance, or sensibly implement a linked representation list or tree.
A: I assume you are asking what is the purpose of c maloc():
Say you want to take an input from user and now allocate an array of that size:
int n;
scanf("%d",&n);
int arr[n];
This will fail because n is not available at compile time. Here comes malloc()
you may write:
int n;
scanf("%d",&n);
int* arr = malloc(sizeof(int)*n);
Actually malloc() allocate memory dynamically in the heap area
A: Some older programming environments did not provide malloc or any equivalent functionality at all. If you needed dynamic memory allocation you had to code it yourself on top of gigantic static arrays. This had several drawbacks:
*
*The static array size put a hard upper limit on how much data the program could process at any one time, without being recompiled. If you've ever tried to do something complicated in TeX and got a "capacity exceeded, sorry" message, this is why.
*The operating system (such as it was) had to reserve space for the static array all at once, whether or not it would all be used. This phenomenon led to "overcommit", in which the OS pretends to have allocated all the memory you could possibly want, but then kills your process if you actually try to use more than is available. Why would anyone want that? And yet it was hyped as a feature in mid-90s commercial Unix, because it meant that giant FORTRAN simulations that potentially needed far more memory than your dinky little Sun workstation had, could be tested on small instance sizes with no trouble. (Presumably you would run the big instance on a Cray somewhere that actually had enough memory to cope.)
*Dynamic memory allocators are hard to implement well. Have a look at the jemalloc paper to get a taste of just how hairy it can be. (If you want automatic garbage collection it gets even more complicated.) This is exactly the sort of thing you want a guru to code once for everyone's benefit.
So nowadays even quite barebones embedded environments give you some sort of dynamic allocator.
However, it is good mental discipline to try to do without. Over-use of dynamic memory leads to inefficiency, of the kind that is often very hard to eliminate after the fact, since it's baked into the architecture. If it seems like the task at hand doesn't need dynamic allocation, perhaps it doesn't.
However however, not using dynamic memory allocation when you really should have can cause its own problems, such as imposing hard upper limits on how long strings can be, or baking nonreentrancy into your API (compare gethostbyname to getaddrinfo).
So you have to think about it carefully.
A:
we could have used an ordinary array
In C++ (this year, at least), arrays have a static size; so creating one from a run-time value:
int lis[n];
is not allowed. Some compilers allow this as a non-standard extension, and it's due to become standard next year; but, for now, if we want a dynamically sized array we have to allocate it dynamically.
In C, that would mean messing around with malloc; but you're asking about C++, so you want
std::vector<int> lis(n, 1);
to allocate an array of size n containing int values initialised to 1.
(If you like, you could allocate the array with new int[n], and remember to free it with delete [] lis when you're finished, and take extra care not to leak if an exception is thrown; but life's too short for that nonsense.)
Well I don't understand exactly how malloc works, what is actually does. So explaining them would be more beneficial for me.
malloc in C and new in C++ allocate persistent memory from the "free store". Unlike memory for local variables, which is released automatically when the variable goes out of scope, this persists until you explicitly release it (free in C, delete in C++). This is necessary if you need the array to outlive the current function call. It's also a good idea if the array is very large: local variables are (typically) stored on a stack, with a limited size. If that overflows, the program will crash or otherwise go wrong. (And, in current standard C++, it's necessary if the size isn't a compile-time constant).
And suppose we replace sizeof(int) * n with just n in the above code and then try to store integer values, what problems might i be facing?
You haven't allocated enough space for n integers; so code that assumes you have will try to access memory beyond the end of the allocated space. This will cause undefined behaviour; a crash if you're lucky, and data corruption if you're unlucky.
And is there a way to print the values stored in the variable directly from the memory allocated space, for example here it is lis?
You mean something like this?
for (i = 0; i < len; ++i) std::cout << lis[i] << '\n';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18702531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Restful Webservice method for get request I am trying to write a web service method for get request and its return type is ResponseEntity. But when i trying to run this from Postman then its gives response body as Not acceptable. following is the result and code of my method.
<html>
<head>
<title>Error</title>
</head>
<body>Not Acceptable</body>
</html>
Code:-
@GetMapping("/v1/showMyDetails.html")
public ResponseEntity tryingGetWithAnnotation(){
ResponseEntity responseEntity = null;
JSONObject jsonObj = new JSONObject();
jsonObj.put("name","nikhil");
responseEntity = new ResponseEntity(jsonObj,HttpStatus.OK);
return responseEntity;
}
Thanks in Advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46804331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: RestSharp double-nested elements not being Deserialized So I am attempting to use the default XmlDeserializer from RestSharp to deserialize the following XML structure. For the life of me, I am unable to get the 'Picks' to be deserialized at all.
<PlayerList>
<Player>
<PlayerName>Name</PlayerName>
<PlayerRank>5</PlayerRank>
<Picks>
<PickID>1</PickID>
<Status>Active</Status>
<CreatedDate>2012-08-30 09:43:38</CreatedDate>
</Picks>
<Picks>
<PickID>2</PickID>
<Status>Disabled</Status>
<CreatedDate>2012-08-30 09:49:33</CreatedDate>
</Picks>
</Player>
</PlayerList>
The closest I ever came was to define them in the "Player" class as...
public class Player {
/*other properties*/
public List<Picks> Picks { get; set; }
}
Which did return a single "Picks" object with all of its properties set to null (or DateTime minimum).
What is the proper way to structure the serializable C# classes to get the data returned from each of the Picks? I wonder if it has something to do with the "Picks" objects having a plural name...
Thanks!
A: Eventually realized what the issue was with this. The change necessary to get this to work was to make these changes to the "Player" class...
public class Player {
/* other properties */
List<Picks> PickList { get; set; }
}
The issue was occurring because RestSharp was confused because the Property's name ("Picks") was the same as the Object Type ("Picks") that it was trying to deserialize.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12200352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make a few div elements responsive I'm having trouble with making some of my div elements responsive.
The image with the magnifying glass is refusing to resize when the window is smaller, for example on a ipad. I have tried other methods of resizing but resulting in failure.
Website link: http://onlinestaff.net
A: You can try something like this to make divs responsive and their position relative to the size of screen:
<body>
<div class="container">
<div class="row row-centered pos">
<div class="col-lg-8 col-xs-12 col-centered">
<div class="well"></div>
</div>
<div class="col-lg-8 col-xs-12 col-centered">
<div class="well"></div>
</div>
<div class="col-lg-8 col-xs-12 col-centered">
<div class="well"></div>
</div>
</div>
</div>
</body>
A: Problem: The magnifying-glass-image on your website uses the attribute max-width:none which causes the image to be displayed in full size even on smaller screens.
Solution: When making images responsive we usually use the CSS attribute max-width:100% to ensure that big images scale down to fit on the screen (or better: fit into the parent container)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46747781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What really lambda looks like? (not a linq lambda expression) I read this thread in converting a lambda to linq. And I am thinking about what slawekwin said in comment.
this already is linq (which is using lambda expressions)
Can someone please give me an example of what really lambda looks like?. Not in Linq Lambda Expression. Thanks
A: Lambda functions are a language construct of defining a function.
LINQ is a library of functions. Many of these functions takes functions as parameters to compare or select elements from your lists. Therefore it is very common to use lambda functions to specify these parameter functions. Simple because that makes puts the definition of what it is supposed to do where you actually use it. But there is nothing preventing you from NOT using lambda functions with LINQ.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39825021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reducing size of an array (by creating a new one) - how does arrayList do it? In one of my classes, I have a method like so:
public void setArray(int size){
myArray = new int[size] //myArray is declared already
}
Now, if I call this and pass in, say, 500 like so:
setArray(500);
And then, later on in my app, I need only an array with, say 50 elements, at the moment, I simply call it again and pass in 50 as my argument.
This array is referenced many times within my app and I'm wondering if the CG will collect the old one?
I know I should really use an arrayList, unfortunately, this would be a major undertaking as my code is now thousands of lines and 18 classes in size (so I guess I've learned for my next project!)
How does arrayList achieve this 'behind the scenes'? Can I emulate the arrayList behavour? Does it simply create a new array like I've done?
A: You are describing the behavior of a dynamic array.
The easiest way to implement this data structure is to create a new array once the array is full or below some threshold (only 1/4 of the cells are occupied, for example), and copy existing values into the new array.
If you want to know how it is done in java, and what optimizations are being made - you might want to have a look on the ArrayList class source.
A: You can read the source for ArrayList here: SOURCE
And you are right, it keeps an array and replaces it as needed to allow room for more objects. But it also stores the length so the array can be longer than is needed. That allows the ArrayList to grow a little without having to re-create the actual array everytime. If the ArrayList gets smaller, it doesn't have to re-create. It just changes the length as stored.
You can read the code to see how they decide when to change the array itself. Whenever they do that, they have to copy the old one's contents over.
You are right, BTW, that the old arrays get garbage collected as long as there are not variables referencing them. It sort of depends on how your code works. If that code you show and the definition is the only reference, then it will get GC'ed when you make a new array and store it.
A: The official implementation of ArrayList never reduces the size of an array, only increases the capacity when needed.
When an element is removed from the ArrayList, it ensures that the posterior elements return one position and sets null for the free element on the right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18063706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NoSuchPropertyException in signed build I am animating a Map Marker via the following code:
final Property<Marker, LatLng> property =
Property.of(Marker.class, LatLng.class, "position");
final ObjectAnimator animator =
ObjectAnimator.ofObject(otherMarker, property, typeEvaluator, toLatLng);
This works fine in a debug build but fails with the following stack trace in a signed build:
0
android.util.NoSuchPropertyException: No accessor method or field found for property with name position
1
at android.util.ReflectiveProperty.<init>(ReflectiveProperty.java:71)
2
at android.util.Property.of(Property.java:55)
3
at com.myapp.fragment.MapWrapperFragment.j(MapWrapperFragment.java:1090)
4
at com.myapp.ActivityA.l(ActivityA.java:860)
5
at com.myapp.fragment.FragmentA$22.onClick(FragmentA.java:377)
6
at android.view.View.performClick(View.java:4438)
7
at android.view.View$PerformClick.run(View.java:18422)
8
at android.os.Handler.handleCallback(Handler.java:733)
9
at android.os.Handler.dispatchMessage(Handler.java:95)
10
at android.os.Looper.loop(Looper.java:136)
11
at android.app.ActivityThread.main(ActivityThread.java:5001)
12
at java.lang.reflect.Method.invokeNative(Native Method)
13
at java.lang.reflect.Method.invoke(Method.java:515)
14
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
15
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
16
at dalvik.system.NativeStart.main(Native Method)
What could be the reason for this? I am not sure if it's relevant, but I am using Proguard.
A: Proguard is either removing or renaming the field, since it doesn't know about any access done via reflection. That's why it fails at runtime.
You should probably add a -keep (or -keepnames) rule to prevent this.
A: I stumbled across the same issue but the provided proguard changes did not do it for me. I guess because I use the new play services ('com.google.android.gms:play-services-maps:7.0.0') and they probably have a different internal structure
What worked for me was:
-keep class com.google.android.gms.** { *; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27326218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I check if any file in an item list exist using msbuild? I would like to run a task if any file in an item list is missing. How do I do that?
My current script has a list of "source" files @(MyComFiles) that I translate another list of "destination" files @(MyInteropLibs), using the following task:
<CombinePath BasePath="$(MyPath)\interop"
Paths="@(MyComFiles->'%(filename).%(extension)')">
<Output TaskParameter="CombinedPaths"
ItemName="MyInteropLibs" />
</CombinePath>
I want to check if any of the files in @(MyInteropLibs) is missing and run a task that will create them.
A: If you only need to create the missing files, and not get a list of the files that were missing you can you the touch task, which will create if the files don't exist.
<Touch Files="@(MyInteropLibs)" AlwaysCreate="True" />
If you only want to create the missing files, and avoid changing timestamps of the existing files, then batching can help
<Touch Files="%(MyInteropLibs.FullPath)" AlwaysCreate="True"
Condition=" ! Exists(%(MyInteropLibs.FullPath)) "/>
If you want a list of the files created then
<Touch Files="%(MyInteropLibs.FullPath)" AlwaysCreate="True"
Condition=" ! Exists(%(MyInteropLibs.FullPath)) ">
<Output TaskParameter="TouchedFiles" ItemName="CreatedFiles"/>
</Touch>
<Message Text="Created files = @(CreatedFiles)"/>
A: I am not very experienced with MSBuild so there may be better solutions than this but you could write a FilesExist task that takes the file list and passes each file to File.Exists returning true if they do exist and false otherwise and thenn react based on the result
Sorry I can't provide code to help out, my knowlege of MSBuild sytax is not strong
A: You can find out pretty easily using Exec.
To test if ALL of a set of files exists: The DOS FOR /D command accepts a semicolon-separated list of files - i.e. a flattened item array.
<!-- All exist -->
<Exec
Command="for /D %%i in (@(MyFiles)) do if not exist %%i exit 1"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ExistExitCode"/>
</Exec>
To test if ANY of a set of files exists: The DOS DIR command accepts a semicolon-separated list of files. It sets the %ERRORLEVEL% to 0 if it finds any files in the list, nonzero if it finds none. (This is the simpler case, but it does not address the original question...)
<!-- Any exists -->
<Exec Command="dir /B @(MyFiles)" IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="DirExitCode"/>
</Exec>
Then most likely you will want to define a boolean property based on the output.
EDIT: BTW this is a code smell. Usually when you find yourself wanting to do this, it's an indication that you should set the Outputs property of the target so it will loop over the items.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/802070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Django function based view allow is_active user whereas ClassBasedView does not allow is_active user I have 2 views. One is function based and the other is class based. When I call the function based view with an is_active user, django does not throw any errors but when I call the class based view it returns 403 error.Any help will be highly appreciated. Thanks
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
@require_POST
@permission_classes([IsAuthenticated,])
def test_function_based_view(request):
return JsonResponse({
'success': "True",
})
class TestClassBasedView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def post(self, request):
return JsonResponse({
'success': "True",
})
Django Version 1.11.21
A: It is possible that the problem is not that the class based view is returning a 403 error, but rather that the function based view is not checking the permissions correctly. This might be caused because @require_POST does not take the permissions into consideration.
Replace @require_POST in your function based view with @api_view(('POST',)).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60510459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reducer not always deleting the correct item My delete callback is sending the correct id but I tested out the reducer with a few console logs and it's not working correctly.So I have a list of components in a menu that I can add to the "board". I notice that if I add only notes for example, it will delete the last one every time. But if I had one note, then one todo list, and another note, if I try to delete the first note, it will delete that one correctly.
reducer
export default function reducer(state: any, action: any) {
switch (action.type) {
case "ADD_COMPONENT":
return {
...state,
components: [...state.components, action.payload],
};
case "DELETE_COMPONENT":
return {
...state,
components: state.components.filter(
// actual code
(component: any) => component.id !== action.payload),
//test code to check what ids were being passed in
//(component: any) => { console.log(component.id, action.payload), console.log(component.id !== action.payload), component.id == action.payload }),
};
default:
return state;
}
}
The Delete case has a line I was using to test to see what ids were being passed in.
The context
import React, { createContext, useReducer, useState } from "react";
import ComponentReducer from "./ComponentReducer";
const NewComponentState: NewComponentsState = {
components: [],
addComponent: () => {},
deleteComponent: () => {},
};
export const NewComponentContext =
React.createContext<NewComponentsState>(NewComponentState);
export const NewComponentProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(ComponentReducer, NewComponentState);
const addComponent = (component: any) => {
dispatch({
type: "ADD_COMPONENT",
payload: component
});
};
const deleteComponent = (id: any) => {
dispatch({
type: "DELETE_COMPONENT",
payload: id,
});
};
return (
<NewComponentContext.Provider
value={{ components: state.components, deleteComponent, addComponent }}
>
{children}
</NewComponentContext.Provider>
);
};
The Note component that I've been using to test this
import { Menu,Transition } from "@headlessui/react";
import React, { useState, Fragment, useContext } from "react";
import NoteColorChanger from "./NoteColor";
import Draggable from 'react-draggable';
import { NewComponentContext } from "../../../Context/NewComponentContext";
interface INote {
id: any
}
const Note: React.FC <INote> = ({ id }) => {
const [content, setContent] = useState<string>()
const [title, setTitle] = useState<string>()
const [color, setColor] = useState<any>()
const [position, setPosition] = useState<any>({x: 0, y: 0})
const { components, deleteComponent } = useContext(NewComponentContext)
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setContent(event.target.value)
};
const handleColor = (notecolor: any) => {
setColor(notecolor)
}
const trackPosition = (pos:any) => {
setPosition({x: pos.x, y: pos.y})
}
const deleteNote = () => {
deleteComponent(id)
}
return (
<div className={`${color} h-64 w-64 bg-yellow-200 text-black rounded-lg p-2 shadow-lg`}>
<div className="flex justify-between items-center pb-6">
<h1 className="font-bold font-Inter">Note</h1>
<Menu>
<Menu.Button>
<div className={`hover:${color} p-1 rounded-lg ease-in-out duration-100`}>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1}
d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z"
/>
</svg>
</div>
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items
as="div"
className={`bg-gray-100 font-Inter w-64 shadow-lg rounded-lg absolute translate-y-24 -translate-x-2 z-50`}
>
<Menu.Item>
{({ active }) => (
<div
id="color"
className={` flex items-center py-2 px-3 rounded-lg w-full`}
>
{<NoteColorChanger handleColor={handleColor}/>}
</div>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<button
id="Todo"
onClick={() => console.log(id)}
className={`${
active ? "bg-blue-500 text-white" : "text-black"
} flex items-center py-2 px-3 rounded-lg w-full`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 mr-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
Edit Title
</button>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<li
onClick={deleteNote}
className={`${
active ? "bg-blue-500 text-white" : " text-black"
} flex items-center py-2 px-3 cursor-pointer rounded-lg`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 mr-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
Delete Note
</li>
)}
</Menu.Item>
</Menu.Items>
</Transition>
</Menu>
</div>
<textarea
className={`${color} bg-yellow-200 font-Inter w-full h-48 border-none focus:border-none focus:ring-0 resize-none`}
onChange={() => {handleChange}}
/>
</div>
);
};
export default Note;
Menu where the components are created
import React, { useContext, Fragment, useState } from "react"
import { NewComponentContext } from "../../Context/NewComponentContext"
import { Menu, Transition } from '@headlessui/react'
import Note from "./Note/Note";
import TodoList from "./Todo/TodoList";
import Photo from "./Photo/Photo";
const NewComponentMenu = () => {
const { addComponent } = useContext(NewComponentContext)
const newComponent = (componentType: number) => {
addComponent({id: Math.floor(Math.random() * 100000000), componentType: componentType})
}
return (
<div className="w-6 h-6 mt-4 ml-4 shadow-md text-gray-800 font-Inter z-50">
<Menu>
<Menu.Button>
<div className="p-1 rounded-lg bg-blue-500 hover:bg-blue-600 ease-in-out duration-100">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 text-blue-50"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z"
clipRule="evenodd"
/>
</svg>
</div>
</Menu.Button>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items as="div" className="w-60 shadow-lg rounded-lg bg-white">
<h1 className="text-center font-Inter text-2xl pb-2">Items</h1>
<Menu.Item>
{({ active }) => (
<button
id="Todo"
onClick={() => newComponent(1)}
className={`${
active ? "bg-blue-500 text-white" : "text-black"
} flex items-center py-2 px-3 rounded-lg w-full`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 mr-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
/>
</svg>
Todo list
</button>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<li
//onClick={() => setComponent(<Moodboard />) }
className={`${
active ? "bg-blue-500 text-white" : " text-black"
} flex items-center py-2 px-3 cursor-pointer rounded-lg`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 mr-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M14.828 14.828a4 4 0 01-5.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
Mood Board
</li>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<li
onClick={() => newComponent(2) }
className={`${
active ? "bg-blue-500 text-white" : " text-black"
} flex items-center py-2 px-3 cursor-pointer rounded-lg`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 mr-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
Image
</li>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<li
onClick={() => newComponent(3)}
className={`${
active ? "bg-blue-500 text-white" : " text-black"
} flex items-center py-2 px-3 cursor-pointer rounded-lg`}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 w-6 mr-3"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
/>
</svg>
Note
</li>
)}
</Menu.Item>
</Menu.Items>
</Transition>
</Menu>
</div>
);
};
export default NewComponentMenu;
component where the menu items are created
import React, { useContext } from "react";
import { NewComponentContext } from "../Context/NewComponentContext";
import NewComponentMenu from "./NewComponents/NewComponentMenu";
import Note from "./NewComponents/Note/Note";
import Photo from "./NewComponents/Photo/Photo";
import TodoList from "./NewComponents/Todo/TodoList";
const Board = () => {
const { components } = useContext(NewComponentContext);
const componentList = components.map((component, i) => {
if (component.componentType == 1) {
return (
<div key={i}>
<TodoList id={component.id} />
</div>
);
}
else if (component.componentType == 2) {
return (
<div key={i}>
<Photo id={component.id} />
</div>
)
}
else {
return (
<div key={i}>
<Note id={component.id} />
</div>
)
}
});
return (
<div className="flex space-x-10 mt-8">
<NewComponentMenu />
<div className="grid grid-cols-6 gap-8">{componentList}</div>
</div>
);
};
export default Board;
A: It is really a good practice to use key attribute while rendering a collection, it helps react to rerender collections of components correctly. So i can assume you should try to add unique key attribute to the place, where you render Note component, e.g <Note key={'some unique id'} />
A: There is an issue with your delete case in reducer. You are not returning the boolean, so no items will be returned,
case "DELETE_COMPONENT":
return {
...state,
components: state.components.filter(
(component: any) => {
console.log(component.id, action.payload)
console.log(component.id !== action.payload)
return component.id !== action.payload // here is the fix
})
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68942377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: expand div onClick Hello i am trying to make an expandable div when i'm clicking on a button:
and i want to make the animation with steps, the first step is clicking on the button, the second one the div width expand, and the step 3 the div height expand for get the full page.
and the text inside the div have to change like hide the first text and display the second one when the steps are finish
Anyone have an idea how to do it?
There is a sketch of the steps i want to make:
A: requires jQuery animate
$('.blue').click(function(){
//expand red div width to 200px
$('.red').animate({width: "200px"}, 500);
setTimeout(function(){
//after 500 milliseconds expand height to 800px
$('.red').animate({height:"800px"}, 500);
},500);
setTimeout(function(){
//after 1000 milliseconds show textarea (or textbox, span, etc)
$('.red').find('input[type="textarea"]').show();
},1000);
});
A: This can be done really easily with CSS. This video explains it very well. There are a ton of other neat tricks in that video, but I linked to the part where she explains a light box.
.container {
padding: 100px;
}
.red,
.blue {
width: 20px;
height: 20px;
float: left;
background-color: blue;
}
.red {
background-color: red;
font-size: 0;
color: white;
width: 50px;
transition: 1s height, 1s margin, 1s font-size, 1s 1s width;
}
.blue:focus ~ .red {
height: 100px;
width: 150px;
font-size: inherit;
margin-top: -40px;
transition: 1s width, 1s 1s height, 1s 1s margin, 1s 1s font-size;
}
.red .hint {
font-size: 14px;
padding: 4px;
transition: 1s 1s font-size;
}
.blue:focus ~ .red .hint {
font-size: 0;
transition: 1s font-size;
}
<div class="container">
<div class="blue" tabindex="-1"></div>
<div class="red"><span class="hint">text1</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt</div>
</div>
A: $(window).load(function(){
$(".blue").click(function(){
$(".red").animate({width:'400px'},1000).animate({height:'400px',top:'150px'},1000).text("qwqwqwq");
})
})
` .blue{
width: 100px;
height: 100px;
background-color: blue;
}
.red{
width:200px;
height:100px;
background-color: red;
left:100px;
}
div{
display: inline-block;
margin:0;
padding: 0;
position: absolute;
top:300px;
}`
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30402207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Count numbers and display a alert dialog I'm trying to create a timer here
How do I create a jscript to count from 1 to 60 and to use alert when I've reached 30 using for loop and while loop method
A: what about this
for( var i = 1;i<=60;i++)
{
if(i == 30){
alert("value is:"+i);
}
}
A: both answers are count from 0 to 59.
Op want to count from 1 to 60
So,
for(i=1; i<=60;i++)
if(i==30) alert(i);
i=1;
while(i<=60){
if(i==30) alert(30);
i++;
}
A: // using for loop
for (i = 0; i < 60; i++) {
if (i === 30) {
alert('reached 30');
}
}
// using while loop
var c=0
while (c < 60) {
if (c === 30) {
alert('reached 30');
}
c++;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42406433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: ValueError: check_hostname requires server_hostname I was going to install pandas and epanettools on my computer using the code shown below with python 3.8.5 and I received one Error exception.
Code:
pip install epanettools
pip install pandas
Actually, I could install epanettools on my old computer and I bought a new computer and I wanted to do the same thing on my new computer, but it didn't work and the error exception shown below after running the code shown above:
Error: Exception:
ERROR: Exception:
Traceback (most recent call last):
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\base_command.py", line 180, in _main
status = self.run(options, args)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\cli\req_command.py", line 204, in wrapper
return func(self, options, args)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\commands\install.py", line 318, in run
requirement_set = resolver.resolve(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 127, in resolve
result = self._result = resolver.resolve(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 473, in resolve
state = resolution.resolve(requirements, max_rounds=max_rounds)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 341, in resolve
name, crit = self._merge_into_criterion(r, parent=None)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _merge_into_criterion
if not criterion.candidates:
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 139, in __bool__
return bool(self._sequence)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in __bool__
return any(self)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 129, in <genexpr>
return (c for c in iterator if id(c) not in self._incompatible_ids)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 30, in _iter_built
for version, func in infos:
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 258, in iter_index_candidate_infos
result = self._finder.find_best_candidate(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 879, in find_best_candidate
candidates = self.find_all_candidates(project_name)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 824, in find_all_candidates
page_candidates = list(page_candidates_it)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates
yield from self._candidates_from_page(self._link)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\package_finder.py", line 783, in process_project_url
html_page = self._link_collector.fetch_page(project_url)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 512, in fetch_page
return _get_html_page(location, session=self.session)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 422, in _get_html_page
resp = _get_html_response(url, session=session)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\index\collector.py", line 120, in _get_html_response
resp = session.get(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 555, in get
return self.request('GET', url, **kwargs)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_internal\network\session.py", line 449, in request
return super().request(method, url, *args, **kwargs)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\cachecontrol\adapter.py", line 53, in send
resp = super(CacheControlAdapter, self).send(request, **kw)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\requests\adapters.py", line 439, in send
resp = conn.urlopen(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 696, in urlopen
self._prepare_proxy(conn)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connectionpool.py", line 964, in _prepare_proxy
conn.connect()
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 359, in connect
conn = self._connect_tls_proxy(hostname, conn)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\connection.py", line 500, in _connect_tls_proxy
return ssl_wrap_socket(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 432, in ssl_wrap_socket
ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py", line 474, in _ssl_wrap_socket_impl
return ssl_context.wrap_socket(sock)
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "c:\users\ziyuan\appdata\local\programs\python\python38\lib\ssl.py", line 997, in _create
raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname
Could you please tell me how to resolve this error? Appreicate a lot if any advices!
A: I fixed the problem.
Go to --> windows setting --> Network& Internet --> Proxy --> Switch Turn on (Use a Proxy server) to Turn Off
A: Are you using proxy software, like V2ray, SSR...?
If so, close the software, and try again.
A: On Linux, the problem can be resolved by replacing https with http in the proxy settings environment variable export https_proxy=http://123.123.123.123:8888. Note, it is proxy settings for https, but an http address is used.
A: So far no one has suggested that the pip version is one of the culprits as well.
If your virtual environment is having a recent version of pip (e.g. 21.3.1), try to download the older version same as the one installed in the main python directory (e.g. pip version 19.0.3).
For Windows, copy it to the venv\Lib\site-packages folder and unzip the contents, then cd into that folder then enter the commands python setup.py install to downgrade the pip version.
A: SSL Trust Issues:
pip install numpy -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
https://jhooq.com/pip-install-connection-error/
A: On windows,the problem can be resolved by add 'pypi.org' to the proxy whitelist in the proxy settings
A: maybe you can try to replace ip to proxy server hostname if commands run in unix and you know server hostname
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67297278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Unusual behavior with std::vector I've written a rather complicated set of classes to deal with iterating over a stream (string, file or memory). These are NOT std streams nor are they related. Anyway, due to iterating over these buffers and performing actions depending on the buffer, I want to be able to see the current buffer position in the debugger. So, for debug reasons only, I copy the whole stream to a vector and hold a pointer to a position in this vector.
The following code acts like a forward iterator. I need to be able to store a position and later either use it or update it. Please note, this code is only to duplicate the problem.
class foo
{
public:
foo ( std::string szTemp )
: nOffset( 0 )
{
vec.resize( szTemp.size() );
std::memcpy( &vec[ 0 ], szTemp.c_str(), szTemp.size() );
pChar = &vec[ 0 ];
}
foo( const foo & Other )
: vec( Other.vec )
, nOffset( Other.nOffset )
{
pChar = &vec[ nOffset ];
}
void Inc ( void )
{
++nOffset;
pChar = &vec[ nOffset ];
}
size_t nOffset;
char * pChar;
std::vector< char > vec;
};
int _tmain ( int argc, _TCHAR* argv[] )
{
foo a( "This is a temp string" );
a.Inc();
{
foo b = a;
b.Inc();
a = b;
} // Here is where the problem is seen
a.Inc();
}
Problem, after copying b back to a then stepping out, the value of b.pChar becomes illegal.
As I understand it, b copies the vector from a, then a in turn copies it back from b. Since I set the value of pChar after this copy, it 'should' always point to something. But, it's acting like the vector is being destroyed.
What's going on?
A: {
foo b = a;
b.Inc();
a = b;
} // Here is where the problem is seen
Your problem is here.
a = b;
request a call to assignment operator, that you are don't implement, so, default one will do memberwise-assignment. After this, your char pointer will be dangling pointer. Following code will do correct work.
class foo
{
public:
foo ( std::string szTemp )
: nOffset( 0 )
{
vec.resize( szTemp.size() );
std::memcpy( &vec[ 0 ], szTemp.c_str(), szTemp.size() );
pChar = &vec[ 0 ];
}
foo( const foo & Other )
: vec( Other.vec )
, nOffset( Other.nOffset )
{
pChar = &vec[ nOffset ];
}
foo& operator = (const foo& other)
{
foo tmp(other);
swap(tmp);
return *this;
}
void Inc ( void )
{
++nOffset;
pChar = &vec[ nOffset ];
}
void Swap(foo& other)
{
std::swap(vec, other.vec);
std::swap(nOffset, other.nOffset);
std::swap(pChar, other.pChar);
}
size_t nOffset;
char * pChar;
std::vector< char > vec;
};
A: Your class doesn't follow the rule of three. You have a custom copy constructor, but not a custom assignment operator (and no custom destructor, but this particular class probably doesn't need it). Which means foo b = a; does what you want (calls your copy ctor), but a = b; does not (calls the default assignment op).
A: As mentioned in the other two answers, aftert he assignment a = b, a.pChar points into b.vec, and since b has left scope, it is a dangling pointer.
You should either obey the rule of three (rule of five with C++11's move operations), or make that rule unnecessary by avoiding the storage of pChar, since that seems to be just a convenience alias for offset:
class foo
{
public:
foo ( std::string szTemp )
: nOffset( 0 )
{
vec.resize( szTemp.size() );
std::coyp( begin(szTemp), end(szTemp), begin(vec) );
}
//special members:
foo(foo const&) = default;
foo(foo&&) = default;
foo& operator=(foo const&) = default;
foo& operator=(foo&&) = default;
~foo() = default;
void Inc ( void )
{
++nOffset;
}
char* pChar() //function instead of member variable!
{
return &vec[nOffset];
}
size_t nOffset;
std::vector< char > vec;
};
This way, pChar() will always be consistent with nOffset, and the special members can be just defaulted (or omitted completely).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17102840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: DocuSign API return URL that transfers control back from WebView to React-Native app after redirection I am using React-Native to build an Android application. I am also using the DocuSign Java API.
My workflow submits a RecipientViewRequest and receives a URL that the android app must view within a WebView to perform the signing:
https://github.com/docusign/docusign-rest-recipes/blob/master/core_recipes/CoreRecipes.java
https://facebook.github.io/react-native/docs/webview.html
This is the code:
'use strict';
var React = require('react-native');
var {
StyleSheet,
View,
WebView,
Component,
} = React;
class DocuSignView extends Component {
render() {
var recipientViewURL = this.props.route.data.url;
console.log('Recipient URL is: ' + recipientViewURL);
return (
<View style={styles.container}>
<WebView
source={{uri: recipientViewURL, method: 'GET'}}
scalesPageToFit={true}
javaScriptEnabled={true}
domStorageEnabled={true}
>
</WebView>
</View>
);
}
}
The DocuSign servers redirect the WebView to a returnURL that I provide.
How can I specify a returnURL that will return control back to my React-Native android application?
(A generic answer for React-Native either iOS or Android would be even better).
A: One option is to use the onNavigationStateChange event handler to intercept and seize control from the WebView:
render() {
var recipientViewURL = this.props.route.data.url;
console.log('Recipient URL is: ' + recipientViewURL);
return (
<View style={styles.container}>
<WebView
source={{uri: recipientViewURL, method: 'GET'}}
scalesPageToFit={true}
javaScriptEnabled={true}
domStorageEnabled={true}
onNavigationStateChange={this.whenNavigationStateChanges.bind(this)}
>
</WebView>
</View>
);
}
whenNavigationStateChanges(navState){
var navigator = this.props.navigator;
var parsed = Url.parse(navState.url, true);
if (parsed.hostname == 'YOUR_HOSTNAME'){
console.log("Event is: " + parsed.query.event);
navigator.pop();
}
}
A: You will need to configure Custom URL Schemes.
For Android: http://developer.android.com/training/basics/intents/filters.html
For iOS: http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36216486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Offset commit failed on partition Kafka consumer continues to print error messages
I built a cluster (kafka version 2.3.0) using 5 machines kafka, which has a partition with a partition of 0 and a data copy of 3. When I consume the kafka-clients api, I continue to output exceptions:
Offset commit failed on partition test-0 at offset 1: The request timed out.
But this topic reads and writes messages are fine.
Consumer configuration:
Auto.commit.interval.ms = 5000
Auto.offset.reset = latest
Bootstrap.servers = [qs-kfk-01:9092, qs-kfk-02:9092, qs-kfk-03:9092, qs-kfk-04:9092, qs-kfk-05:9092]
Check.crcs = true
Client.id =
Connections.max.idle.ms = 540000
Default.api.timeout.ms = 60000
Enable.auto.commit = true
Exclude.internal.topics = true
Fetch.max.bytes = 52428800
Fetch.max.wait.ms = 500
Fetch.min.bytes = 1
Group.id = erp-sales
Heartbeat.interval.ms = 3000
Interceptor.classes = []
Internal.leave.group.on.close = true
Isolation.level = read_uncommitted
Key.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
Max.partition.fetch.bytes = 1048576
Max.poll.interval.ms = 300000
Max.poll.records = 500
Metadata.max.age.ms = 300000
Metric.reporters = []
Metrics.num.samples = 2
Metrics.recording.level = INFO
Metrics.sample.window.ms = 30000
Partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]
Receive.buffer.bytes = 65536
Reconnect.backoff.max.ms = 1000
Reconnect.backoff.ms = 50
Request.timeout.ms = 30000
Retry.backoff.ms = 100
Sasl.client.callback.handler.class = null
Sasl.jaas.config = null
Sasl.kerberos.kinit.cmd = /usr/bin/kinit
Sasl.kerberos.min.time.before.relogin = 60000
Sasl.kerberos.service.name = null
Sasl.kerberos.ticket.renew.jitter = 0.05
Sasl.kerberos.ticket.renew.window.factor = 0.8
Sasl.login.callback.handler.class = null
Sasl.login.class = null
Sasl.login.refresh.buffer.seconds = 300
Sasl.login.refresh.min.period.seconds = 60
Sasl.login.refresh.window.factor = 0.8
Sasl.login.refresh.window.jitter = 0.05
Sasl.mechanism = GSSAPI
Security.protocol = PLAINTEXT
Send.buffer.bytes = 131072
Session.timeout.ms = 10000
Ssl.cipher.suites = null
Ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
Ssl.endpoint.identification.algorithm = https
Ssl.key.password = null
Ssl.keymanager.algorithm = SunX509
Ssl.keystore.location = null
Ssl.keystore.password = null
Ssl.keystore.type = JKS
Ssl.protocol = TLS
Ssl.provider = null
Ssl.secure.random.implementation = null
Ssl.trustmanager.algorithm = PKIX
Ssl.truststore.location = null
Ssl.truststore.password = null
Ssl.truststore.type = JKS
Value.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
java code:
ConsumerRecords<K, V> consumerRecords = _kafkaConsumer.poll(50L);
for (ConsumerRecord<K, V> record : consumerRecords.records(topic)) {
kafkaConsumer.receive(topic, record.key(), record.value(), record.partition(), record.offset());
}
I have tried the following:
*
*Increase request timeout to 5 minutes (not working)
*Replaced another group-id (it work): I found that as long as I use this group-id, there will be problems.
*Kill the machine where the group coordinator is located. After the group coordinator switches to another machine, the error remains.
I get continuous error message output in the console
2019-11-03 16:21:11.687 DEBUG org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-1, groupId=erp-sales] Sending asynchronous auto-commit of offsets {test-0=OffsetAndMetadata{offset=1, metadata=''}}
2019-11-03 16:21:11.704 ERROR org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-1, groupId=erp-sales] Offset commit failed on partition test-0 at offset 1: The request timed out.
2019-11-03 16:21:11.704 INFO org.apache.kafka.clients.consumer.internals.AbstractCoordinator - [Consumer clientId=consumer-1, groupId=erp-sales] Group coordinator qs-kfk-04:9092 (id: 2147483643 rack: null) is unavailable or invalid, will attempt rediscovery
2019-11-03 16:21:11.705 DEBUG org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-1, groupId=erp-sales] Asynchronous auto-commit of offsets {test-0=OffsetAndMetadata{offset=1, metadata=''}} failed due to retriable error: {}
org.apache.kafka.clients.consumer.RetriableCommitFailedException: Offset commit failed with a retriable exception. You should retry committing the latest consumed offsets.
Caused by: org.apache.kafka.common.errors.TimeoutException: The request timed out.
2019-11-03 16:21:11.708 DEBUG org.apache.kafka.clients.NetworkClient - [Consumer clientId=consumer-1, groupId=erp-sales] Manually disconnected from 2147483643. Removed requests: OFFSET_COMMIT.
2019-11-03 16:21:11.708 DEBUG org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient - [Consumer clientId=consumer-1, groupId=erp-sales] Cancelled request with header RequestHeader(apiKey=OFFSET_COMMIT, apiVersion=4, clientId=consumer-1, correlationId=42) due to node 2147483643 being disconnected
2019-11-03 16:21:11.708 DEBUG org.apache.kafka.clients.consumer.internals.ConsumerCoordinator - [Consumer clientId=consumer-1, groupId=erp-sales] Asynchronous auto-commit of offsets {test-0=OffsetAndMetadata{offset=1, metadata=''}} failed due to retriable error: {}
org.apache.kafka.clients.consumer.RetriableCommitFailedException: Offset commit failed with a retriable exception. You should retry committing the latest consumed offsets.
Caused by: org.apache.kafka.common.errors.DisconnectException: null
*
*Why did the submission of the offset fail?
*Why is the offset information in the kafka cluster still correct when the submission fails?
Thank you for your help.
A: Group coordinator Unavailability is the main cause of this issue.
Group coordinator is Unavailable --
This issue is already raised in the KAFKA Community (KAFKA-7017).
You can fix this by deleting the topic _offset_topics and restart the cluster.
You can go through the following to get few more details.
https://www.stuckintheloop.com/posts/my_first_kafka_outage/
A: @Rohit Yadav, Thanks for the answer, I have replaced a consumer group for the time being and I am working very well. But now the client has another problem, continuous output:
2019-11-05 14:11:14.892 INFO org.apache.kafka.clients.FetchSessionHandler - [Consumer clientId=consumer-1, groupId=fs-sales-be] Error sending fetch request (sessionId=2035993355, epoch=1) to node 4: org.apache.kafka.common.errors.DisconnectException.
2019-11-05 14:11:14.892 INFO org.apache.kafka.clients.FetchSessionHandler - [Consumer clientId=consumer-1, groupId=fs-sales-be] Error sending fetch request (sessionId=181175071, epoch=INITIAL) to node 5: org.apache.kafka.common.errors.DisconnectException.
What is this caused by this? 4, 5 node status is OK
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58678704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: spritenode child/parent I have a skspritenode(ship) that is the parent node then it has a child skspritenode(gun) that rotates freely. The gun has a child called skspritenode(bullet). The bullet shoots from the gun in the direction the gun is facing and that is perfct.
The problem is when the ship moves or if the turret rotates after a bullet is fired the bullet moves and rotates with the ship and gun. Is there anyway to prevent this from happening?
A: Add the bullets to the ship's parent (or directly to the scene), just not the ship or the turret because that will make the position of the bullet relative to either one.
A: Think of it this way: the ship is facing in a specific direction when it fires the bullet.
Once it fires the bullet, you wouldn't expect it to have any control over the bullet? If it turned around, the bullet should keep moving in the same direction (not stay directly in front of the ship).
This is a hint that the bullet should probably not have the ship as a parent node; it is an entity existing alongside the ship and not as part of it.
Once the bullet is fired, it should be in the same 'system' as the ship, so as @LearnCocos2D suggested it should share a parent with the ship.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20428634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I write BLOBs in android FAST? I have an app that downloads many images that are about 50k to 100k in size. The full database can be anywhere from 50MB to 500MB.
We are currently using sqlite, but it has slow inserts. We did a test writing files and that was slow as well. It seems to be taking about 300 to 800ms per image to write - which comes out to about 250kb/sec (slower than the network speed). I did a benchmark with A1 benchmark and it says my write speed is 14MB/sec, so i'm not sure why my app is so slow?
Here are the primary requirements:
1) Fast writes
2) Fast reads/lookups via an custom integer key (this can be converted a file path for individual files)
3) Prevents user from easily accessing the images (if we save as images they can connect the external storage to their computer and browser, but we can write the files in reverse byte order)
hopefully we can still use the sqllite solution, as i like one file, but either way it seems like a storage issue?
A: As suggested in the comments, I think you are better off using the private memory storage for the actual images. This will have better speed then storing BLOBs in SQLite.
If you still need to keep a DB, for example for complex image searches or such, I suggest you just replace the BLOB field in your DB with a string with the actual location of the image file.
Another solution is to keep the images as app assets, but this assumes the images are always the same and can't change dynamically, and I doubt this is your use case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32142676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how to represent web form variables in a form when submitted using Spring webmvc? I've been using using @ModelAttribute to "cast" my form variables into a class (which represents a table in the database) and this has worked quite nicely.
But I'm working on another form and I need to have a hidden field in the form that doesn't represent data in the database. I'm just passing it for the business logic section of my code.
How do I access this hidden field now in my function? I don't want to edit my table class to add this new field as that seems bad programming. And I know I can create a new class that just contains the all the fields in my form but I'm unsure if that is the best way to go.
thanks! :)
These are what I have right now(only has table fields but works).
my jsp page
<form:form modelAttribute="fab" method="post" action="SaveEventRegistration.html">
my java code to accept form submission
@RequestMapping("/SaveEventRegistration")
public ModelAndView saveEventRegistration(@ModelAttribute Fab fab) {
System.out.println(fab.getStudentId());
A: You don't need to change the table and its pojo. To get the hidden fields values those are not available to be bind in your ModelAttribute object, you can just simply declare that hidden field in the jsp inside your form with html input tag and make it hidden with required value.
Now in the controller function you need to have a parameter HttpServletRequest request and get the value of your hidden field say with name hdParam with request.getParameter("hdParam").
I hope this helps you. Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14744113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: acessing network shared folder with a username and password string in vb.net i am using the following code to read the details from a network folder which is restricted for only one user
shell("net use q: \\serveryname\foldername /user:admin pwrd", AppWinStyle.Hide, True, 10000)
Process.Start(path)
shell("net use q: /delete")
when i run this to open any pdf or jpg or any other files except word/excel/powerpoint, everything is working fine. but the problem comes only when i access a word file.
in the step one, i am giving permission to access the word file.
in the step two, word file is open.
in the third, i am deleting the q drive.
the problem is the word file is still open. so i am getting a dos window, saying that "some connections of still connected or searching some folders, do you want to force disconnect"
please help.... how to access a word file (editable files) providing user name and password from the code and at the same time he shoud not have access to any other folders directly.
A: Why not just copy the word file to the local drive, then close the share and then open the file.
Though I'd suggest that it might be worth looking at some other kind of access control. This seems fairly unsafe (for example, what if your process crashes after the first command but before the second, then the share would be left open for anyone to use).
A: This seems like a really bad way to do it. There are a number of problems with it:
*
*As you discovered, Word keeps the file open for as long as you're using the file, so you can't just pull the share out from under it.
*You cannot reliably know when Word has finished with the file (for example, you can't just wait for the process to exit, because it might just be a wrapper that starts up for a second, notify the "original" word process to open the file and exits)
*Even if you could reliably detect when word had finished using the file, the fact that you had the share open the whole time seems to contradict your requirement to lock it down in the first place
*I assume you don't have the password hard-coded like that, but if you do then it's trivial for someone to just open up your executable and find out the password.
Perhaps if you tell us why you're trying to do this, we can suggest a better way, but if all you want to do is provide read-only access to the file (which seems to be the case) then you can just grant read-only access on the share itself: no need for this complicated process at all!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2727447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to build project with CoreData classes I am trying to migrate my sandpit code into my main project but for some reason I am getting the following strange error when trying to compile
syntax error before 'NSManagedObjectModel'
At first I thought this was because coredata wasnt in the prefix.pch file but I have added it in there too.
This is the top of AppDelegate where the code is being used (straight out of an Apple example)
#import <UIKit/UIKit.h>
#import "AppSettings.h"
#import "Skin.h"
@interface JeanieAppDelegate : NSObject <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
A: #import <CoreData/CoreData.h> and don't forget to link it in.
A: Also, beware adding just anything to your .pch file. When you do so, those header files will be included all throughout your projectYou should only really put things there that are truly going to be universally required all through your project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2159482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I am fetching data from api in react using useeffect hook.But its getting called multiple times.But i need to call it once I am fetching data from api in react using useeffect hook.But its getting called multiple times.But i need to call it once.Can anyone tell how to achieve that?
I tried using useeffect hook
const getData = () => {
fetch("https://countriesnow.space/api/v0.1/countries/capital")
.then((response) => {
return response.json();
})
.then((data) => {
scname(data.data);
});
};
useEffect(() => {
getData();
}, []);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74374617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WooCommerce bug iPhone 7 plus iOS 10.3.* I am developing a website (WordPress + WooCommerce). When I tested the website on mobile (iPhone7+ with iOS 10.3), I found two bugs.
*
*custom loading symbol can't work (use svg with animation).
*when add a item into cart. It show 2 items and can't add more items into cart as well.
The website works all devices except iPhone with IOS 10.3. I also test on Iphone6 with version 10.2 and it works normally, then the phone is updated to 10.3 for testing, it got same problems. Therefore, I guess that the problem is from iOS.
Does anyone test WooCommerce website on iPhone with iOS 10.3?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44283176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding a datasource to Codesmith I am trying to add a DataSource to Codesmith 7.1.0 rev 15317
This is a new install on a Windows 10 box.
I keep getting the error
Test Failed. Arithmetic operation resulted in an overflow.
I have done this many times on my old win8 box.
The provider I am using is SqlSchemaProvider (SQL Server)
This is the connection string
Data Source=localhost;InIitial Catalog=gregsData;Persist Security Info=True;User ID=sa;Password=catdog;
I have tried using the string builder, copying from my app where I know it is working, adding and deleting various parts.
I have an issue open w/ CodeSmithTools, but not making a lot of progress.
Is anyone using CodeSmith w/ windows 10? It has to work right? This cant be a bug.
Has anyone had a similar issue?
A: I have no idea what resolved this. maybe a reboot? maybe some odd update.
I came in one monday and it started working.
A: I can not find an answer anywhere.
uninstalled and reinstalled...again. No luck.
I finally had the ODBC idea. I created an ODBC datasource, then used that using the ADOXSchemaProvider.
This works.
Not great, but this beats coding by hand, and for now, it beats converting all my templates to something else.
here is a sample ODBC connection string if you need to go this route.
DSN=myDsn;Uid=myUsername;Pwd=mypwd;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34191825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP mailer not validating after sending a second email This is an updated msg's with a working code for sending two different emails using php mailer. It also has working validation server site.
You need to create you own mail class or use the normal one.
Hope someone else can use it two!
Thank you!!
<?php
require"validation.php";
ob_start();
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
$info_email= 'example@example.com';
$info_name = 'Example';
require"PHPMailer/mail.inc.php";
$cams="$name has just made a comment or posted a question";
$camb= "<html>
<head>
<h3> $name has asked the following question or comment on you website:</h3>
</head>
<body>
$comments <br><br><br>
Their information: <br><br>
<table cellspacing=\"4\" cellpadding=\"4\" border=\"1\">
<tr>
<td align=\"center\">Name:</td>
<td align=\"center\"> $name</td>
</tr>
<tr>
<td align=\"center\">Email:</td>
<td align=\"center\"> $email</td>
</tr>
</table>
<br>
<img src=\"cid:mailhead\" alt=\"shop logo used in emails\" />
Pleasy try to reply as soon as possible.<br>
Thank you!!
</body>
</html>";
$mail = new MailCon;
$mail->IsSMTP();
$mail->isHTML(true);
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress($info_email, $info_name);
$mail->Subject = $cams;
$mail->MsgHTML($camb);
if ($mail->Send()) {
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->ClearCustomHeaders();
$cums = 'Thank you for using our contact form.';
$message = file_get_contents('mail/example.html');
$message = str_replace('%username%', $name, $message);
$message = str_replace('%email%', $email, $message);
$message = str_replace('%comments%', $comments, $message);
$alt_body="Thank you for asking us a question or making a comment. We will reply as soon as possible.";
$mail = new MailCon;
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->From = $info_email;
$mail->FromName = $info_name;
$mail->AddAddress($email, $name); // Add a recipient
$mail->Subject = $cums;
$mail->MsgHTML($message);
$mail->AltBody = $alt_body;
$mail->Send();
}
ob_end_flush();
?>
This is the validation bit wich you can include using require once.
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$comments = $_POST['comments'];
if (strlen($name) < 2) {
$error['name'] = "Please enter your name";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address";
}
if (strlen($comments) < 3) {
$error['comments'] = "Please leave a comment.";
}
if (!$error) {
echo "<div class='alert-box success'>Thanks " . $name . ". Your message has been sent.<a href='' class='close' onclick='clearForms()'>×</a></div>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<div class='alert-box alert'>" . $error['name'] . "</div> \n" : null;
$response .= (isset($error['email'])) ? "<div class='alert-box alert'>" . $error['email'] . "</div> \n" : null;
$response .= (isset($error['comments'])) ? "<div class='alert-box alert'>" . $error['comments'] . "</div>" : null;
echo $response;
exit();
} # end if there was an error sending
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21243892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android SQLite take the first element from database column I am working on a project and created a database with SQLite. In my database I have just two columns, column names are r_id and m_id. I want to take the first element of the r_id and assign it in to a string. The elements of the r_id column is like 1, 2, 3.. in this situation my String has to be 1.
My code; creating a db query:
There is no problem I can add data correcly.
my_table = "CREATE TABLE "my_table"("r_id" Text, "m_id" Text);";
db.execSQL(my_table );
Code to take the first element of the column;
public String getSetting() {
String result = "";
String[] columns = {"r_id"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(true, "r_id", columns, "row", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
databaseHelper.close();
return result;
}
The error I am getting:
android.database.sqlite.SQLiteException: no such column: row (code 1 SQLITE_ERROR): , while compiling: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
A: The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row".
Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code.
So your query (translated in SQL) is:
SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
which is invalid.
But you don't need a WHERE clause if you want just the min value of the column r_id.
You can do it with a query like:
SELECT MIN(r_id) AS r_id FROM my_table
without DISTINCT and a WHERE clause.
Or:
SELECT r_id FROM my_table ORDER BY r_id LIMIT 1;
So your java code should be:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null);
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
I used rawQuery() here instead of query().
Or:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1");
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66785116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Add field to json in Postman I recieve json object as a response from a service (request 1).
I need to add extra field to it and to send it again (lets' call it "request 2").
I have applied this code to responseBody of "request 1":
var jsonData=JSON.parse(responseBody);
jsonData.back_uri= "http:\/\/192.168.2.3\/newpage\/";
I can't make postman add new node to top level of json, new field every time get node2 as a parent. I need new field to be next to "field11" or "field1".
Here is original Json from "request1"
{
"field1": 1,
"field_2": "09.28.2018",
"node1": {
"field3": 1,
"field4": "09.08.2018",
"node1-2": [
{
"field5": 1,
"field6": 1
}
]
},
"node2": {
"field7": 1,
"field8": "09.08.2018",
"node2-2": [
{
"field9": 1,
"field10": 1
}
]
},
"field11": ""
}
A: Corrently I have solved the task by cutting last } from response text and adding ,"fieldname":"value"} to the end of it. Till someone would not share a better idea, it could help somebody else.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52586352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can i remove the path from zip file I have a zip file that has a path. When I unzip the file and put it in my target folder, it then creates folders of the path.
public boolean doZip(String fileName, String zipfilename) {
boolean zipStatus = true;
try {
String[] filesToZipP = new String[1];
filesToZipP[0] = fileName;
byte[] buffer = new byte[1000];
ZipOutputStream out =
new ZipOutputStream(new FileOutputStream(zipfilename));
out.setLevel(Deflater.DEFAULT_COMPRESSION);
for (int i = 0; i < filesToZipP.length; i++) {
FileInputStream in = new FileInputStream(filesToZipP[i]);
out.putNextEntry(new ZipEntry(filesToZipP[i]));
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
}
catch (IllegalArgumentException e) {
zipStatus = false;
}
return zipStatus;
}
A: For that i simply use my own path and the name of the file.
fis = new FileInputStream(dirList[i])
ZipEntry anEntry = new ZipEntry(rootName + "/" + dirList[i].name)
zos.putNextEntry(anEntry)
with rootName = "" if your zip file does not contain any folder.
Basically your path must be relative to the root of your zip file.
I hope you understand what i mean.
A: String name = new File(filesToZipP[i]).getName();
out.putNextEntry(new ZipEntry(name));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14832522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Moving Data from Matrix A to Matrix B in R I want to cut/move/replace some data (to be precise 2500) from Matrix A to Matrix B in R.
for example Move cell(i,j) from matrix A to cell(i,j) in matrix B. both i and j have some fixed value(50 to be precise) and replace that cell(i,j) in matrix A with "0".
Since I am newto programming can anyone help me with the coding?
Thanks in Advance
Regards
A: You can first define a two column coordinate-matrix of the values you want to replace, where the first column refers is the row-index and the second column is the column-index. As an example, suppose you want to replace the cells c(2,1), c(2,2) and c(1,2) in a 3x3 matrix B with the calues from a 3x3 matrix A:
ind <- cbind(c(2,2,1), c(1,2,2))
A <- matrix(1:9, ncol = 3)
B <- matrix(NA, ncol = 3, nrow = 3)
B[ind] <- A[ind]; A[ind] <- 0
B
[,1] [,2] [,3]
[1,] NA 4 NA
[2,] 2 5 NA
[3,] NA NA NA
A
[,1] [,2] [,3]
[1,] 1 0 7
[2,] 0 0 8
[3,] 3 6 9
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29017575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Visual Studio - Outputting SQL table data to Datagridview Apologies if this has been covered. The examples I seemed to find were more complicated than I need it to be
I'm trying to output the entire contents of an SQL table to a DatagridView when a button "Display All Records" is clicked
I'm having a bit of trouble, here is what I have so far
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
Here is all my code if you need to refer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
public MainWindow()
{
InitializeComponent();
establishConnection();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Boolean postSuccess = false;
if (validation() == true)
{
SqlCommand details = new SqlCommand("INSERT INTO Student (Firstname, LastName, MatriculationNo, GradeOne, GradeTwo, GradeThree) VALUES (@FirstName, @LastName, @MatriculationNo, @GradeOne, @GradeTwo, @GradeThree)", con);
details.Parameters.AddWithValue("@FirstName", firstnameTextbox.Text);
details.Parameters.AddWithValue("@LastName", lastnameTextbox.Text);
details.Parameters.AddWithValue("@MatriculationNo", matriculationnoTextbox.Text);
details.Parameters.AddWithValue("@GradeOne", Component1Textbox.Text);
details.Parameters.AddWithValue("@GradeTwo", Component2Textbox.Text);
details.Parameters.AddWithValue("@GradeThree", Component3Textbox.Text);
con.Open();
details.ExecuteNonQuery();
postSuccess = true;
if (postSuccess)
{
MessageBox.Show("Details entered succesfully!");
firstnameTextbox.Clear();
lastnameTextbox.Clear();
matriculationnoTextbox.Clear();
Component1Textbox.Clear();
Component2Textbox.Clear();
Component3Textbox.Clear();
}
else
{
MessageBox.Show("Data not entered succesfully, please check DB connection");
}
con.Close();
}
}
private void establishConnection()
{
try
{
con.Open();
System.Diagnostics.Debug.Print("Connected to SQL database");
connectionLabel.Content = "Connected to SQL Database";
con.Close();
}
catch (Exception)
{
connectionLabel.Content = "not connected to sql database";
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
firstnameTextbox.Clear(); //Clears the first name textbox
lastnameTextbox.Clear(); //Clears the last name textbox
matriculationnoTextbox.Clear(); //Clears the Matriculation Number textbox
Component1Textbox.Clear(); //Clears the component one textbox
Component2Textbox.Clear(); //Clears the component two textbox
Component3Textbox.Clear(); //Clears the component three textbox
}
private Boolean validation()
{
if (!Regex.Match(firstnameTextbox.Text, "^[A-Z][a-zA-Z]*$").Success)
{
MessageBox.Show("Please Enter a valid First Name");
firstnameTextbox.Clear();
return false;
}
else
{
return true;
}
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
con.Open();
string sql = @"DELETE FROM Student;"; //Deleting all from Student table
SqlCommand purge = new SqlCommand(sql, con);
MessageBox.Show("Are you sure you want to purge the entire contents of the database?"); //Prompting user to make sure they want to delete
purge.ExecuteNonQuery(); //Execute purge query
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
}
}
}
Any help would be much appreciated, thank you
A: try this....
private void Button_Click_2(object sender, EventArgs e)
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataTable dt = new DataTable();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dt);
con.Close();
da.Dispose();
dataGridView1.DataSource = dt;
}
A: MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from student";
try
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
con.Close();
Try this
A: Just fill DataTable with your table and bind it to GridView.DataContext.
Like so:
First Add DataGrid in XAML editor <DataGrid Name="customDataGrid" ItemsSource="{Binding}">
then Code behind:
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable table = null;
string query = "select * from student";
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
table = new DataTable();
adapter.Fill(table);
}
}
}
catch (Exception ex)
{
//handle caught exception
}
if (table != null)
{
customDataGrid.DataContext = table.DefaultView;
}
}
}
}
Binding part: customDataGrid.DataContext = table.DefaultView;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35917841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error compiling project with NodeJs and Gulp I'm running the mvn clean install command to compile my project which is made with java in the backend and angular in the front.
I do this on Linux normally but I'm configuring the environment on windows and I'm getting errors
Error
[10:52:34] Starting '<anonymous>'...
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'D:\git\java\flextotal\src\main\webapp\build'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
[10:52:34] '<anonymous>' errored after 45 ms
[10:52:34] Error: 1
at formatError (D:\git\java\flextotal\src\main\webapp\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\format-error.js:21:10)
at Gulp.<anonymous> (D:\git\java\flextotal\src\main\webapp\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\log\events.js:33:15)
at Gulp.emit (events.js:327:22)
at Gulp.EventEmitter.emit (domain.js:467:12)
at Object.error (D:\git\java\flextotal\src\main\webapp\node_modules\undertaker\lib\helpers\createExtensions.js:61:10)
at handler (D:\git\java\flextotal\src\main\webapp\node_modules\now-and-later\lib\mapSeries.js:47:14)
at f (D:\git\java\flextotal\src\main\webapp\node_modules\once\once.js:25:25)
at f (D:\git\java\flextotal\src\main\webapp\node_modules\once\once.js:25:25)
at tryCatch (D:\git\java\flextotal\src\main\webapp\node_modules\async-done\index.js:24:15)
at done (D:\git\java\flextotal\src\main\webapp\node_modules\async-done\index.js:40:12)
[10:52:34] 'cliBuildProd' errored after 83 ms
[10:52:34] 'copyReleaseBundles' errored after 89 ms
[10:52:34] 'buildRelease' errored after 90 ms
[10:52:34] '<anonymous>' errored after 91 ms
[10:52:34] 'default' errored after 92 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! flextotal@1.0.0 build:release: `gulp --release`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the flextotal@1.0.0 build:release script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
My Gulp File
process.setMaxListeners(Number.POSITIVE_INFINITY);
const cp = require('child_process');
const gulp = require('gulp');
const del = require('del');
const browserSync = require('browser-sync');
const plugins = require('gulp-load-plugins')();
const tslint = require("tslint");
const gulpMultiProcess = require('gulp-multi-process');
const fs = require('fs');
const debug = process.argv.indexOf("--development") > -1;
const useAot = !debug; // constante usada para testes sem AOT
console.log("debug: " + debug);
const ngBuildArgs = ['build', '--deploy-url', 'dist/'];
const ngBuildArgsProd = [...ngBuildArgs, '--prod', '--extract-licenses', 'false'];
// o cli não está gerando os paths corretos sem usar extract-css
const ngBuildArgsDebug = [...ngBuildArgs];
const ngBuildArgsWatch = [...ngBuildArgsDebug, '--watch', '--no-delete-output-path', '--progress', 'false'];
if (debug) {
var localConfig = JSON.parse(fs.readFileSync('./local-config.json'));
if (!localConfig.deployPath) {
throw new Error("deployPath não definido no local-config.json");
}
if (!localConfig.applicationUrl) {
throw new Error("applicationUrl não definido no local-config.json");
}
}
// workaround pra remover reflect do build aot
// https://github.com/angular/angular-cli/issues/6325
gulp.task('processPolyfills', gulp.series(function() {
return gulp.src("app/polyfills." + (debug ? "development" : "production") + ".ts")
.pipe(plugins.rename("polyfills.ts"))
.pipe(gulp.dest("app/"));
}));
gulp.task('clean', (done) => {
del.sync(['./app.jsp', 'dist/**/*', 'dist-aot']);
done();
});
function copyAppJsp() {
const html = fs.readFileSync('./dist-aot/index.html', 'utf-8');
fs.writeFileSync('app.jsp', html);
if (debug) {
fs.writeFileSync(localConfig.deployPath + 'app.jsp', html);
}
}
gulp.task('compileDebug', gulp.series(['processPolyfills'], function(cb) {
const ng = cp.spawn(process.execPath, ngBuildArgsDebug, { stdio: 'inherit' });
ng.on('close', code => cb(code));
}));
gulp.task('copyDebugBundles', gulp.series(['compileDebug'], function() {
copyAppJsp()
return gulp.src(['dist-aot/**/*'])
.pipe(gulp.dest('dist'));
}));
gulp.task('startNgWatch', gulp.series(['processPolyfills'], function(done) {
// criamos o diretório antes pois o watch não funciona com diretórios
// inexistentes (que serão criados no ng build, e não tem como verificar quando)
fs.mkdirSync('dist-aot');
cp.spawn(process.execPath, ngBuildArgsWatch, { stdio: 'inherit' });
done();
}));
gulp.task('multiProcessBundle', gulp.series(function(cb) {
// por padrão o node executa tudo na mesma thread,
// este plugin usa child_process pra torná-lo multi processo
return gulpMultiProcess(['lint'], cb);
}));
gulp.task('watch', gulp.series(['clean', 'startNgWatch', 'multiProcessBundle'], function() {
let firstFile = true;
// plugin utilizado porque o watch padrão do gulp não detecta criação de arquivos
return plugins.watch('dist-aot/**/*', { readDelay: 500 })
.pipe(gulp.dest('dist'))
.pipe(gulp.dest(localConfig.deployPath + 'dist'))
.pipe(plugins.tap(function(file) {
if (file.path.endsWith("/index.html")) {
copyAppJsp();
}
if (firstFile) {
firstFile = false;
browserSync.init({
proxy: localConfig.applicationUrl,
browser: localConfig.browser,
ghostMode: false,
reloadDebounce: 500
});
} else {
browserSync.reload(file);
}
}));
}));
gulp.task('lint', gulp.series(function() {
var program = tslint.Linter.createProgram("./tsconfig.json");
return gulp.src('app/**/*.ts')
.pipe(plugins.tslint({
program: program
}))
.pipe(plugins.tslint.report({
allowWarnings: true
}));
}))
gulp.task('cliBuildProd', gulp.series(['processPolyfills'], function(cb) {
const ng = cp.spawn(process.execPath, ngBuildArgsProd, { stdio: 'inherit' });
ng.on('close', code => cb(code));
}));
gulp.task('copyReleaseBundles', gulp.series(['cliBuildProd'], function() {
copyAppJsp()
return gulp.src(['dist-aot/**/*', '!dist-aot/index.html'])
.pipe(gulp.dest('dist'));
}));
gulp.task('_test', gulp.series(gulp.parallel(['clean', 'copyDebugBundles', 'multiProcessBundle']), function(cb) {
const ng = cp.spawn(process.execPath, ['test', '--single-run'], { stdio: 'inherit' });
ng.on('close', code => cb(code));
}));
gulp.task('buildDebug', gulp.series(gulp.parallel(['clean', 'copyDebugBundles', 'multiProcessBundle']), function() {
return del(['dist-aot']);
}));
gulp.task('buildRelease', gulp.series(gulp.parallel(['clean', 'copyReleaseBundles', 'multiProcessBundle']), function() {
return del(['dist-aot']);
}));
gulp.task('test', gulp.series('_test', function() {
return del(['dist-aot']);
}));
function runTaskIf(condition, task) {
task = gulp.series(task) // make sure we have a function that takes callback as first argument
return function(cb) {
if (condition()) {
task(cb)
} else {
cb()
}
}
}
isDebug = function() {
return debug;
}
isRelease = function() {
return !debug;
}
gulp.task('default', gulp.parallel([
runTaskIf(isDebug, 'buildDebug'),
runTaskIf(isRelease, 'buildRelease')
]));
Something seems to have changed in Windows compared to Linux
However, I redid the environment with the same version for all installations
I would be grateful if anyone could shed some light on this matter.
I tried changes in the Gulp file and also tried deleting the package-lock.json folder and the NodeModules folder and running npm install again
but without success
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74744279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create Time Based User Sessions in R I have a dataset which consists of three columns: user, action and time which is a log for user actions. the data looks like this:
user action time
1: 618663 34 1407160424
2: 617608 33 1407160425
3: 89514 34 1407160425
4: 71160 33 1407160425
5: 443464 32 1407160426
---
996: 146038 8 1407161349
997: 528997 9 1407161350
998: 804302 8 1407161351
999: 308922 8 1407161351
1000: 803763 8 1407161352
I want to separate sessions for each user based on action times. Actions done in certain period (for example one hour) are going to be assumed one session.
The simple solution is to use a for loop and compare action times for each user but that's not efficient and my data is very large.
Is there any method that can I use to overcome this problem?
I can group users but separate on users actions into different sessions is somehow difficult for me :-)
A: Try
library(data.table)
dt <- rbind(
data.table(user=1, action=1:10, time=c(1,5,10,11,15,20,22:25)),
data.table(user=2, action=1:5, time=c(1,3,10,11,12))
)
# dt[, session:=cumsum(c(T, !(diff(time)<=2))), by=user][]
# user action time session
# 1: 1 1 1 1
# 2: 1 2 5 2
# 3: 1 3 10 3
# 4: 1 4 11 3
# 5: 1 5 15 4
# 6: 1 6 20 5
# 7: 1 7 22 5
# 8: 1 8 23 5
# 9: 1 9 24 5
# 10: 1 10 25 5
# 11: 2 1 1 1
# 12: 2 2 3 1
# 13: 2 3 10 2
# 14: 2 4 11 2
# 15: 2 5 12 2
I used a difference of <=2 to collect sessions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35957474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: expo run:android --variant release Running: expo run:android --variant release.
Getting the following error:
Package "expo-camera" does not contain a valid config plugin.
Learn more: https://docs.expo.dev/guides/config-plugins/#creating-a-plugin.
Unexpected token 'export'.
In my app.json, I added the following:
"plugins": [
"expo-camera",
"expo-av",
"expo-location",
"expo-file-system",
"expo-constants"
],
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70707345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to insert only digits in a string I have this code that should check if the user inputs 3 digits into a string variable:
std::string digits;
bool error = false;
do {
error = false;
std::cout << "Type 3 digits. (0 to 9)\n";
std::cin >> digits;
if (digits.size() != 3) {
std::cout << "\nError, you must type 3 digits.\n\n";
error = true;
}
else {
for (int i = 0; i < 3; i++) {
if (digits[i] < 0 || digits[i] > 9) {
std::cout << "\nError, you must type only digits. (0 to 9)\n\n";
error = true;
break;
}
}
}
} while (error == true);
This isn't giving any error but still it doesn't work, it correctly checks when user inserts more than 3 characters but even if the input is correct (123) it restarts the loop.
A: Try this:
#include <string>
#include <iostream>
int main() {
std::string digits;
bool error = false;
do {
error = false;
std::cout << "Type 3 digits. (0 to 9)\n";
std::cin >> digits;
if (digits.size() != 3) {
std::cout << "\nError, you must type 3 digits.\n\n";
error = true;
}
else {
for (int i = 0; i < 3; i++) {
if (!isdigit(digits[i])) {
std::cout << "\nError, you must type only digits. (0 to 9)\n\n";
error = true;
break;
}
}
}
} while (error == true);
}
This uses the function isdigit() to check if the current char is a digit.
The reason your code before wasn't working is because the char (0 for this example, as it is a digit) '0' actually has a character code different than 0. Quoting from https://www.tutorialspoint.com/ascii-nul-ascii-0-0-and-numeric-literal-0#:~:text=The%20ASCII%20NUL%20character%20is,The%20decimal%20equivalent%20is%2048
,
When programmer used '0' (character 0) it is treated as 0x30. This is a hexadecimal number. The decimal equivalent is 48.
Table of ascii chars:
https://www.techonthenet.com/ascii/chart.php
A: if (digits[i] < 0 || digits[i] > 9) is checking if digits[i] has a character value less than 0 or greater than 9. The character '0' is character 48 in most encodings Today (most notably, ASCII), so that check will not work. You should be checking if (digits[i] < '0' || digits[i] > '9') - and there is already a function that does this. std::isdigit.
You could also use the standard algorithm std::all_of to check if all chars in the string are in fact digits.
Example:
#include <algorithm> // std::all_of
#include <cctype> // std::isdigit
#include <iostream>
#include <string>
int main() {
std::string digits;
// A char to unsigned char casting lambda (to make isdigit safe)
auto isdigit_lambda = [](char ch) {
return std::isdigit(static_cast<unsigned char>(ch)) != 0; };
while(true) {
std::cout << "Type 3 digits. (0 to 9)\n";
if(not (std::cin >> digits)) {
// input failure - deal with that somehow
}
// if it has the correct size and all are digits, break out of the loop
if(digits.size() == 3 &&
std::all_of(digits.begin(), digits.end(), isdigit_lambda)) break;
std::cout << "\nError, you must type 3 digits.\n\n";
}
}
A: I tried my best to keep the code minimal:
#include <string>
#include <iostream>
#include <algorithm>
int main() {
std::string digits;
bool error = true;
while (error){
std::cout << "Type 3 digits. (0 to 9)\n";
std::cin >> digits;
if (digits.size() not_eq 3 and (error = true))
std::cout << "\nError, you must type 3 digits.\n";
else if(std::any_of(digits.begin(), digits.end(), [](const auto& digit){ return not std::isdigit(digit);}) and (error = true))
std::cout << "\nError, you must type only digits. (0 to 9)\n\n";
else error = false;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67676272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: blob in data module I am using the data module in drupal 7 and i created a view which shows my table.
*
*But I have a blob in my table and this is filling my page with content.Is there any way that I can get the blob to display as a link and the file must be downloaded when clicked.
*Also is it possible for the data module to access tables in a different database than the default drupal database mentioned in settings.php.I added another database in the settings.php which has the required table but I am not able to adopt tables from there.(They do not show up in the orphaned tables list).Is there a place where I can change so that the data module only sees the new database and not the default database
A: Fixed the first problem by doing this in the theme.inc
if($vars['fields'][$field] == 'content')
{
$field_output = "<form action=\"download.php\"
method=\"POST\">
<input type=\"submit\" name=\"download\" value=\"Download\">
<input type=\"hidden\" name=\"did\" value=\"$num+1\">
</form>";
}
and download.php needs to have something like this
<?php
if(isset($_POST['id']))
{
$table = 'tablename';
$download_id = $_POST['id'];
$q="SELECT * FROM {$table} where id = $download_id";
$link = mysqli_connect(...);
$res = mysqli_query($link,$q);
if($res)
{
$row = mysqli_fetch_assoc($res);
$id = $row['id'];
$name = $row['name'];
$status = $row['status'];
$content = $row['content'];
header("Content-type: required type");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
else{
echo "Cannot download";}
}
?>
I am still unable to fix the second problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9856263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Create Excel Formula to Get pass or fail in final level exam? There are 6 Subjects, (A,B,C,D,E,F are columns)
A- Maths
B- Bio Science
C- Physics
D -Chemistry
E -English
F -Computer Science
all student's subject wise Passing score is 50, Maths and Bio and physics Pass is compulsory and also from remain 3 subject any one subject should pass to get final level. how to create excel formula for that?
i tried IF Function but I don't know how to select random subject according to the condition
A:
Formula used in H2
=IF(AND(AND(B2>=50,C2>=50,D2>=50),OR(E2>=50,F2>=50,G2>50)),"Pass","Fail")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74229971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why PowerShell treats slash in DateTime format string as dot? PS C:\> (Get-Date).ToString("MM/dd/yyyy")
11.12.2016
PS C:\> [DateTime]::ParseExact('10/14/2016', 'MM/dd/yyyy', $null)
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."At line:1 char:1
+ [DateTime]::ParseExact('10/14/2016', 'MM/dd/yyyy', $null)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
PS C:\> [DateTime]::ParseExact('10.14.2016', 'MM/dd/yyyy', $null)
14 Oct 2016 0:00:00
PS C:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
5 0 10586 117
It is on Windows Server 2008 R2.
On Windows 10 version is 5.1.14393.206 and it works correctly.
What is going on?
A: As Jeroen Mostert pointed out in the comments to your question, the forward slash has a special meaning in date/time format strings.
From the documentation:
The "/" custom format specifier
The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.
Note
To change the date separator for a particular date and time string, specify the separator character within a literal string delimiter. For example, the custom format string mm'/'dd'/'yyyy produces a result string in which "/" is always used as the date separator. To change the date separator for all dates for a culture, either change the value of the DateTimeFormatInfo.DateSeparator property of the current culture, or instantiate a DateTimeFormatInfo object, assign the character to its DateSeparator property, and call an overload of the formatting method that includes an IFormatProvider parameter.
For matching a literal forward slash instead of the date separator defined in the system's regional settings escape it with a backslash ('MM\/dd\/yyyy').
Also, passing $null for the format provider is not recommended. Either specify the correct culture for the date string, or use InvariantCulture if you want the string parsed independent of a particular culture.
[DateTime]::ParseExact('10/14/2016', 'MM\/dd\/yyyy', [Globalization.CultureInfo]::InvariantCulture)
A: Use the InvariantCulture if you have a non-localized value to handle.
PS C:\> ([Globalization.CultureInfo]::InvariantCulture).DateTimeFormat.DateSeparator
/
On my system, I have the date format set for ISO-8601. That causes my separator to be a hyphen -.
PS C:\> (Get-Culture).DateTimeFormat.DateSeparator
-
Interesting conversion.
PS C:\> (Get-Date).ToString("MM/dd/yyyy")
11-12-2016
A: Long form:
Get-Date -Format "yyyy\/MM\/dd"
Short-hand:
date -f "yyyy\/MM\/dd"
Note that, yes, in this instance, you use backslashes as the escape character, instead of tildes.
A: you can use this :
get-date -format "yyyy/MM/dd"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40566528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: float fmodf(float_x, float_y) function, math.h, c++ hello I was hoping someone could help me with this.
I am using the float fmodf(float_x, float_y) function from math.h.
i am able to code with it properly but I was just wanted to know does anyone know the functions exact code is, so i can understand it better
A: The exact code depends on your math library (probably included in the same package as your C library). You can look at the glibc implementation if you want to see one implementation. This is the function that gets used in glibc (from sysdeps/ieee754/flt-32/e_fmodf.c).
float
__ieee754_fmodf (float x, float y)
{
int32_t n,hx,hy,hz,ix,iy,sx,i;
GET_FLOAT_WORD(hx,x);
GET_FLOAT_WORD(hy,y);
sx = hx&0x80000000; /* sign of x */
hx ^=sx; /* |x| */
hy &= 0x7fffffff; /* |y| */
/* purge off exception values */
if(hy==0||(hx>=0x7f800000)|| /* y=0,or x not finite */
(hy>0x7f800000)) /* or y is NaN */
return (x*y)/(x*y);
if(hx<hy) return x; /* |x|<|y| return x */
if(hx==hy)
return Zero[(u_int32_t)sx>>31]; /* |x|=|y| return x*0*/
/* determine ix = ilogb(x) */
if(hx<0x00800000) { /* subnormal x */
for (ix = -126,i=(hx<<8); i>0; i<<=1) ix -=1;
} else ix = (hx>>23)-127;
/* determine iy = ilogb(y) */
if(hy<0x00800000) { /* subnormal y */
for (iy = -126,i=(hy<<8); i>=0; i<<=1) iy -=1;
} else iy = (hy>>23)-127;
/* set up {hx,lx}, {hy,ly} and align y to x */
if(ix >= -126)
hx = 0x00800000|(0x007fffff&hx);
else { /* subnormal x, shift x to normal */
n = -126-ix;
hx = hx<<n;
}
if(iy >= -126)
hy = 0x00800000|(0x007fffff&hy);
else { /* subnormal y, shift y to normal */
n = -126-iy;
hy = hy<<n;
}
/* fix point fmod */
n = ix - iy;
while(n--) {
hz=hx-hy;
if(hz<0){hx = hx+hx;}
else {
if(hz==0) /* return sign(x)*0 */
return Zero[(u_int32_t)sx>>31];
hx = hz+hz;
}
}
hz=hx-hy;
if(hz>=0) {hx=hz;}
/* convert back to floating value and restore the sign */
if(hx==0) /* return sign(x)*0 */
return Zero[(u_int32_t)sx>>31];
while(hx<0x00800000) { /* normalize x */
hx = hx+hx;
iy -= 1;
}
if(iy>= -126) { /* normalize output */
hx = ((hx-0x00800000)|((iy+127)<<23));
SET_FLOAT_WORD(x,hx|sx);
} else { /* subnormal output */
n = -126 - iy;
hx >>= n;
SET_FLOAT_WORD(x,hx|sx);
x *= one; /* create necessary signal */
}
return x; /* exact output */
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12656057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: AttributeError: dlsym(RTLD_DEFAULT, Error_GetLastErrorNum): symbol not found I recently downloaded the OSMnx package to work with street networks. However, it always gives me back the error below whenever I try to import the package. I've followed several steps that people from other posts suggested, but nothing changes. If anyone has had this problem or knows a way to solve it, please share it with me. Thank you!
Traceback (most recent call last):
File "/Users/qle/Documents/OSMnx/test.py", line 1, in <module>
import osmnx as ox
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/osmnx/__init__.py", line 3, in <module>
from ._api import *
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/osmnx/_api.py", line 3, in <module>
from .bearing import add_edge_bearings
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/osmnx/bearing.py", line 9, in <module>
from . import projection
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/osmnx/projection.py", line 3, in <module>
import geopandas as gpd
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/geopandas/__init__.py", line 1, in <module>
from geopandas._config import options # noqa
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/geopandas/_config.py", line 126, in <module>
default_value=_default_use_pygeos(),
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/geopandas/_config.py", line 112, in _default_use_pygeos
import geopandas._compat as compat
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/geopandas/_compat.py", line 202, in <module>
import rtree # noqa
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/rtree/__init__.py", line 9, in <module>
from .index import Rtree, Index # noqa
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/rtree/index.py", line 6, in <module>
from . import core
File "/Users/qle/Library/Python/3.8/lib/python/site-packages/rtree/core.py", line 77, in <module>
rt.Error_GetLastErrorNum.restype = ctypes.c_int
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ctypes/__init__.py", line 386, in __getattr__
func = self.__getitem__(name)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ctypes/__init__.py", line 391, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: dlsym(RTLD_DEFAULT, Error_GetLastErrorNum): symbol not found
A: Your error means, that rtree, a dependency of osmnx, cannot find spatialindex.
First, make sure that spatialindex is installed:
brew install spatialindex
The next problem is that rtree only checks in very specific locations for spatialindex but brew installs to /opt/homebrew/Cellar.
You set the ENV variable and check if that's the issue with
export SPATIALINDEX_C_LIBRARY='/opt/homebrew/Cellar/spatialindex/1.9.3/lib'
python -c 'import geopandas'
and it should work.
However, depending on your spatialindex and brew version, this path might change.
A: The problem has been solved, and I want to share in case anyone later could try if encountering the same problem.
After I installed the latest version for rtree, which you can see below, it still gave me back the same problem
conda install -c ioos rtree=0.9.7
I had to install brew package for my Mac.
https://brew.sh
Then I ran these 2 lines of code that my friend Philippe found from another page
Installing Rtree from libspacialindex to use .clip() in geopandas
https://github.com/gboeing/osmnx/issues/3
brew install spatialindex
pip install rtree
The problem has been solved completely.
A: This isn't an OSMnx issue - it's an rtree issue. You might want to open an issue directly with the rtree GitHub repo. That said, you're on OS X so you may want to try to install with rtree
conda install -c ioos rtree=0.8.2
Some of my students that have macs struggled to install rtree with pip, but succeeded with that conda command if you're on windows, you can follow these instructions to install geopandas and rtree.
reference
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68464704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I unmarshall this XACML XML snippet using JAXB? <Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
PolicyId="ClientType"
RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
Version="1.0">
<Target>
<AnyOf>
<AllOf>
<Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Reply</AttributeValue>
<AttributeDesignator
AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"
DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true" />
</Match>
</AllOf>
</AnyOf>
</Target>
<Rule Effect="Permit" RuleId="Rule_for_all">
<Target>
<AnyOf>
<AllOf>
<Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">A</AttributeValue>
<AttributeDesignator AttributeId="Reply"
Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="true" />
</Match>
</AllOf>
</AnyOf>
</Target>
</Rule>
<Rule Effect="deny" RuleId="Rule_deny_all" />
</Policy>
Please help me to unmarshall this xml using JAXB. I tried doing it but in between I got confused and got error. I have a quite big xml file but this fragment will help me understand.
A: The fragment you sent is actually an incomplete XML fragment. It's lacking for instance the closing </Policy> element.
The fragment you sent corresponds to a XACML 3.0 policy. This means that before you close the policy you should also have 1 or more rules (technically the schema does allow zero rules but that doesn't make sense).
To marshall and unmarshall using JAX-B, you need to use the XACML 3.0 schema which you can find here. It's pretty straightforward to configure JAXB to create the Java objects based on that schema. You'll need to create a simple XJB file to configure the marshalling.
That said, considering there are several XACML engines out there (both open source and vendor such as the one I work for, Axiomatics), what's your rationale for implementing a XACML parser yourself?
Cheers,
David.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20605372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Send email from Android application I wanted to know if there is any way we can manipulate the android emulator to use the email clients available on devices to send email from a custom application. Will using third party emulators like the ones available on MANYMO make any difference? Thank you.
A: The emulator doesn't include any email application for security purposes. In order to send email you need to download any email client (k9mail is a good option) and it will work without any issues.
A: Alternatively, you can send an e-mail in Android using the JavaMail API and the Gmail authentication.
Relevant code for that will be :
GMailSender sender = new GMailSender("username@gmail.com", "password");
sender.sendMail("This is Subject",
"This is Body",
"user@gmail.com",
"user@yahoo.com");
See the Stack Working Example Here .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19045711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Jenkins Jmeter Distributed Testing in Cloud Current Setup
Master – Local Desktop
Slaves – 3 Linux machines in AWS
So before starting the performance test I will be starting the master agents from the slave machines by logging in manually and then start with the performance test.
Current Scenario
Right now have created a performance test framework using Jenkins-Jmeter-Maven integration. This Jenkins is currently hosted in my laptop so my laptop acts as the master. I am not sure how to jenkins can connect to slave jmeter linux machines without me logging in manually. Has anyone resolved this scenario ? can you please share the approach to resolve it ?
I have tried using the following in pom.xml
<remoteConfig>
<startServersBeforeTests>true</startServersBeforeTests>
<serverList>1.2.3.4</serverList>
<stopServersAfterTests>true</stopServersAfterTests>
</remoteConfig>
but no use as I got this error
failure connecting to remote host: 1.2.3.4 java.rmi.ConnectException: Connection refused to host: 1.2.3.4; nested exception is:
[info] java.net.ConnectException: Connection refused: connect
[info] Failed to configure 1.2.3.4
[info] No remote engines were started.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41286699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PNG truecolor, 8 bit depth, how to read IDAT chunk I have a question regarding a PNG file that I am trying to read (I have attached it in this question)
The file size 328750 bytes
Width 660
Height 330
Color type - truecolor
Bit depth - 24 bits
So here's my question. If it's true color, I assume it's RGB, which is 24 bits. But you do the math, the number doesn't add up. 660 (width) * 330 (height) * 3 bytes (from 24 bits) = 653400 bytes, which is double the actual file size.
Why is that?
I tried to read the IDAT chunk, pretending that each pixel is 3 bytes, and I tried to check the colour and it doesn't match what is displayed.
A: PNG is a compressed image format, so the IDAT chunk(s) contain a zlib-compressed representation of the RGB pixels. Probably the easiest way for you to access the pixel data is to use a converter such as ImageMagick or GraphicsMagick to decompress the image into the Netpbm "PPM" format.
magick image.png image.ppm
or
gm convert image.png image.ppm
Then read the "image.ppm" in the same way you tried to read the PNG. Just skip over the short header, which in the case of your image is
P 6 \n 6 6 0 3 3 0 \n 2 5 5 \n
where "P6" is the magic number, 660 and 330 are the dimensions, and 255 is the image depth (maximum value for R,G,and B is 255, or 0xff). The remainder of the file is just the R,G,B values you were expecting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39019568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Filter Fabricjs to remove the red-eye effect or change part of the image object I'm doing a red-eye filter for fabricjs:
(function(global) {
'use strict';
var filters = fabric.Image.filters,
createClass = fabric.util.createClass;
filters.NoRedEyes = createClass(filters.BaseFilter, {
type: 'NoRedEyes',
fragmentSource: 'precision highp float;\n' +
'uniform sampler2D uTexture;\n' +
'uniform float uMyParameter;\n' +
'varying vec2 vTexCoord;\n' +
'void main() {\n' +
'vec4 color = texture2D(uTexture, vTexCoord);\n' +
// add your gl code here
'gl_FragColor = color;\n' +
'}',
myParameter: 0,
mainParameter: 'myParameter',
applyTo: function (options) {
console.log(options);
var canvasEl = options.targetCanvas;
var context = canvasEl.getContext('2d'),
imageData = context.getImageData(this.left, this.top, this.width, this.height),
data = imageData.data;
var p = imageData.width * imageData.height, pix = p * 4, r, g, b;
while (p--) {
pix -= 4;
r = data[pix];
b = data[pix + 1];
g = data[pix + 2];
if (parseFloat(r / (g + b) / 2) > 0.5) // лучший результат - 0.4 / 1.5 because it gives the best results
{
imageData.data[pix] = Math.round((g + b) / 2);
}
}
context.putImageData(imageData, this.left, this.top);
},
});
fabric.Image.filters.NoRedEyes.fromObject = fabric.Image.filters.BaseFilter.fromObject;
})(typeof exports !== 'undefined' ? exports : this);
I have errors:
Error: WebGL warning: readPixels: Framebuffer not complete. (status: 0x8cd7)
fabric.js:19844:3
Error: WebGL warning: readPixels: Framebuffer must be complete.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48649760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot access AppDelegate while testing Xcode project func testExample() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// some code ...
}
The above function always crash and gives this error:
Could not cast value of type 'MyAppName.AppDelegate' (0x10dc09e80) to 'MyAppNameTests.AppDelegate' (0x11cc190c0).
A: You are probably compiling AppDelegate into your test target. Don't do this.
Instead, only compile into your normal app target MyAppName. In you test class write in XCode 7
@testable import MyAppName
and before XCode 7
import MyAppName
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31179382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Testing a Meteor JS API endpoint I've recently created a small application using Meteor JS. The application handles user input via a series of forms and stores the data in MongoDB.
One of the requirements for this projects was to developer an API with around 8 end-points.
When requested, an end-point returns a JSON object.
The API end-points/routes have been created using Iron Router.
My question is; how would one go about testing these end-points in Meteor JS. Ideally I'd like to mock the requests.
A: There are many tools. Below are my suggestions.
For GET, I usually just type it in the browser's URL bar.
For POST or all other including GET, I use cURL from the command line like so:
curl -X POST \
https://saturnapi.com/access/demo/demo \
-H 'saturnapi-access-key':'API_KEY' \
-d 'SaturnParams'='28' \
-H specifices the headers, which in this case is my API key. -d specifies the data, which in this case is SaturnParams field. For more on cURL, see docs here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31921273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.