text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: SQL Count Data 1/2 hourly I have a stored procedure that counts data for each hour,
Declare @DateTimeToFilter DATETIME;
--set @DateTimeToFilter = GetDate();
set @DateTimeToFilter = '6/5/14'
SET NOCOUNT ON;
WITH H ([Hour]) AS
( SELECT 7 UNION
SELECT 8 UNION
SELECT 9 UNION
SELECT 10 UNION
SELECT 11 UNION
SELECT 12 UNION
SELECT 13 UNION
SELECT 14 UNION
SELECT 15 UNION
SELECT 16 UNION
SELECT 17 UNION
SELECT 18 UNION
SELECT 19
)
SELECT H.[Hour],
COUNT(T.BookingID) AS NoOfUsers
FROM H
LEFT JOIN tbl_Visitor T
ON H.[Hour] = DATEPART(HOUR, T.TimeofArrival) AND
((DATEDIFF(dd, T.TimeofArrival, @DateTimeToFilter) = 0) AND (DATEDIFF(mm, T.TimeofArrival, @DateTimeToFilter) = 0) AND
(DATEDIFF(yy, T.TimeofArrival, @DateTimeToFilter) = 0))
GROUP BY H.[Hour];
This forces the data returned for each hour irrespective of whether there is any data or not.
How could I add the half hourly data to be added also, so the returned data look like.
Hour Count
7 0
7.5 0
8 0
8.5 0
9 0
9.5 0
10 4
10.5 0
11 0
11.5 0
12 0
12.5 0
13 0
13.5 0
14 5
14.5 0
15 2
15.5 0
16 2
16.5 0
17 0
17.5 0
18 0
18.5 0
19 0
19.5 0
The data is stored in the database as a smalltimedate, i.e. 2014-06-05 14:00:00
Any help is appreciated.
A: You can use minutes instead of hours:
with h ([Minute]) as (
select 420 union all
select 450 union all
select 480 union all
select 510 union all
select 540 union all
...
Divide the minutes to get fractional hours:
select h.[Minute] / 60.0 as [Hour], ...
Calculate the start and stop time for the interval to filter the data:
... on T.TimeofArrival >= dateadd(minute, h.[Minute], @DateTimeToFilter) and
T.TimeofArrival < dateadd(minute, h.[Minute] + 30, @DateTimeToFilter)
A: Below is an example that groups by half-hour intervals and can easily be extended for other intervals. I suggest you avoid applying functions to columns in the WHERE clause as that prevents indexes on those columns from being used efficiently.
DECLARE
@DateTimeToFilter smalldatetime = '2014-06-05'
, @IntervalStartTime time = '07:00:00'
, @IntervalEndTime time = '20:00:00'
, @IntervalMinutes int = 30;
WITH
t4 AS (SELECT n FROM (VALUES(0),(0),(0),(0)) t(n))
, t256 AS (SELECT 0 AS n FROM t4 AS a CROSS JOIN t4 AS b CROSS JOIN t4 AS c CROSS JOIN t4 AS d)
, t64k AS (SELECT ROW_NUMBER() OVER (ORDER BY (a.n)) AS num FROM t256 AS a CROSS JOIN t256 AS b)
, intervals AS (SELECT DATEADD(minute, (num - 1) * @IntervalMinutes, @DateTimeToFilter) AS interval
FROM t64k
WHERE num <= 1440 / @IntervalMinutes)
SELECT
interval
, CAST(DATEDIFF(minute, @DateTimeToFilter, interval) / 60.0 AS decimal(3, 1)) AS Hour
, COUNT(T.BookingID) AS NoOfUsers
FROM intervals
LEFT JOIN dbo.tbl_Visitor T
ON T.TimeofArrival >= intervals.interval
AND T.TimeofArrival < DATEADD(minute, @IntervalMinutes, intervals.interval)
WHERE
interval >= DATEADD(minute, DATEDIFF(minute, '', @IntervalStartTime), @DateTimeToFilter)
AND interval < DATEADD(minute, DATEDIFF(minute, '', @IntervalEndTime), @DateTimeToFilter)
GROUP BY interval
ORDER BY Hour;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24095556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Gradle circular dependency, force ignore I am trying to create a service registry where all the modules are added as compile(project(..)). The service registry module expose an unified function to call any function from any module. This is to reduce the direct coupling between two modules and to provide a proper separation of concern. To call any function from any module one can add dependency of service-registry as project and get the function. But if we do that the project has circular dependency.
Is there a way I can force gradle to ignore circular dependency,
project root
project A
-- compile(project(':SR'))
project B
-- compile(project(':SR'))
project SR
-- compile(project(':A')
-- compile(project(':B')
I will be moving the dependencies to nexus and use versioning, but in initial phase it would be great if somehow I can force gradle not to do so.
Can it be done by doing some condition as
if(calling_project_name!=root) compile(project(':A'),project(':B'))exclude(project(':calling project name')
is it possible to do? Other suggestions are also welcome.
I am using gradle 2.7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32960182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: easyRTC has bad audio in low bandwith in tablet with 3G internet i create audio chat with easyRTC But it have noise and it work bad when I use tablet and 3g internet !
But in computer I work true !
How i can change audio quality in easyRTC ?
A: You should reduce quality of Video to improve audio quality.
By default, easyRTC config Video quality with resolution of 1280x720.
You could reconfig quality base on status of bandwidth or device and set quality on client side with:
easyrtc.setVideoDims(X, Y);
Given X and Y params are your intend res.
You should refer the detailed of setVideoDims function on easyrtc client as bellow:
easyrtc.setVideoDims = function(width, height) {
if (!width) {
width = 1280;
height = 720;
}
easyrtc.videoFeatures = {
mandatory: {
minWidth: width,
minHeight: height,
maxWidth: width,
maxHeight: height
},
optional: []
};
};
A: I was actually exploring this same issue for a recent project!
Here's something that worked for us.
(1) First, pass an echoCancellation configuration option into MediaTrackConstraints: https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/echoCancellation - this is the built-in echo cancellation feature available natively in most browsers as part of their WebRTC support.
(2) Mute any video element where sound isn't needed - I don't need to hear my own video projecting sound, only the other, remote, user does. This applies only if you're using some video (or similar-enough audio) html element.
(3) EasyRTC supports: https://easyrtc.com/docs/client-api/Easyrtc_Rates.php - there's an example of how that can be used here: https://demo.easyrtc.com/demos/demo_lowbandwidth.html - play around with the options and you'll likely find a use-case specific setting that works for your needs!
Edit: (3) provides actual codec settings for video and audio!
Hope that helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28916084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: issues with center aligning content I've the below HTML.
<div class="para align-center">SCHEDULE 1 <span class="align-right">[r.32]</span></div>
<div class="para align-center">PART I</div>
and the below CSS
.para {
text-indent: 0em;
margin-bottom: 0.85em;
}
.para + .align-right {
margin-top: 1.2em;
}
.align-center {
text-align: center;
}
div.align-center span.align-right {
float: right;
}
Here I'm trying to center align the SCHEDULE 1 word, it is in center but there is some left inclination, and the second div PART 1 is in the exact center. Please let me know how can I get the first div in center and the right aligned text has to be there in right on same line. When I delete that right aligned text, SCHEDULE 1 appears in exact center.
.para {
text-indent: 0em;
margin-bottom: 0.85em;
}
.para + .align-right {
margin-top: 1.2em;
}
.align-center {
text-align: center;
}
div.align-center span.align-right {
float: right;
}
<div class="para align-center">SCHEDULE 1 <span class="align-right">[r.32]</span>
</div>
<div class="para align-center">PART I</div>
A: You can do it with using position field in CSS
HTML:
<div class="para align-center">SCHEDULE 1 <span class="align-right">[r.32]</span>
</div>
<div class="para align-center">PART I</div>
CSS:
.para {
text-indent: 0em;
margin-bottom: 0.85em;
}
.align-center {
text-align: center;
}
div{
position: relative;
}
div.align-center span.align-right {
float: right;
}
div span.align-right{
position: absolute;
right: 0;
}
Please look at the demo code
DEMO
A: you can remove .para + .align-right remove +
Css:
.para {
text-indent: 0em;
margin-bottom: 0.85em;
}
.align-center {
text-align: center;
}
div.align-center span.align-right {
float:right;
margin-left:-38px;
}
DEMO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32779912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Better performance and lower memory usage I am developing an application where I will store complex XMLs in Snappydata for future analysis.
For better analysis performance and lower memory consumption, what do you recommend? Store in xml, json or object?
Previously, thanks for your attention.
A: Obtain a DataFrame from your XML source and save into a Row or Column table in SnappyData.
Something like this if SQL is your preferred choice .... (Refer to docs for DF API)
snappy> CREATE external TABLE myXMLTable USING com.databricks.spark.xml
OPTIONS (path "pathToYourXML.xml", rowTag "Refer to docs link below");
snappy> create table myInMemoryTable using column as (select * from myXMLTable);
https://github.com/databricks/spark-xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48133158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to find text in Word, insert additional values before text with VBA I'm entirely new to VBA. I need to write a macro to do as the following pseudo code describes. Any references to VBA code are from looking at examples I've found so far from googling. Many thanks for any guidance you can offer.
Dim myText as string;
Dim myAutoTextFieldValue as string;
Set myText='Figure';
Set myAutoTextFieldValue = 'fignum';
// fignum is a autotext value that will insert a sequence type field
.Find text which matches this Word expression \[[0-9]*[0-9]*[0-9]\]
// this expression works in the Find what function in Word, not strictly regex
For each
.InsertBefore (myText + myTextAutoFieldValue);
// I'm guessing I'll need a With expression and a Do While.
EDIT:
I now have the following but I get "Method or Data Member not found" when I try to run it.
Sub EditFindLoop()
'find text where the string equals [00:00:00] or numeric sequence as per input mask
'then insert myText and myAutoTextFieldValue before it
Dim myText As String
Dim myAutoTextFieldValue As String
Dim myFind As String
myFind = "\[[0-9]*[0-9]*[0-9]\]"
myAutoTextFieldValue = "fignum"
myText = "Figure"
With ActiveDocument.Content.Find
'.Text = myFind
'.ClearFormatting
.MatchWildcards = True
Do While .Execute(findText:=myFind, Forward:=True) = True
.InsertBefore myText & myAutoTextFieldValue
Loop
End With
End Sub
A: And here's the answer to my own question, should anyone else require a similar piece of code.
Sub EditFindLoop()
Dim myText As String
Dim myFind As String
Dim x As Integer
myFind = "\[[0-9]*[0-9]*[0-9]\]"
myText = "Figure "
mySpace = ". "
x = 1
Dim oRange As Word.Range
Set oRange = ActiveDocument.Range
With oRange.Find
.Text = myFind
.ClearFormatting
.MatchWildcards = True
.MatchCase = False
.MatchWholeWord = False
Do While .Execute = True
If .Found Then
oRange.InsertBefore (myText & x & mySpace)
End If
oRange.Start = oRange.End
oRange.End = ActiveDocument.Range.End
x = x + 1
Loop
End With
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33554267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Constructor to allocate my own array class I have a class like Quete (first in , first out)
public class Tor<T>
{
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
}
I need to build a Constructor that get one parameter (queue size (int). and it allocate the arrary and initilizes the variable,
how to do it?
A: What about simple
public Tor(int size)
{
elements = new T[size];
}
A: public class Tor<T> where T : new()
{
public Tor(int size)
{
elements = new T[size];
for (int i = 0; i < size; i++)
{
elements[i] = new T();
}
}
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
}
or
public class Tor<T> where T : new()
{
public Tor(int size)
{
elements = Enumerable.Range(1,size).Select (e => new T()).ToArray();
}
...
}
A: public class Tor<T>
{
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
public Tor(int capacity)
{
elements = new T[capacity];
}
}
should do it.
A: public class Tor<T>
{
private T[] elements;
private int next;
public event EventHandler<EventArgs> queueFull;
public Tor(int size)
{
if (size < 0)
throw new ArgumentOutOfRangeException("Size cannot be less then zero");
elements = new T[size];
next = 0;
}
}
A: Consider using existing classes
*
*derive from Queue if needed events like suggested in C#: Triggering an Event when an object is added to a Queue
*or if you want to build your own use List which will allow to grow array as needed/preallocate if you want to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9938127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't find any java examples of using the androidx navigation architecture for single activity using bottom navigation I'm unable to find any examples using java, all the codelabs given by google seem to be in kotlin and ideally i don't want to learn that language.
Is there any simple example of using 1 activity, 2/3 fragments all linked in by the bottom navigation bar that I can browse for?
I've looked at all the documentation provided by google and unable to make any sense of it.
All I do know is that i am expected to use
NavHostFragment.findNavController(Fragment)
Navigation.findNavController(Activity, @IdRes int viewId)
Navigation.findNavController(View)
And that in java i should be using
Navigation.createNavigateOnClickListener()
I am hoping i am not too far off with this:
public class MainActivity extends AppCompatActivity {
NavController navController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupWithNavController(navView,navController);
}
}
Thanks.
A: Eventually found the answer, for anyone else who is facing similar newbie issues:
/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_graph"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/nav_view"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java under onCreate
BottomNavigationView navView = findViewById(R.id.nav_view);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupWithNavController(navView,navController);
Under /res/navigation/nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/mapFragment">
<fragment
android:id="@+id/mapFragment"
android:name="com.company.pinpoint.MapFragment"
android:label="fragment_map"
tools:layout="@layout/fragment_map">
<action
android:id="@+id/action_mapFragment_to_newsFeedFragment"
app:destination="@id/newsFeedFragment" />
<!--app:enterAnim="@anim/slide_in_right"-->
<!--app:exitAnim="@anim/slide_out_left"-->
<!--app:popEnterAnim="@anim/slide_in_left"-->
<!--app:popExitAnim="@anim/slide_out_right" />-->
</fragment>
<fragment
android:id="@+id/newsFeedFragment"
android:name="com.company.pinpoint.NewsFeedFragment"
android:label="fragment_news_feed"
tools:layout="@layout/fragment_news_feed" />
</navigation>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55764886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access everyone who has link in Google Cloud Storage Blob in Java?
I am trying to create a cloud storage using google cloud functions in java. I have created a link via Blob but I have problem when I try to give access to users. I did not understand how **setAcsl() **function works.
I have tried
List<Acl> acls = new ArrayList<>();
acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75581303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to enable content-assist (autocomplete) in Eclipse's Expressions view? For example when I debug in Visual Studio I have a view with the same functionality where I can create an expressions, and while I'm creating an expression I can use content-assist (autocomplete) exactly like in the main code window.
In Eclipse's Expression view, it looks that is absent content-assist functionality or I don't know how to use it. I tried to use Display view but it switches between views every time when I need to evaluate an expression, so it isn't convenient.
Is there possible any plugin with required functionality or something?
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30529044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Using layout as a sublayout & accessing it programatically in android? I have a layout called thumb_unit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="320dp"
android:layout_height="240dp"
android:orientation="horizontal"
>
<ImageView
android:id="@+id/thumbImage"
android:layout_marginLeft="10dp"
android:layout_width="160dp"
android:layout_height="220dp"
android:scaleType="fitXY"
android:src="@drawable/app_icon"
android:layout_marginTop="20dp"/>
<LinearLayout
android:layout_width="160dp"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:orientation="vertical" >
<TextView
android:id="@+id/issueName"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:text="Summer 2012"
android:textSize="18dp"
android:layout_marginLeft="6dp"
/>
<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="151dp"
android:layout_marginLeft="6dp"
android:text="Description"
android:textSize="14dp"
android:textStyle="italic" />
<Button
android:id="@+id/view_download"
android:layout_marginTop="5dp"
android:layout_width="80dp"
android:layout_marginLeft="5dp"
android:layout_height="30dp"
android:text="View"
android:textSize="14dp"
android:textColor="@drawable/push_button_text_color"
android:background="@drawable/push_button"
android:layout_marginBottom="40dp"
/>
</LinearLayout>
</LinearLayout>
and another layout called grid_unit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="170dp"
android:layout_height="130dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/thumbImage"
android:layout_width="77dp"
android:layout_height="105dp"
android:src="@android:drawable/ic_menu_gallery"
android:layout_marginTop="10dp"
/>
<LinearLayout
android:layout_width="73dp"
android:layout_height="120dp"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
>
<TextView
android:id="@+id/issueName"
android:layout_width="77dp"
android:layout_marginTop="5dp"
android:layout_height="30dp"
android:text="South Louisiana PnK"
android:layout_marginLeft="3dp"
android:textSize="11dp"
android:textStyle="bold" />
<TextView
android:id="@+id/productName"
android:layout_marginTop="5dp"
android:layout_width="70dp"
android:layout_height="30dp"
android:layout_marginLeft="3dp"
android:text="South Louisiana PnK"
android:textSize="9dp" />
<Button
android:id="@+id/viewButton"
android:layout_width="70dp"
android:layout_height="20dp"
android:text="View"
android:textSize="9dp"
android:textColor="@drawable/push_button_text_color"
android:background="@drawable/push_button"
android:layout_marginTop="5dp"
android:layout_marginLeft="3dp"
/>
</LinearLayout>
</LinearLayout>
and now finally, I have main activity_main.xml, I want to use the combination of these as
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="440dp"
android:orientation="vertical"
tools:context="com.mirabel.activities.MainActivity" >
<include layout="@layout/thumb_unit" android:id="@+id/main_thumb"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<include layout="@layout/grid_unit" android:id="@+id/left_grid"/>
<include layout="@layout/grid_unit" android:id="@+id/right_grid"/>
</LinearLayout>
</LinearLayout>
sublayout in the activity_main.xml and programatically I want to set the image, text for all these things. How to do that?
A: You can do it in the Activity file for activity_layout.xml in the following way:
View view = findViewById(R.id.left_grid);
ImageView image = view.findViewById(R.id.thumbImage);
image.setBackgroundResource(R.id.image)); //or whatever you wish to set
TextView text = view.findViewById(R.id.issueName);
text.setText("Whatever text you want to set);
In this way, you can access all the Views in the included layout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12858192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I use pandas loc method to select multiple columns and replace the resulting row values with NaN I have a DataFrame like this:
students = {'ID': [2, 3, 5, 7, 11, 13],
'Name':['John','Jane','Sam','James','Stacy','Mary'],
'Gender':['M','F','F','M','F','F'],
'school_name':['College2','College2','College10','College2','College2','College2'],
'grade':['9th','10th','9th','9th','8th','5th'],
'math_score':[90,89,88,89,89,90],
'art_score':[90,89,89,78,90,94]}
students_df = pd.DataFrame(students)
Can I use the loc method on the students_df to select all the math_scores and art_scores from the 9th grade at College2 and replace them with NaN?
Is there a clean way of doing this without breaking the process into two parts: one for the subsetting and the other for the replacing?
I tried to select this way:
students_df.loc[(students_df['school_name'] == 'College2') & (students_df['grade'] == "9th"),['grade','school_name','math_score','art_score']]
I replaced this way:
students_df['math_score'] = np.where((students_df['school_name']=='College2') & (students_df['grade']=='9th'), np.NaN, students_df['math_score'])
Can I achieve the same thing in a much cleaner and efficient way using loc and np.NaN?
A: Select columns for replace missing values first and set NaN:
students_df.loc[(students_df['school_name'] == 'College2') & (students_df['grade'] == "9th"),['math_score','art_score']] = np.nan
print (students_df)
ID Name Gender school_name grade math_score art_score
0 2 John M College2 9th NaN NaN
1 3 Jane F College2 10th 89.0 89.0
2 5 Sam F College10 9th 88.0 89.0
3 7 James M College2 9th NaN NaN
4 11 Stacy F College2 8th 89.0 90.0
5 13 Mary F College2 5th 90.0 94.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67499135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C passing by value or reference with pointers Which function calls are passed by value and which are passed by reference?
int *a;
int b;
int **c;
f(a);
g(&b);
h(*c);
Just simple examples, I am just confused with pointers and how you tell how they are passed.
A: Formally, C doesn't have pass by reference. It only has pass by value.
You can simulate pass by reference in two ways:
*
*You can declare a function parameter as a pointer, and explicitly use & to pass a pointer to an object in the caller.
*You can declare a function parameter as a pointer, and pass an array, since when you try to pass an array, what actually happens is that the array's value "decays" into a pointer to its first element. (And you can also declare the function parameter as an array, to make it look even more like there's an array being passed, but you're actually declaring a pointer in any case.)
So it's more a question of which parameters you think of as being passed by reference.
You'll often hear it said that "arrays are passed by reference in C", and this isn't false, but arguably it isn't strictly true, either, because (as mentioned) what's actually happening is that a pointer to the array's first element is being passed, by value.
A: The pedantic answer is that all of them are passed by value, but sometimes that value is an address.
More usefully, assuming there's no errors in what you have here, all of these functions are pass-by-address which is as close as C gets to pass-by-reference. They take in a pointer as an argument and they may dereference that pointer to write data to wherever it points. Only the call to g() is safe with just these lines because the other pointers are undefined.
This is the standard in C APIs for in/out parameters which don't need to be reallocated.
Functions that need to return a new variable-sized buffer usually take in a pointer to a pointer, so they may dereference the argument to get an address in the caller to which they write a pointer to a buffer they allocate, or which is a static variable of the function.
As mentioned in the comments it's possible to just return a pointer from a function. Memory allocation wouldn't work in C without it. But it's still pretty common to see functions that have size_t ** parameters or similar for returning pointers. That might be mostly a Unix pattern where almost every function returns a success/error code so the actual function output gets shifted to the arguments.
A: To make your question more clear let's initialize the variables
int b;
int *a = &b;
int **c = &a;
Then this call
f(a);
passes the object b by reference through the pointer a. The pointer itself is passed by value that is the function deals with a copy of the value of the pointer a.
This call
g(&b);
in fact is equivalent to the previous call relative to the accepted value. The variable b is passed by reference.
And this call also equivalent to the previous call
h(*c);
the variable b is passed by reference through the pointer *c value of which is equal to the value of the pointer a.
So all three functions accept the variable b by reference.
A: The easiest way to tell is in the size of the arithmetic, but this is not so for the char type. For address arithmetic, the sizeof operator is invoked which is not the case for ordinary arithmetic as in the type of unsigned int.
#include <iostream>
using namespace std;
int main() {
unsigned int ui, *uiPtr;
ui = 11;
cout << ui << endl;
ui += 1; //increases value by 1
cout << ui << endl;
uiPtr = &ui;
cout << uiPtr << endl;
uiPtr += 1; //increases value by sizeof
cout << uiPtr << endl;
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57960949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mongodb aggregation: restore structure after unwinding nested arrays Say I have the following aggregation:
db.foo.aggregation([
{ $unwind: '$bar' },
// match something on bar
{ $unwind: '$bar.baz' },
// match something on bar.baz
])
What is the procedure to regroup the unwound arrays back to the same structure they were originally in?
(Note - we are using mongodb 3.0)
For clarity, the main purpose of this is to pre-filter the data before the server receives it, so that only certain bar's and baz's are returned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44178036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to send gmail thread id in reply mail using PhpMailer I am using PHPMailer for sending and replying mail. Here i am facing issue is the reply thread mail is not linked with existing group. It will send separate mail. How can i send it with existing group. I am having thread id. Here is my code.
require_once 'plugins/PHPMailer/src/PHPMailer.php';
require_once 'plugins/PHPMailer/src/Exception.php';
require_once 'plugins/PHPMailer/src/SMTP.php';
$mail = new PHPMailer(true);
$mail->Username = GMAIL_MAIL;
$mail->Password = GMAIL_PWD; // SMTP password
$mail->SMTPSecure = 'tls';
$mail->Port = 587; $mail->setFrom(MAIL_FROM, '');
$mail->addAddress($request['mail_to'], $request['mail_to']);
$mail->addReplyTo(MAIL_FROM, MAIL_FROM);
$mail->addCustomHeader( 'In-Reply-To', '<' . MAIL_FROM . '>' );
$mail->addCustomHeader( 'X-GM-THRID', '' . $request['thread_id']. '' );
$mail->addCustomHeader('References', '[' . $request['thread_id'] . ']');
A: Setting Message-ID is important for mail thread via phpmailer, you will get the thread id via
$this->email->_get_message_id();
append this code to
$this->email->set_header('Message-ID', $this->email->_get_message_id());
and your total code will be like
$this->email->set_header('References', "CABOvPkdN1ed8NTkph0Ep+ogNaAgW_9R0dR4ZPLTpBn=vc7K7QA@mail.gmail.com");
$this->email->set_header('In-Reply-To', "CABOvPkdN1ed8NTkph0Ep+ogNaAgW_9R0dR4ZPLTpBn=vc7K7QA@mail.gmail.com");
$this->email->set_header('Message-ID', $this->email->_get_message_id());
please get in touch if it is not work :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57163301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: null pointer exception on adding string object to arraylist Cant get around this. Null Pointer exception occurs when trying to add a String object to an ArrayList. Trouble is, I believe I have already initialized the 'temp' ArrayList properly. Please help.
void initialConbinations(String[] headers) {
//Dataset is SN,FN,RN,PN
//Map the headers to the appropriate portions
String[] newHeaders = {"SN,high", "SN,medium", "SN,low", "FN,high", "FN,medium", "FN,low", "RN,high", "RN,medium", "RN,low"};
List<List> assRuleHeaders = new ArrayList<List>();
ArrayList<String> temp = new ArrayList<String>();
//Use bitwise shifting to do the rest
int k = 0, l = 0;
for (int i = 1; i < 511; i++) {
for (int j = 0; j < 9; j++) {
l = i;
k = (l >> j) & 0x00000001;
if (k == 1) {
System.out.println(k + " , " + i + " , " + j);
System.out.println(newHeaders[j]);
temp.add(newHeaders[j]); //Getting a Null Pointer Exception here
}
}
assRuleHeaders.add(temp);
temp = null;
}
for (int i = 0; i < assRuleHeaders.size(); i++) {
this.printArray(assRuleHeaders.get(i));
}
}
A: At the last step of i loop you are setting temp to null instead of setting it to a new array using new ArrayList<String>();. This will cause temp.add(newHeaders[j]); to through the null pointer exception.
change
temp = null;
to
temp = new ArrayList<String>();
A: The error is with the line
temp = null;
You are not reinitializing temp again.
if you move the line
ArrayList<String> temp = new ArrayList<String>();
between the two for loops all should be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16240463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: matplotlib.pyplot, preserve aspect ratio of the plot Assuming we have a polygon coordinates as polygon = [(x1, y1), (x2, y2), ...], the following code displays the polygon:
import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.show()
By default it is trying to adjust the aspect ratio so that the polygon (or whatever other diagram) fits inside the window, and automatically changing it so that it fits even after resizing. Which is great in many cases, except when you are trying to estimate visually if the image is distorted. How to fix the aspect ratio to be strictly 1:1?
(Not sure if "aspect ratio" is the right term here, so in case it is not - I need both X and Y axes to have 1:1 scale, so that (0, 1) on both X and Y takes an exact same amount of screen space. And I need to keep it 1:1 no matter how I resize the window.)
A: 'scaled' using plt
The best thing is to use:
plt.axis('scaled')
As Saullo Castro said. Because with equal you can't change one axis limit without changing the other so if you want to fit all non-squared figures you will have a lot of white space.
Equal
Scaled
'equal' using ax
Alternatively, you can use the axes class.
fig = plt.figure()
ax = figure.add_subplot(111)
ax.imshow(image)
ax.axes.set_aspect('equal')
A: There is, I'm sure, a way to set this directly as part of your plot command, but I don't remember the trick. To do it after the fact you can use the current axis and set it's aspect ratio with "set_aspect('equal')". In your example:
import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.axes().set_aspect('equal', 'datalim')
plt.show()
I use this all the time and it's from the examples on the matplotlib website.
A: Does it help to use:
plt.axis('equal')
A: Better plt.axis('scaling'), it works better if you want to modify the axes with xlim() and ylim().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2934878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: OneM2M, IOTKETI Mobius RETRIEVE Group Member ContentInstances In my example architecture; I have an IN-Mobius and a ADN-AE-Thyme (nCube Thyme).
First of all; i created a AE which is called "ae_test_02", i can GET this resource via Postman.
After this step; i run ADN-AE-Thyme, thyme.js, and it created a container which is called "thyme_01", and also i can GET this resource via Postman.
Also in that step, thyme.js add containerInstances into the "thyme_01" container. Then, i can get that latest containerInstance with "/la" parameter via Postman
In this point, the problem has began. I create a group resource, while creating i tried couple solutions, always fail. I tried in "mid" attribute;
{ "m2m:grp": {
"rn": "grp_test_100520_08",
"mt": 3,
"mid": ["3-20200505012920476/la",
"Mobius/3-20200505012920476/la",
"Mobius/thyme_01/la",
"Mobius/ae_test_02/3-20200505012920476/la",
"Mobius/ae_test_02/thyme_01/la",
"ae_test_02/thyme_01/la",
"ae_test_02/3-20200505012920476/la"],
"mnm": 10
}
The problem is that, i tried these mid paths one by one, but never works. When i try to get latest containerInstances via Postman, i use this URL and the results is "resource does not exist (get_target_url)"
The containers and contentInstances in the IN-Mobius, and i requested to the IN-Mobius. By using these informations how should i implement group "mid" attribute; for the get containerInstances via group resources ?
First Edit.
Hi Andreas.
For the first issue, i can get resource correctly. In this point my aim is GET containerInstance in the container, which is a member (mid) in that .
Second; now I understand, there is not existing resource in resource, okay. As you mentined, i want to pass a request to all member (containers) of a resource. For this purpose, i will use https://localhost:7579/Mobius/grp_test_100520_08/fopt, but it gives an error "ERR_INVALID_ARG_TYPE". I know that, at least one mid structure is correct, but which one is the correct ?
For the smaller issue, i already know that resouce multiple times in the mid attribute, because i did not know which one is the correct adressing scheme ?
Also, while creating a resource, the resource should be in the ae resource (/Mobius/ae_test_02/grp_name) or in the Mobius (/Mobius/grp_name)
resources can be in directly in IN-Mobius or should in MN-Rosemary? Is fanOutPoint only using by external resource like MN or even IN, fopt using ?
Second Edit.
The "thyme" comes from nCube Thyme (https://github.com/IoTKETI/nCube-Thyme-Nodejs), it creates a container and then randomly create ContainerInstances.
The resource tree looks like;
Mobius >> ae_test_02 (AE resource) >> thyme_01 (Container It created from nCube Thyme https://github.com/IoTKETI/nCube-Thyme-Nodejs) >> ContainerInstances
I have also a resource in >> Mobius >> grp_test_100520_08 (GROUP resource which is uses)
I tried;
{ "m2m:grp": {
"mid": ["Mobius/ae_test_02/thyme_01"],
"mnm": 5
}
}
In this request, fopt.js gives an error "callback is not a function".
{ "m2m:grp": {
"mid": ["ae_test_02/thyme_01"],
"mnm": 5
}
}
In this request, fopt.js gives same "callback is not a function", but in different line.
I guess my fopt.js file is old, then i checked mobius github page and get that file, however it not solve this.
Also my resource look like this;
Also my fopt.js file is same as this;
https://github.com/IoTKETI/Mobius/blob/master/mobius/fopt.js
UPDATE 3.
The "cnm" attribute problem is this; while creating a resouce, CSE will automaticly assign "cnm" attribute according to member size. However, CSE will not this process in UPDATE (PUT) request. From this point, i will create resources, not UPDATE them.
As you mentioned, i send requests to the group's resource, but it gives the "callback is not a function" error. To solve this problem, i downloaded and installed the whole distribution. (https://github.com/IoTKETI/Mobius) After that, i will do same processes again for understand the fopt.js file behaviour. The result wasn't changed, it gives the same error.
I planning to explain whole situation and create an issue, in Mobius github page. I hope they will response soon.
A: I think there are two issues with your example.
The first issue is with the request to the <Group>. You need to distinguish between requests to the <Group> resource itself and requests to the members of the <Grou>.
There is no child resource <la> of the <Group> resource itself. This is why you receive an error message. If you want to pass a request to all members of a <Group> resource then you need to target the virtual child resource <fopt>. In your case the request should target URI https://localhost:7579/Mobius/grp_text_100520/fopt. Since you already have the <la> resources as members you won't need to add the /la part to the request. However, I would recommend to only add the <Container> resources to the group and use the target URI https://localhost:7579/Mobius/grp_text_100520/fopt/la to retrieve the latest <ContentInstances> of each container.
The second (smaller) issue is that from what I can get from your example code that you add the same resource multiple times to the group, but only with different addressing schemes. Please be aware that the CSE must removes duplicate resources when creating or updating the mid attribute.
Edit after question update
It is not very clear what your resource tree looks like. So, perhaps you should start with only one resource references and continue from there. Valid ID's in the mid attribute are either structured (basically the path of the rn attributes) or unstructured ID's (the ri's). The CSE should filter the incorrect ID, so you should get the correct set of ID's in the result body of the CREATE request.
btw, where does "thyme" come from? This is only in a label, which does not form an ID.
Regarding the <fanOutPoint> resource: Normally all request would be targeted to the <Group> resource, but requests to the virtual <fanOuPoint> resource are forwarded to al the members of the group. If a resource referenced in mid is accessible then the request is forwarded and the result is collected and is part of the result body of the original request.
You also need to be careful and regard the resource types: only send valid requests to the group's members.
Update 2
From the IDs in the mid attribute of the <Group> resource it looks like that the CSE validated the targets (though the cnm (current number of members) is obviously wrong, which seems to be an error of the CSE).
So, you should be able to send requests to the group's <fopt> resource as discussed above.
For the CSE runtime error you should perhaps contact the Mobius developers. But my guess is that you perhaps should download and install the whole distribution, not only a single file.
A: for anyone in the future; who is dealing with this problem.
The problem is simply is that; in the app.js there is 4 function call (fopt.check). While calling the function in the app.js file, there are 5 parameter exists, on the other hand, while getting these arguments in the function it takes only 4 arguments. For this reason, body_obj always becomes "undefined" then it will never reach the "Container" or "ContainerInstance" source. Lately, KETI was sent a new commit to the Mobius Github page (https://github.com/IoTKETI/Mobius/commit/950182b725d5ffc0552119c5c705062958db285f) to solve this problem. It solves this problem unless you are using use_secure == 'disable'. If you try to use use_secure == 'enable' you should add an if statement to check use_secure and add import HTTPS module.
Also, while creating resource, defining the "mid" attribute is not very clear. Just for now, if you want to reach (latest) source; you should add "/la" for all members of the group. This is recommended by KETI on Github page issue 5.
(https://github.com/IoTKETI/Mobius/issues/5#issuecomment-625076540)
And lastly, thank you Andreas Kraft; your help was very useful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61709911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Error in entering Date in My SQL I was trying to enter date into MySQL and was trying to figure out the right syntax through trial and error. In one such command, MySQL accepted the value, however when I displayed the values it showed all zeroes.
can anyone help me understand why?
A: If you are not passing Date in default format then you need to intimate system that I am passing this string as date by mentioning format of date as describe below.
INSERT INTO test VALUES STR_TO_DATE('03-12-2016','%d-%m-%Y');
Hopefully this will help.
A: Try this and also check your date format(data type) set in the database
INSERT INTO test VALUES ('2-03-2016')
A: you must ensure that the value passed to mysql is in year-month-day sequence ("YYYY-MM-DD")
INSERT INTO test VALUES ('2016-03-02');
note:- please use another keyword instead inbuilt keyword.date is inbuilt mysql keyword.
Read here
A: Trial and error? This isn't some uncharted scientific territory where you need to strap on some goggles and use a bunsen burner. There's a whole chapter in the manual devoted to it.
Dates in MySQL should be in ISO-8601 format, that is YYYY-MM-DD or YYYY-MM-DD HH:MM:SS in 24-hour notation.
Please, before wasting tons of your time on pointless experimentation:
READ THE MANUAL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41626976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to add non blocking stderr capture to threaded popen's I've got a python 3 script i use to backup and encrypt mysqldump files and im having a particular issues with one database that is 67gb after encryption & compression.
The mysqldump is outputting errorcode 3, so i'd like to catch the actual error message, as this could mean a couple of things.
The random thing is the backup file is the right size, so not sure what the error means. it worked once on this database...
the code looks like the below and i'd really appreciate some help on how to add non-blocking capture of stderr when the return code is anything but 0 for both p1 and p2.
Also, if im doing anything glaringly obvious wrong, please do let me know, as i'd like to make sure this is a reliable process. it has been working fine on my databases under 15gb compressed.
def dbbackup():
while True:
item = q.get()
#build up folder structure, daily, weekly, monthy & project
genfile = config[item]['DBName'] + '-' + dateyymmdd + '-'
genfile += config[item]['PubKey'] + '.sql.gpg'
if os.path.isfile(genfile):
syslog.syslog(item + ' ' + genfile + ' exists, removing')
os.remove(genfile)
syslog.syslog(item + ' will be backed up as ' + genfile)
args = ['mysqldump', '-u', config[item]['UserNm'],
'-p' + config[item]['Passwd'], '-P', config[item]['Portnu'],
'-h', config[item]['Server']]
args.extend(config[item]['MyParm'].split())
args.append(config[item]['DBName'])
p1 = subprocess.Popen(args, stdout=subprocess.PIPE)
p2 = subprocess.Popen(['gpg', '-o', genfile, '-r',
config[item]['PubKey'], '-z', '9', '--encrypt'], stdin=p1.stdout)
p2.wait()
if p2.returncode == 0:
syslog.syslog(item + ' encryption successful')
else:
syslog.syslog(syslog.LOG_CRIT, item + ' encryption failed '+str(p2.returncode))
p1.terminate()
p1.wait()
if p1.returncode == 0:
#does some uploads of the file etc..
else:
syslog.syslog(syslog.LOG_CRIT, item + ' extract failed '+str(p1.returncode))
q.task_done()
def main():
db2backup = []
for settingtest in config:
db2backup.append(settingtest)
if len(db2backup) >= 1:
syslog.syslog('Backups started')
for database in db2backup:
q.put(database)
syslog.syslog(database + ' added to backup queue')
q.join()
syslog.syslog('Backups finished')
q = queue.Queue()
config = configparser.ConfigParser()
config.read('backup.cfg')
backuptype = 'daily'
dateyymmdd = datetime.datetime.now().strftime('%Y%m%d')
for i in range(2):
t = threading.Thread(target=dbbackup)
t.daemon = True
t.start()
if __name__ == '__main__':
main()
A: Simplify your code:
*
*avoid unnecessary globals, pass parameters to the corresponding functions instead
*avoid reimplementing a thread pool (it hurts readability and it misses convience features accumulated over the years).
The simplest way to capture stderr is to use stderr=PIPE and .communicate() (blocking call):
#!/usr/bin/env python3
from configparser import ConfigParser
from datetime import datetime
from multiprocessing.dummy import Pool
from subprocess import Popen, PIPE
def backup_db(item, conf): # config[item] == conf
"""Run `mysqldump ... | gpg ...` command."""
genfile = '{conf[DBName]}-{now:%Y%m%d}-{conf[PubKey]}.sql.gpg'.format(
conf=conf, now=datetime.now())
# ...
args = ['mysqldump', '-u', conf['UserNm'], ...]
with Popen(['gpg', ...], stdin=PIPE) as gpg, \
Popen(args, stdout=gpg.stdin, stderr=PIPE) as db_dump:
gpg.communicate()
error = db_dump.communicate()[1]
if gpg.returncode or db_dump.returncode:
error
def main():
config = ConfigParser()
with open('backup.cfg') as file: # raise exception if config is unavailable
config.read_file(file)
with Pool(2) as pool:
pool.starmap(backup_db, config.items())
if __name__ == "__main__":
main()
NOTE: no need to call db_dump.terminate() if gpg dies prematurely: mysqldump dies when it tries to write something to the closed gpg.stdin.
If there are huge number of items in the config then you could use pool.imap() instead of pool.starmap() (the call should be modified slightly).
For robustness, wrap backup_db() function to catch and log all exceptions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30162766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does UMPConsentStatusObtained mean for Consenting with the User Messaging Platform SDK I'm looking at https://developers.google.com/admob/ump/ios/quick-start#present_the_form_if_required How can I tell if the user did or didn't agree to personalized ads?
There are only 4 enum:
UMPConsentStatusUnknown: Unknown consent status.
UMPConsentStatusRequired: User consent required but not yet obtained.
UMPConsentStatusNotRequired: User consent not required. For example, the user is not in the EEA or UK.
UMPConsentStatusObtained: User consent obtained. Personalization not defined.
Will Google handle user responses automatically in the next Admob request or do I have to somehow figure it out myself?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64235585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the recommended way to handle large file uploads to s3? I'm using AWS SDK for Ruby to upload large files from users to s3.
The server is a sinatra app with a POST /images endpoint accepting multipart/form-data. I'm experiencing a noticeable delay with user uploads. This is to be expected, because it's making a request to s3 synchronously. I wanted to move this to a background job using something like Sidekiq, but I'm not sure I like that solution.
I read online that some people are promoting direct uploads to s3 on the client side. Some even called this a "best practice." I'm hesitant to do this for several reasons:
*
*My client side code would be heavily tied down to my cloud provider. I love AWS (great experiences), but I like to remain somewhat cloud-agnostic. I don't want my mobile and web apps to have to know the details of my AWS setup. If I choose to move away from s3 at a later date (unlikely but plausible), I would want this to be a seamless transition. Obviously, this works ok for a web app, because I can always redeploy quickly. However, I have to worry about mobile. Users may not update, and everything will become a lot more complicated if some users are uploading to s3 and some are uploading to another service.
*Business logic regarding determining which bucket and region to use would need to either exist on the client side or I'd need to expose an endpoint for determining which bucket and region to use for each user. Then, I'd have to make a request to my server to figure out the parameters before I can begin uploading to s3. I want to be able to change buckets or re-route users to alternative regions and so I'm not a fan of this tight coupling or the additional request.
*Security is a huge concern. When files are uploaded and processed through my server, I can utilize AWS IAM to properly ensure that these files are only coming from my server. I believe that I have to grant an "all-write" privilege to users which is problematic. If I use AWS IAM credentials in JavaScript, I do not see how you can ensure that users do not get unlimited write access to my bucket. All client side javascript, can be read by a user. In addition, I'm unaware of how to process validations. On my server, I can scan the files and determine whether or not to upload to s3. If I upload directly from the client, I would have to move this processing into lambda functions. I'm ok with that, but there is a chance the object could be retrieved by users before the processing has occurred. Then, I'd have to build some sort of locking system to prevent access before processing.
So, the bottom line is I have no idea where to go from here. I've hacked around some solutions, but I'm not thrilled with any of them. I'd love to learn how other startups and enterprises are tackling this kind of problem. What would you recommend? How would you counter my argument? Forgive me if I'm missing something, I'm still relatively an AWS-newbie.
A: *
*If you're worried about changing the post service I would suggest using an API and that way you can change the backed storage for your service. The mobile or web client would call the service and then your api would place the file where it needed to go. The api you have more control over and you could just created a signed s3 url to send to the client and let them still do the uploading.
*An api, like in 1, solves this problem too, the client doesn't have to do all the work.
*Use Simple Token Services and Temporary Security Credentials.
A: I agree with strongjz, you should use an API to upload your files from the server side.
Cloudinary provides an API for uploading images and videos to the cloud.
From what I know from my experience in using Cloudinary it is the right solution for you.
All your images, videos and required metadata are stored and managed by Cloudinary in Amazon S3 buckets owned by Cloudinary.
The default maximum file size limit for videos is 40MB. This can be customized for paid plans.
For example in Ruby:
Cloudinary::Uploader.upload("sample_spreadsheet.xls", :resource_type =>
:raw)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45067934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Model Structure in Rails I'm relatively new to Rails and I'm trying to figure out the ideal model structure for my application, which is a simple reminder service for home maintenance. The central model in the app is a Home.
Each home has many Appliance in it (i.e. a dishwasher, laundry, water heater etc).
Each Appliance has a set of reminders associated with it (i.e. if you have a water heater, you have to do XYZ every 3 months, and ABC every 6 months).
On a regular basis (monthly/weekly), there is a mailer sent to the homeowner with a list of all the reminders.
I'm trying to figure out the best model structure for this.
Right now, these are the models I have but I don't know if this is overkill or not?
*
*Home (Address, Postal Code, etc)
*Appliance (Name, Manufacturer)
*Reminder (Appliance_ID, Reminder, Frequency)
*HomeAppliance (Home_ID, Appliance_ID)
*HomeReminders (Home_ID, Reminder_ID)
The Associations:
*
*Home has_many HomeAppliances
*Appliance has_many Reminders
*Home has_many HomeReminders
Any help is appreciated.
A: I'd go for something a little less complex. You need three models:
class Home < ActiveRecord::Base
has_many :appliances
has_many :reminders, :through => :appliances
end
class Appliance < ActiveRecord::Base
belongs_to :home
has_many :reminders
end
class Reminder < ActiveRecord::Base
belongs_to :appliance
end
Notice that we're using the has_many :through relation to allow us to call home.reminders directly.
See the Document example here for more info on has_many :through: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association
In your original example you seem to want to store various pre-defined appliances in the db for reference. I'd do it differently. Have a config file with the various makes and models that you can use to populate dropdowns on the form users use when setting up their appliance details. Then you can skip the extra models and simplify things as described above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10365070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to save fields from a data structure to filename field in Matlab? In Matlab I have a structural array that is as follows.
We basically have a number of datasets and each one has a name. For each dataset there is a certain number of data points, that are data that has been recorded from electrical activity in the brain, from presentation of a stimulus, over a certain number of seconds.
For each dataset, there was a recording of 2 seconds before the stimulus was presented and a recording of 3 seconds after the stimulus was presented. So I actually want to chop my data into 2, with data points associated to "pre" and data points associated with "post". This is quite simple to do using a for loop and I have done it and have now 2 additional fields associated with each data set.
FYI
ALLEEG(data_set).data ----- > this field has the original unchopped data
ALLEEG(data_set).data_pre ----- > this field has the "pre" data
ALLEEG(data_set).data_post ---- > this field has the "post" data
ALLEEG(data_set).filename ---- > this field has the filename
Now I wish to take the original filename of each dataset for e.g. if one of them was called
1234L01.set
and had a field labelled data containing the full data recording of (non-chopped into "pre" and "post"), I want to save the "pre" and "post" fields that I created such that I have 2 new datasets
1234L01_pre.set and 1234L01_post.set
and the data field in each of these is the "pre" and the "post" respectively and any other fields associated with the dataset are maintained.
I am a bit confused on how to do it because I don't understand how to take the original filename and modify it and I have lots of datasets so I don't want to do it all by hand.
Could anybody help with this please?
A: Something like:
[p,f,e] = fileparts ( ALLEEG(data_set).filename );
newFilename = sprintf ( '%s_pre.%s', f, e )
pre = ALLEEG(data_set).pre;
save ( newFilename, 'pre' );
newFilename = sprintf ( '%s_post.%s', f, e )
post = ALLEEG(data_set).post;
save ( newFilename, 'post' );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29672991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get data from another EntityProxy in GXT ColumnConfig? Here is the thing: I have an application to manage user's tickets.
I have 2 basic classes : Ticket and User.
Using GXT I have some ColumnConfig class like this:
ColumnConfig<TicketProxy, String> dateColumn = new ColumnConfig<TicketProxy, String>(
new ValueProvider<TicketProxy, String>() {
public String getValue(TicketProxy object) {
Date initialDate = object.getInitialDate();
String date = "";
if (initialDate != null) {
date = dtFormat.format(initialDate);
}
return date;
}
public void setValue(TicketProxy object, String initialDate) {
if (object instanceof TicketProxy) {
object.setInitialDate(dtFormat.parse(initialDate));
}
}
public String getPath() {
return "initialDate";
}
}, 70, "Date");
columnsChamado.add(dateColumn);
but I want to get some data from UserProxy class, some like this:
ColumnConfig<UserProxy, String> userRoomColumn = new ColumnConfig<UserProxy, String>(
new ValueProvider<UserProxy, String>() {
public String getValue(UserProxy object) {
String userRoom = object.getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(UserProxy object, String userRoom) {
if (object instanceof UserProxy) {
object.setUserRoom(userRoom);
}
}
public String getPath() {
return "userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
But GWT doesn't allow me to change the "Proxy" parameter to another class in the same ColumnConfig.
How can I get data from other Proxy class in this ColumnConfig?
I use GXT 3.0 (Sencha) + Hibernate.
Proxy classes:
BaseEntityProxy:
package com.acme.ccc.shared;
import com.acme.ccc.server.locator.CCCLocator;
import com.acme.db.base.DatabaseObject;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import com.google.web.bindery.requestfactory.shared.SkipInterfaceValidation;
@SkipInterfaceValidation
@ProxyFor(value = DatabaseObject.class, locator = CCCLocator.class)
public interface BaseEntityProxy extends EntityProxy {
Long getId();
Long getVersion();
void setId(Long id);
void setVersion(Long version);
}
TicketProxy:
package com.acme.ccc.shared.entityproxy;
import java.util.Date;
import java.util.List;
import com.acme.ccc.db.Ticket;
import com.acme.ccc.server.locator.CCCLocator;
import com.acme.ccc.shared.BaseEntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
@ProxyFor(value = Ticket.class, locator = CCCLocator.class)
public interface TicketProxy extends BaseEntityProxy {
Date getPrazo();
void setPrazo(Date prazo);
TicketTipoProxy getTicketTipo();
void setTicketTipo(TicketTipoProxy chamadoTipo);
CanalOrigemProxy getCanalOrigem();
void setCanalOrigem(CanalOrigemProxy canalOrigem);
UserProxy getUser();
void setUser(UserProxy user);
CategoriaProxy getPedidoTipo();
void setPedidoTipo(CategoriaProxy pedidoTipo);
Date getInitialDate();
void setInitialDate(Date dt);
Long getTotal();
void setTotal(Long total);
}
UserProxy:
package com.acme.ccc.shared.entityproxy;
import java.util.List;
import com.acme.ccc.db.User;
import com.acme.ccc.server.locator.CCCLocator;
import com.acme.ccc.shared.BaseEntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
@ProxyFor(value = User.class, locator = CCCLocator.class)
public interface UserProxy extends BaseEntityProxy {
String getName();
String getUserRoom();
Long getTotal();
void setName(String name);
void setUserRoom(Sting room)
void setTotal(Long total);
}
A: If you have a Column of TicketProxy, you can get the UserProxy from the TicketProxy ?
ColumnConfig<TicketProxy, String> userRoomColumn = new ColumnConfig<TicketProxy, String>(
new ValueProvider<TicketProxy, String>() {
public String getValue(TicketProxy object) {
String userRoom = object.getUser().getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(TicketProxy object, String userRoom) {
object.getUser().setUserRoom(userRoom);
}
public String getPath() {
return "user.userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
A: An gxt grid is able to show the data only of one data type. If you put a single TicketProxy row, how do you expect to access a user object?
If you want to display both Tickets and Users independently (so a row is either a Ticket OR a User), you have to use BaseEntityProxy in your Grid: Grid<BaseEntityProxy>. Then you can define your columns as ColumnConfig<BaseEntityProxy, ?> and check the type within your getters and setter:
List<ColumnConfig<BaseEntityProxy, ?>> columnsChamado = new ArrayList<ColumnConfig<BaseEntityProxy, ?>>();
ColumnConfig<BaseEntityProxy, String> dateColumn = new ColumnConfig<BaseEntityProxy, String>(
new ValueProvider<BaseEntityProxy, String>() {
private final DateTimeFormat dtFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL);
public String getValue(BaseEntityProxy object) {
Date initialDate = ((TicketProxy) object).getInitialDate();
String date = "";
if (initialDate != null) {
date = dtFormat.format(initialDate);
}
return date;
}
public void setValue(BaseEntityProxy object, String initialDate) {
if (object instanceof TicketProxy) {
((TicketProxy) object).setInitialDate(dtFormat.parse(initialDate));
}
}
public String getPath() {
return "initialDate";
}
}, 70, "Date");
columnsChamado.add(dateColumn);
ColumnConfig<BaseEntityProxy, String> userRoomColumn = new ColumnConfig<BaseEntityProxy, String>(
new ValueProvider<BaseEntityProxy, String>() {
public String getValue(BaseEntityProxy object) {
String userRoom = ((UserProxy)object).getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(BaseEntityProxy object, String userRoom) {
if (object instanceof UserProxy) {
((UserProxy)object).setUserRoom(userRoom);
}
}
public String getPath() {
return "userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
ColumnModel<BaseEntityProxy> cm = new ColumnModel<BaseEntityProxy>(columnsChamado);
If, on the other hand, you want one grid row to display a User AND a Ticket, you have to use a wrapper class:
class TicketWithUserProxy extends BaseEntityProxy{
private UserProxy userProxy;
private TicketProxy ticketProxy;
public UserProxy getUserProxy() {
return userProxy;
}
public void setUserProxy(UserProxy userProxy) {
this.userProxy = userProxy;
}
public TicketProxy getTicketProxy() {
return ticketProxy;
}
public void setTicketProxy(TicketProxy ticketProxy) {
this.ticketProxy = ticketProxy;
}
}
and setup your grid (Grid<TicketWithUserProxy>) accordingly:
List<ColumnConfig<TicketWithUserProxy, ?>> columnsChamado = new ArrayList<ColumnConfig<TicketWithUserProxy, ?>>();
ColumnConfig<TicketWithUserProxy, String> dateColumn = new ColumnConfig<TicketWithUserProxy, String>(
new ValueProvider<TicketWithUserProxy, String>() {
private final DateTimeFormat dtFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL);
public String getValue(TicketWithUserProxy object) {
Date initialDate = object.getTicketProxy().getInitialDate();
String date = "";
if (initialDate != null) {
date = dtFormat.format(initialDate);
}
return date;
}
public void setValue(TicketWithUserProxy object, String initialDate) {
object.getTicketProxy().setInitialDate(dtFormat.parse(initialDate));
}
public String getPath() {
return "initialDate";
}
}, 70, "Date");
columnsChamado.add(dateColumn);
ColumnConfig<TicketWithUserProxy, String> userRoomColumn = new ColumnConfig<TicketWithUserProxy, String>(
new ValueProvider<TicketWithUserProxy, String>() {
public String getValue(TicketWithUserProxy object) {
String userRoom = object.getUserProxy().getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(TicketWithUserProxy object, String userRoom) {
object.getUserProxy().setUserRoom(userRoom);
}
public String getPath() {
return "userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
ColumnModel<TicketWithUserProxy> cm = new ColumnModel<TicketWithUserProxy>(columnsChamado);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20290626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's wrong with the output? this is my first time here. I'm learning C++ by myself from the book "Starting Out With C++" by Gaddis. Therefore I don't know who to ask, and then I found this website. Hope you don't mind to help me and I will learn a lot from you.
Here is one problem in the book:
Write a function named arrayToFile. The function should accept three arguments:
the name of a le, a pointer to an int array, and the size of the array. The function
should open the speci ed le in binary mode, write the contents of the array to the
le, and then close the le.
Write another function named fileToArray. This function should accept three arguments:
the name of a le, a pointer to an int array, and the size of the array. The
function should open the speci ed le in binary mode, read its contents into the array,
and then close the le.
Write a complete program that demonstrates these functions by using the arrayToFile
function to write an array to a le, and then using the fileToArray function to read
the data from the same le. After the data are read from the le into the array, display
the array s contents on the screen.
And here is my code:
# include <iostream>
# include <string>
# include <fstream>
using namespace std;
const int SIZE = 10;
bool arrayToFile(fstream&, int*, int);
bool fileToArray(fstream&, int*, int);
int main()
{
int arr[SIZE] = { 10, 8, 9, 7, 6, 4, 5, 3, 2, 1 },
arrTest[SIZE];
fstream file;
if (arrayToFile(file, arr, SIZE))
{
if (fileToArray(file, arr, SIZE))
{
for (int n = 0; n < SIZE; n++)
{
cout << arrTest[n] << " ";
}
cout << endl;
return 0;
}
}
return 1;
}
bool fileToArray(fstream &file, int* a, int size)
{
file.open("t.dat", ios::in | ios::binary);
if (!file)
{
cout << "Can't open file t.dat\n";
return false;
}
file.read((char*)a, size);
file.close();
return true;
}
bool arrayToFile(fstream &file, int* a, int size)
{
file.open("t.dat", ios::out | ios::binary);
if (!file)
{
cout << "Can't open file t.dat\n";
return false;
}
file.write((char*)a, size);
file.close();
return true;
}
AND HERE IS THE OUTPUT:
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -85
8993460 -858993460 -858993460
I don't know what's wrong here, because the output is supposed to be like this: 10 8 9 7 6 4 5 3 2 1
Thanks for your help.
A: Before I begin, you must understand that a char is of size sizeof(char) bytes and an int is of size sizeof(int) bytes, which in general is 1 byte and 4 bytes respectively. This means that 4 chars can make up 1 int.
Now if you look at file.write((char*)a, size);, you are converting the int* to char*, which means to look at the data in a as chars and not ints.
Performing some simple math, your array of 10 ints is of size 10 * 4 = 40 bytes. However, the amount of data you're writing to the file is of 10 chars which is only 10 bytes.
Next, you attempt to write arr to the file, and you read from the file back into arr. I assume you want to read into arrTest but as you've failed to do so, attempting to access the contents of arrTest will give you the output that you see, which as explained by the rest of the community is uninitialized memory. This is because arrTest[SIZE] defines an array of SIZE but the memory within it is uninitialized.
To sum it up, the cause of your current output is due to a problem in your program logic, and your incorrect usage of read and write poses a potential problem.
Thank you for reading.
A: file.write((char*)a, size);
writes size bytes to the file.
file.read((char*)a, size);
reads size bytes to the file.
You are using 10 for size. You are writing and reading just 10 bytes of data. You need to change those lines to:
file.write((char*)a, size*sizeof(int));
and
file.read((char*)a, size*sizeof(int));
And call fileToArray using the right argument. Instead of
if (fileToArray(file, arr, SIZE))
use
if (fileToArray(file, arrTest, SIZE))
without that, arrTest remains an uninitialized array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27477076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Mutable state of value from viewModel is not working I have a mutablestate in my ViewModel that I'm trying to set and access in my composable. When I use delegated Property of remember it is working but after creating it in viewModel and accessing it in compose the state of the variable is empty how to use the state with viewModel
Everything is working fine when the state is inside the compose
var mSelectedText by remember { mutableStateOf("") }
But when i use it from viewModel change and set my OutlinedTextField value = mainCatTitle and onValueChange = {mainCatTitle = it} the selected title is not Showing up in the OutlinedTextField is empty
private val _mainCatTitle = mutableStateOf("")
val mainCatTitle: State<String> = _mainCatTitle
my Composable
var mSelectedText by remember { mutableStateOf("") }
var mainCatTitle = viewModel.mainCatTitle.value
Column(Modifier.padding(20.dp)) {
OutlinedTextField(
value = mainCatTitle,
onValueChange = { mainCatTitle = it },
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
mTextFieldSize = coordinates.size.toSize()
},
readOnly = true,
label = { Text(text = "Select MainCategory") },
trailingIcon = {
Icon(icon, "contentDescription",
Modifier.clickable { mExpanded = !mExpanded })
}
)
DropdownMenu(expanded = mExpanded,
onDismissRequest = { mExpanded = false },
modifier = Modifier.width(with(
LocalDensity.current) {
mTextFieldSize.width.toDp()
})) {
selectCategory.forEach {
DropdownMenuItem(onClick = {
mainCatTitle = it.category_name.toString()
mSelectedCategoryId = it.category_id.toString()
mExpanded = false
Log.i(TAG,"Before the CategoryName: $mainCatTitle " )
}) {
Text(text = it.category_name.toString())
}
}
}
}
Log.i(TAG,"Getting the CategoryName: $mainCatTitle " )
}
in my First log inside the DropDownMenuItem the log is showing the Selected field but second log is empty
Have attached the image
A: Your'e directly modifying the mainCatTitle variable from onClick, not the state hoisted by your ViewMoel
DropdownMenuItem(onClick = {
mainCatTitle = it.category_name.toString()
...
and because you didn't provide anything about your ViewModel, I would assume and suggest to create a function if you don't have one in your ViewModel that you can call like this,
DropdownMenuItem(onClick = {
viewModel.onSelectedItem(it) // <-- this function
...
}
and in your ViewModel you update the state like this
fun onSelectedItem(item: String) { // <-- this is the function
_mainCatTitle.value = item
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74388432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Laravel using an OR style combination in Route Middleware I am trying to use multiple middleware in a route as follows
Route::get('devices', ['as' => 'devices.index', 'uses' => 'deviceController@index', 'middleware' => ['permission:manage_devices', 'permission:device.view']]);
This will implement AND logic between the two middlewares. I want to implement an 'OR' Logic but could not find any help.
A: Tough it isn't the most eloquent solution, you could try to create your own middleware that loads other middleware in a if/else or switch statement. That way you might be able to achieve the behaviour you'd want.
Check the docs on the link below on how to program your own middleware:
https://laravel.com/docs/5.3/middleware#defining-middleware
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40883033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a divide in lookup and got error in Mongodb I'm new to MongoDB and it's really hard to do divide with lookup. I want to make a monthly salary for each employee. How can I do that? Thanks in advance. Any help would be greatly appreciated. Also, I converted my salary field to float. However, still, I'm still getting error. When I use it without a divide it's showing fine. I tried to find an answer to these in hourly and didn't get succeed.
db.Salary.insertMany([
{
"POSITION": "1",
"BRANCH_SIZE": "HQ",
"SALARY": "150000"
},
{
"POSITION": "2",
"BRANCH_SIZE": "HQ",
"SALARY": "100000"
},
{
"POSITION": "3",
"BRANCH_SIZE": "HQ",
"SALARY": "70000"
},
{
"POSITION": "4",
"BRANCH_SIZE": "HQ",
"SALARY": "30000"
},
{
"POSITION": "5",
"BRANCH_SIZE": "HQ",
"SALARY": "56000"
}
])
db.Employee.insertMany([
{
"EMPLOYEE_NO": "1000",
"LNAME": "Wyatt",
"FNAME": " Stefan",
"STREET": "1255 Harrinton Ave.",
"CITY": "MANKATO",
"STATE": "MN",
"ZIP": "56001",
"STATUS": "1",
"DOB": "12-MAY-54",
"START_DATE": "06-MAY-76",
"END_DATE": "",
"BRANCH_NO": "100",
"BRANCH_SIZE": "HQ",
"POSITION": "1",
"RATE": "",
"COMMISSION": ""
},
{
"EMPLOYEE_NO": "1029",
"LNAME": "Martin",
"FNAME": "Edward",
"STREET": "1250 Harrinton Ave.",
"CITY": "SPRINGFIELD",
"STATE": "IL",
"ZIP": "62701",
"STATUS": "1",
"DOB": "08-MAY-68",
"START_DATE": "02-MAY-95",
"END_DATE": "",
"BRANCH_NO": "103",
"BRANCH_SIZE": "MD",
"POSITION": "3",
"RATE": "",
"COMMISSION": ""
},
{
"EMPLOYEE_NO": "1089",
"LNAME": "Stewart",
"FNAME": "Macy",
"STREET": "3415 Olanwood Court, Suite 202",
"CITY": "SAINT PAUL",
"STATE": "MN",
"ZIP": "55101",
"STATUS": "2",
"DOB": "30-APR-29",
"START_DATE": "24-APR-55",
"END_DATE": "",
"BRANCH_NO": "101",
"BRANCH_SIZE": "BG",
"POSITION": "4",
"RATE": "",
"COMMISSION": ""
}
])
I convert salary field to float using below code.
db.Salary.find({SALARY: {$exists: true}}).forEach(function(obj) {
obj.SALARY = parseFloat(obj.SALARY);
db.Salary.save(obj);
});
> db.Employee.aggregate([{
... $lookup: {
... from: "Salary",
... localField: "POSITION",
... foreignField: "POSITION",
... as: "MOnthlySalary"}},
... {$project: {"EMPLOYEE_NO":1,"LNAME":1,"FNAME":1,
... "MOnthlySalary": {$divide: ["$SALARY", 12]}
... }}])
Output:-
{ "_id" : ObjectId("5efa025aeeaa35a209477ebe"), "EMPLOYEE_NO" : "1000", "LNAME" : "Wyatt", "FNAME" : " Stefan", "MOnthlySalary" : null }
{ "_id" : ObjectId("5efa025aeeaa35a209477ebf"), "EMPLOYEE_NO" : "1029", "LNAME" : "Martin", "FNAME" : "Edward", "MOnthlySalary" : null }
{ "_id" : ObjectId("5efa025aeeaa35a209477ec0"), "EMPLOYEE_NO" : "1089", "LNAME" : "Stewart", "FNAME" : "Macy", "MOnthlySalary" : null }
A: db.Employee.aggregate([{
$lookup: {
from: "Salary",
localField: "POSITION",
foreignField: "POSITION",
as: "MOnthlySalary"}},
{$unwind:"$MOnthlySalary"},
{$match:{}},
{$project: {"EMPLOYEE_NO":1,"LNAME":1,"FNAME":1,"SALARY":1,
"avgSalary": {$divide: ["$MOnthlySalary.SALARY", 12]}
}}])
Change is $MOnthlySalary.SALARY
Output:
/* 1 */
{
"_id" : ObjectId("5efa0fffc8a4b73cb0b8e320"),
"EMPLOYEE_NO" : "1000",
"LNAME" : "Wyatt",
"FNAME" : " Stefan",
"avgSalary" : 12500.0
}
/* 2 */
{
"_id" : ObjectId("5efa0fffc8a4b73cb0b8e321"),
"EMPLOYEE_NO" : "1029",
"LNAME" : "Martin",
"FNAME" : "Edward",
"avgSalary" : 5833.33333333333
}
/* 3 */
{
"_id" : ObjectId("5efa0fffc8a4b73cb0b8e322"),
"EMPLOYEE_NO" : "1089",
"LNAME" : "Stewart",
"FNAME" : "Macy",
"avgSalary" : 2500.0
}
You can use $round to round the avgSalary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62641998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: On Google can Kubernetes nodes be configured to have multiple network interfaces? On Google Container Platform can Kubernetes nodes (or node pools) be configured to have multiple network interfaces?
A: Unfortunately they cannot. All of the parameters that you can configure through the Google Kubernetes Engine API are here.
If you want to customize the nodes beyond what is offered through the API you can create your own instance template as described in this stackoverflow answer. The downside is that you will no longer be able to manage the nodes via the Google Kubernetes Engine API (e.g. for upgrading).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50976985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: replce value of column in phpmyadmin I am working with phpmyadmin. I have one table log in phpmyadmin. I would like to change a value in one column. If I add new value, it must show me Arbeitsplatz 1 instead of 1 in the Station column.
This is my log table. In the third column I would like to replace values for every new entry. For example, if the new value is 3 in station column, it should show me Arbeitsplatz 3 in the log table. If it is 4, then Arbeitsplatz 4 and so on.
How do I implement this?
A: You probably need to change the column datatype from integer to varchar first, then update that row:
update `log` set `Station` = CONCAT('Arbeitsplatz ', `Station`);
But first, back up that table just in case something fails...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58879243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Postback parent page when using an ASP.NET ModalPopup control I have a custom UserControl that displays a modal popup (from the Ajax Toolkit). The control allows the user to add a note to a customer record which the parent page displays in a GridView.
I'm unable to force the parent page to reload the grid after the user clicks the "Add Note" button on the modal popup and closes it. The note is added to the database correctly, but I have to manually refresh the page to get it to display instead of it automatically refreshing when I save+close the popup.
A: You can use a delegate to fire an event in parent page after note is added to the database.
// Declared in Custom Control.
// CustomerCreatedEventArgs is custom event args.
public delegate void EventHandler(object sender, CustomerCreatedEventArgs e);
public event EventHandler CustomerCreated;
After note is added, fire parent page event.
// Raises an event to the parent page and passing recently created object.
if (CustomerCreated != null)
{
CustomerCreatedEventArgs args = new CustomerCreatedEventArgs(objCustomerMaster.CustomerCode, objCustomerMaster.CustomerAddress1, objCustomerMaster.CustomerAddress2);
CustomerCreated(this, args);
}
In parent page, implement required event to re-fill grdiview.
protected void CustomerCreated(object sender, CustomerCreatedEventArgs e)
{
try
{
BindGridView();
}
catch (Exception ex)
{
throw ex;
}
}
In your case, you can not use any custom event args, and use EventArgs class itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4453623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Splitting a string into an array of n words I'm trying to turn this:
"This is a test this is a test"
into this:
["This is a", "test this is", "a test"]
I tried this:
const re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/
const wordList = sample.split(re)
console.log(wordList)
But I got this:
[ '',
' ',
' ']
Why is this?
(The rule is to split the string every N words.)
A: As an alternate approach, you can split string by space and the merge chunks in batch.
function splitByWordCount(str, count) {
var arr = str.split(' ')
var r = [];
while (arr.length) {
r.push(arr.splice(0, count).join(' '))
}
return r;
}
var a = "This is a test this is a test";
console.log(splitByWordCount(a, 3))
console.log(splitByWordCount(a, 2))
A: your code is good to go. but not with split. split will treat it as a delimitor.
for instance something like this:
var arr = "1, 1, 1, 1";
arr.split(',') === [1, 1, 1, 1] ;
//but
arr.split(1) === [', ', ', ', ', ', ', '];
Instead use match or exec. like this
var x = "This is a test this is a test";
var re = /\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g
var y = x.match(re);
console.log(y);
A: The String#split method will split the string by the matched content so it won't include the matched string within the result array.
Use the String#match method with a global flag (g) on your regular expression instead:
var sample="This is a test this is a test"
const re = /\b[\w']+(?:\s+[\w']+){0,2}/g;
const wordList = sample.match(re);
console.log(wordList);
Regex explanation here.
A: Use whitespace special character (\s) and match function instead of split:
var wordList = sample.text().match(/\s?(?:\w+\s?){1,3}/g);
Split breaks string where regex matches. Match returns whatever that is matched.
Check this fiddle.
A: You could split like that:
var str = 'This is a test this is a test';
var wrd = str.split(/((?:\w+\s+){1,3})/);
console.log(wrd);
But, you have to delete empty elements from the array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40817167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: how to clear a certain content in a rich text box i have a rich text box that displays items.These items have column names.The column names are loaded when the form loads.They hold values as rows.These rows are appended at a click of a button (when add button is clicked).
At the bottom,let me say i have another field(total amount) in the rtb which displays total value of a Amount column.This is also displayed when calculate button is clicked.
If someone wants to add another row to be calculated it would create the format displayed.so i wanted to clear the total amount field when another item gets added.Is there a way to do that.
A: Richtextbox1.text = mid(Richtextbox1.text,1,len(richtextbox1.text)-x) & NewTotal
Where x is the length of the previous total and NewTotal is the new total string.
Edit (see comments):
Use this code to solve your issue:
dim numberofcolumns as integer = listview1.ColumnHeaders.Count
dim str(numberofcolumns-1) as string
str(numberofcolumns-2) = "TotalAmount"
str(numberofcolumns-1) = totalammountvariable
Dim itm As ListViewItem
itm = New ListViewItem(str)
ListView1.Items.add(itm)
A: First Clear All Data and Rebind
RichTextBox1.Clear()
Using this Command clear all data in Richtextbox and rebind you data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19815002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exception in Fortran DLL after upgrading Visual Studio I have a C++ DLL. We developed it originally in Visual Studio 2005 and recently upgraded it to Visual Studio 2013. This DLL then calls into a Fortran DLL for some functionality (the Fortran DLL is provided by a third party developer who cannot share source code). Recently, for some inputs, the call to the Fortran library has started throwing an exception:
First-chance exception at 0x1C00BA50 in Application.exe: 0xC0000005: Access violation executing location 0x1C00BA50.
This exception only occurs when the Fortran DLL is called from the Visual Studio 2013 generated executable on Windows 7. When I call the same Fortran DLL with the same input from the Visual Studio 2005 executable, there is no exception and the Fortran DLL produces correct results. Additionally, running the Visual Studio 2005 solution on Windows XP SP3 does not produce an error either.
Supporting details:
*
*The C++ DLL that calls the Fortran is a 32-bit, x86 DLL
*Fortran DLL is built against DFort 6.1a
*In dependency walker, needs: DFORRT.DLL, MSVCRT.DLL, and KERNEL32.DLL
*The C++ executable is built for x86 using the "Visual Studio 2013 - Windows XP (v120_xp)" Platform Toolset
*The crash does not happen on Windows XP SP3; it does on both 32 and 64-bit Windows 7 machines. I am setting up a Vista environment to test there, but won't have results for a few days.
If it helps, the function signature is:
extern "C"
{
typedef long (__stdcall *FUNCTIONID)
(
float* array1,
float* array2,
float* array3,
long& numItems,
long& numThings,
float* thingData,
float* thing2data,
float& result,
long* resArray,
float* resArray2,
float* resArray3);
}
The library is loaded by:
m_funcDLL = ::LoadLibrary("DLLNAME.DLL");
Additionally, we call this by:
FUNCTIONID pfnFUNC = nullptr;
pfnFUNC = (FUNCTIONID)GetProcAddress(m_funcDLL, "FUNCNAME");
if(pfnFUNC) {
try {
iErr = (*pfnFUNC)( args...);
}
}
The args are a mix of static arrays and dynamic arrays (although we have experimented with C++11's std::array and std::vector to pass things around; we get the same error using both container types).
We're not using Unicode on our builds (that's a wishlist item for now), so we're using Multibyte Character Sets (although none of the arrays passed in are char arrays).
The primary question I have is: Is anyone aware of any binary compatibility issues with Visual Studio 2013 on Windows 7 that would cause crashes like this? Are there things I should be looking at that I'm not?
A: DLLs and code using DLLs which are linked against different versions of the runtime library (and possibly other libraries) are in danger of breaking, if one or more of the following happens:
*
*Interface to DLL uses classes/structures, where the size might differ depending on version of runtime library. (One unfortunate member might be enough).
*Heap objects are not being allocated/freed at the same side of the interface.
*Sometimes people play with compiler settings regarding alignment. Maybe different versions of compilers also change their "policy".
*Look out for #pragma (pack,..), __declspec(align()) etc.
*In older Versions of VS there were "single threaded" and "multi-threaded" versions of run time libraries. Mixing DLLs and Applications not linked against the same kind of library could cause trouble.
*#include <seeminglyharmlessheader.h> in header files, seen by both application and DLL can hold some nasty surprises in stock.
*Maybe an (unnoticed) change in other compiler/linker settings, e.g. regarding exception handling.
I could not fully follow the 32bit/64bit things you said in the question part. I don't think, mixing both works, but I also think you are not trying that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28571655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: GIL context - switching So, I generally have a pretty good understanding of how the Global Interpreter Lock (GIL) in Python works. Essentially, while the interpreter is running, one thread holds the GIL for N ticks (where N can be set using sys.setcheckinterval), at which point the GIL is released and another thread can acquire the GIL. The also happens if one thread begins an I/O operation.
What I'm a bit confused about is how this all works with C extension modules.
If you have a C extension module that acquires the GIL, and then executes some python code using PyEval_EvalCode, can the interpreter release the GIL and give it to some other thread? Or will the C thread that acquired the GIL hold the GIL permanently until PyEval_EvalCode returns and the GIL is explicitly released in C?
PyGILState gstate = PyGILState_Ensure();
....
/* Can calling PyEval_EvalCode release the GIL and let another thread acquire it?? */
PyObject* obj = PyEval_EvalCode(code, global_dict, local_dict);
PyGILState_Release(gstate);
A: Yes, the interpreter can always release the GIL; it will give it to some other thread after it has interpreted enough instructions, or automatically if it does some I/O. Note that since recent Python 3.x, the criteria is no longer based on the number of executed instructions, but on whether enough time has elapsed.
To get a different effect, you'd need a way to acquire the GIL in "atomic" mode, by asking the GIL not to be released until you release it explicitly. This is impossible so far (but see https://bitbucket.org/arigo/cpython-withatomic for an experimental version).
A: As Armin said, the GIL can be released inside PyEval_EvalCode. When it returns, it is of course acquired again.
The best way is just to make sure that your code can handle that. For example, incref any objects where you have C pointers to before the GIL might get released. Also, be careful if there might be cases where the Python code again calls the very same function. If you have another mutex there, you can easily end up in a dead-lock. Use recursive-safe mutexes and while waiting on them, you should release the GIL so that the original thread can releases such mutexes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16257587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I get the big picture of my custom notification take the whole width of the notification while also keeping the Android system decorations? I have an app currently with 19 (KitKat) as the min sdk.
I need a notification that acts as a mix of BigPictureStyle and BigTextStyle. For that, I am using remote views alongside DecoratedCustomViewStyle to get the desired effect, but the result is that the big image doesn't take the whole width, and instead I get this:
The problem shouldn't be the image size I'm using, because removing DecoratedCustomViewStyle from the notification builder fixes the width problem, but without it, I don't get all the system decorations(see image below), and the requirement is to the have them too.
I also found Accengage's notifications templates where they have this style called BigTextBigPicture which is exactly what I need, but while they provide the layout files, I cannot get it to work for phones with Nougat and above, as I am getting the same result that I got by removing DecoratedCustomViewStyle, so no system decorations.
Here is the notification builder:
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(),
Constants.CHANNEL_ID)
.setSmallIcon(R.drawable.my_app_logo)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle());
Here is the notification_large layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="256dp"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:fadingEdge="horizontal"
android:maxLines="2"
style="@style/TextAppearance.Compat.Notification.Title"
android:text="@string/notification_test_title"/>
<TextView
android:id="@+id/msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:fadingEdge="horizontal"
android:maxLines="6"
style="@style/TextAppearance.Compat.Notification"
android:text="@string/notification_test_msg"/>
<ImageView
android:layout_marginStart="2dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/test_cute_kirby"
android:scaleType="fitXY"/>
</LinearLayout>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54833320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Using .htaccess rewrites to redirect from old url to new url I have a website example.com which was the old domain name for my site. We wish to switch from the old domain name to a new domain name theexample.com.
As the site is hosted using a web host we currently have both domain names pointing to the same ip address. I thought that I should be able to put a .htaccess file in the server's root directory which would redirect from the old site to the new site based on a rewritecond. I was the thinking the code below would do the trick but it doesn't work
RewriteEngine on
rewritecond %{http_host} ^example.com [nc]
rewriterule ^(.*)$ http://theexample.com/$1 [r=301,nc]
A: Okay.. The code in your question seems right! However, you can still try these configuration directives in your .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^(.*)$ http://theexample.com/$1
But first, make sure that there's an Apache HTTP Server with mod_rewrite in your web host.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15916382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Check optional mutex before scoped locking I have a constructor that optionally allows the user to pass a ponter to a Boost mutex. If no mutex is supplied, the member pointer pMyMutex is set to NULL. This gives the user the option of applying some thread safety if they wish. However, I cannot use a scoped_lock with this kind of check for obvious reasons :)
if (pMyMutex != NULL)
const boost::mutex::scoped_lock l(*pMyMutex);
//The lock is already out of scope
processStuff(x, y, z);
Can anyone suggest a neat and simple solution to such a requirement?
A: Implement your own wrapper similar with scoped_lock to hide the decision inside it: wrapping a pointer to a mutex and checking if the pointer is null (no locking applied) or not null (locking applied). Some skeleton:
class ScopedLockEx
{
public:
ScopedLockEx( boost::mutex* pMutex)
: pMutex_( pMutex)
{
if( pMutex_) pMutex_->lock();
}
~ScopedLockEx()
{
if( pMutex_) pMutex_->unlock();
}
private:
boost::mutex* pMutex_;
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10752280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I join denormalized tables in MySQL? I have a table with different people. And I want to connect them to my house table
house table:
+-------+---------+---------+---------+
| house | person1 | person2 | person3 |
+-------+---------+---------+---------+
| 1 | 2 | 4 | 1 |
| 2 | 3 | 1 | 2 |
+-------+---------+---------+---------+
people table:
+----+------+
| id | name |
+----+------+
| 1 | fred |
| 2 | john |
| 3 | leo |
| 4 | tom |
+----+------+
Is something like this possible?
$pdo = $db->query('
SELECT *
FROM house
LEFT JOIN people
ON house.person1=people.id
AND house.person2=people.id
;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "Person 1 = ".$row['name'];
echo "Person 2 = ".$row['name'];
}
A: You are close, you need OR or IN() instead of AND:
SELECT *
FROM house h
LEFT JOIN people p ON p.id IN(h.person1,h.person2,h.person3)
But I believe, a better approach is to change your table design as proposed by the comments. In that case you will simply need:
SELECT *
FROM house h
LEFT JOIN people p ON h.person = p.id
A: You should use self join on table people 3 name with 3 alias
$pdo = $db->query('
SELECT *, people1.name as name1, people2.name as name2, people3.name as name3
FROM house
LEFT JOIN people as people1 ON house.person1=people1.id
LEFT JOIN people as people2 ON house.person2=people2.id
LEFT JOIN people as people3 ON house.person3=people3.id
;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "Person 1 = ".$row['name1'];
echo "Person 2 = ".$row['name2'];
echo "Person 3 = ".$row['name3'];
}
A: if you need to know the name of the 3 person in every house, you can use this
$pdo = $db->query('
select A.house, B.name as person1, C.name as person2, D.name as person3
from house A join people B on (A.person1=B.id) left join people C on (A.person2=C.id) join people D on (A.person3=D.id)
;');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo "house = ".$row['house'];
echo "Person 1 = ".$row['person1'];
echo "Person 2 = ".$row['person2'];
echo "Person 2 = ".$row['person3'];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42652569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laravel Mix unknown option '--hide-modules' error When I try to compile React component with Laravel Mix in my Laravel project it raises error 2 lifecycle.
E:\MY PROJECTS\Samriddhi Institute> npm run dev
@ dev E:\MY PROJECTS\Samriddhi Institute
npm run development
@ development E:\MY PROJECTS\Samriddhi Institute
cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/
setup/webpack.config.js
[webpack-cli] Error: Unknown option '--hide-modules' [webpack-cli] Run
'webpack --help' to see available commands and options npm ERR! code
ELIFECYCLE npm ERR! errno 2 npm ERR! @ development: cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=no de_modules/laravel-mix/setup/webpack.config.js npm ERR! Exit status 2
npm ERR! npm ERR! Failed at the @ development script. npm ERR! This is
probably not a problem with npm. There is likely additional logging
output above.
npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\RADHESHYAM\AppData\Roaming\npm-cache_logs\2021-09-17T05_52_36_957Z-debug.log
npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! @ dev: npm run development npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the @
dev script. npm ERR! This is probably not a problem with npm. There is
likely additional logging output above.
npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\RADHESHYAM\AppData\Roaming\npm-cache_logs\2021-09-17T05_52_37_148Z-debug.log
PS E:\MY PROJECTS\Samriddhi Institute>"
A: Update Laravel Mix
npm install --save-dev laravel-mix@latest
Update Your NPM Scripts
If your build throws an error such as Unknown argument: --hide-modules, the scripts section of your package.json file will need to be updated. The Webpack 5 CLI removed a number of options that your NPM scripts was likely referencing.
While you're at it, go ahead and switch over to the new Mix CLI.
Before
"scripts": {
"dev": "npm run development",
"development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "npm run development -- --watch",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --disable-host-check --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
After
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production"
},
A: I had this issue and solved it by downgrading laravel-mix to
"laravel-mix": "^5.0.9"
then running:
npm install
A: Remove --hide-modules from your package.json and than run npm run dev it will run without erros.
A: In my case i had to switch to node version 14 as i was on 18.
My steps.
(1) Check current node version.
nvm list # -->v18.4
(2) Switched to node 14.
nvm use 14.19
(3) Installed again
npm install
(4) Run dev
npm run dev
It worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69218549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Making Ionic2 Slides using Firebase data I stored profile data in firebase and
trying to retrieve them and show them in template with slides.
(I am making a matching service.)
But it seems the template is loaded before data is assigned to variable.
When I am just retrieving one data, not list,
it works fine.
I tried all the solutions on the goole,
like using 'NgZone', *ngIf, etc but nothing worked.
Please help me.
My Error message.
FindMatePage.html:21 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff (core.es5.js:7083)
at NgForOf.ngDoCheck (common.es5.js:1699)~~
My find-mate.ts file.
export class FindMatePage implements OnInit{
@ViewChild('profileSlide') slider: Slides;
profileList = [] as Profile[];
constructor(public navCtrl: NavController, public navParams: NavParams,
private databaseService: DataServiceProvider, private auth:
AuthServiceProvider,
) {}
ngOnInit(){
this.auth.getActiveUser().getIdToken()
.then((token: string) => (
this.databaseService.fetchProfileList(token)
.subscribe((list: Profile[]) => {
if(list) {
this.profileList = list;
console.log(this.profileList)
} else {
this.profileList = [];
}
})
))//then ends
}
My find-mate.html file
<ion-content class="tutorial-page">
<ion-slides *ngIf="profileList" #profileSlide pager
(ionSlideDidChange)="slideChanged()">
<ion-slide>
<h2 class="profile-title">Ready to Play?</h2>
<button ion-button large clear icon-end color="primary">
Continue
<ion-icon name="arrow-forward"></ion-icon>
</button>
</ion-slide>
<ion-slide *ngFor="let profile of profileList">
<ion-buttons block>
<button ion-button color="primary">채팅하기</button>
</ion-buttons>
<ion-item> {{profile.username}}</ion-item>
<ion-item> {{profile.gym}</ion-item>
<ion-item> {{profile.goal}}</ion-item>
<ion-item> {{profile.level}}</ion-item>
</ion-slide>
My part of data-service.ts file
//프로필 목록 가져오기
fetchProfileList(token: string) {
return this.http.get('https://fitmate-16730.firebaseio.com/profile-list.json?auth=' + token)
.map((response: Response) => {
return response.json();
})
.do((profileList: Profile[]) => {
if (profileList) {
console.log(profileList);
return this.profileList = profileList;
} else {
return this.profileList = null;
}
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46641667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using checkboxes and counting them in Lightswitch HTML I am currently using this code to display checkboxes as a custom control, and it works perfect:
// Create the checkbox and add it to the DOM.
var checkbox = $("<input type='checkbox'/>")
.css({
height: 20,
width: 20,
margin: "10px"
})
.appendTo($(element));
// Determine if the change was initiated by the user.
var changingValue = false;
checkbox.change(function () {
changingValue = true;
contentItem.value = checkbox[0].checked;
changingValue = false;
});
contentItem.dataBind("value", function (newValue) {
if (!changingValue) {
checkbox[0].checked = newValue;
}
});
however now I want to extend this a little, and I am wondering if anyone knows how I can count values based on whether they are true or false.
What im looking for:
I have 2 checkboxes below, the 1st is "TRUE" and the 2nd is "FALSE"
*
*I want to be able to count up these values using something like var count then put it in a while loop, or an array and then display it back on a button like the following for testing purposes: window.alert("add in text here" + add_code_here)
so example data would be:
var trueCount = 0;
var falseCount = 0;
window.alert("There are: " + trueCount + " values that are true and " + falseCount + " that are false");
and the above example trueCount = 1 and falseCount = 1
Thanks for any input people can give me, it is most appreciated
A: I couldn't get it to work with the custom control check boxes but for the standard switches this code worked for me:
var trueCount = 0;
var falseCount = 0;
myapp.TableName.ColumnName_postRender = function (element, contentItem) {
// count the true or false values
contentItem.dataBind("value", function (newValue) {
if (contentItem.value == true) {
trueCount ++;
falseCount--;
} else if (contentItem.value == false) {
falseCount++;
trueCount--;
}
});
//count 3 sets both trueCount and falseCount to 0 as they would already be affected by the
//post render method. This works by adding or subtracting the amount of false values non
//screen (works my my scenario)
var count3 = 0;
if (contentItem.value == false) {
count3++;
}
falseCount = falseCount - count3;
trueCount = trueCount + count3;
};
myapp.TableName.Save_execute = function (screen) {
window.alert("True Count: " + trueCount + " | falseCount: " + falseCount);
//set both count values back to 0 for when the screen is next run
trueCount = 0;
falseCount = 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27949429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dax Measure - Value table compare value I have a table FactSales
And tried but didn’t get ant satisfactory result.
Id like to calculate old results and compare to my actual one and see how many customers whose bought product B before (before 90 days) didn’t buy the same product in last 3 months according to the date filter
I tried this:
Customers inactive =
VAR Daysbefore90: Max(DimDate[date]) -90
> RETURN CALCULATE( DISTINCTCOUNT(FSales[CustomerKey]); DimProduct[Product] = “A”; FILTER( ALL ( DimDate[Date] );
DimDate[Date] < DaysBefore90 ); NOT(CONTAINS( FILTER(FSales;
RELATED(DimDate[Date]) >= Daysbefore90 && DimDate[Date]) <=
MAX(Daysbefore90): RELATED(DimProduct[Product]) = “A”) ;
FSales[CustomerKey]; FSales[CustomerKey] ) ) )
A: This will get you all customer who purchased item 'B' in the last 90 Days:
Customers Who Bought Product B 90 Days Ago :=
CALCULATE (
DISTINCTCOUNT ( 'FSale'[CustomerKey] ),
ALL ( 'DimDate'[Date] ),
KEEPFILTERS (
DATESINPERIOD ( 'DimDate'[Date], MAX ( 'DimDate'[Date] ), -90, DAY )
),
KEEPFILTERS ( DimProduct[Product] = "B" )
)
Your question is a little hard to read, so maybe update it and we can go from there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52011554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails render partial with block and collection This is similar to this question but with a collection:
<div class="panel-body">
<%= render layout: 'today_items_list', locals: {items: @pos} do |po| %>
<% @output_buffer = ActionView::OutputBuffer.new %>
<%= link_to "##{po.id}", po %>
<%= po.supplier.name %>
<% end %>
</div>
with partial/layout:
.tableless_cell.no_padding
%h3.no_margin_vertical= title
%ul.no_margin_vertical
- for item in items
%li= yield(item)
This renders as you expect but if I omit the weird '@output_buffer = ActionView::OutputBuffer.new', the buffer is not cleared and the list is rendered this way:
<li>
<a href="/purchase_orders/4833">#4833</a>Supplier name
</li>
<li>
<a href="/purchase_orders/4833">#4833</a>Supplier name
<a href="/purchase_orders/4835">#4835</a>Supplier name 2
</li>
<li>
<a href="/purchase_orders/4833">#4833</a>Supplier name
<a href="/purchase_orders/4835">#4835</a>Supplier name 2
<a href="/purchase_orders/4840">#4840</a>Supplier name 3
</li>
Never clearing the buffer between block invocation. What am I missing here?
(Riding on Rails 3.2.22)
A: I don't have much experience with Rails 3.2; with newer versions, you're able to pass collections to partials:
<%= render @pos, layout: 'today_items_list' %>
#app/views/pos/_today_items_list.html.erb
.tableless_cell.no_padding
%h3.no_margin_vertical= title
%ul.no_margin_vertical
<%= yield %>
#app/views/post/_po.html.erb
<%= link_to "##{po.id}", po %>
<%= po.supplier.name %>
You can read more about collections etc (I presume for Rails 4+) here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34873585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade i have a large scale project in my hands but i simulated the problem i'm struggling with in this example:
my first class:
package asd;
import java.io.Serializable;
public class Grade implements Serializable{
String name;
Integer score;
public String getName() {
return name;
}
public Grade() {}
public Grade(String name, Integer score) {
this.name = name;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
my second class:
package asd;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private Object grade;
public String getName() {
return name;
}
public Student(String name, Object grade) {
this.name = name;
Grade = grade;
}
public Student() {}
public void setName(String name) {
this.name = name;
}
public Object getGrade() {
return Grade;
}
public void setGrade(Object grade) {
Grade = grade;
}
}
and this is my main class:
package asd;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
System.out.println("Grade Name: " + ((Grade)s2.getGrade()).getName());
System.out.println("Grade Score: " + ((Grade)s2.getGrade()).getScore());
}
}
Output:
Json string is :
{"name":"JeanPierre","Grade":{"name":"Math","score":8}}
Student Name: JeanPierre
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade
at asd.Test.main(Test.java:24)
My problem is when i call:
System.out.println("Grade Name: " + ((Grade)s2.getGrade()).getName());
or
System.out.println("Grade Score: " + ((Grade)s2.getGrade()).getScore());
i get this exception:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade
at asd.Test.main(Test.java:24)
A: Declaration and setting of the Grade in Student is syntactically wrong. Not sure how it's even building like that.
public class Student implements Serializable
{
protected String name ;
protected Grade grade ;
public Student( String name, Grade grade )
{
this.setName(name).setGrade(grade) ;
}
public String getName()
{ return this.name ; }
public Student setName( String name )
{
this.name = name ;
return this ;
}
public Grade getGrade()
{ return this.grade ; }
public Student setGrade( Grade grade )
{
this.grade = grade ;
return this ;
}
}
A: You need to parse the grade class as well. It won't convert the entire complex object in one attempt. Try the below code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
Grade g = gson.fromJson(s2.getGrade().toString(), Grade.class);
System.out.println("Grade Name: " + g.getName());
System.out.println("Grade Score: " + g.getScore());
}
}
Here s2.getGrade().toString() is still a valid JSON string. You are converting that to Grade class and using it. This is the right way to parse complex objects. Hope you understood.
A: I changed everything to XML and using XStream now, which works on my tests. Thanks for everyone's answers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35431297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to verify the csrf token is working well in the browser while using django and react I am sorry in advance if the question is more a beginner one but i have built an application with django backend and react frontend, now i am trying to implement the csrf token for the post request on the create endpoint with the codes below.
getCookie.js
import React from 'react';
const getCookie = (name) => {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
export default getCookie;
CsrfToken.js
import React from 'react';
import getCookie from './getCookie';
var csrftoken = getCookie('csrftoken');
const CSRFToken = () => {
return (
<input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />
);
};
export default CSRFToken;
Create.js
import React from 'react';
import axios from "axios";
import CsrfToken from './CsrfToken';
const Create = () => {
...
const options = {
headers: {
'Content-Type': 'application/json',
}
};
const handleSubmit = (e) => {
e.preventDefault();
axios.post("http://xyz/create/", fields, options)
.then(response => {
...
};
return (
<>
<div className="somecontainer">
<div className="row">
<div className="col-md">
<Form onSubmit={handleSubmit}>
<CsrfToken /> < ==== CSRF TOKEN COMPONENT
<Form.Group className="sm-3" controlId="username">
<Form.Control
size="lg"
className="submit-button-text"
type="name"
placeholder="Enter username"
value={fields.name}
onChange={handleFieldChange}
/>
</Form.Group>
...
Assuming the script above is correct (Please let me know if it is not), where in the browser using chrome inside of the network tab do i check whether the csrf feature is actually enabled whenever i generate a post request?
I couldnt see it here:
A: If you are using Chrome: Inspect > Application > Cookies > csrftoken
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69369239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: try block in python am I using the try block correctly?
try:
def add(num1, num2):
return(float(num1) + float(num2))
except ValueError:
return(None)
else:
return(add(num1, num2))
I am using treehouse and am getting the error that task 1 is no longer passing meaning something has gone wrong with my def add(num1, num2)
is my try in the right spot? it says "Add a try block before where you turn your arguments into floats."
A: Place the try-except block inside the function.
Ex:
def add(num1, num2):
try:
return (float(num1) + float(num2))
except ValueError:
return None
A: Try needs to be inside a function definition and does not need an else. Basically, the except functions as the try's else.
def add(num1, num2):
try:
return(float(num1) + float(num2))
except ValueError:
return(None)
A: you should do:
def add(num1, num2):
try:
return float(num1)+float(num2)
except:
return None
The problem is that you are trying to create a function but returning values outside that function, and for the case of your else statement, the function is not even defined at that point and you are calling it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50095327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: django_nose unit tests fail (no such option) I have a new project and can't get django_nose set up correctly. I have never had this problem before. So, makes me think that it's a configuration issue. But, I can't spot it.
I'm using virtualenv and have both nose and django-nose installed. Here is my requirements.txt
Django==1.3.1
distribute==0.6.24
django-nose==1.0
nose==1.1.2
psycopg2==2.4.5
wsgiref==0.1.2
settings.py
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_nose',
'main',
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-spec', '--spec-color',
# Packages to test
'main',
]
With my virtualenv activated, when I run:
python manage.py test
I get the following:
nosetests --verbosity 1 --with-spec --spec-color main
Usage: manage.py [options]
manage.py: error: no such option: --with-spec
Has anybody had this problem? Can someone see what I'm doing wrong?
A: I figured it out. My fault (as usual). Just for future reference... those are actually not nose arguments and probably shouldn't be in there. They are args for pinocchio.
pinocchio
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10667481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: use of tight_layout() in matplotlib with incomplete axis array: I am creating PDFs of an array of axes. Sometimes the page is not full, ie not all axes have data. In this case, I want the unused axes not to show on the PDF. But I want the layout to be the same as if they were being used. I'm using tight_layout() to get non-overlapping axes and ylabels.
The following code shows first the case where the axes are used, then what happens if I delete the unused ones (tight_layout does not work properly), and then, if I instead just set them not to be visible, tight_layout() fails with a
AttributeError: 'NoneType' object has no attribute 'is_bbox'
error.
import numpy as np
import matplotlib.pyplot as plt
def prep_figure():
plt.close('all')
fig, axs = plt.subplots(4,3, figsize=(11,8.5))
axs=np.concatenate(axs)
for ii in range(5):
axs[ii].plot([1,2,3],[-10,-1,-10])
axs[ii].set_ylabel('ylabel')
axs[ii].set_xlabel('xlabel')
return fig,axs
fig,axs=prep_figure()
plt.tight_layout()
plt.show()
plt.savefig('tmp.pdf', )
# Try deleting extra axes
fig,axs=prep_figure()
for ii in range(5,12):
fig.delaxes(axs[ii])
plt.tight_layout()
plt.show()
plt.savefig('tmpd.pdf', )
# Try hiding extra axes
fig,axs=prep_figure()
for ii in range(5,12):
axs[ii].set_visible(False)
plt.tight_layout()
plt.show()
plt.savefig('tmph.pdf', )
I want the layout of the first version, but without the extra axes visible.
A: You could create the axes independently of the figure. I would also recommend this method because you have more control over the axes, for example you could have different shaped axes.
Code:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
for ii in range(5):
ax = fig.add_subplot(4,3,ii+1)
ax.scatter(np.random.random(5),np.random.random(5))
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
fig.tight_layout()
fig.show()
Result:
A: The second case of deleting the axes works fine if it is used on its own (without the code from the first case executed) and if the figure is first saved and then shown,
fig,axs=prep_figure()
for ii in range(5,12):
fig.delaxes(axs[ii])
plt.tight_layout()
plt.savefig('tmpd.pdf', )
plt.show()
The third case works fine if again, the figure is saved before showing it, and instead of making it invisible, turning the axes off via ax.axis("off").
fig,axs=prep_figure()
for ii in range(5,12):
axs[ii].axis("off")
plt.tight_layout()
plt.savefig('tmph.pdf', )
plt.show()
The created pdf is the same in both cases:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44059159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I would like to know if I am encrypting the password correctly using OO I have had this doubt for some time, because I don't know if I'm actually correctly encrypting the data, if I'm passing the correct values when instantiating the class and calling the function, and I also don't know if the return of the functions is correct, using password_hash
I believe it is correct, the hash works perfectly, but I would like to make sure that there is nothing wrong with my code, as I am a novice and object orientation can leave me a little confused
<?php
class SignUp {
private $email;
private $password;
public function setEmail($e) {
$this->email = $e;
}
public function getEmail() {
return $this->email;
}
public function setPassword($p) {
$this->password = $p;
}
public function getPassword() {
return $this->password = password_hash($_POST['password'], PASSWORD_BCRYPT);
}
}
$obj = new SignUp();
$obj->setEmail($_POST['email']);
$obj->setPassword($_POST['password']);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64733510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SyntaxError: Invalid Syntax without solution It's my first request here, I hope you'll could help me.
I try to explain this particular situation.
Files that use are bases for launch a neuronal simulation and they were for Python 2. Using an Atom's plug-in, I fixed manually any Indent errors and details.
But for this error I can't find a solution.
Traceback (most recent call last):
File "./protocols/01_no_channels_ais.py", line 4, in <module>
from Purkinje import Purkinje
File "/Users/simonet/Desktop/purkinjecell/Purkinje.py", line 202
listgmax = []
^
SyntaxError: invalid syntax
From file Purkinje
self.subsets_cm = np.genfromtxt("ModelViewParmSubset_cm.txt")
for cm in self.subsets_cm:
for d in self.ModelViewParmSubset[int(cm[0])]:
d.cm = cm[1] * 0.77/1.64
self.dend[138].cm = 8.58298 * 0.77/1.64
self.subsets_paraextra = np.genfromtxt("modelsubsetextra.txt", dtype=[('modelviewsubset','f8'),('channel','S5'),('channel2','S5'),('value','f8')])
for para in self.subsets_paraextra:
for d in self.ModelViewParmSubset[int(para[0])]:
d.insert(para[1])
exec('d.gmax_'+para[2]+' = '+str(para[3])
listgmax = [] ############ PROBLEM WOULD BE HERE ##############
for d in self.ModelViewParmSubset[2]:
d.gmax_Leak = d.gmax_Leak/2
self.dend[138].insert('Leak')
self.dend[138].gmax_Leak = 1.74451E-4 / 2
"listgmax" is a unique term in this code. I can't understand where is the problem.
If I delete it, the problem continue in the next line with the same error of Sintax.
Can you help me?
Thanks a lot for your time.
Hope I was clear.
A: The error is simple, you forgot the closing brackets on the line above, so just say:
exec('d.gmax_'+para[2]+' = '+str(para[3]))
This should fix the errors. Keep in mind for such SyntaxError: invalid syntax the problem mostly is you missing to close brackets or something.
If any doubts or errors, do let me know
Cheers
A: You're missing a closing parenthesis in the line prior. It should be:
exec('d.gmax_' + para[2] + ' = ' + str(para[3]))
The Python interpreter is reporting the error on the next line because that's the soonest it can tell you didn't just continue the same expression there. In general, with syntax errors, good to look above if you don't find the error exactly where reported.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63551185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove timestamp in XMLGregorianCalendar I have a utility and when I run this utility in main method, I get the desired output. But when I convert that data into Xml format then I get output in timestamp format. How can I avoid this issue?
Utility for converting String to XMLGregorianCalendar
public static void main(String[] args) throws ParseException, DatatypeConfigurationException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2019-08-06 14:17:35");
XMLGregorianCalendar xmlGregCal = null;
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(xmlGregCal);
}
Output in Java - 2019-08-06T14:17:35.000+05:30
Ouput in XML - 1517769000000
I need same java time in xml output.
Using jackson to create XML file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60506685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP page is delivering the same result regardless of IF condition I am trying to view a PHP page with and without using an iframe, but the result is the same regardless of the IF condition using $_SERVER['HTTP_SEC_FETCH_DEST'] to detect that it is in an iframe.
if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) and $_SERVER['HTTP_SEC_FETCH_DEST'] == 'iframe') {
// do something
}
The result is always true until I manually refresh the page that isn't using the iframe. Any suggestions to make this work? Seems like some kind of buffer issue, but I have not been able to solve it with flush().
A: Adding a header to revalidate solved my problem.
header('Cache-Control: no-store, no-cache, must-revalidate');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65829518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spritekit: Separating randomly placed non-dynamic "block" nodes by a set X and Y value? my script below does exactly what i need it to do, add blocks to a scene in any random order in the view. the only problem is, as i increase the amount of "block" nodes, they tend to overlap on one another and clump up, I'm wondering if there is a way i can add a "barrier" around each block node so that they cannot overlap but still give a random feel? My current code is below:
-(void) addBlocks:(int) count {
for (int i = 0; i< count; i++) {
SKSpriteNode *blocks = [SKSpriteNode spriteNodeWithImageNamed:@"Ball"];
blocks.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:(blocks.size.width/2)];
blocks.physicsBody.dynamic = NO;
blocks.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
[self addChild:blocks];
int blockRandomPositionX = arc4random() % 290;
int blockRandomPositionY = arc4random() % 532;
blockRandomPositionY = blockRandomPositionY + 15;
blockRandomPositionX = blockRandomPositionX + 15;
blocks.position = CGPointMake(blockRandomPositionX, blockRandomPositionY);
}
}
Any help highly appreciated, thanks!
A: To prevent two nodes from overlapping, you should check the newly created node's random position with intersectsNode: to see if it overlaps any other nodes. You also have to add each successfully added node into an array against which you run the intersectsNode: check.
Look at the SKNode Class Reference for detailed information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23654110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Expected Character for no reason in a JsonPath Assuming that I have this JSON:
{
"response" : {
"code" : "XXX",
"label" : "Lorem Ipsum",
"items" : [
{
"code" : "200",
"label" : "200 !!!"
},
{
"code" : "300",
"label" : "300 !!!!!"
},
{
"code" : "500",
"label" : "+500 !!!!!"
}]
}
}
I want to get the label of the item when code = 500 (as for example) in Java.
I'm using jayWay Library and this jsonPath:
"$.response.items[?(@.code='500')].label"
I'm getting this error while parsing : Expected character: )
The java code :
public static String getElementValueByJsonPath(String jsonContent, String jsonPath) {
if (checkJsonValidity(jsonContent)) {
String returnedValue ="";
Configuration config = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
try {
returnedValue = ""+JsonPath.using(config).parse(jsonContent).read(jsonPath);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return returnedValue;
}
return null;
Anyone knows why I have this error, and can I bypass it with another library or method.
Thanks
A: You get the error for a very valid reason, that is not a valid jsonpath query.
If you go to https://jsonpath.herokuapp.com/ ( which uses jayway ) and enter the same data and path you will see this is not a valid jsonpath query for jayway, or two of the other implementations, the only one that does not fail outright does not return what you are expecting. I think you need to go back and re-read the jsonpath documentation as this syntax clearly is not valid.
The correct syntax is $.response.items[?(@.code=='500')].label as the documentation clearly states.
I would not rely on implementations that do not fail on incorrect syntax.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50911200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Deployment to Heroku Error: Cannot find module '/app/server.js' I'm deploying an Angular 6 application created with the angular-cli to Heroku. The build completes successfully, however, when I go to the deployed application, I get a blank page.
After running the Heroku logs, it appears the error/crash happens upon starting up the node server instance. "Cannot find module '/app/server/js". The server.js file lives under the src directory so I don't know why this is happening.
from the logs:
Here is the package.json, I removed the node and npm engines to run the default versions from the heroku build:
{
"name": "blog-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "node server.js",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"postinstall": "ng build --prod"
},
"private": true,
"dependencies": {
"@angular/animations": "^6.0.0",
"@angular/cdk": "^6.0.0",
"@angular/cli": "~6.0.0",
"@angular/common": "^6.0.0",
"@angular/compiler": "^6.0.0",
"@angular/compiler-cli": "^6.0.0",
"@angular/core": "^6.0.0",
"@angular/forms": "^6.0.0",
"@angular/http": "^6.0.0",
"@angular/material": "^6.0.1",
"@angular/platform-browser": "^6.0.0",
"@angular/platform-browser-dynamic": "^6.0.0",
"@angular/router": "^6.0.0",
"@ng-bootstrap/ng-bootstrap": "^2.0.0",
"@ngrx/effects": "^5.2.0",
"@ngrx/store": "^5.2.0",
"angularfire2": "^5.0.0-rc.8.1-next",
"bootstrap": "^3.3.7",
"core-js": "^2.5.4",
"express": "^4.16.3",
"firebase": "^5.0.2",
"ngx-quill": "^3.1.0",
"rxjs": "^6.0.0",
"rxjs-compat": "^6.1.0",
"typescript": "~2.7.2",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.6.0",
"@angular/language-service": "^6.0.0",
"@types/jasmine": "~2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~1.4.2",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1"
}
}
And the server.js:
import express from "express";
const app = express();
app.use(static(__dirname + '/dist'));
app.all('*', (req, res) => {
res.status(200).sendFile(__dirname + '/dist/index.html');
});
app.listen(process.env.PORT || 8080);
File tree:
Any idea on what the problem could be?
EDIT: I added a Procfile at src/Procfile:
web: node src/server.js
After adding this file, the app still crashes with the following output in the Heroku logs:
A: Create Procfile in main folder and add:
web: node src/<you-app-name>.js
Check the below image for where to put Procfile:
A: Create a Procfile with following content
web: node src/server.js
The Procfile is always a simple text file that is named Procfile exactly. For example, Procfile.txt is not valid.
The Procfile must live in your app’s root directory. It does not function if placed anywhere else.
Heroku app dynos executes the commands of Procfile
Read more about Procfile here https://devcenter.heroku.com/articles/procfile
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50571078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: App/website model not showing on Alexa Developer console I am trying to connect my alexa skill with the custom android app. For that I need App/Website model in Alexa developers console. But I can't find it. Is there anything I need to do to activate that model option.
A: Alexa for Apps is a currently only available to select developers as part of a developer preview program. To use this feature, you must register for the preview.
For more information, please see the documentation here:
https://developer.amazon.com/en-US/docs/alexa/alexa-for-apps/use-developer-console.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73932202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to delete multiple lines in a python console window? I am currently working on a text-adventure, which should have a more or less complex fight system. To create such, I decided to generate a 16x16 tile battlefield, which will be represented by ASCII-characters. But, because a fight may take more than turn, I don't want to reprint the battlefield multiple times, but delete the "old" one and print the new situation to the same place. But I suppose that it won't work with sys.stdout.write() and sys.stdout.flush() since there have to be removed multiple lines. So my question is: how do I accomplish my goal? At the moment I open a new console window, where everything is reprinted, which is ahem... not very elegant.
Another problem would be the cross-platform use of the programm.
A: Check out the curses module (http://docs.python.org/2/library/curses.html).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19344962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to turn off different items in a select box through jQuery? Working with Wordpress (contact-form plugin by iDeasilo ) and needed help performing a certain task. I've searched Google, but was unable to find what I was looking for. New to working with jQuery, so any help will help.
My question is:
How would I be able to hide or not allow a user from selecting other option in a select box, if he/she clicks on a specific radio button?
So if there is three different radio buttons (sandwich, taco and pizza), and I was to click on "pizza". The select box option should stay just at it's default. When I click the select box, all other options should disappear or be disabled so you can't choose from the list. But this should only happen when you click on "pizza".
How would I accomplish this?
A: I would attach an event handler to the one control (radio button), which affects/changes the options in the select control:
$('#myRadioButtonInput').click(function() { $('#theSelectToAffect option.Conditional').hide(); });
Just attach the 'Conditional' class to the conditional options when you make the drop down/select.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5122288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Brand new Laravel 8 installation: "/admin" route redirects to "/" for no apparent reason I originally created a new Laravel 8 project, made some adjustments and then had this issue where going to '/admin' just redirects the URL back to '/', where as '/admin/' went where I expected it to, despite the routing.
But now in testing I have just done a brand new fresh Laravel 8 install, and I haven't changed a single thing. Yet I still get the same issue where '/admin' specifically, gets redirected to '/' home.
Just to clarify, going to another random path like '/test' gives a 404 as expected, so its just admin. Does anyone have any idea why this is happening like this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68286062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to correctly start activity from PostExecute in Android? I have an AsyncTask, that fills a custom List with parsed data from Internet.
In PostExecute I fill that List and get it ready to transfer it to a new Activity.
I do it this way:
@Override
protected void onPostExecute(List<VideoDataDescription> result)
{
super.onPostExecute(result);
MainActivity.progressDialog.dismiss();
context.startActivity(new Intent(context, ResultsQueryActivity.class));
}
where context
private Context context;
In LogCat after executing this code I get a Java.lang.NullPointerException.
Is this possible and correct to start an Activity as I do it?
UPD
I have added
private Context mContext;
public YoutubeAndYahooParser(Context context)
{
super();
this.mContext = context;
}
to initialize context and call
YoutubeAndYahooParser youtubeAndYahooParser = new YoutubeAndYahooParser(ResultsQueryActivity.this);
youtubeAndYahooParser.execute("my string to pass in asynctak");
After this in PostExecute
Intent intent = new Intent(mContext, ResultsQueryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
I added new flag because of I have got in LogCat the next:
*Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?*
Am I right?
A: You should pass in the application context rather than a context from the local activity. I.e. use context.getApplicationContext() and save that in a local variable in your AsyncTask subsclass.
The code might looks something like this:
public class MyAsyncTask extends AsyncTask {
Context context;
private MyAsyncTask(Context context) {
this.context = context.getApplicationContext();
}
@Override
protected Object doInBackground(Object... params) {
...
}
@Override
protected void onPostExecute(List<VideoDataDescription> result) {
super.onPostExecute(result);
MainActivity.progressDialog.dismiss();
context.startActivity(new Intent(context, ResultsQueryActivity.class));
}
}
you'd call it like this:
new MyAsyncTask(context).execute();
A: I tried this just now ... it works in PostExecute Method!!!
Intent intent_name = new Intent();
intent_name.setClass(getApplicationContext(),DestinationClassName.class);
startActivity(intent_name);
A: But its better if you start a new Intent Based on the response(result) obtained from the previous activities.
This will eliminate the possibility of the error response from invoking the new intent.
Example if the previous activity was supposed to return Succesfully... or Welcome to allow the new intent to start, the i could check it out in this way
protected void onPostExecute(String result) {
if (result.equals("Succesfully...")){
context.startActivity(new Intent(context, Login_Activity.class));
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}else if (result.contains("Welcome")){
context.startActivity(new Intent(context, MainActivity.class));
}else {
Toast.makeText(context,result,Toast.LENGTH_LONG).show();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9118015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Xcode - Sliding Tab Bar? Is there a tutorial I am overlooking online for a sliding tab bar application? I've been going at this research for little over a week. I'm wanting to use this feature instead of having the "more" tabs on the main screen. The iOS "Thousand Foot Krutch" app has this feature, so I know Apple does allow this kind of feature.
If there isn't one online, is someone able to explain to me how I can go at making one? I do use Storyboard (lightly) if that is an advantage/disadvantage. I mostly code out details in the view controllers .m file, but for storyboard I use a physical view controller, D&D some details as I follow tutorials online (Ray Wenderlich, Geeky Lemon).
My layout is simple: "UITabController >> UINavigationController >> ViewController".
Thank you everyone!
-TG52
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15593094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I uninstall JVCL? I want to uninstall Jedi because it replaces my GIF handling library. Even though I uninstalled JVCL, Delphi keeps using the Jedi gif library and it keeps adding the JVGif unit to my project which adds extra compiling time.
A: Run the JVCL installer and uninstall. Then open the JVCL root folder in the command line and type "clean.bat all" and that should take care of the rest of it.
A: There is no automatic way to nicely uninstall Jedi.
To uninstall Jedi and restore the functionality of previous GIF library do this:
*
*Close Delphi
*Run the JCL uninstaller
*Run the JVCL uninstaller
*Run the cleaning utility as explained by Mason Wheeler (in both folders)
*Manually delete JCL folders
*Manually delete JVCL folders
*Start Delphi. Reinstall TGifImage component
Note: To start the uninstallers run the "install.bat".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/3312658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Parse push notifications can take a long time to get delivered I am relatively new to Parse, and am finding that push notifications can take anywhere from being instantaneous, to taking a day or more to deliver. I can see the notifications registered in the admin panel immediately in every case, so issue is not on the send side.
I am developing on Android, but need the cross-platform capability of Parse so I can support iOS.
A: Well you should prefer to use Google Cloud Messaging GCM for push notifications rather than using 3rd Parties like Parse etc. GCM is super fast and i am using in all my apps which are live.
Here are Good Links to Startoff with GCM
http://developer.android.com/google/gcm/index.html
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
A: I am aware about the parse notification.I am also having same problem,but the problem is because of the Wifi.
It means when you send an parse notification from panel it would take some time to deliver because of wifi is enable on your mobile.
So go with your mobile 3G connection it works within less time.
A: Turns out, Parse has a GCM handler, and it also needs to be added to the manifest. Otherwise Parse uses its own service, which can be very slow. Enabling GCM, I now have the notifications arriving in under 20 seconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24924798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is GameObject.FindObjectOfType() less expensive in performance than GameObject.Find() in Unity? I'm on my last finishing touches with my indie game using Unity and I've been thinking about improving my game's performance. I was wondering if GameObject.FindObjectOfType() is less expensive than GameObject.Find()? Thanks!
A: If you really care about performance, try using none of them - or at least minimise it.
Using these Methods will loop through the list of GameObjects and return the object and because of the looping it is pretty heavy on the performance. So if you use them, never call them in the Update()-Method, call them in Start() or any method that doesn't get called often and store the value.
To be honest I don't know, which one is faster. If I had to guess, I would say it is GameObject.Find(), since it's only checking the name, whereas FindObjectOfType() checks the components.
But even if I would consider using FindObjectOfType(), because Find() uses a string and you might want to avoid that, because of typos (if you are not storing it inside a single class and just reference the variable)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74418791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: " A device-specific color space (DeviceGray) without an appropriate output intent is used" when using XSL-FO for PDF validation I was asked to generate a PDF type A-3 using XSL-FO with Apache FOP configuration.
The PDF is already generated but it can't be validated
error : A device-specific color space (DeviceGray) without an appropriate output intent is used.
I think the issue will be related to the FOP configuration, this is the one I used:
<fop version="1.0">
<!-- Base URL for resolving relative URLs -->
<base>.</base>
<!-- Source resolution in dpi (dots/pixels per inch) for determining the size of pixels in SVG and bitmap images, default: 72dpi -->
<source-resolution>72</source-resolution>
<!-- Target resolution in dpi (dots/pixels per inch) for specifying the target resolution for generated bitmaps, default: 72dpi -->
<target-resolution>72</target-resolution>
<!-- Default page-height and page-width, in case
value is specified as auto -->
<default-page-settings height="11in" width="8.26in"/>
<!-- Information for specific renderers -->
<!-- Uses renderer mime type for renderers -->
<renderers>
<renderer mime="application/pdf">
<version>1.4</version>
<filterList>
<!-- provides compression using zlib flate (default is on) -->
<value>flate</value>
</filterList>
<fonts>
<font embed-url="ZapfDingbats.ttf" kerning="yes" sub-font="ZapfDingbats">
<font-triplet name="ZapfDingbats" style="normal" weight="normal"/>
<font-triplet name="ZapfDingbats" style="normal" weight="bold"/>
</font>
<font embed-url="symbol.ttf" kerning="yes" sub-font="Symbol">
<font-triplet name="Symbol" style="normal" weight="normal"/>
<font-triplet name="Symbol" style="normal" weight="bold"/>
</font>
<font metrics-url="ariali.xml" kerning="yes" embed-url="ariali.ttf" embedding-mode="full">
<font-triplet name="Arial" style="italic" weight="normal"/>
</font>
<font metrics-url="arial.xml" kerning="yes" embed-url="arial.ttf" embedding-mode="full">
<font-triplet name="Arial" style="normal" weight="normal"/>
</font>
<font metrics-url="arialbd.xml" kerning="yes" embed-url="arialbd.ttf" embedding-mode="full">
<font-triplet name="Arial" style="normal" weight="bold"/>
</font>
</fonts>
</renderer>
<renderer mime="application/postscript">
</renderer>
<renderer mime="application/vnd.hp-PCL">
</renderer>
<renderer mime="image/svg+xml">
<format type="paginated"/>
<link value="true"/>
<strokeText value="false"/>
</renderer>
<renderer mime="application/awt">
</renderer>
<renderer mime="image/png">
<!--transparent-page-background>true</transparent-page-background-->
</renderer>
<renderer mime="image/tiff">
<!--transparent-page-background>true</transparent-page-background-->
<!--compression>CCITT T.6</compression-->
</renderer>
<renderer mime="text/xml">
</renderer>
<!-- RTF does not have a renderer
<renderer mime="text/rtf">
</renderer>
-->
<renderer mime="text/plain">
<pageSize columns="80"/>
</renderer>
</renderers>
</fop>
A: Read the Apache FOP configuration, you will need an output colorspace specified in the pdf renderer filterList like:
<output-profile>C:\FOP\Color\EuropeISOCoatedFOGRA27.icc</output-profile>
See https://xmlgraphics.apache.org/fop/1.1/configuration.html
Of course, you need to select the appropriate ".icc" file for your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68019695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: adding inertia to a UIPanGestureRecognizer I am trying to move a sub view across the screen which works, but i also want to add inertia or momentum to the object.
My UIPanGestureRecognizer code that i already have is below.
Thanks in advance.
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[self addGestureRecognizer:panGesture];
(void)handlePan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:self.superview];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.superview];
if (recognizer.state == UIGestureRecognizerStateEnded) {
[self.delegate card:self.tag movedTo:self.frame.origin];
}
}
Again thanks.
A: Have a look at RotationWheelAndDecelerationBehaviour. there is an example for how to do the deceleration for both linear panning and rotational movement. Trick is to see what is the velocity when user ends the touch and continue in that direction with a small deceleration.
A: Well, I'm not a pro but, checking multiple answers, I managed to make my own code with which I am happy.
Please tell me how to improve it and if there are any bad practices I used.
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translatedPoint = [recognizer translationInView:self.postViewContainer];
CGPoint velocity = [recognizer velocityInView:recognizer.view];
float bottomMargin = self.view.frame.size.height - containerViewHeight;
float topMargin = self.view.frame.size.height - scrollViewHeight;
if ([recognizer state] == UIGestureRecognizerStateChanged) {
newYOrigin = self.postViewContainer.frame.origin.y + translatedPoint.y;
if (newYOrigin <= bottomMargin && newYOrigin >= topMargin) {
self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + translatedPoint.y);
}
[recognizer setTranslation:CGPointMake(0, 0) inView:self.postViewContainer];
}
if ([recognizer state] == UIGestureRecognizerStateEnded) {
__block float newYAnimatedOrigin = self.postViewContainer.frame.origin.y + (velocity.y / 2.5);
if (newYAnimatedOrigin <= bottomMargin && newYAnimatedOrigin >= topMargin) {
[UIView animateWithDuration:1.2 delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^ {
self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + (velocity.y / 2.5));
}
completion:^(BOOL finished) {
[self.postViewContainer setFrame:CGRectMake(0, newYAnimatedOrigin, self.view.frame.size.width, self.view.frame.size.height - newYAnimatedOrigin)];
}
];
}
else {
[UIView animateWithDuration:0.6 delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^ {
if (newYAnimatedOrigin > bottomMargin) {
self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, bottomMargin + self.postViewContainer.frame.size.height / 2);
}
if (newYAnimatedOrigin < topMargin) {
self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, topMargin + self.postViewContainer.frame.size.height / 2);
}
}
completion:^(BOOL finished) {
if (newYAnimatedOrigin > bottomMargin)
[self.postViewContainer setFrame:CGRectMake(0, bottomMargin, self.view.frame.size.width, scrollViewHeight)];
if (newYAnimatedOrigin < topMargin)
[self.postViewContainer setFrame:CGRectMake(0, topMargin, self.view.frame.size.width, scrollViewHeight)];
}
];
}
}
}
I have used two different animation, one is the default inertia one and the other if for when the user flings the containerView with high velocity.
It works well under iOS 7.
A: I took the inspiration from the accepted answer's implementation. Here is a Swift 5.1 version.
Logic:
*
*You need to calculate the angle changes with the velocity at which the pan gesture ended and keep rotating the wheel in an endless timer until the velocity wears down because of deceleration rate.
*Keep decreasing the current velocity in every iteration of the timer
with some factor (say, 0.9).
*Keep a lower limit on the velocity to
invalidate the timer and complete the deceleration process.
Main function used to calculate deceleration:
// deceleration behaviour constants (change these for different deceleration rates)
private let timerDuration = 0.025
private let decelerationSmoothness = 0.9
private let velocityToAngleConversion = 0.0025
private func animateWithInertia(velocity: Double) {
_ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in
guard let this = self else {
return
}
let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity
let newVelocity = concernedVelocity * this.decelerationSmoothness
this.currentVelocity = newVelocity
var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle
if !this.isClockwiseRotation {
angleTraversed *= -1
}
// exit condition
if newVelocity < 0.1 {
timer.invalidate()
this.currentVelocity = 0.0
} else {
this.traverseAngularDistance(angle: angleTraversed)
}
}
}
Full working code with helper functions, extensions and usage of aforementioned function in the handlePanGesture function.
// deceleration behaviour constants (change these for different deceleration rates)
private let timerDuration = 0.025
private let decelerationSmoothness = 0.9
private let velocityToAngleConversion = 0.0025
private let maximumRotationAngleInCircle = 360.0
private var currentRotationDegrees: Double = 0.0 {
didSet {
if self.currentRotationDegrees > self.maximumRotationAngleInCircle {
self.currentRotationDegrees = 0
}
if self.currentRotationDegrees < -self.maximumRotationAngleInCircle {
self.currentRotationDegrees = 0
}
}
}
private var previousLocation = CGPoint.zero
private var currentLocation = CGPoint.zero
private var velocity: Double {
let xFactor = self.currentLocation.x - self.previousLocation.x
let yFactor = self.currentLocation.y - self.previousLocation.y
return Double(sqrt((xFactor * xFactor) + (yFactor * yFactor)))
}
private var currentVelocity = 0.0
private var isClockwiseRotation = false
@objc private func handlePanGesture(panGesture: UIPanGestureRecognizer) {
let location = panGesture.location(in: self)
if let rotation = panGesture.rotation {
self.isClockwiseRotation = rotation > 0
let angle = Double(rotation).degrees
self.currentRotationDegrees += angle
self.rotate(angle: angle)
}
switch panGesture.state {
case .began, .changed:
self.previousLocation = location
case .ended:
self.currentLocation = location
self.animateWithInertia(velocity: self.velocity)
default:
print("Fatal State")
}
}
private func animateWithInertia(velocity: Double) {
_ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in
guard let this = self else {
return
}
let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity
let newVelocity = concernedVelocity * this.decelerationSmoothness
this.currentVelocity = newVelocity
var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle
if !this.isClockwiseRotation {
angleTraversed *= -1
}
if newVelocity < 0.1 {
timer.invalidate()
this.currentVelocity = 0.0
this.selectAtIndexPath(indexPath: this.nearestIndexPath, shouldTransformToIdentity: true)
} else {
this.traverseAngularDistance(angle: angleTraversed)
}
}
}
private func traverseAngularDistance(angle: Double) {
// keep the angle in -360.0 to 360.0 range
let times = Double(Int(angle / self.maximumRotationAngleInCircle))
var newAngle = angle - times * self.maximumRotationAngleInCircle
if newAngle < -self.maximumRotationAngleInCircle {
newAngle += self.maximumRotationAngleInCircle
}
self.currentRotationDegrees += newAngle
self.rotate(angle: newAngle)
}
Extensions being used in above code:
extension UIView {
func rotate(angle: Double) {
self.transform = self.transform.rotated(by: CGFloat(angle.radians))
}
}
extension Double {
var radians: Double {
return (self * Double.pi)/180
}
var degrees: Double {
return (self * 180)/Double.pi
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17083570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: nullpointerexecption when trying to execute delete method of databasehelper I'm new to android and i m creating application contact application
I m trying to delete a row from table but its giving me nullpointerexception as shown in log below
this indicates that delete method is getting null value but through bundle i m getting the correct value and i m passing the same val in deketecontact method.
com.example.ViewRecord
public class ViewRecord extends Activity {
int val;
SQLiteDatabase sdb;
databaseHelper dbh;
//=new databaseHelper(getBaseContext(), "stud", null, 1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_record);
Bundle b = getIntent().getExtras();
if(b!=null){
String n=b.getString("pname").toUpperCase(Locale.ENGLISH);
TextView t= (TextView) findViewById(R.id.tv1);
t.setText("WELCOME "+ n);
val = b.getInt("pid");
}
Button del= (Button) findViewById(R.id.button1);
del.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(ViewRecord.this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dbh.deleteContact(val);
Toast.makeText(getApplicationContext(), "Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),AddRecord.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
}
});
}
}
//and this is delete method in databasehelper.class
public Integer deleteContact (Integer id)
{
Log.d("val1", ""+id);
SQLiteDatabase db = this.getWritableDatabase();
// db.delete("studrec", "id=", null);
return db.delete("studrec",
"id = ? ",new String[] { Integer.toString(id) });
}
log file
01-10 19:19:00.680: E/AndroidRuntime(10261): FATAL EXCEPTION: main
01-10 19:19:00.680: E/AndroidRuntime(10261): Process: com.assign6, PID: 10261
01-10 19:19:00.680: E/AndroidRuntime(10261): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Integer com.assign6.databaseHelper.deleteContact(java.lang.Integer)' on a null object reference
01-10 19:19:00.680: E/AndroidRuntime(10261): at com.assign6.ViewRecord$1.onClick(ViewRecord.java:66)
01-10 19:19:00.680: E/AndroidRuntime(10261): at android.view.View.performClick(View.java:4756)
01-10 19:19:00.680: E/AndroidRuntime(10261): at android.view.View$PerformClick.run(View.java:19749)
01-10 19:19:00.680: E/AndroidRuntime(10261): at android.os.Handler.handleCallback(Handler.java:739)
01-10 19:19:00.680: E/AndroidRuntime(10261): at android.os.Handler.dispatchMessage(Handler.java:95)
01-10 19:19:00.680: E/AndroidRuntime(10261): at android.os.Looper.loop(Looper.java:135)
01-10 19:19:00.680: E/AndroidRuntime(10261): at android.app.ActivityThread.main(ActivityThread.java:5221)
01-10 19:19:00.680: E/AndroidRuntime(10261): at java.lang.reflect.Method.invoke(Native Method)
01-10 19:19:00.680: E/AndroidRuntime(10261): at java.lang.reflect.Method.invoke(Method.java:372)
01-10 19:19:00.680: E/AndroidRuntime(10261): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
01-10 19:19:00.680: E/AndroidRuntime(10261): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
A:
NullPointerException: Attempt to invoke virtual method
'java.lang.Integer com.example.databaseHelper.deleteContact
Because you are not initializing dbh object of databaseHelper class before calling deleteContact using dbh object. Initialize it before calling method:
dbh=new databaseHelper(...);
dbh.deleteContact(val);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27877150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to feed the `find` output as the argument for bash? I find a list of bam files using
$bams=$(find /data/and/ -type f -regex ".*\.bam")
#/data/DNA128441.bam
#/data/DNA128442.bam
#/data/DNA128443.bam
And wanted to feed in a script test.sh
#!/bin/bash
bam="$@"
echo "You provided the arguments:" ${bam}
s=${bam##*/}
r1=${s%.bam}_R1.fastq
r2=${s%.bam}_R2.fastq
echo $r1
echo $r2
But when I run:
$bams=$(find /data/and/ -type f -regex ".*\.bam")
./test.sh $bam
You provided the arguments: /data/and/DNA128441.bam /data/and/DNA128342.bam /data/and/DNA128343.bam
DNA128343_R1.fastq
DNA128343_R2.fastq
My question is how to make it process one by one such like a desired output:
$bams=$(find /data/and/ -type f -regex ".*\.bam")
./test.sh $bam
You provided the arguments: /data/and/DNA128341.bam
DNA128341_R1.fastq
DNA128341_R2.fastq
You provided the arguments: /data/and/DNA128342.bam
DNA128342_R1.fastq
DNA128342_R2.fastq
You provided the arguments: /data/and/DNA128343.bam
DNA128343_R1.fastq
DNA128343_R2.fastq
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62703889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to prevent vaadin default styles and how to increase width and height of textfield I am developing application using vaadin framework. I am new in vaadin framework.
I have lot of confusion in designing.
1) I am creating layout to display loginform but it will come with some default styles. That styles collapsed my desgin.
Please any one say How can I remove or prevent that vaadin default styles.
2) If I increase text-field height it automatically changed to text-area.
Please help any one How can I increase text-field height.
A: answer for number 2 :
Setting height for TextField also has a side-effect that puts TextField into multiline mode (aka "textarea"). Multiline mode can also be achieved by calling setRows(int). The height value overrides the number of rows set by setRows(int).
If you want to set height of single line TextField, call setRows(int) with value 0 after setting the height. Setting rows to 0 resets the side-effect.
A: I cannot see any function setRow and setHeight doesnt allow to edit more lines. Only one line vertically i middle. Vaadin 7
A: for question 1, you should first setPrimaryStyleName and if you need other style, addStyleName
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15787629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# Google Sheets API - Delete Row I searched everything already on the whole internet :) and did not find a solution for this.
I can add new rows, update old rows and do a lot of things in google sheets via C#, but I can't delete a row in a google sheet... can someone, please help me with this?
[EDITED]
OK, I finally found how to delete the rows...
So, what I had to do was first to build list of all indexes that are to be deleted. After doing that I had to build list of key pairs values with start and end of the index to delete, BUT for the end I had to add +1, as it seems like starts and ends are not deleted, only things that are between..
Finally I had to loop the list of key pairs from the end till the start and this deleted the rows...
The code to delete is here. Maybe this will help someone else who is looking how to delete rows in google sheets:
List<KeyValuePair<int, int>> _listStartEndIndexToDelete = new List<KeyValuePair<int, int>>();
List<int> _tempListOfAllIndex = new List<int>();
for (int i = 1; i <= ValuesInternal.Values.Count() - 1; i++)
{
if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
{
_tempListOfAllIndex.Add(i);
}
}
for (int rowNumber = 0; rowNumber <= _tempListOfAllIndex.Count() - 1; rowNumber++)
{
int tempStart = _tempListOfAllIndex[rowNumber];
if(rowNumber != _tempListOfAllIndex.Count() - 1)
{
while (_tempListOfAllIndex[rowNumber] + 1 == _tempListOfAllIndex[rowNumber + 1])
{
rowNumber++;
if (rowNumber == _tempListOfAllIndex.Count() - 1) { break; }
}
}
int tempEnd = _tempListOfAllIndex[rowNumber] + 1;
KeyValuePair<int, int> tempPair = new KeyValuePair<int, int>(tempStart, tempEnd);
_listStartEndIndexToDelete.Add(tempPair);
}
for(int keyValuePair = _listStartEndIndexToDelete.Count()-1; keyValuePair >= 0; keyValuePair--)
{
List<Request> deleteRequestsList = new List<Request>();
BatchUpdateSpreadsheetRequest _batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
Request _deleteRequest = new Request();
_deleteRequest.DeleteDimension = new DeleteDimensionRequest();
_deleteRequest.DeleteDimension.Range = new DimensionRange();
_deleteRequest.DeleteDimension.Range.SheetId = SheetIDnumberWhereDeleteShouldBeDone;
_deleteRequest.DeleteDimension.Range.Dimension = "ROWS";
_deleteRequest.DeleteDimension.Range.StartIndex = _listStartEndIndexToDelete[keyValuePair].Key;
_deleteRequest.DeleteDimension.Range.EndIndex = _listStartEndIndexToDelete[keyValuePair].Value;
deleteRequestsList.Add(_deleteRequest);
_batchUpdateSpreadsheetRequest.Requests = deleteRequestsList;
sheetsService.Spreadsheets.BatchUpdate(_batchUpdateSpreadsheetRequest, SheetIDInternal).Execute();
}
A: I checked the links that You provided here, but non of them solved the problem.
For example this one:
Request request = new Request()
.setDeleteDimension(new DeleteDimensionRequest()
.setRange(new DimensionRange()
.setSheetId(0)
.setDimension("ROWS")
.setStartIndex(30)
.setEndIndex(32)
)
);
The problem is that, there is no such a thing like .setDeleteDimension under Request. This shouldn't be such a problem, but it is....
Below You can find my code. What does it do, is to take data from one sheet (internal) and put it to another sheet (internal archive). When this is done (and this works well), I want to delete data from internal as it is already archived... and that part is not working. I just don't know how to delete the rows.. if anyone could have a look on this, it would be great. Thanks for your help...
public void RunArchiveInternal2(bool testRun)
{
//internal
string SheetIDInternal = "googlesheetid_internal";
string RangeInternal = testRun ? "test_task tracking" : "Task Tracking - INTERNAL";
SpreadsheetsResource.ValuesResource.GetRequest getRequestInternal = sheetsService.Spreadsheets.Values.Get(SheetIDInternal, RangeInternal);
ValueRange ValuesInternal = getRequestInternal.Execute();
//internal archive
string SheetIDInternalArchive = "googlesheetid_internal_archive";
string RangeInternalArchive = testRun ? "test_archive_internal" : "Sheet1";
SpreadsheetsResource.ValuesResource.GetRequest getRequestInternalArchive = sheetsService.Spreadsheets.Values.Get(SheetIDInternalArchive, RangeInternalArchive);
ValueRange ValuesInternalArchive = getRequestInternalArchive.Execute();
//Get data from internal and put to internal archive
List<IList<object>> listOfValuesToInsert = new List<IList<object>>();
for (int i = 1; i <= ValuesInternal.Values.Count() - 1; i++)
{
List<object> rowToUpdate = new List<object>();
if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
{
rowToUpdate = (List<object>)ValuesInternal.Values[i];
listOfValuesToInsert.Add(rowToUpdate);
}
}
SpreadsheetsResource.ValuesResource.AppendRequest insertRequest = sheetsService.Spreadsheets.Values.Append(new ValueRange { Values = listOfValuesToInsert }, SheetIDInternalArchive, RangeInternalArchive + "!A1");
insertRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
insertRequest.Execute();
//delete things from internal
BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
List<DeleteDimensionRequest> requests = new List<DeleteDimensionRequest>();
for (int i = ValuesInternal.Values.Count() - 1; i >= 1; i--)
{
DeleteDimensionRequest request = new DeleteDimensionRequest();
//Request request = new Request();
if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
{
request.Range = new DimensionRange
{
Dimension = "ROWS",
StartIndex = i,
EndIndex = i
};
requests.Add(request);
}
}
batchUpdateSpreadsheetRequest.Requests = requests;//this is wrong
SpreadsheetsResource.BatchUpdateRequest Deletion = sheetsService.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, SheetIDInternal);
Deletion.Execute();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59457663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: PHP Website - Navigation links with sub directories I have a site with this directory structure:
index.php
folder1/index.php
folder2/index.php
inc/nav.php
All the index.php pages include the nav.php page which contains the top horizontal navigation bar, e.g.:
<?php include_once 'inc/nav.php' ?>
Inside the nav.php file are the links to various pages, eg. home and logout etc. These work fine when on the index.php file at the site root, but when on any of the index.php pages in any of the subfolders these don't work as they link to:
http://www.mywebsite.com/folder1/logout.php
whereas the link should be to:
http://www.mywebsite.com/logout.php
The nav.php has links like this:
<li> <a href="logout.php">Logout</a> </li>
so I see how that only works when called from the root index.php page but can't work out how to have it so that it works from any index.php page whether at the site root level or a subfolder.
A: Assuming that you've logout.php on the root, use a slash before the page name like this, to point the page from the root.
<li> <a href="/logout.php">Logout</a> </li>
As what you are using is just logout.php which will point the page name in that specific directory, but the server will return 404 as it may be available when you are on the root, but it will fail when you are in the directory.
If it still complicates the navigation, you can also use if conditions to change the paths accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17801046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove/delete embeds from a message I made my own Discord bot for my Minecraft server with an order system (for developers).
When you react on the ,essage for the order, the message should edit to The Order was claimed by @Discord
And that works, but I also want to remove the EmbedMessage, that was sent with.
But there doesn't exists a method like message.removeEmbeds() or message.deleteEmbeds().
So, how is it possible to do that?
A: The documentation for MessageAction explains:
When updating a Message, unset fields will be ignored by default. To override existing fields with no value (remove content) you can use override(true). Setting this to true will cause all fields to be considered and will override the Message entirely causing unset values to be removed from that message.
This can be used to remove existing embeds from a message:
message.editMessage("This message had an embed").override(true).queue()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66640848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pass std::map object to thread Mycode is trying to pass a std::map as reference to thread but it seems something is bad and result in
error: invalid conversion from ‘void* (*)(std::map<std::basic_string<char>,
std::vector<std::basic_string<char> > >)’ to ‘void* (*)(void*)’ [-fpermissive]
I need to pass
map to thread and insert the key and value of map in that thread and after successful. In main process i need to update or copy(thread map) in another object of same map i.e myMapcache
int main()
{
std::map< std::pair<std::string , std::string> , std::vector<std::string> > myMap,myMapCache;
pthread_t threads;
//how to pass map object in thread as reference
int rc = pthread_create(&threads, NULL, myfunction, std::ref(myMap));
if (rc)
{
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
// if true then update to local myMapCache
if(update)
{
std::copy(myMap.begin(), myMap.end(), std::inserter(MyMapCache, myMapCache.end()) );
}
}
void * myfunction (std::map< std::pair<std::string , std::string> , std::vector<std::string> >& myMap)
{
// here i will insert data in a map
myMap[std::make_pair(key1,key2)].push_back(value);
// if update make the flag true
Update=true;
}
A: pthread_create is not a template, and it does not understand C++ types. It takes a void*, which is what C libraries do in order to fake templates (kind of).
You can pass a casted pointer instead of a C++ reference wrapper object:
int rc = pthread_create(&threads, NULL, myfunction, static_cast<void*>(&myMap));
// ...
void* myfunction(void* arg)
{
using T = std::map<std::pair<std::string, std::string>, std::vector<std::string>>;
T& myMap = *static_cast<T*>(arg);
…or, better yet, use boost::thread (C++98) or std::thread (C++11 and later) to get type safety and a longer lifespan. You're not writing a C program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44788618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is Google App Engine better than Webfaction for a beginner in Django dev? I am a beginner in developing websites by Django.
I run small discussion websites similar to SO.
I have an account at Bluehost which has been a nightmare in developing by Django.
I have found that Webfaction and Google App Engine seems to be the best choices for Django.
However, I am not sure which one is the best for me.
Is Google App Engine better than Webfaction in running small websites?
A: I can't speak for Google App Engine, but as a rather recent Django user myself I recently moved my development site over to a WebFaction server and I must say I was extremely impressed. They are extremely friendly to Django setups (among others) and the support staff answered any small problems I had promptly. I would definitely recommend them.
For other Django-friendly hosts, check out Djangofriendly.com.
A: If you have already written your django application, it may be really difficult to install it on Google App Engine, since you will have to adapt your data model. GAE uses big table, a (key,data) store, instead of a traditional relational model. It is great for performance but makes your programming more difficult (no built in many-to-many relationship handlers, for example).
Furthermore, most apps available for django will not work on GAE since these apps use the relational data model. The most obvious problem is that the great admin app of django will not work. Furthermore, GAE tends to make you use google accounts for identification. This can be circumvented but again, not using readily available django apps. This could be great for you, but it can be a hassle (for example, lots of user names are already taken at google).
So, my final advice is that, if you are a beginner, you should avoid GAE.
If you are based in Europe, djangohosting.ch is also a good choice, instead of webfaction.
A: A bit late with my answer, but nevertheless... I am Django beginner and have my first Django App up and running at GAE. It was App Engine Patch that made it happen. Using it you have django admin and several other apps available out of the box. If you'd like to try it, go for the trunk version. This project is reasonably well documented and have responsive community.
A: I'm a Google app engine developer, so I can't say much about webfaction, but as far as I have used it setting up a web app with app-engine is pretty straight forward¹. The support staff however is not quite good.
1- http://code.google.com/appengine/articles/django.html
A: Webfaction:
Plus:
*
*Great shell access. Ability to install python modules, or anything else you might need. You will love checking out source code from shell to update your production (no need for FTPing anything anymore!)
*Very good performance and reliability
*Great support + wealth of info on help knowledge base and in the forums. (FORGET bluehost or anything else you ever tried). I was surprised by amount of answers I found to what I thought would be difficult questions.
*You can use regular database and you can do joins (see app engine minus #2)
Minus:
*
*Setting up initial deployment can be a bit tricky the first few times around (as is to be expected from shell).
*Growing-scaling can be expensive and you probably will not survive beign "slashdotted"
App Engine
Plus:
*
*Free to start with
*Initial database is easier to setup.
*Deployment is a breeze
*Enforcement of "good" design principles from the start which help you with #5. (Such as hard limits, db denormalizing etc)
*Scalability (but this does not come free - you need to think ahead).
*No maintanence: auto backups, security comes for free, logging + centralized dashboard, software updates are automatic.
Minus:
*
*Setting up Django on App Engine is not so straightforward, as well as getting used to this setup. The webapp framework from google is weak.
*Database model takes a little bit of time to wrap your head around. THis is not your moma's SQL server. For example you have to denormalize your DB from the start, and you cannot do Joins (unless they are self joins)
*The usual things you are used to are not always there. Some things such as testing and data-importing are not that easy anymore.
*You are tied down to App Engine and migrating your data to another DB or server, while not impossible, is not easy. (Not that you do data migration that often! Probably never)
*Hard limits in requests, responses and file sizes (last time I heard about 1MB).
*App Engine currently supports Python 2.5 only.
Can't think of anything else so far.
I am currently with Webfaction and am testing App Engine as well. I have no difficulty going from Django-Webfaction to App-Engine way of thinking. However, I am not sure if the AppEngine -> Standalone servers route would be just as easy.
References
Talks:
*
*Guido on Google App Engine http://www.youtube.com/watch?v=CmyFcChTc4M
*Task Queues in App Engine: http://www.youtube.com/watch?v=o3TuRs9ANhs
A: The thing to remember about GAE is that it works differently than a standard python install and apps you have may not work well (or at all) in that environment. The biggest difference is the database. While there are advantages to the non-relational database available with GAE, you need to treat it differently and there are many things that your code may be expecting your database to be able to do that it cannot.
If you are starting from scratch on an app, either platform would work fine. If you have an existing python app, getting it to work on GAE will take considerable work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/722463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Not able to globally install electron on MacOS due to error I'm getting an error while trying to globally install electron, I'm not sure why.
npm ERR! code 1
npm ERR! path /usr/local/lib/node_modules/electron
npm ERR! command failed
npm ERR! command sh -c node install.js
npm ERR! HTTPError: Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/v19.0.9/electron-v19.0.9-darwin-ia32.zip
npm ERR! at EventEmitter.<anonymous> (/usr/local/lib/node_modules/electron/node_modules/got/source/as-stream.js:35:24)
npm ERR! at EventEmitter.emit (node:events:390:28)
npm ERR! at module.exports (/usr/local/lib/node_modules/electron/node_modules/got/source/get-response.js:22:10)
npm ERR! at ClientRequest.handleResponse (/usr/local/lib/node_modules/electron/node_modules/got/source/request-as-event-emitter.js:155:5)
npm ERR! at Object.onceWrapper (node:events:510:26)
npm ERR! at ClientRequest.emit (node:events:402:35)
npm ERR! at ClientRequest.origin.emit (/usr/local/lib/node_modules/electron/node_modules/@szmarczak/http-timer/source/index.js:37:11)
npm ERR! at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:623:27)
npm ERR! at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
npm ERR! at TLSSocket.socketOnData (node:_http_client:487:22)
npm ERR! A complete log of this run can be found in:
A: For some reason I don't know, your npm tries to install Electron with the ia32 architecture, resulting in a downloadable zip file which is not provided by the Electron maintainers. That's why you're getting a 404 HTTP status code.
Going back in Electron's releases page, I cannot seem to find any darwin-ia32 assets (darwin is the codeame for macOS).
You can try forcing npm to install the appropriate architecture using
npm install --arch=x64 electron
as suggested in Electron's installation guide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73138701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing json to mvc controller I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
[JsonProperty("color")]
public string HeaderColor { get; set; }
[JsonProperty("font-size")]
public string HeaderFontSize { get; set; }
[JsonProperty("font-family")]
public string HeaderFontFamily { get; set; }
}
The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
//Do some validation
return Json("OK");
}
And my jQuery looks like:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["font-size"] = value;
console.log(JSON.stringify({ innerStyle: headerObj }));
$.ajax({
type: "POST",
url: "@Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({ innerStyle: headerObj}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}
Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.
A: I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "@Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}
A: @Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "@Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46214779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Required parameters for launching headless chrome What are the required options for launching google chrome headless from C#? These are the options I’ve got now:
var options = new ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("start-maximized");
options.AddArgument("--disable-gpu");
options.AddArgument("--disable-extensions");
options.AddArgument("--window-size=1024,768");
var driver = new ChromeDriver(options);
A: It would appear that when running headless chrome from, at least, inside Visual Studio the "no-sandbox" option is required.
options.AddArgument("no-sandbox");
Found by accident here:
https://stackoverflow.com/a/39299877/71376
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49352071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firefox WebExtensions API how to make AJAX call to current tab website I want my web extension to make an AJAX call to the website which the user is currently looking at. I know that the current website has an endpoint available at /foo/bar?query=.
Is there anything blocking me from using the fetch API or an XMLHttpRequest to contact this endpoint?
My attempts to use these methods just tell me that a server error has occurred, and nothing comes up in the network tab while I'm trying to debug my extension. I feel like there should be a WebExtensions API for this task, but I can't find one.
A: You can get an object describing the current tab the user is looking at using browser.tabs.getCurrent(). This object has a property url, which you can then use to make an XMLHttpRequest.
browser.tabs.getCurrent().then(currentTab => {
let xhr = new XMLHttpRequest();
xhr.open("GET", currentTab.url);
// ...
});
Edit:
As pointed out by Makyen, tabs.currentTab is not actually what you want. Instead tabs.query with active: true should be used. Something like that should work:
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
let currentTab = tabs[0];
let xhr = new XMLHttpRequest();
xhr.open("GET", currentTab.url);
// ...
})
In order to make cross origin requests, you will need to get permission in your manifest.json file:
{
...
"permissions": [
"tabs",
"<all_urls>"
],
...
}
<all_urls>for instance will allow you to make http requests to any url.
You can read more here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44907697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to perform a unittest on a unittest How do you do a unittest on a unittest. I have a unittest and obviously when it is succesfully it generates an ok message in the terminal but I have struggled to find a way of creating a test for the test based upon that.
Basically looking for a way to test if the below test returns ok.
The Test Below:
import unittest
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(2+2, 4)
if __name__ == '__main__':
unittest.main()
What this returns in the shell :
Ran 1 test in 0.000s
OK
A: First of all you have to have function that does the calculation, so you pass that function to the test case.
Example:
import unittest
# Defined the function that does the calculation
def sum_numbers(x, y):
return x + y
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum_numbers(2, 2), 4)
if __name__ == '__main__':
unittest.main()
Now this test will evaluate to ok and you can add more test to test_sum
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75021580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to use a python package - shouldn't i be able to access anything listed in __all__? I'm trying to use the pyupnp package (http://code.google.com/p/pyupnp/)
I've built and installed it and in my code I have:
import pyupnp
b = pyupnp.UpnpBase()
...
But I get this error: AttributeError: 'module' object has no attribute 'UpnpBase'
Now I had a look in the code for the package, and it has the following:
__all__ = [
'UpnpNamespace',
'UpnpDevice',
'UpnpBase',
...
I thought that I would be able to access anything in the __all__ list? What am I doing wrong?
Thanks so much
A: Looking at this package, you should import pyupnp.upnp, not pyupnp. The contents of __all__ are irrelevant here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5480354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Migrating stripe express into stripe standard I already have a stripe standard account but a platform created a stripe espress account for me. Even though I used the same email address for both, they are now two separate accounts managed in two separate places with two separate dashboards even though both are for my business. Is there a way of migrating the express data into the standard account? My goal is to close the Express account and have All my transactions and management in one location
I had come across some documentation that indicated creating an express account with the same email as an existing standard account would automatically merge the accounts but I can't seem to find that documentation again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75118465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UWP service to app call I have UWP app service with TimeTrigger. Every time this trigger fires i'm trying to download some data from the internet.
Is there anyway my service can notify my second UWP UI app about data load success|fail? The only way i've found is to run the second service in UI app thread and call it to send the notification.
The original task is to create an always-running data update checking service and load a data consuming UWP UI app that may or may not be running.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46202444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Moving from one div to another on click of a menu link I want to make an animation effect on my website where, when we click on a menu link (say, about-section), it will animate to that div in a parallax style.
So guys if you know any jquery plugin that can help me in this context, then please let me know, and it would be better if you demonstrate me a example of that as well.
See the code for help:
.Home-section {
height: 500px;
background: deepskyblue;
}
.About-section {
height: 300px;
background: deeppink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<a href="#">Home</a>
<a href="#">About</a>
<div class="Home-section">
<h1> Hello </h1>
</div>
<div class="About-section">
<h1>Bye</h1>
</div>
So, According to the code i want to animate to About-section on click on the link stating About
A: Hope you want this. Thanks
// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
// target element id
var id = $(this).attr('href');
// target element
var $id = $(id);
if ($id.length === 0) {
return;
}
// prevent standard hash navigation (avoid blinking in IE)
e.preventDefault();
// top position relative to the document
var pos = $(id).offset().top - 10;
// animated top scrolling
$('body, html').animate({scrollTop: pos});
});
.Home-section {
height:500px;
background: deepskyblue;
}
.About-section {
height:300px;
background:deeppink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#home">Home</a>
<a href="#about">About</a>
<div class="Home-section" id="home"><h1> Hello </h1>
</div>
<div class="About-section" id="about"><h1>Bye</h1>
</div>
A: To get more like a parallax effect, you can add background-attachment: fixed;
.About-section {
height: 300px;
background: url('http://lorempicsum.com/futurama/627/200/3') no-repeat;
background-size: cover;
background-attachment: fixed;
}
Like this
Note : I use @sagar kodte JS code which works good for the animation.
A: please try this
.Home-section {
height:500px;
background: deepskyblue;
}
.About-section {
height:300px;
background:deeppink;
}
a{cursor:pointer}
html code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("a").click(function() {
var ourclass = $(this).attr('class');
$('html, body').animate({
scrollTop: $("#"+ourclass).offset().top-10
}, 2000);
});
});
</script>
<a class="home">Home</a>
<a class="about">About</a>
<div class="Home-section" id="home"><h1> Hello </h1></div>
<div class="About-section" id="about"><h1>Bye</h1></div>
and also js fiddlde here
A:
.Home-section {
height: 500px;
background: deepskyblue;
}
.About-section {
height: 300px;
background: deeppink;
}
<a href="#home">Home</a>
<a href="#about">About</a>
<div class="Home-section" id="home">
<h1> Hello </h1>
</div>
<div class="About-section" id="about">
<h1>Bye</h1>
Try this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36761442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Deserialize Dynamic JSON Object I am using a thirdparty API and the Json response that I receive back is as below.
Usually, using something like
Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(response);
I can easily create a .Net model. However, I am struggling on how to formulate the below. I've tried KeyValuePairs, strings, modifying the actual Json but cannot seem to get any joy.
What am I missing?
{
"1": [
{
"qty": 1,
"discount": "flat",
"price": 71.68
}
],
"2": [
{
"qty": 1,
"discount": "flat",
"price": 62.75
}
],
"3": [
{
"qty": 1,
"discount": "flat",
"price": 77.28
}
],
"4": [
{
"qty": 1,
"discount": "flat",
"price": 82.88
}
],
"5": [
{
"qty": 1,
"discount": "flat",
"price": 67.84
}
]
}
Now, what is throwing me is that the numbers(1,2,3,4,5) are Identifiers so will not stay constant and could change each time you receive the response.
A: I think Newtonsoft can do this for you.
string json = @"{
'Email': '[email protected]',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
var jsonReturn = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>( json );
Console.WriteLine( jsonReturn.Email );
Based on this link:
https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
This is the most basic explanation. Use a foreach to iterate over de nodes
A: Using @Liam's suggestion of JObject I have come up with this working solution
public class MyObject
{
public int id { get; set; }
public int qty { get; set; }
public string discount { get; set; }
public decimal price { get; set; }
}
and then after retrieving the JSON response...
var jsonObj = JsonConvert.DeserializeObject<JObject>(response);
List<MyObject> myObjects = new List<MyObject>();
foreach (var item in jsonObj.AsJEnumerable())
{
var csp = JsonConvert.DeserializeObject<List<MyObject>>(item.First.ToString());
csp.ForEach(a => { a.product_id = Convert.ToInt32(item.Path); });
myObjects.AddRange(csp);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62952744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: _e printed before layout WPML/Wordpress/PHP I am using WPML to translate English to a different language.
Everything works fine except the mail form.
For some reason when is use the _e() function the string gets printed before the layout.
But still inside the body element. Please help here is the code:
if(trim($_POST['contactSubject']) === '') {
$subjectError = _e('Please enter a subject.', 'wpml_contact');
$hasError = true;
} else {
$subject = trim($_POST['contactSubject']);
}
A: You should use the __() function (codex link). This function returns the translated string:
if(trim($_POST['contactSubject']) === '') {
$subjectError = __('Please enter a subject.', 'wpml_contact');
$hasError = true;
} else {
$subject = trim($_POST['contactSubject']);
}
The _e() function returns and displays the translated string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21208812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Returning the Most Negative Two's Complement Number in C with Bitwise Operators I have a function in C that should return the most negative two's complement number:
int mostNegTwosComp(void) {
return 0;
}
I am constrained to using a maximum of 4 bitwise operators. These operators include: ! ~ & ^ | + << >>. How would I go about doing this? Wouldn't the most negative two's comp number be dependent on how many bits the selected number is? For instance, 10000 would be the most negative two's comp number of a 16 bit int?
A: return ~ (~0u >> 1);
~ turns on all bits in the unsigned zero. Then >> 1 shifts right, resulting in the high bit becoming zero. Then ~ inverts all bits, producing one in the high bit and zero in the rest.
Then the return converts this to int. This has implementation-defined behavior, but class assignments of this sort generally presume a behavior suitable for the exercise.
A: If you don't need a portable version, you can abuse the knowledge that integers are almost always 4 bytes.
return 0x80000000;
In fact, if you know the size of the type you're going to return, you can skip the bitwise game and cheat with the format:
*
*In 0x__, each number is 4 bits.This means 2 digits are one byte.
*You want the first bit to be 1, and all other bits to be 0.
*0x8 = 0b1000
*As such, you can represent the value as 0x80 + 2 '0's for every byte of the type past the first.
But to answer the rest of your question.
How would I go about doing this?
If you're templating, you'd (probably) use the bitwise trick the other answer suggests. Otherwise you can cheat with the above code or use a definition from limits.h (iirc).
~ (~0u >> 1);
Would be a portable solution.
Wouldn't the most negative two's comp number be dependent on how many bits the selected number is?
The most negative two's compliment is dependent upon the size of the containing variable, so I suppose you could say "selected number". In fact, the range of values depends on the size of the containing variable.
For instance, 10000 would be the most negative two's comp number of a 16 bit int?
For 16 bits, the most negative two's comp would be 0x8000, 0b1000000000000000 or -32768, depending on how you'd like it represented.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54526282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: using a pushbutton's call back in an other callback in matlab I have two push buttons in my MATLAB GUI. I am trying to recognize a push button in button1's callback function and do something with regard to which button was pressed. I have tried to use button group and put all my buttons in that group. It seems as if there is no code when any of these push buttons is clicked. Why?
Here is my code:
function uibuttongroup1_SelectionChangeFcn(hObject,eventdata)
switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
case 'notSimul'
disp('notSimul clicked')
case 'simul'
% Code for when radiobutton2 is selected.
case 'stopTest'
% Code for when togglebutton1 is selected.
case 'start'
% Code for when togglebutton2 is selected.
% Continue with more cases as necessary.
otherwise
% Code for when there is no match.
end
A: If I understand your question correctly that you placed a push button in a button group, the answer is it would not work because button group is supposed to be composed of only toggle button and radio button. When I tried putting a push button in a button group, nothing would happen, just as you described.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17423716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to search CalDav Blob from MySql Db? I'm currently trying to integrate a CalDav Calendar into my website.
I'm using "baikal" and it actually works fine, i'm already able to access my
calendar via iphone, macbook and so on.
What I wanna do now is reading the Events from the mysql database and display
them in my own calendar.
It works fine so far, I found a library that can parse these Blobs which stores all calendardata.
My problem now is:
How can I search through this blob? For example, i want to display all events between date x and y, or display all events that contain "concert" in the summary/title.
I did some research on this but i wasn't able to find anything so I thought I ask!
looking forward to your replies and thanks in advance!
david
A: Why dont you use CalDAV to access the calendar, instead of trying to directly hit the MySQL DB ? From what I understand, you don't even own the schema as it comes from the Baikal server (?...) so you are running the risk of having to redo the work if/when Baikal changes the way they store the data.
Another advantage is that you are guaranteed to get a more consistent result: for example, time range queries (from date x to date y) can be tricky so by using CalDAV queries, both CalDAV clients and your calendar are going to return the same set of events whereas by trying to implement something on your own, you will likely diverge from what the CalDAV server returns.
There are php CalDAV clients. See for example Is there any php CalDav client library?
See https://www.rfc-editor.org/rfc/rfc4791#section-7.8.1 for a timerange based CalDAV query.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17543521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: R value of i and j in a loop I am learning to run a loop (2 rounds of loop) for a DCC GARCH model. However, the loop is out of my control because:
Problem 1: Round 1, I want R to run for i from 1 to n-1 (n is total numbers of countries): however
it keeps run from i==0 --> I put i in (2:length(msci)-1); so it is ok for now, but I just don't understand why there is the case.
Round 2, I want R to run for j from i+1 to n. Somehow, R run j until n+ 1 --> I bypass it by setting
j in (i+1:length(msci)-1
It is ok for i=1 (it runs for j from 2 to 49). When i=2, it runs from 3 to 50
So it issues the error: "[1] "Now is loop j 50"
Error in [.data.frame(msci, j) : undefined columns selected"
Any help (how to stop j reach the value of 50) is greatly appreciated. thanks
My code is:
library(R.oo)
library(rmgarch)
library(tidyverse)
setwd("C:/data/Garch output")
#define the function####
my_model <- function(country1, country2) {
uspec <- ugarchspec(variance.model = list(model="eGARCH",garchOrder = c(1,1)),mean.model = list(armaOrder = c(2,2)))
mspec=multispec(replicate(2,uspec))
multf=multifit(mspec,data=data.frame(country1,country2),solver = "nlminb",fit.control = list(stationarity = 1, fixed.se = 0, scale = 1, rec.init = "all"))
#define the DCC model
spec1=dccspec(uspec=mspec,dccOrder=c(1,1), model = "DCC",distribution="mvnorm")
#estimate DCC
fit1=dccfit(spec1,data=data.frame(country1,country2),fit.control = list(eval.e=TRUE),fit=multf)
return(fit1)
}
for (i in 2: length(msci)-1) {
print(paste("LOOP i IS NOW", i))
if (j >= i+1:length(msci)-1) {
if (i != j) {
print(paste("Now is loop j", j))
print(paste("this is the loop of correlation between", names(msci[i]), "and", names(msci[j])))
#create name for the output
temp_name <- paste0("fit_",names(msci[i]), "_", names(msci[j]))
file_name <- temp_name
#estimate model
temp_name <- tryCatch({my_model(msci[i], msci[j])},
error = function(e) {cat("There is a error in", names(msci[i]), "and", names(msci[j]), "\n")}
)
saveRDS(temp_name, file = paste0(file_name,".RDS"))
print(paste("Finish loop of correlation between", names(msci[i]), "and", names(msci[j])))
}
}}
my data is in the below google link.
https://docs.google.com/spreadsheets/d/1ygaoOvby4mTpFIfHTkcyjq-Uwby671yQWI-xfU3Li7Y/edit#gid=0
A: Your issue is order of operations -- in R, : has higher precedence than + and -.
## Demonstration:
1:5 - 1
# [1] 0 1 2 3 4
1:(5 - 1)
# [1] 1 2 3 4
## In your case
## change this:
for (i in 2: length(msci)-1)
## to this:
for (i in 1:(length(msci) - 1))
## I don't see `j` defined in your code, but I assume you have the same issue and need
for (j in (i + 1):n))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65912093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to round up to the higher 10 in C#? I have to write a program at school that allows the user to input a 7-digits of a GTIN-8 barcode and calculate check digit. To calculate the check digit the seven input numbers are multiplied by 3, 1, 3, 1 etc.
for (i = 0; i < 7; i++)
{
//Convert String to Character
ch = gtinNum[i];
//Convert Character to Integer
number = Convert.ToInt32(ch);
product = number * weights[i];
total = total + product;
}//end for loop
After that, the total is taken away from the nearest higher ten. For example if the total was 43 then it would be 50-43.
In the simplest way possible, how do I round up to the higher ten?
A: You can use Math.Ceiling, you just need to divide by ten first and multiply by 10 afterwards. Divide by 10.0 to avoid integer division(Math.Ceiling takes double):
int num = 43;
int nextHigherTen = (int)Math.Ceiling(num / 10.0) * 10;
This "rounds" 41-50 up to 50. If you want it from 40-49 you could use this:
int nextHigherTen = (int)Math.Ceiling((num + 1) / 10.0) * 10;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37544613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I pass a class object from Activity to a class to be able to call its methods? I need to create an object of the BLE class in the Activity, in onCreate, I tried to implement it with Parcel (passing the object via Intent), but I have an application crash from it.
As it turned out, the reason was that in the BLE class when I accept The content:
mDeviceListAdapter = getEnableIntent().getParcelableExtra("lVAdapter");
mDeviceListAdapter == null
Later I learned that the Intent serves to transfer data only in the onCreate from one Activity to another.
Please tell me how I can transfer objects of the created classes to other classes (not Activity). Thankful in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51204700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to view Lambda results in CloudWatch Event Logs? I was following Tutorial: Schedule AWS Lambda Functions Using CloudWatch Events - Amazon CloudWatch Events on how to Schedule AWS Lambda Functions Using CloudWatch Events.
It all makes sense and work as expected, but in my logs I cannot find the results of the lambda calls, but only custom logs that were written in the code and I can see the incoming payloads.
Are results supposed to show or do I specifically need to Log them in my code?
A: If lambda has got these IAM permissions it will show the custom loggers as well as default AWS invocation/error logs
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64093627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java Jar's library conflicts
I've been struggling for a while trying to figure out which war application is using a couple of libraries (ie "cxf-2.0.3-incubator.jar" & "cxf-manifest-incubator.jar") that are causing me troubles at the moment of deploying a new war application on a jboss.4.0.5.GA java application server. The thing is that if I remove those jars, the conflict disappears and the newly deployed application works fine. However trying to deploy this application without removing the mentioned jars fails.
Is there any tool or (linux bash command) suitable for listing all jar dependencies for war applications? (I've already tried tattletale tool, but it seems to work only with jars components).
Regards
A: If you can then try to mavenize your web application project to get all the dependencies that are required and to get away from all the non-required ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18000229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to parse nested keys and values using JsonReader? I am learning Java and I'm trying to make a Fortnite stat tracking app. I'm using the Fortnite tracker API and JsonReader to read the keys and values that get returned. This works fine but the problem is the stats like 'kills' etc are nested and I'm not sure how to read those.
Can I read nested keys and values using JsonReader?
I tried JSONObject but I'm not entirely sure I was using it correctly so I didn't get very far.
{ "accountId": "c48bb072-f321-4572-9069-1c551d074949", "platformId": 1, "platformName": "xbox", "platformNameLong": "Xbox", "epicUserHandle": "playername", "stats": {
"p2": {
"trnRating": {
"label": "TRN Rating",
"field": "TRNRating",
"category": "Rating",
"valueInt": 1,
"value": "1",
"rank": 852977,
"percentile": 100.0,
"displayValue": "1"
},
"score": {
"label": "Score",
"field": "Score",
"category": "General",
"valueInt": 236074,
"value": "236074",
"rank": 6535595,
"percentile": 3.0,
"displayValue": "236,074"
}
Above is a sample of the information that I pulled so that you can see the structure
public class MainActivity extends AppCompatActivity {
TextView tv;
TextView tv2;
TextView tv3;
Button submit;
EditText tbplatform;
EditText tbhandle;
String TAG = "TESTRUN";
String id = "";
InputStreamReader responseBodyReader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvOne);
tv2 = (TextView) findViewById(R.id.tvTwo);
tv3 = (TextView) findViewById(R.id.tvThree);
submit = (Button) findViewById(R.id.btnSubmit);
tbplatform = (EditText) findViewById(R.id.tbPlatform);
tbhandle = (EditText) findViewById(R.id.tbHandle);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String platform = String.valueOf(tbplatform.getText());
final String username = String.valueOf(tbhandle.getText());
AsyncTask.execute(new Runnable() {
@Override
public void run() {
// All your networking logic
// should be here
// Create URL
URL githubEndpoint = null;
try {
githubEndpoint = new URL("https://api.fortnitetracker.com/v1/profile/" + platform+ "/" + username);
} catch (MalformedURLException e) {
e.printStackTrace();
}
// Create connection
HttpsURLConnection myConnection = null;
try {
myConnection =
(HttpsURLConnection) githubEndpoint.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
myConnection.setRequestProperty("TRN-Api-Key", "API_KEY_HERE");
try {
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
final String key = jsonReader.nextName(); // Fetch the next key
//Log.v(TAG, key);
if (key.equals("epicUserHandle") || key.equals("platformName") || key.equals("accountId")) { // Check if desired key
// Fetch the value as a String
final String value = jsonReader.nextString();
if (key.equals("epicUserHandle")) {
Log.v(TAG, "Gamertag: " + value);
}
if (key.equals("platformName")) {
Log.v(TAG, "Console: " + value);
}
if (key.equals("stats")) {
Log.v(TAG, "Kills: " + value);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
//stuff that updates ui
if(key.equals("epicUserHandle")) {
tv.setText("Username: " + value);
}
if(key.equals("platformName")) {
tv2.setText("Platform: " +value);
}
if(key.equals("accountId")) {
tv3.setText("Account ID: " +value);
}
}
});
//Log.v(TAG, "" +value);
// Do something with the value
// ...
//break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
}
A: I think this may help you
You Need To Create Some Classes As Given Below
class Score implements Serializable {
private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;
public Score() {
this("", "", "", 0, "", 0, 0.0, "");
}
public Score(String label, String field,
String category, Integer valueInt,
String value, Integer rank,
Double percentile, String displayValue) {
this.label = label;
this.field = field;
this.category = category;
this.valueInt = valueInt;
this.value = value;
this.rank = rank;
this.percentile = percentile;
this.displayValue = displayValue;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getValueInt() {
return valueInt;
}
public void setValueInt(Integer valueInt) {
this.valueInt = valueInt;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Double getPercentile() {
return percentile;
}
public void setPercentile(Double percentile) {
this.percentile = percentile;
}
public String getDisplayValue() {
return displayValue;
}
public void setDisplayValue(String displayValue) {
this.displayValue = displayValue;
}
}
class TRNRating implements Serializable {
private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;
public TRNRating() {
this("", "", "", 0, "", 0, 0.0, "");
}
public TRNRating(String label, String field,
String category, Integer valueInt,
String value, Integer rank,
Double percentile, String displayValue) {
this.label = label;
this.field = field;
this.category = category;
this.valueInt = valueInt;
this.value = value;
this.rank = rank;
this.percentile = percentile;
this.displayValue = displayValue;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getValueInt() {
return valueInt;
}
public void setValueInt(Integer valueInt) {
this.valueInt = valueInt;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Double getPercentile() {
return percentile;
}
public void setPercentile(Double percentile) {
this.percentile = percentile;
}
public String getDisplayValue() {
return displayValue;
}
public void setDisplayValue(String displayValue) {
this.displayValue = displayValue;
}
}
class P2 implements Serializable {
private TRNRating trnRating;
private Score score;
public P2() {
this(new TRNRating(), new Score());
}
public P2(TRNRating trnRating, Score score) {
this.trnRating = trnRating;
this.score = score;
}
public TRNRating getTrnRating() {
return trnRating;
}
public void setTrnRating(TRNRating trnRating) {
this.trnRating = trnRating;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this.score = score;
}
}
class Stats implements Serializable {
private P2 p2;
public Stats() {
this(new P2());
}
public Stats(P2 p2) {
this.p2 = p2;
}
}
//You Need To Change Name Of This Class
class Response implements Serializable {
private String accountId;
private Integer platformId;
private String platformName;
private String platformNameLong;
private String epicUserHandle;
private Stats stats;
public Response() {
this("", 0, "", "", "", new Stats());
}
public Response(String accountId, Integer platformId,
String platformName, String platformNameLong,
String epicUserHandle, Stats stats) {
this.accountId = accountId;
this.platformId = platformId;
this.platformName = platformName;
this.platformNameLong = platformNameLong;
this.epicUserHandle = epicUserHandle;
this.stats = stats;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public Integer getPlatformId() {
return platformId;
}
public void setPlatformId(Integer platformId) {
this.platformId = platformId;
}
public String getPlatformName() {
return platformName;
}
public void setPlatformName(String platformName) {
this.platformName = platformName;
}
public String getPlatformNameLong() {
return platformNameLong;
}
public void setPlatformNameLong(String platformNameLong) {
this.platformNameLong = platformNameLong;
}
public String getEpicUserHandle() {
return epicUserHandle;
}
public void setEpicUserHandle(String epicUserHandle) {
this.epicUserHandle = epicUserHandle;
}
public Stats getStats() {
return stats;
}
public void setStats(Stats stats) {
this.stats = stats;
}
}
If your response is same as explained in question. Then this will work.
//In your code after status check you need to do like this
if (myConnection.getResopnseCode() == 200) {
BufferedReader br=new BufferedReader(responseBodyReader);
String read = null, entireResponse = "";
StringBuffer sb = new StringBuffer();
while((read = br.readLine()) != null) {
sb.append(read);
}
entireResponse = sb.toString();
//You need to change name of response class
Response response = new Gson().fromJson(entireResponse , Response.class);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49752576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dojo: Saving changes with EnhancedGrid using JsonRestStore? I'm trying to use a EnhancedGrid and a JsonRestStore:
<script type="text/javascript">
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.data.JsonRestStore");
dojo.ready(function(){
/*set up data store*/
var store = dojox.data.JsonRestStore({
target: "test/id"
});
/*set up layout*/
var layout = [[
{name: 'Column 1', field: 'id', width: '100px', editable : true},
{name: 'Column 2', field: 'col2', width: '100px', editable : true, type : dojox.grid.cells.Bool},
{name: 'Column 3', field: 'col3', width: '200px'},
{name: 'Column 4', field: 'col4', width: '150px', editable : true, type : dojox.grid.cells.Select, options : ['ON','OFF'] , values: [ '0', '1' ]}
]];
/*create a new grid:*/
var grid = new dojox.grid.EnhancedGrid({
id: 'grid',
store: store,
structure: layout,
rowsPerPage: 5,
rowSelector: "20px",
selectionMode: "single",
},
document.createElement('div'));
/*append the new grid to the div*/
dojo.byId("gridDiv").appendChild(grid.domNode);
/*Call startup() to render the grid*/
grid.startup();
});
</script>
<style type="text/css">
@import "/js/dojox/grid/resources/claroGrid.css";
/*Grid need a explicit width/height by default*/
#grid {
width: 80em;
height: 40em;
}
</style>
<div id="gridDiv" class="claro"></div>
On the server side I have a Rest service which handles Get, Put, Post and Delete requests.
I have two distinct problems, but I wonder wether they are linked:
1- When I double click on any of the editable cells it works fine, I can change the cells' content. But then I can't edit any other editable cell. No matter on which one I click, I won't be able to edit it. For instance if I double click on the 'Select' cell, I will be able to select between the two values, ON or OFF. But then I can no longer edit any other cell. The cell I've just edited will remain displayed with an arrow, and his row will remain selected.
2- The server will never receive any PUT requests. It will receive the GET requests on the initial display and when I scroll the grid, but this is the only REST request I will get on the server side. So I can't figure how to make and save any changes in the grid!
Any clue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9090403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I reposition and resize gameObjects in Unity via scripting? So I am trying to build a game similar to the Snakes and Ladders game in Unity, but I am finding it hard to deal with when multiple player tokens land on the same square.
I have the following GameObjects in my scene:
On the click of the Player1 button one of the player tokens (cylindrical gameObjects) advances to the first square (the die is hard coded to roll a 1 everytime for testing purposes) as shown below:
Now when the Player2 button is clicked the other player token should advance to the first square and it does, however, it overlaps the first player token and it looks like there is only 1 player token in the scene now as shown below:
I am trying to find a way to resize and reposition both the tokens such that there is enough space between them and they still remain on the same square.
Also, once a player token leaves the square and advances to another square I need to resize the player tokens on both the squares based on whether other player tokens (in case of more than 2 players of course) exist on each square or not
I have tried the following in my method that is called on the click of the button:
public void MovePlayerToken(GameObject currentPlayer)
{
var startingSquare = currentPlayer.GetComponent<PlayerToken>().StartingSquare;
var landingSquare = GetLandingSquare(startingSquare);
var existingPlayerTokensOnLandingSquare = GetExistingPlayerTokens(playerTokens, landingSquare);
//var existingPlayerTokensOnStartingSquare = GetExistingPlayerTokens(playerTokens, startingSquare);
if (existingPlayerTokensOnLandingSquare.Count > 0)
{
TransformPlayerTokens(existingPlayerTokensOnLandingSquare, landingSquare, SquareType.LandingSquare);
if (currentPlayer.transform.localScale == new Vector3(1, 1, 1))
{
currentPlayer.transform.localScale = new Vector3(currentPlayer.transform.localScale.x / 2,
currentPlayer.transform.localScale.y / 2,
currentPlayer.transform.localScale.z / 2);
}
switch (existingPlayerTokensOnLandingSquare.Count)
{
case 1:
existingPlayerTokensOnLandingSquare[0].transform.position = new Vector3(landingSquare.transform.localPosition.x + 0.25f, landingSquare.transform.localPosition.y, landingSquare.transform.localPosition.z + 0.25f);
currentPlayer.transform.position = new Vector3(landingSquare.transform.localPosition.x + -0.25f, landingSquare.transform.localPosition.y, landingSquare.transform.localPosition.z + -0.25f);
break;
case 2:
existingPlayerTokensOnLandingSquare[0].transform.position = new Vector3(landingSquare.transform.localPosition.x + 0.25f, landingSquare.transform.localPosition.y, landingSquare.transform.localPosition.z + 0.25f);
existingPlayerTokensOnLandingSquare[1].transform.position = new Vector3(landingSquare.transform.localPosition.x + -0.25f, landingSquare.transform.localPosition.y, landingSquare.transform.localPosition.z + -0.25f);
currentPlayer.transform.position = landingSquare.transform.position;
break;
}
}
else
{
currentPlayer.transform.position = landingSquare.transform.position;
}
currentPlayer.GetComponent<PlayerToken>().StartingSquare = landingSquare;
}
private Square GetLandingSquare(Square startingSquare)
{
Square landingSquare = startingSquare;
for (int i = 0; i < _stateManager.DiceTotal; i++)
{
if (landingSquare.NextSquares.Length > 1)
landingSquare = landingSquare.NextSquares[Random.Range(0, landingSquare.NextSquares.Length)];
else
landingSquare = landingSquare.NextSquares[0];
}
return landingSquare;
}
private List<PlayerToken> GetExistingPlayerTokens(PlayerToken[] playerTokens, Square square)
{
List<PlayerToken> existingPlayerTokens = new List<PlayerToken>();
foreach (var playerToken in playerTokens)
{
if (playerToken.transform.position == square.transform.position ||
playerToken.transform.position == new Vector3(square.transform.localPosition.x + 0.25f, square.transform.localPosition.y, square.transform.localPosition.z + 0.25f) ||
playerToken.transform.position == new Vector3(square.transform.localPosition.x + -0.25f, square.transform.localPosition.y, square.transform.localPosition.z + -0.25f))
{
existingPlayerTokens.Add(playerToken);
}
}
return existingPlayerTokens;
}
private void TransformPlayerTokens(List<PlayerToken> existingPlayerTokens, Square landingSquare, SquareType squareType)
{
foreach (var playerToken in existingPlayerTokens)
{
if(playerToken.transform.localScale == new Vector3(1, 1, 1))
{
playerToken.transform.localScale = new Vector3(
playerToken.transform.localScale.x / 2,
playerToken.transform.localScale.y / 2,
playerToken.transform.localScale.z / 2
);
}
}
}
The problem with this approach is that the more the player tokens the more hard coding will be needed... I really don't like this approach and I am sure there is a better way to do this using the Physics Engine or something (BTW I am a complete newbie and have never worked with Unity before - this is my first ever project so please expect me to know little to nothing about the Physics Engine)
Thank you.
A: You can reposition with GameObject.transform.position = (new position here).
A: For the resizing, you can do this
var players = existingPlayerTokensOnLandingSquare.Count + 1;
currentPlayer.transform.localScale = new Vector3(currentPlayer.transform.localScale.x / players,
currentPlayer.transform.localScale.y / players,
currentPlayer.transform.localScale.z / players);
Don't know about the repositioning, or can't think about that now. Hope someone else can answer that one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68445998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android: Any way to remove AM/PM in TextClock? I am currently using TextClock in my xml, however I do not want the AM/PM to be in the displayed time. Is there a way to remove it?
A: Based on the documentation you could use the following:
setFormat12Hour( "K:m" );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32103872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deleting document inside a nested Collection I was making a function to clear all documents inside a nested collection. I've accessed it as follow.
const deleteChat = async () => {
const chatSnapShot = await db
.collection("chats")
.doc(router.query.id)
.collection("messages")
.get();
chatSnapShot.forEach((doc) => {
console.log(doc.data());
});
};
How can I do that? This doc.data() returns the data inside the messages collection. I've tried using other solutions but things doesn't work. Help would be appreciated :)
A: The get() reads all documents from that collection. You need to use delete() to delete a document. Try refactoring the code as shown below:
const deleteChat = async () => {
const chatSnapShot = await db
.collection("chats")
.doc(router.query.id)
.collection("messages")
.get();
const deletePromises = chatSnapshot.docs.map(d => d.ref.delete());
await Promise.all(deletePromises)
console.log("Documents deleted")
};
Here chatSnapShot.docs is an array of QueryDocumentSnapshot and you can get DocumentReference for each doc using .ref property. Then the doc reference has .delete() method to delete the document. This method returns a promise so you can map an array of promises and run them at once using Promise.all()
You can also delete documents in batches of up to 500 documents using batched writes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71634708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits