id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23529500
|
Is it possible to have a combo box that always display certain text (when collapsed)? It is bound to an ItemSource and user can expand the dropdown and select an item, but I want the text to always display "Insert macro" or something like that when it is collapsed. I don't want the custom text to be displayed as selection
A: Sure it is possible.
First you have to define your own ToggleButtonStyle. The ControlTemplate holds a contentpresenter whose content is bound.
<ContentPresenter Content="{TemplateBinding Content}"
OverridesDefaultStyle="True"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
You can add additional styling if you want to.
then you have to create a custom ComboBoxStyle. The easiest way to create it is to alter the default-template (in Blend rightclick on your ComboBox -> Edit Template -> Edit a copy).
The ContentPresenter within this template should have a Binding which looks like this:
Content="{TemplateBinding SelectionBoxItem}"
Simply delete this line and your ToggleButton should not get a new Content if a Item is selected.
Now you should be able to create your ComboBox with a fixed Content like this:
<ComboBox Style="{StaticResource ComboBoxStyle}" Text="Title">
Here are also some ControlTemplateExamples http://msdn.microsoft.com/en-us/library/ms752094(v=vs.85).aspx
Hope this helps.
| |
doc_23529501
|
List someVar = new List();
However when I try this in Visual Studio I get an error. What is the reason for VS not letting me declare List this way?
Let me show you where I saw it:
public override IEnumerable SomeMethod()
{
List someVar= new List();
// more code
return someVar;
}
P.S After contacting the owner of the project it turned out Wordpress striped out the tags <> after List and IEnumerable, so it actually should be List<SomeClass> and IEnumerable<SomeClass>
public override IEnumerable<SomeClass> SomeMethod()
{
List<SomeClass> someVar= new List<SomeClass>();
// more code
return someVar;
}
A: There is not an inbuilt class called List. There is ArrayList, but: click on List and press f12. This will show you where it is declared. There are two options:
*
*a class called List that is nothing whatsoever to do with List<T> has been declared in the local project; for example:
class List { ...} // here we go; a class called List
*a using alias (at the top of the file) has been used to spoof List as a name; for example:
using List = System.Collections.Hashtable;
or
using List = System.Collections.Generic.List<int>;
A: You get an error because the List class does not exist in the .NET Framework. If you want to use a non-generic list that can hold any type of object, use ArrayList.
A: I don't recognise it (I thought it was ArrayList before List<T> arrived?). Either way it would be an older class invented before generics was implemented. I'd use List<object>.
| |
doc_23529502
|
My POJO.
class Coordinates {
private final BigDecimal latitude
private final BigDecimal longitude
...
}
My database table contains coordinates for cities perimeter, so there are three columns: city_name, latitude, longitude. Each city contains lots (really, LOTS) of perimeter coordinates that will be used to build a shadow area in Google Maps.
I intend to build a simple native query on that table that should return a list of coordinates.
A: This is https://jira.spring.io/browse/DATAJPA-980 and Here is a project that demonstrates the issue.
@Query(value = "SELECT name AS name, age AS age FROM Person", nativeQuery = true)
List<PersonSummary> findAllProjectedNativeQuery();
It is fixed in the Spring Data JPA 2.0 GA (Kay) release which comes with Hibernate 5.2.11.
The issue is also fixed for Spring Data 1.10.12 (Ingalls) and 1.11.8 (Hopper) but will need to be run on Hibernate 5.2.11 to work.
A: You will have to use sql result set mapping which is part of JPA.
A: Found the answer on another post. Basically I used SqlResultSetMapping along with ConstructorResult (no other way worked out) with a special attention to a comment on the accepted answer of the mentioned post: you need to add the @NamedNativeQuery annotation to the entity of the used interface AND prepend the entity's name with a . otherwise it won't work.
Example:
@Entity
@Table(name = "grupo_setorial")
@SqlResultSetMapping(
name = "mapeamentoDeQuadrantes",
classes = {
@ConstructorResult(
targetClass = Coordenada.class,
columns = {
@ColumnResult(name = "latitude"),
@ColumnResult(name = "longitude")
}
)
}
)
@NamedNativeQuery(
name = "GrupoCensitario.obterPerimetroDosSetores",
query = "SELECT latitude as latitude, longitude as longitude FROM coordenadas where id_setor IN (:setores)",
resultSetMapping = "mapeamentoDeQuadrantes"
)
public class GrupoCensitario {
A: If you are using a recent version of spring-data and also making use of the Repositories, I personally think that the answer from Itsallas leads to the right solution.
I actually did't now about (Spring Data) Projections yet and needed a moment to understand what he was showing in his example.
Therefore I just want to add a link to the Spring Data JPA - Reference Documentation, have a look at the Projections chapter.
Spring Data query methods usually return one or multiple instances of the aggregate root managed by the repository. However, it might sometimes be desirable to create projections based on certain attributes of those types. Spring Data allows modeling dedicated return types, to more selectively retrieve partial views of the managed aggregates.
A: The answer I found:
public interface UserEventRepository extends JpaRepository<UserEvent, Long> {
List<UserEvent> findAllByUserId(Long userId);
@Query(value = "SELECT user_id FROM user_event ue " +
"WHERE ue.user_id = :userId", nativeQuery = true)
List<Long> findUserIdByEventId(@Param("userId") Long userId);
}
That way we return List of Long - list of ids. The key here is that we are setting the nativeQuery property to true. The value itself is the query we want to be executed.
I hope that helps. It seems a clear solution.
A: The projections solutions was the best. (query by id just an example, you can just use extends CRUD Operations)
Just add the Interface as response to the query as
Example repository :
@Query(select * from tableA where tableA = :id)
DisplayLangLongI findTableAbyId(@Param(value = "id") Long id)
Example Interface (DisplayLangLongI.java)
public interface DisplayLangLongI () {
BigDecimal getLatitude();
BigDecimal getLongitude();
...... (you can add more)
}
In interface, you can select which parameter/object just to display
| |
doc_23529503
|
Table 1:
+-------+-------+-------+-------+-------+
| | col A | col B | col C | col D |
+-------+-------+-------+-------+-------+
| row 1 | 1 | | | |
| row 2 | | 2 | | |
| row 3 | 8 | 3 | | |
| row 4 | 9 | | 4 | |
+-------+-------+-------+-------+-------+
Table 2:
+-------+-------+--------------+
| | col A | col B |
+-------+-------+--------------+
| row 1 | 1 | dog |
| row 2 | 2 | cat |
| row 3 | 3 | zebra |
| row 4 | 4 | donkey |
| row 5 | 8 | horse |
| row 6 | 9 | honey badger |
+-------+-------+--------------+
Is there a SQL query that will return the following?
+-------+--------------+-------+--------+-------+
| | col A | col B | col C | col D |
+-------+--------------+-------+--------+-------+
| row 1 | dog | | | |
| row 2 | | cat | | |
| row 3 | horse | zebra | | |
| row 4 | honey badger | | donkey | horse |
+-------+--------------+-------+--------+-------+
At the moment I am SELECT * IN Table_1.
Then querying Table_2 six times to get the result. Is there a more elegent way?
I do want to use SELECT * -- I do not want to specify the table headings in the query (because there are 50+ table headings).
A: The only way to do lookups for all columns is by mentioning all the columns in the SQL query.
This could be done with one left join for each column, or with correlated subqueries:
SELECT (SELECT colB FROM Table2 WHERE colA = Table1.colA) AS colA,
(SELECT colB FROM Table2 WHERE colA = Table1.colB) AS colB,
(SELECT colB FROM Table2 WHERE colA = Table1.colC) AS colC,
...
FROM Table1
You cannot use SELECT *. If you do not know the columns of Table1, you can read them from the database, and construct the query dynamically.
| |
doc_23529504
|
But I do not know how to trigger this in android. I thought that WebViewClient will be used for this even though i don know how to code this.
Can anyone help me with source code for this?
Thanks in advance.
A: Did you try to hyperlink your phone number?
Something like below
<a href="tel:0094775373891">94-77-5373891</a>
A: you need to use tel keyword in your link instead of callme
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
}else if(url.startsWith("http:") || url.startsWith("https:")) {
view.loadUrl(url);
}
return true;
}
and your link look like this <a href="your_number">your_number</a>
Edit
you can inject the code into the loading page at on page start/finish time using this way
webView.loadUrl("javascript:(function() { ... })()");
Here in the function you can write replace code for your element using DOM
and impelement in both onPageStarted() and onPageFinished().
| |
doc_23529505
|
I'm using a Box object to hold the contents of each entry and have declared an Image object as its first element.
From my understanding, all elements within a Box object are "stacked" so that elements declared later(further down) appear visually on top of elements declared earlier (further up), so I'm not sure why the image background - which is declared first - is rendered on top of my Text element declared further down inside the ProfileContent composable at Line#93:
Here is a screenshot with the dark honeycomb Image element disabled:
and here, with the dark honeycomb Image element enabled:
Somehow, the background image is being correctly rendered behind the player icon yet it is rendered on top of the Text element - although both the icon and text are declared within the same Row object.
Anybody have any ideas how to fix this issue and force the background image to be rendered behind both elements instead?
A: It doesn't render on top of the TextField, it looks like its on top of it because of the TextField's background blending with the Image behind it, so it looks like its overlapping them.
I tried implementing your code and changed the the TextField backgroundColor to Color.LightGray.
Card(
modifier = Modifier
.fillMaxWidth()
.size(90.dp)
.padding(top = 6.dp)
.wrapContentHeight(align = Alignment.Top),
shape = CutCornerShape(topEnd = 20.dp),
elevation = 8.dp
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = R.drawable.honeycomb),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.matchParentSize()
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
// ProfilePicture() composable
Box(
modifier = Modifier
.size(80.dp)
.clip(CircleShape)
.background(Color.Red)
)
Spacer(modifier = Modifier.size(size = 16.dp))
// ProfileContent() composable
Box(
modifier = Modifier
.fillMaxWidth()
.padding(end = 16.dp)
) {
TextField(
value = "Text",
onValueChange = {},
label = { Text("Player Name")},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.LightGray
)
)
}
}
}
}
Edit: Refactored and corrected posted solution description from Text to TextField
| |
doc_23529506
|
A: You can try to use VARCHAR(65535) in MySQL.
A: There is no list data type in MySQL.
Given the info that you are coming from Oracle DB, you might wanna know that MySQL does not have a strict concept of objects. And, as answered here, unfortunately, you cannot create a custom data type on your own.
The way to work around it is to imagine a table as a class. Thus, your objects will become records of the said table.
You have to settle for one of the following approaches:
*
*Concatenated IDs: Store the concatenated IDs you want to operate on in a string equivalent datatype- like VARCHAR(5000) or TEXT. This way you can either split and loop over the string or compose a prepared statement dynamically and execute it.
*Use a temporary table: Fetch the child table objects, on the fly, into the temporary table and process them. This way, once you create the temporary table with the fields & constraints that you like, you can use
SELECT ... INTO TEMPORARY_TABLE_NAME to populate the table accordingly. The SELECT statement should fetch the properties you need.
Depending on the size of the data, you might want to choose the temp table approach for larger data sets.
A: You can use Text data type for store large amount of data in single variable
you can define in sp as:
In Variable_name TEXT
| |
doc_23529507
|
Let's say there are 2 fields in the data source: productName and ProductID
In the following code:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<%#Eval("productName")%> <br/>
<asp:HyperLink ID="lnkDetails" runat="server" NavigateUrl="~/Details.aspx?ID=">See Details</asp:HyperLink>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
What do I need to modify in
<asp:HyperLink ID="lnkDetails" runat="server" NavigateUrl="~/Details.aspx?ID=">See Details</asp:HyperLink>
to include value retreived from the ProductID in the link NavigateUrl="~/Details.aspx?ID="
A: NavigateUrl="~/Details.aspx?ID=<%# Eval("productID") %>" should work...
... but it doesn't!
The most elegant way should be:
<asp:HyperLink ID="lnkDetails" runat="server" NavigateUrl='<%# Eval("ProductID", "~/Details.aspx?ID={0}") %>'>See Details</asp:HyperLink>
| |
doc_23529508
|
I'm interested to know which Method is faster and when to use a method instead of other...
And how to evaluate if a code is good or bad?
My programming language is C#.
Hi all,
Thanks for your replies, they are very helpful.
I'm editing my question to be more specific specially that optimization is unlimited.
I want to know what is the best method in each condition.
For example using StringBuilder is better than string if i am appending lines to a string...
I only need this simple things.
A: Sure. Here's what we do:
*
*Begin the journey by deciding when the journey is over. Set meaningful, customer-focussed, realistic performance goals. (For both speed and resource consumption.)
*Carefully test your code frequently to see if you are meeting your performance targets.
*If you are meeting your performance targets, don't worry about performance. Things are fine. Worry about bugs, or robustness, or features.
*If you are not meeting your performance targets, run a profiler. Use it to identify what is the worst offending code. It only makes sense to fix the worst code; making something that is already incredibly fast and light slightly faster and lighter does not solve your performance problem.
*Rewrite the slow code so that it's more performant. (This is the hard bit.) Make sure you test it to make sure it really is better.
*If despite your best efforts you cannot make it good enough, either re-evaluate what your goals are, or cancel the project and spend your time on something that you can be successful at.
Keep iterating on that until you ship something.
A: Basically implement first, then test where to optimize.
If you are using Visual Studio Profissional you can use Analyze -> Launch Performance Wizard to analyze method performance. I am not sure about whether the other versions support this feature, however, there are also some commercial/free applications around ... look for profiler (see here for a list).
A: Type REALLY fast.
A: You should look at hidden features of c#, this post covers the most best practises in c# development
A: You can get a ton on advice of on this. But be aware of :
Premature optimization is root of all evil.
A: Aim first for correctness, next for clarity and only then performance.
As the old saying goes,
"No one cares how quickly you can calculate the wrong answer"
(on a practical level though, use a profiler)
A: If one method was always faster than another, they wouldn't bother including the slower one.
The only invariant when it comes to performance is that you need to profile. Everything follows from that.
A: If you get yourself a profiler, it will help you along, some will even give you great tips.
Example: ANTS Profiler
Usually you will find that reducing the number of times you create Strings to be the main performance boost you can get.
That and not messing with the Garbage Collector manually (unless you really really know what you're doing)
This link for Java design patterns is way too involved, don't get too put off by the word Java there, you can use what they teach for development in any language.
The thing is, if you want to know when to do what and what methods to use and so on, design patterns is what you are talking about.
I wish someone had pointed this to me earlier in my career.
A: Be aware of sub optimization.
Even though one specific function is faster than another replacing this isn't necessarily gonna make any difference in the runtime of your application. You need to understand which parts of your code that actually is a potential problem, and focus on optimizing these parts. Be aware of the O notation of your functions, and how often they are called. To identify parts that needs optimization a profiler can be of good help.
This question has some interesting points on why you shouldn't optimize until there is actually a need to do so.
A: In terms of general advice:
*
*Try to use the fewest loops necessary
*Move code out of loops where possible
*Avoid copying things (like strings) in loops
*Avoid creating objects in loops
*Cache where warranted (generally small objects that take a lot of time to make), but make sure your cache has a good disposal policy or it turns into a memory leak
A: You can compile your program in native mode to improve the runtime performance.
A: One of the ways of figuring this out yourself is having a console app where you try running discrete pieces of code against each other and timing them. Like here.
| |
doc_23529509
|
My process right now is copy the object > Paste as Image > Move to the correct location > Delete the "Worksheet Object". It's a very time consuming and tedious process. Is there a macro I can write or something that can convert all these objects automatically? I tried googling and no luck so far
A: This should get you started:
Sub ConvertAllShapesToPic()
Dim oSl As Slide
Dim oSh As Shape
For Each oSl In ActivePresentation.Slides
For Each oSh In oSl.Shapes
' modify the following depending on what you want to
' convert
Select Case oSh.Type
Case msoChart, msoEmbeddedOLEObject, msoLinkedOLEObject
ConvertShapeToPic oSh
Case msoPlaceholder
If oSh.PlaceholderFormat.ContainedType = msoEmbeddedOLEObject _
Or oSh.PlaceholderFormat.ContainedType = msoLinkedOLEObject _
Or oSh.PlaceholderFormat.ContainedType = msoChart _
Then
ConvertShapeToPic oSh
End If
Case Else
End Select
Next
Next
End Sub
Sub ConvertShapeToPic(ByRef oSh As Shape)
Dim oNewSh As Shape
Dim oSl As Slide
Set oSl = oSh.Parent
oSh.Copy
Set oNewSh = oSl.Shapes.PasteSpecial(ppPasteEnhancedMetafile)(1)
With oNewSh
.Left = oSh.Left
.Top = oSh.Top
Do
.ZOrder (msoSendBackward)
Loop Until .ZOrderPosition < oSh.ZOrderPosition
End With
oSh.Delete
End Sub
A: Other quick alternative if you do not want to write a macro is to cut the object (Ctrl + x) and then paste it (Ctrl + v) as img (we can use paste special to select the image format or when we do a paste (Ctrl + v) MS power point will prompt with options to paste then select image in it). This way we need not have to save the image to a location on drive and then insert it back in the slide. Cut and Paste will work while being on the same slide.
| |
doc_23529510
|
I need to count entries by hour and date and as the list is huge formula will save my life.
Bellow is the example how it looks.
Thank you in advance for your help!
17/05/2017 00:40
17/05/2017 01:10
17/05/2017 04:30
17/05/2017 05:00
17/05/2017 05:00
17/05/2017 05:05
17/05/2017 05:15
17/05/2017 05:20
17/05/2017 05:20
17/05/2017 05:30
17/05/2017 05:30
17/05/2017 05:30
17/05/2017 05:40
17/05/2017 05:45
17/05/2017 05:45
17/05/2017 05:50
17/05/2017 06:00
17/05/2017 06:00
17/05/2017 06:00
17/05/2017 06:20
17/05/2017 06:25
A: Edit: If the date and time is in one column, just use DATA --> Text to Columns, and use SPACE as the delimiter to put them in to two columns. There may be other ways to get your answer, keeping the info in one column, but that would likely be a relatively convoluted/complex formula. Text to Columns allows for quicker analysis.
If your data is in two columns, you can use COUNTIFS():
=COUNTIFS($B$1:$B$21,">="&E1,$B$1:$B$21,"<="&F1)
A: If your data is in one column, then add to the right column the following formula
=REPLACE(REPT(REPT("0",2-LEN(HOUR(A1)))&HOUR(A1),2),3,0,":00 - ")&":55"
and then use pivot table to count each group
enter image description here
A: To do it with your date and times in one column use:
=SUMPRODUCT((MOD($A$1:$A$21,1)>=C1)*(MOD($A$1:$A$21,1)<=D1))
| |
doc_23529511
|
//Create a set which orders the elements according to their size.
auto comp = [](const vector<int>& a, const vector<int>& b) -> bool
{
if (a.size() < b.size())
return true;
if (a.size() > b.size())
return false;
return a < b;
};
auto path = std::set <vector<int>, decltype(comp)> (comp);
//Create an instance of Dijkstra's algorithm and execute it.
Dijkstra<Graph, LengthMap> dijkstra_test(g,length);
dijkstra_test.run(s);
int size =0;
//Print the path the algorithm found.
for (Node v=t;v != s; v=dijkstra_test.predNode(v))
{
std::cout << g.id(v) << "<-";
++size;
}
cout << g.id(s) << endl;;
//Fill the path set with all edges between source s and sink t. These will be used as tasks for the slaves.
for (ListGraphBase::Arc v=dijkstra_test.predArc(t);s!=g.target(v); v=dijkstra_test.predArc(g.source(v)))
{
path.insert(vector<int>{g.id(v)});
}
which works for small dataSets but for bigger one it throws a segmentation fault. The printing of the path is still executed correctly.
[Laptop:03801] *** Process received signal ***
[Laptop:03801] Signal: Segmentation fault (11)
[Laptop:03801] Signal code: Address not mapped (1)
[Laptop:03801] Failing at address: 0x7f5665be2ff8
[Laptop:03801] [ 0] /usr/lib/libpthread.so.0(+0x10f00)[0x7f5687345f00]
[Laptop:03801] [ 1] ./main[0x4102da]
[Laptop:03801] [ 2] ./main[0x409e31]
[Laptop:03801] [ 3] ./main[0x40b0b8]
[Laptop:03801] [ 4] /usr/lib/libc.so.6(__libc_start_main+0xf1)[0x7f5686fb4741]
[Laptop:03801] [ 5] ./main[0x4094e9]
[Laptop:03801] *** End of error message ***
The whole program:
#include <limits>
#include <set>
#include <map>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include "GraphElements.h"
#include "Graph.h"
#include "DijkstraShortestPathAlg.h"
#include "YenTopKShortestPathsAlg.h"
#include <sys/time.h>
#include <mpi.h>
#include <stdlib.h>
#include <lemon/concepts/digraph.h>
#include <lemon/smart_graph.h>
#include <lemon/list_graph.h>
#include <lemon/lgf_reader.h>
#include <lemon/dijkstra.h>
#include <lemon/path.h>
#include <lemon/bin_heap.h>
using namespace lemon;
//mpic++ main.cpp -o main Graph.cpp YenTopKShortestPathsAlg.cpp DijkstraShortestPathAlg.cpp -lemon
//mpirun -np 4 ./main
void run(int *argc, char ***argv )
{
//Initiate the program run time counter.
//Here starts the MPI block.
MPI_Init(argc, argv);
//Init the k for the number of paths
int k = 5;
//Init the rank of the MPI process
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//Init the number of processes.
int nOSlaves;
MPI_Comm_size(MPI_COMM_WORLD, &nOSlaves);
//Define the Parameter types of the lemon libraries.
typedef lemon::ListGraph Graph;
typedef Graph::EdgeIt EdgeIt;
typedef Graph::Edge Edge;
typedef Graph::NodeIt NodeIt;
typedef Graph::Node Node;
typedef Graph::EdgeMap<int> LengthMap;
using lemon::INVALID;
//Initialize the test graph.
Graph g;
for(int i = 1; i<= 1070376; i++)
{
g.addNode();
}
LengthMap length(g);
string line;
ifstream file ("output.gr");
if (file.is_open())
{
string word;
while (getline (file,line) )
{
std::string::size_type sz;
file >> word;
int node1 = stoi(word, &sz);
file >> word;
int node2 = stoi(word, &sz);
file >> word;
int distance = stoi(word, &sz);
Edge edge = g.addEdge(g.nodeFromId(node1),g.nodeFromId(node2));
length[edge] = distance;
}
file.close();
}
else cout << "Unable to open file";
Node s = g.nodeFromId(10);
Node t = g.nodeFromId(200);
cout << "done adding graph, starting execution" << endl;
//If the process is a coordinator.
if(rank==0)
{
//Contains the shortest paths.
multimap<int,vector<int>> shortestPaths;
//Contains the already tried examples **Debug purpose**
vector<vector<int>> removedPaths;
//Contains the job of the currently running slaves at their index.
vector<int> runningTasks[nOSlaves];
//Create a set which orders the elements according to their size.
auto comp = [](const vector<int>& a, const vector<int>& b) -> bool
{
if (a.size() < b.size())
return true;
if (a.size() > b.size())
return false;
return a < b;
};
auto path = std::set <vector<int>, decltype(comp)> (comp);
//Create an instance of Dijkstra's algorithm and execute it.
Dijkstra<Graph, LengthMap> dijkstra_test(g,length);
dijkstra_test.run(s);
//Fill the path set with all edges between source s and sink t. These will be used as tasks for the slaves.
for (ListGraphBase::Arc v=dijkstra_test.predArc(t);s!=g.target(v); v=dijkstra_test.predArc(g.source(v)))
{
path.insert(vector<int>{g.id(v)});
}
MPI_Finalize();
}
int main(int argc, char **argv)
{
run(&argc,&argv);
}
| |
doc_23529512
|
my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help']
And I want to club every three elements together, like:
new_list = ['hello this is', 'a sample list', 'thanks for help']
A: Just split into chunks and join:
[' '.join(my_list[i:i+3]) for i in range(0, len(my_list), 3)]
A: Option 1: This solution drop elements if my_list length is not divisible by 3
input string: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']
[" ".join(i) for i in zip(*[iter(my_list)]*3)]
result: ['hello this is', 'a sample list', 'thanks for help']
how python iter trick works: How does zip(*[iter(s)]*n) work in Python?
Option 2: keep extra element with zip_longest
input string: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']
[" ".join(i) for i in zip_longest(*[iter(my_list)]*3, fillvalue='')]
result: ['hello this is', 'a sample list', 'thanks for help', 'foo ']
A: You can solve this by iterating using a step, in this case 3 steps, and adding the individual strings under each step, i.e., my_list[i], my_list[i+1]. my_list[i+2 ]. Note that you need to add a space after each first and second string. This piece of code does that:
new_list = []
for i in range(0, len(my_list), 3):
if i + 2 < len(my_list):
new_list.append(my_list[i] + ' ' + my_list[i+1] + ' ' + my_list[i+2])
print(new_list)
The output is as expected:
['hello this is', 'a sample list', 'thanks for help']
A: A couple of solutions using itertools are possible.
Using groupby:
[' '.join(x[1] for x in g) for _, g in groupby(enumerate(my_list), lambda x: x[0] // 3)]
Using tee and zip_longest:
a, b = tee(my_list)
next(b)
b, c = tee(b)
next(c)
[' '.join(items) for items in zip_longest(a, b, c, fillvalue='')]
Using just zip_longest:
[' '.join(g) for g in zip_longest(*[iter(my_list)] * 3, fillvalue='')]
The last two are adapted from the pairwise and grouper recipes in the documentation. Only the first option won't add extra spaces at the end of your last group if the aren't a multiple of 3 words.
| |
doc_23529513
|
Is there a built in Angular mechanism to specify that my directive can only be applied to an <input /> tag? Or will I have to specifically check the element reference?
A: As already mentioned in the comments, you can archive this by using a restrictive selector in the metadata of the directive:
@Directive({
...
selector: 'input[fooDirective]',
exportAs: 'fooDir'
...
})
export class FooDirective {
}
| |
doc_23529514
|
and another log:
SimpleMessageListenerContainer : Broker not available; cannot force queue declarations during start: java.net.ConnectException: Connection refused (Connection refused)
Consumer raised exception, processing can restart if the connection factory supports it. Exception summary: org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused (Connection refused)
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no queue 'result.queue' in vhost '/', class-id=50, method-id=10)
RabbitMq version in the serve is 3.8.8 and the version of Erlang is 23.0.3.
Anyone can help me why my code on server throw an exception?
My java code with spring boot for declare queues is here:
@Configuration
public class RequestConfiguration extends RabbitMqConfiguration {
@Value("${spring.rabbitmq.queue}")
String queueName;
@Value("${spring.rabbitmq.exchange}")
String exchange;
@Value("${spring.rabbitmq.routingkey}")
String routingkey;
@Bean
Queue queue() {
return new Queue(queueName, true);
}
@Bean
DirectExchange exchange() {
return new DirectExchange(exchange);
}
@Bean
Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(routingkey);
}
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public AmqpTemplate rabbitTemplate() {
final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory());
rabbitTemplate.setMessageConverter(jsonMessageConverter());
return rabbitTemplate;
}
}
#And for consumer:
@Configuration
public class ResultConsumerConfiguration extends RabbitMqConfiguration {
@Value("${spring.rabbitmq.resultQueue}")
String resultQueueName;
@Value("${spring.rabbitmq.resultExchange}")
String exchange;
@Value("${spring.rabbitmq.resultRoutingkey}")
String routingkey;
@Bean
Queue queue() {
return new Queue(resultQueueName, true);
}
@Bean
DirectExchange exchange() {
return new DirectExchange(exchange);
}
@Bean
Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(routingkey);
}
@Bean
public MessageConverter jsonMessageConverter() {
final Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
converter.setClassMapper(classMapper());
return converter;
}
@Bean
public DefaultClassMapper classMapper() {
DefaultClassMapper typeMapper = new DefaultClassMapper();
typeMapper.setDefaultType(ResultMessageGeneral.class);
return typeMapper;
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
template.setRoutingKey(this.resultQueueName);
template.setMessageConverter(jsonMessageConverter());
return template;
}
@Bean
public SimpleMessageListenerContainer listenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory());
container.setQueueNames(this.resultQueueName);
container.setMessageListener(listenerAdapter());
return container;
}
@Bean
MessageListenerAdapter listenerAdapter() {
return new MessageListenerAdapter(rabbitMqListener, jsonMessageConverter());
}
}
| |
doc_23529515
|
Some clarification we have related to it:
*
*Is it possible to achieve multiple instance of an application
accessed by same user in different browser windows in same PC
without clashing the sessions?
*Will this solve by having multiple or partitions or security realms
*Weblogic Domain Partitions\ it available for ADF Applications
Application and Server Version Info
*
*Application Server - WebLogic Server Version: 12.2.1.0.0
*Application Framework – ADF, JDev 12.2.1
*Database – ORACLE 12C
A: We have overcome this issue my setting different listening IP address to each managed server, these IP address has to be configured as server network's alternate IP also
| |
doc_23529516
|
The idea is to document the data connections between some components. The resulting diagrams shall resemble the following. This is mostly for own internal doc. so it doesn't really need to generate fancy diagrams. Blocks with annotation, connections with annotation and maybe some notes is definitely sufficient.
http://www.automation.com/images/article/mathworks/MathWorks_Simulink_robot_arm_simulation_model.png
http://www.randservice.com/images/screen2.jpg
Thanks a lot in advance,
Paul
A: Check out: GraphViz -- It generates graphs out of a list of vertices and edge definitions
Also, check out IPE, a vector drawing program that can create exactly what you want, but it will be a manual process.
| |
doc_23529517
|
After research i found this command
>>>import os
>>>b=os.path.getsize('/somepath')
>>>b
but i am not sure if it gives result in samples.
Anyone can help?
A: os.path.getsize will get the size of files in bytes.
>>> import os
>>> b = os.path.getsize('C:\\Users\\Me\\Desktop\\negley.wav')
>>> b
31449644 #This is in bytes, in megabytes it would be 31.45 Megabytes (which is accurate)
Want to get the size in megabytes?
>>> b = int(os.path.getsize('C:\\Users\\Will\\Desktop\\negley.wav')) / 1024 / 1024
>>> b
29.992717742919922 #Close enough?
Or to get the length in seconds, you can use Achilles method of:
import wave
import contextlib
audiofile = 'C:\\Users\\Will\\Desktop\\negley.wav'
with contextlib.closing(wave.open(audiofile,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
length = frames / float(rate)
print(length)
A: If you are using scipy you can get the length in seconds using scipy.io
import scipy.io.wavfile as wav
file_path = "/path/to/yourfile.wav"
(source_rate, source_sig) = wav.read(file_path)
duration_seconds = len(source_sig) / float(source_rate)
If you are using pydub you can simply read the audio segment and get duration.
from pydub import AudioSegment
audio = AudioSegment.from_file(file_path)
print(audio.duration_seconds)
A: The length of an audio or wave file is determined by it's framerate.To get the length try this:
import wave
import contextlib
audiofile = '/pathto/your.wav'
with contextlib.closing(wave.open(audiofile,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
length = frames / float(rate)
print(length)
A: You can simply use the scipy library. Try this:
from scipy.io.wavfile import read
audiofile = '/path/to/file.wav'
sample_rate_in_s, data = read(audiofile)
print(len(data))
| |
doc_23529518
|
I have two UIView that I would like to swap between controlled by the UIViewController
In IB I have created 3 UIViews:
TopView
A_View
B_View
Then in ViewDidLoad I add [
[self addSubView] A_View];
Then in some IBAction method I do this
[A_View removeFromSuperview];
[self.view addSubview:B_View];
This is indeed swapping the two views, with TopView just sitting there. But my first thought was just to call [[self view] removeFromSuperView]]; and then add B_view.
This gives me an empty screen?
So is my solution the right way?
Thanks in advance
Regards
Christian
A: Looks fine to me. It's a pretty normal swapping style, just remove one and add the other.
You should always watch out with modifying the UIViewController's view itself. Your solution is fine.
A: That way is fine and perfectly straightforward.
If you're on iOS 4.0 or later, you can also use the transitionFromView:toView:duration:options:completion: method in UIView, which removes and adds for you, plus provides a transition animation.
The reason [[self view] removeFromSuperview] left you with a blank window is because you're removing your controller's base view object (including it's subviews, e.g. Top_View, etc) from it's superview (likely the window object). Your solution works when you remove A_View and add B_View, as both are being added or removed as subviews to your controller's view, i.e. self.view.
| |
doc_23529519
|
I have a method (defined using spring and hibernate), which is of the form:
private void updateUser() {
updateSomething();
updateSomethingElse();
}
This is called from two places, the website when a user logs in and a batch job which runs daily. For the web server context, it will run with a transaction created by the web server. For the batch job, it must have one transaction for each user, so that if something fails during this method, the transaction is rolled back. So we have two methods:
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void updateUserCreateNewTransaction() {
updateUser();
}
@Transactional(propagation=Propagation.REQUIRED)
public void updateUserWithExistingTransaction() {
updateUser();
}
updateUserCreateNewTransaction() is called from the batch job, and updateUserWithExistingTransaction() from the web server context.
This works. However, it is very important that this behaviour (of the batch) not be changed, so I wish to create a test that tests this behaviour. If possible, I would like to do this without changing the code.
So some of the options open to me are:
*
*Count the transactions opened in the
database during the run of the batch
job.
*Change the data in some sublte way so that at least one user update fails, in the updateSomethingElse() method, and check that the updateSomething() for that user has not taken place.
*Code review.
1 is a very database dependent method, and how do I guarantee that hibernate won't create a transaction anyway?. 2 seems better, but is very complex to set up. 3 is not really practical because we will need to do one for every release.
So, does anyone have a method which would enable me to test this code, preferably through a system test or integration test?
A: I would try to setup a test in a unit test harness using an in memory HSQLDB and EasyMock (or some other mocking framework).
You could then have the updateSomething() method really write to the HSQL database but use the mock framework to mock the updateSomethingElse() method and throw a RuntimeException from that method. When that is done you could perform a query against the HSQLDB to verify that the updateSomething() stuff was rolled back.
It will require some plumbing to setup the HSQLDB and transaction manager but when that is done you have a test without external dependencies that can be re-run whenever you like.
A: Another thing you can do is configure logging output for Hibernate's transactions:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-logging
If you make a log4j category for org.hibernate.transaction with trace log leve, it should tell everything that Hibernate does transaction-wise during a unit test.
| |
doc_23529520
|
HTML
<table>
<td>
<div class="header">Spring!</div>
<div class="footer">Spring!</div>
<div class="header">Spring!</div>
<div class="footer">Spring!</div>
<div class="header">Spring!</div>
<div class="footer">Spring!</div>
<div class="header">Spring!</div>
<div class="footer">Spring!</div>
<div class="header">Spring!</div>
<div class="footer">Spring!</div>
<div class="header">Spring!</div>
<div class="footer">Spring!</div>
</td>
</table>
CSS
.header {
background-color: #ffffff;
padding: 5px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
cursor: pointer;
}
.footer {
background-color: #cccccc;
padding: 5px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
cursor: pointer;
}
jQuery:
$(document).ready(function () {
$(".header").hover(function () {
$(".footer").slideToggle();
}
}
A: I think you just forgot some )
$(document).ready(function () {
$(".header").hover(function () {
$(".footer").slideToggle();
}) //forgot a ")" here
}) //forgot a ")" here
Fiddle
A: Your missing brackets and semi-colons.Try this:
$(document).ready(function(){
$(".header").hover(function(){
$(".footer").slideToggle();
}); //here you were missing ")" and ";"
}); //here you were missing ")" and ";"
Updated answer:
I suggested you to use .on() method instead of shorthand operator. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. You can also do like this:
$(document).ready(function(){
$(document).on('mouseenter','.header',function(){
$(".footer").slideToggle();
}).on('mouseleave','.header', function(){
$(".footer").slideToggle();
});
});
Demo: http://jsfiddle.net/MsC9k/1/
A: Only your script needs to be corrected:
<script type="text/javascript">
$(document).ready(function(){
$(".header").hover(function(){
$(".footer").slideToggle();
});
});
| |
doc_23529521
|
I tried the code below to sort, but the output was not exactly how I needed it, and I haven't found any other resources online to get it to sort how I need to.
people_list = [['jim', 33000], ['james', 22000], ['john', 33000], ['zack', 10000]]
sorted_by_int_then_name = sorted(people_list, key=lambda person: (person[1], person[0]), reverse=True)
The output for this code is:
>>> sorted_by_int_then_name
[['john', 33000], ['jim', 33000], ['james', 22000], ['zack', 10000]]
This is sorted correctly numerically, but the names are not sorted alphabetically like I need them to be. I think the issue I'm having might be because I'm using the reverse=True parameter, but if I don't include that parameter then the list is sorted from lowest numerical value to highest. The output I am looking for would be this:
>>> sorted_by_int_then_name
[['jim', 33000], ['john', 33000], ['james', 22000], ['zack', 10000]]
How can I properly sort by numerical value for people_list[i][1] and then by people_list[i][0] whenever the numerical value is tied?
I am running this code using python version 3.8.10 on Ubuntu 20.04.3 LTS
A: One approach is to multiply the integer by -1 instead of using reverse=True:
people_array = [['jim', 33000], ['james', 22000], ['john', 33000], ['zack', 10000]]
sorted_by_int_then_name = sorted(people_array, key=lambda person: (-1 * person[1], person[0]))
print(sorted_by_int_then_name)
Output
[['jim', 33000], ['john', 33000], ['james', 22000], ['zack', 10000]]
As an alternative, and taking advantage of the fact that sorted is stable, use a two-pass sort:
from operator import itemgetter
people_array = [['jim', 33000], ['james', 22000], ['john', 33000], ['zack', 10000]]
sorted_by_int_then_name = sorted(people_array, key=itemgetter(0))
sorted_by_int_then_name.sort(key=itemgetter(1), reverse=True)
print(sorted_by_int_then_name)
Output
[['jim', 33000], ['john', 33000], ['james', 22000], ['zack', 10000]]
The two-pass sort can be faster, see this.
| |
doc_23529522
|
My models:
class BaseObject(models.Model):
name = models.TextField()
object_type = models.ForeignKey(ObjectType)
class ObjectStatus(models.Model):
baseobject_id = models.ForeignKey('objects.BaseObject', related_name='status')
object_status = models.IntegerField()
object_status_timestamp = models.DateTimeField()
My serializers:
class ObjectStatusSimplifiedSerializer(serializers.ModelSerializer): #helper serializer to simplify status objects
class Meta:
model = ObjectStatus
fields = ['object_status', 'object_status_timestamp']
class ObjectStatusListSerializer(serializers.ModelSerializer): #request for last status of several objects
status = ObjectStatusSimplifiedSerializer(many=True)
class Meta:
model = BaseObject
fields = ['id', 'name', 'object_type', 'status']
My current view:
class ObjectStatusListView(generics.ListCreateAPIView):
serializer_class = ObjectStatusListSerializer
def get_queryset(self):
queryset = BaseObject.objects.all()
id = self.request.query_params.getlist('id')
if id:
queryset = queryset.filter(id__in=id)
return queryset
Current URL:
url(r'^objectstatus/status/list$', views.ObjectStatusListView.as_view()),
So now, when going to, for example, [...]/objectstatus/status/list?id=9, the result I get looks like this:
[
{
"id": 9,
"name": "r5",
"object_type": "router",
"status": [
{
"object_status": 1,
"object_status_timestamp": "2019-10-24T09:40:15.605391Z"
},
{
"object_status": 2,
"object_status_timestamp": "2019-10-24T09:40:28.133296Z"
},
{
"object_status": 3,
"object_status_timestamp": "2019-10-24T09:40:40.829486Z"
},
{
"object_status": 1,
"object_status_timestamp": "2019-10-24T09:40:53.333332Z"
}
]
}
]
What I want is to display only the object status with the most recent timestamp.
Also, I can't figure out how to flatten the JSON object, like this:
[
{
"id": 9,
"name": "r5",
"object_type": "router",
"object_status": 1,
"object_status_timestamp": "2019-10-24T09:40:53.333332Z"
}
]
A: you can try change serializer to like this. I assum your ObjectType have field is name for line code object_type.name
class ObjectStatusSimplifiedSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField()
object_type = serializers.SerializerMethodField()
@staticmethod
def get_name(instance):
return instance.status.name
@staticmethod
def get_object_type(instance):
return instance.status.object_type.name
class Meta:
model = ObjectStatus
fields = ['id', 'name', 'object_type', 'object_status', 'object_status_timestamp']
class ObjectStatusListSerializer(serializers.ModelSerializer):
status = serializers.SerializerMethodField()
@staticmethod
def get_status(instance):
queryset = ObjectStatus.objects.filter(baseobject_id=instance).order_by('-object_status_timestamp')[:1]
if queryset.count():
return ObjectStatusSimplifiedSerializer(queryset, many=True).data
return []
class Meta:
model = BaseObject
fields = ['id', 'name', 'object_type', 'status']
A: With the following serializer, you should get the desired output. We filter the status list and get only the latest one and then we flatten the structure as you need.
class ObjectStatusListSerializer(serializers.ModelSerializer): #request for last status of several objects
status = serializers.SerializerMethodField(read_only=True)
class Meta:
model = BaseObject
fields = ['id', 'name', 'object_type', 'status']
def get_status(self, obj):
return ObjectStatusSimplifiedSerializer(instance=obj.status.order_by('object_status_timestamp').first()).data
def to_representation(self, obj):
"""Move fields from status to main object representation."""
representation = super().to_representation(obj)
status_representation = representation.pop('status')
for key in status_representation:
representation[key] = status_representation[key]
return representation
| |
doc_23529523
|
var bodyParser = require('body-parser');
var multiparty = require('multiparty');
var formidable = require('formidable');
var app = express();
...
app.use(bodyParser.raw({limit: 1024 * 1024 * 20}));
app.use(bodyParser.text({limit: 1024 * 1024 * 20}));
app.use(bodyParser.json({limit: 1024 * 1024 * 20}));
app.use(bodyParser.urlencoded({ limit: 1024 * 1024 * 20, extended: false }));
...
...
app.put('/fileupload', function(req, res, next){
console.log('FILE UPLOAD REQUEST');
var form = new formidable.IncomingForm();
//var form = new multiparty.Form();
form.parse(req, function(err, fields, files){
var file = files.file;
//var file = files.file[0]
/*... Logic to save file to disk...*/
...
console.log('Received new file');
});
});
This code is able to write files to disk with sizes smaller than 70-80kb. However when size is larger, the callback function of form.parse is not called(!) and there are no logs in the console. No error is thrown.
On my personal computer (OS X), I am able to write large files using PUT requests from the localhost. The problem occurs when the server is a remote computer running Ubuntu 14.04.
Prior to this problem, I had received the 'Request Entity Too Large' error in the Ubuntu server. After configuring nginx to 20Mb, the error stopped. The 20Mb limits on various bodyParsers are there just to show that I tried any configuration on that. Same goes for multiparty code that I commented out. Both Formidable and Multiparty won't parse those files.
What is happening here? How to parse files larger than ~80kb?
A: I have no idea why this happened, but I was able to transfer files of greater sizes using Busboy instead of Multiparty or Formidable
| |
doc_23529524
|
I can do that with Properties without a problem:
FactoryGirl.define do
factory :property do
...fields...
end
factory :property_with_assumption do
after(:create) do |property|
FactoryGirl.create(:assumption, assumable: property)
end
end
end
And I have a similar definition for Tenants:
FactoryGirl.define do
factory :tenant, :class => 'Tenant' do
...fields...
end
factory :tenant_with_assumption do
after(:create) do |tenant|
FactoryGirl.create(:assumption, assumable: tenant)
end
end
end
But when I try
FactoryGirl.create(:tenant_with_assumption, property: [valid property])
I get
NameError: uninitialized constant TenantWithAssumption
Why does it work for one model but not the other? Thanks in advance.
A: You need to provide the :class parameter:
factory :tenant_with_assumption, :class => 'Tenant' do
A: you can do it in a nested way as well.
FactoryGirl.define do
factory :tenant, :class => 'Tenant' do
...fields...
factory :tenant_with_assumption do
after(:create) do |tenant|
FactoryGirl.create(:assumption, assumable: tenant)
end
end
end
end
| |
doc_23529525
|
Something like command > output.txt --exclude_lines=*.OK is what I was looking for.
A: Assuming that the word OK is supposed to be at the end of the line, you could do it by
your_command | grep -vw 'OK$' >output.txt
The $ ensures that an OK inside the line is ignored, and the -w ensures that a line ending in i.e. NOK is not missed.
| |
doc_23529526
|
My data is as follows:
structure(list(`video number` = 1:40, category = c("neutral",
"neutral", "neutral", "neutral", "neutral", "neutral", "neutral",
"neutral", "neutral", "neutral", "pleasant", "pleasant", "pleasant",
"pleasant", "pleasant", "pleasant", "pleasant", "pleasant", "pleasant",
"pleasant", "unpleasant", "unpleasant", "unpleasant", "unpleasant",
"unpleasant", "unpleasant", "unpleasant", "unpleasant", "unpleasant",
"unpleasant", "painful", "painful", "painful", "painful", "painful",
"painful", "painful", "painful", "painful", "painful"), frequency = c(55,
56, 90, 104, 47, 38, 48, 52, 43, 38, 162, 139, 137, 131, 143,
177, 151, 117, 164, 82, 116, 75, 105, 67, 75, 61, 133, 109, 123,
150, 196, 191, 182, 141, 151, 148, 181, 77, 134, 128), intensity = c(2.8,
2.7, 3.2, 3.2, 3.5, 2.6, 3.2, 2.9, 3.4, 2.8, 3.6, 3.6, 3.7, 3.5,
3.7, 3.9, 3.6, 3.6, 3.6, 3.4, 3.8, 3.2, 3.7, 3.7, 3.3, 3.6, 4.4,
3.7, 3.8, 4.2, 5, 4.8, 4.4, 4, 4.1, 3.9, 4.8, 3.7, 4, 4), threat = c("1.4",
"1.5", "1.6", "1.5", "1.9", "1.4", "1.8", "1.8", "1.3", "1.5",
"1.3", "1.2", "1.3", "1.2", "1.2", "1.5", "1.5", "1.4", "1.5",
"1.2", "5.6", "3.2", "5.2", "2.9", "4.0", "3.4", "5.6", "3.5",
"5.5", "6.6", "8.0", "7.8", "7.1", "4.5", "6.3", "6.7", "6.2",
"5.0", "6.5", "5.4"), arousal = c("1.7", "1.9", "2.2", "2.1",
"1.8", "2.0", "2.0", "2.3", "2.2", "2.0", "5.3", "4.8", "4.5",
"3.9", "4.0", "4.5", "4.6", "3.3", "4.2", "3.2", "4.7", "3.2",
"4.2", "3.0", "3.4", "3.1", "5.2", "3.8", "4.4", "5.3", "6.6",
"6.2", "6.0", "4.9", "5.2", "6.5", "4.8", "4.0", "5.1", "4.6"
)), row.names = c(NA, -40L), class = "data.frame")
intensity_plot<- ggplot(freq_intensity, aes(x= reorder (category, -intensity), y=intensity))+
stat_summary(fun.y="mean", geom="bar") +
stat_summary(fun.data = mean_cl_normal, fun.args = list(mult=1), geom = "errorbar", width=0.3, size=0.7) +
geom_jitter(colour="limegreen",shape=16,size=1, position=position_jitter(0.2))+
#facet_wrap(~groups_all)+
ggtitle("") +
xlab("") + ylab("Mean intensity") +
theme_bw(base_size = 10) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_blank(),
axis.line = element_line())
print(intensity_plot)
A: Add fill = category and then use scale_fill_manual.
library(ggplot2)
ggplot(freq_intensity, aes(x = reorder(category, -intensity),
y=intensity, fill = category))+
stat_summary(fun.y="mean", geom="bar") +
stat_summary(fun.data = mean_cl_normal, fun.args = list(mult=1),
geom = "errorbar", width=0.3, size=0.7) +
geom_jitter(colour="limegreen",shape=16,size=1, position=position_jitter(0.2))+
ggtitle("") +
xlab("") + ylab("Mean intensity") +
theme_bw(base_size = 10) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.border = element_blank(),
axis.line = element_line()) +
scale_fill_manual(values=c("#dda832", "#165e70", "#d5927c", "#4f9694"))
| |
doc_23529527
|
Route::get('/{source}/{path:.*}', 'HomeController@index');
By this the /database/path/to/folder URL will be parsed as the $source = 'database'; and the $path = 'path/to/folder'; It's great!
But what when I would have optional query parameters too, for example: /database/path/to/folder?attr1=foo&attr2=bar
How can I define to get the whole query part in a property as a route parameter?
A: Since they are optional and it is a query string, you do not have to define them in your route registration.
You can simply pass them when you generate the url. For instance:
Route::get('/{source}/{path:.*}', [
'as' => 'home',
'uses' => 'HomeController@index'
]);
Then you could do:
route('home', [
'source' => 'database',
'path' => 'path/to/folder',
'attr1' => 'foo',
'attr2' => 'bar'
]);
And the output would be:
http://example.com/database/path/to/folder?attr1=foo&attr2=bar
Update
Since you want to put all into a route parameter, you could achieve the same like this:
Route::get('{source}/{path:[a-z0-9/]+}[/{query:[a-z0-9=&]+}]', [
'as' => 'home',
'uses' => 'HomeController@index'
]);
Then you would generate the route like this:
route('home', [
'source' => 'database',
'path' => 'path/to/folder',
'query' => 'attr1=foo&attr2=bar'
]);
And the output would be:
http://example.com/database/path/to/folder/attr1=foo&attr2=bar`
| |
doc_23529528
|
A: I suppose you could add the view as a subview of UIWindow, and not your respective view controller. Alternatively, why not subclass UITabBar?
| |
doc_23529529
| ||
doc_23529530
|
#include "Hello1.h"
#include "Hello2.h"
int main(int argc, char ** argv)
{
// Hello1 and Hello2 are derevied classes of Hello
// And there constructor throws an exception
Hello * h;
try
{
if (argv[1][0]=='1')
h = new Hello1;
else
h = new Hello2;
}
catch (std::exception ex) { /*print error*/ }
delete h;
}
If Hello1 and Hello2 throws an exception, It segfault. However If I add
Hello h = NULL;
It works!!!
Hello is a class with a constructor that throw's an exception
All I can think of is that the exceptions in constructor's remove the object from memory! Why where who...Explain! Please.
A:
However If I add Hello h = NULL; it works!!! Why where who...Explain! Please.
That is because operator delete does nothing when the pointer is null. It is expected to do nothing, that's standard behavior. Paragraph 3.7.4.2 of the C++11 Standard specifies:
[...] The value of the
first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation
function is one supplied in the standard library, the call has no effect. [...]
If it is not null, on the other hand, operator delete will try to delete the object pointed to by hello, and since the pointer is uninitialized (because construction threw and control was transferred to the exception handler before the assignment to hello happened), you get undefined behavior.
Per paragraph 5.3.5/2:
[...] In the first alternative (delete object), the value of the operand of delete may be a null pointer
value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8)
representing a base class of such an object (Clause 10). If not, the behavior is undefined. [...]
A:
Why where who...Explain! Please.
If Hello's constructor throws h is never initialised - delete tries to read from that uninitialised variable and behaviour in undefined.
I recommend using a smart pointer.
A: delete can throw exception if you try to delete something you should not delete. As others have pointed out, delete will not throw if you try to delete something set to null
new will, as far as I know, never throw unless you are out of memory.
So what happens is that argv[1] is not '1' and which means h is pointing to something unknown and this makes delete throw an exception
| |
doc_23529531
|
*
*All messages in a single conversation are rendered in a single WebView (specifically a com.google.android.gm.CustomWebView, seen on the left). Only the body of the messages is rendered - the spaces where the headers would go are left blank.
*On top of the WebView is overlaid a com.google.android.gm.MessageHeaderScrollView (seen on the right) which uses a HybridConversationScrollContainer to position a MessageHeaderView in the correct position for each message in the conversation view.
<->
So, how (and why) is this achieved? Is it something that an Android developer could & should aspire to re-create in their own apps?
Obviously the probable why is performance - WebView uses the fast native WebKit rendering of the message text, and a single WebView is probably more efficient than a separate WebView for each message. If anyone has seen any good blogposts on the performance benefits of this I'd be interested.
Yet there's an obvious complexity cost to this approach (against naively using an ExpandableListView with some TextViews inside it or whatever) - the HybridConversationScrollContainer has to somehow work out where the message headers should go over the web-rendering, in order to position it's MessageHeaderViews correctly. What I'd like to know is: How does it work out those offsets?
A: Incidentally, the only approach I can think of is javascript-based - use javascript in the WebView to gather the header coordinates, and then use WebView.addJavascriptInterface() to pass those coordinates on to Java and the HybridConversationScrollContainer. I haven't tried doing this myself though so I'm not sure if it could actually work.
There is a short post on the android Developer blog talking about the addJavascriptInterface() method:
http://android-developers.blogspot.com/2008/09/using-webviews.html
It would be wonderful if MessageHeaderScrollView could be released as an open-source library - I'd use it! - but seeing as the Gmail app is closed, it doesn't seem immediately likely.
| |
doc_23529532
|
When same HTTP-request executes from Front on React-Redux, the TTFB (time to first byte) gains to 3000-7000ms.
SQL query logging shows times up to 50ms per query (~10 queries), but Enter point's (public/index.php) execute time is only 1-3ms.
Where should i look for a problem??
A: Use Barryvdh's debug bar.
It will provide full profiling information for your app and let you know where the slow-down is.
| |
doc_23529533
|
The problem is that the ">" symbol prematurely closes the HTML tag.
ex.
this: <div ng-if="foo>0" class="bar"> (HTML STUFF) </div>
is read as: <div ng-if="foo"> (0 class="bar"> HTML STUFF) </div>
I ended up getting around this by using ng-if="foo!=0" but I could probably use the less than comparator instead but I was just curious in case I absolutely HAD to use the greater than symbol for some reason. Or would I perhaps have to move this logic somewhere else like in my controller instead of in my view?
EDIT 1
So it definitely seems like the comparator itself isn't the problem and something else is going on in my code. Oddly, when I have spaces before and after the comparator it works but without spaces it doesn't. I'm also using angular 1.3.15 if that means anything.
<div class="paginate" ng-if="list.total > 0"> works
<div class="paginate" ng-if="list.total>0"> does not work
A: I recommend creating a method on the scope and abstracting the logic of the condition. The business rules may expand and change. With a separate method you don't need to alter the template.
// in controller
$scope.isValidFoo = function () {
return $scope.foo > 0;
}
// in template
<div ng-if="isValidFoo()">...</div>
A: This is an example of using the > symbol. This works fine.
<div ng-if="myvariable.length > 2">
</div>
| |
doc_23529534
|
I'm using MaterializeCSS
where the "main" content of the page it's width decreases when the sidebar is open and it becomes the fullpage width when the sidebar is closed.
I'm trying to do this with the ui-router.
This is my current setup:
<header>
<div ui-view="header"></div>
</header>
<main ui-view="container"></main>
<footer>
<div ui-view="footer"></div>
</footer>
and each element has it's corresponding controller.
I was thinking of creating a new controller for the sidebar.
But I can't seem to make this work like I want:
this is what I tried:
<main>
<div class="navigation" ng-hide="shownav"><span class="flow-text">This div is 7-columns wide on pushed to the right by 5-columns.</span></div>
<div class="content" ui-view="container"></div>
</main>
css:
main {
width: 100%
}
.navigation {
width: 20%;
float: left;
}
.content {
min-width: 80%;
float: left;
}
A: Work with float:right and float:left, then position the footer using position: absolute with the parameters like bottom:0 and left:0to position on the bottom and left of the page, setting a width that I want.
Then mark the divs with background-colors and text to see exactly whats happening when I'm coding.
All your content wrapped inside the <main>, because it's where it's gonna the left bar and the content.
I'm sorry if I couldn't explain better
main {
width: 100%;
position: relative;
height: 100%;
}
.navigation {
width: 20%;
float: left;
background: black;
color: white;
height: 100px;
}
.content {
width: 80%;
float: right;
background: red;
color: white;
height: 100px;
}
footer {
position: absolute;
background-color: green;
color: white;
bottom: 0;
left: 0;
width: 100%;
height: 50px;
}
<header>
<div ui-view="header"></div>
</header>
<main ui-view="container">
<main>
<div class="navigation" ng-hide="shownav"><span class="flow-text">This div is 7-columns wide on pushed to the right by 5-columns.</span>
</div>
<div class="content" ui-view="container">aaaaaa</div>
</main>
</main>
<footer>
<div ui-view="footer"></div>
</footer>
| |
doc_23529535
|
As part of my debugging, I wanted to see what was produced which is the reason for the text file. However, it is empty. I have no idea why.
Any ideas?
post_pages = ['https://coffeeforums.co.uk/topic/4843-a-little-thank-you/', 'https://coffeeforums.co.uk/topic/58690-for-sale-area-rules-changes-important/']
for topic_url in post_pages:
post_page = urlopen(topic_url)
post_soup = BeautifulSoup(post_page, 'lxml')
messy_posts = post_soup.find_all('div', class_='ipsColumn ipsColumn_fluid')
with open('messy_posts.txt', 'w') as f:
f.write(str(messy_posts))
edit: you can swap in this variable to see how it should work. These websites are built on the same platform so the scrape should be the same (I would think):
post_pages = ['https://forum.cardealermagazine.co.uk/topic/8603-customer-comms-and-the-virus/', 'https://forum.cardealermagazine.co.uk/topic/10096-volvo-issue-heads-up/']
A: The class_ takes a list for multiple classes and not a string for an OR operation. You could change it from
class_='ipsColumn ipsColumn_fluid'
it to this and it should work.
class_=['ipsColumn', 'ipsColumn_fluid']
and it should work.
Alternatively, if you are going for an AND(where you want a div with both classes). I advise you to use select as such:
post_soup.select('div.ipsColumn.ipsColumn_fluid')
This would return the div that includes both classes
| |
doc_23529536
|
Recently, I built 4.8.2 libraries from source under C:\qt-source like this:
configure -platform win32-g++ -no-phonon -no-phonon-backend -no-webkit \
-fast -debug -opensource -shared -no-qt3support -no-sql-sqlite \
-no-openvg -no-gif -no-libpng -no-libmng -no-libtiff -no-libjpeg \
-no-script -no-scripttools -nomake examples -nomake demos -no-xmlpatterns
mingw32-make
To link against the new libraries, I added Manual Qt 4.8.2 C:\qt-source\4.8.2\bin\qmake.exe under Tools > Options > Build & Run > Qt Versions. However, Qt Creator still seems to pick up .dll libs from C:\QtSDK
| |
doc_23529537
|
A: Follow these steps :
1) Click on plus and and duplicate release configuration
2) Edit scheme so that archive is done using distribution
3) Click you distribution profile as code signing identity
4) Then next to Run .in Xcode..make sure you have your device selected..not the simulator..then Go to Product and click archive..The Rest step will be easy since Xcode will help you in the,.
| |
doc_23529538
|
So the format I want is:
00:00:00.000 --> 00:00:01.000
and what it's changed it to is:
00: 00: 00,000 -> 00: 00: 01,000
What I have so far is:
ActiveCell.Select
Dim String1 As String
String1 = ActiveCell.Characters
Replace(String1, " ", "") = String1
Replace(String1, "->", " --> ") = String1
Replace(String1, ",", ".") = String1
ActiveCell.Offset(3, 0).Select
I'm then going to loop through the whole document - so selecting the cell 3 down from the edited one and performing the same operations.
What am I doing wrong that's not working? Thank you.
A: Something like this:
Dim String1 As String, c as range
Set c = ActiveCell
Do While Len(c.Value) > 0
String1 = Replace(c.Value, ": ", ":")
String1 = Replace(String1, " -> ", " --> ")
String1 = Replace(String1, ",", ".")
c.value = String1
Set c = c.Offset(3, 0)
Loop
| |
doc_23529539
|
In my case, The alert pops up even if one of the radio button is checked. I am guessing I am missing on something very minute but couldn't figure out.
Below is the code:
<input type="checkbox" name="my_cr" id="CR"/>CR
<input type="radio" id="IA" name="Initial" />IA
<input type="radio" id="FA" name="Final" />FA
<input type="submit" />
<script>
else if(this.CR.checked)
{
if((!this.IA.checked) || (!this.FA.checked))
{
alert("Choose the approver type");
return false;
}
}
</script>
PS: "Else if" because, I am doing a couple of other validations too.
Thanks for the help.
A: Your or (||) should be an and (&&).
Right now, if either is unchecked, the alert pops up.
A: You should consider making that boolean more readable by doing the following:
var bothUnchecked = ( !this.IA.checked && !this.FA.checked )
if( bothUnchecked ) {
...
}
| |
doc_23529540
|
public event EventHandler MyEvent;
private void TriggerEvent()
{
this.MyEvent?.Invoke(this, EventArgs.Empty);
}
Now, with NRTs enabled, should the event type be declared as EventHandler or EventHandler?:
public event EventHandler MyEvent;
// or
public event EventHandler? MyEvent;
private void TriggerEvent()
{
this.MyEvent?.Invoke(this, EventArgs.Empty);
}
I'd say EventHandler? but all the C# documentation I could find (still) says EventHandler (without ?).
Update: Editing this question because someone (?) flagged this as duplicate of this question - which is clearly not a duplicate. I know what ? means. That's not the question here.
A: You are correct; it should indeed be EventHandler? since unsubscribed events (the default) are backed by a null delegate instance (at least when using field-like-events, as per here). The documentation simply doesn't always accommodate nullable reference type signatures.
| |
doc_23529541
|
<?php
$email_to = "sales@topmarble.co.uk";
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];
$text = "NAME : $name<br>
EMAIL : $email<br>
SUBJECT : $subject<br>
MESSAGE : $message";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=utf-8" . "\r\n";
$headers .= "From: <$email>" . "\r\n";
mail($email_to, "TopMarble Contact Form", $text, $headers);
?>
Server log: W3SVC574 P3NWVPWEB029 50.62.160.37 POST /Contact/sendCONTACT.php - 80 - 81.149.69.10 (Windows+NT+6.3;+WOW64)+(KHTML,+like+Gecko)+Chrome/47.0.2526.111 utmt=1;+_gat=1;+_ga=GA1.3.1022338839.1454154856;+sc_is_visitor_unique=rx10308068.1454164056.5FE680C8F5B04F09E54B2D70E903ED0B.2.2.1.1.1.1.1.1.1;+__utma=119944973.1022338839.1454154856.1454154856.1454163827.2;+__utmb=119944973.6.10.1454163827;+utmc=119944973;+__utmz=119944973.1454154856.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) topmarble.co.uk/Contact/index.html www.topmarble.co.uk 500 0 0 1637 961 1171
| |
doc_23529542
|
A: I think everything you say is right. If you only have a single large store, you need sufficiently many small nodes around it in order to fill the large one.
Our disk balancing tries to keep equal amounts of data on each store until a store is almost full, at which point it will prefer less full ones.
| |
doc_23529543
|
I want to keep the constructor private because I will later be doing a lot of checks before adding an object, modifying previous objects when all submitted variables are not unique rather than creating new objects.
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <list>
#include <map>
using namespace std;
using namespace tr1;
class Referral
{
public:
string url;
map<string, int> keywords;
static bool submit(string url, string keyword, int occurrences)
{
//if(Referrals.all.size == 0){
// Referral(url, keyword, occurrences);
//}
}
private:
list<string> urls;
Referral(string url, string keyword, int occurrences)
{
url = url;
keywords[keyword] = occurrences;
Referrals.all.push_back(this);
}
};
struct All
{
list<Referral> all;
}Referrals;
int main()
{
Referral.submit("url", "keyword", 1);
}
A: What's wrong with having a private constructor and a static factory method?
class Example {
Example() { ... }
public:
static Example CreateExample() {
return Example();
}
};
A: Based on your main code I think what you're shooting for is a singleton, which would look something like:
class Referral
{
private:
Referral()
{
//...
}
public:
static Referral& instance()
{
static Referral instance_s;
return instance_s;
}
bool submit(string url, string keyword, int occurrences)
{
//...
}
};
Then your call in main would look like:
int main()
{
Referral::instance().submit("url", "keyword", 1);
}
Another possibility is that you're looking to keep a list of Referrals around, in which case you can use a struct and a list of them to accomplish what you're looking for:
struct Referral
{
Referral(string url, string keyword, int occurrences) :
url_m(url), keyword_m(keyword), occurrences_m(occurrences)
{ }
string url_m;
string keyword_m;
int occurrences_m;
};
typedef std::vector<Referral> ReferralSet;
Then your call in main would look like:
int main()
{
ReferralSet set;
set.push_back(Referral("url", "keyword", 1));
}
A: First, you need to make Submit a static function. Then you can just say
Referral::Submit( url, keyword, occurrences );
without creating a Referral instance.
Then, in your Submit function, you're only creating a temporary Referral object that disappears almost immediately. Probably what you want to do is create an instance dynamically with new. Depending on how you want to manage this, you may want to move the code pushing onto the list into Submit.
Lastly, I would make your list of Referral instances a static member variable rather than how you have it now.
(Also, passing those string arguments by reference would probably be a good idea.)
A: While the whole code has some smell around, you can make it work just by making slight changes that are unrelated to your question.
To make it compile, I have removed the regex include (I am not using a compiler with C++0x support) and the 'using namespace tr1'. Move the constructor implementation after the definition of the Referral global object. Change the . for a :: in the main function when you refer to a static method.
// changes...
//#include <regex>
...
//using namespace tr1;
...
class Referral {
...
Referral(string url, string keyword, int occurrences); // added ; moved the implementation bellow the Referrals variable definition
...
struct All {
...
} Referrals;
// added constructor implementation here (Referrals global must be defined before use):
Referral::Referral(string url, string keyword, int occurrences)
{
url = url;
keywords[keyword] = occurrences;
Referrals.all.push_back(*this); // added dereference, this is of type Referral*, not Referral
}
int main()
{
Referral::submit("url","keyword",1);
}
Now, from a design point of view the code has a stench to it. If really want to have a global list where you add your Referral objects, consider making it a private static attribute of the Referral class so that you can have a little more control over it (only methods in the Referral class could break the contents). Make all your attributes private and provide only accessors to the functionality that user code will need (read-only access can suffice in most cases). Use initialization lists in your constructors, and initialize all members there in the same order they appear in the class definition.
With all that fixed, it still has some smell to it. The static function creates an instance of the class but the constructor is the one that includes itself in the map (??) It would make a little more sense if the constructor did not interact with the map, and the submit() method would create the object and then include it in the list...
I think you might benefit from expressing what you intend to do, many people here will help you both with design choices and reasons for them.
| |
doc_23529544
|
error
No value given for one or more required parameters.
Code
public int GetDrID_MonthWise(string DrName,int month,int year, int refDrID)
{
int data = 0;
try
{
string sql = "Select d.DoctorID From Doctor_Master d,Patient_registration p where d.LastName + ' ' + d.FirstName = '" + DrName + "' AND datepart(mm,p.[RegDate])=@month AND datepart(yyyy,p.[RegDate])=@year AND p.DoctorID=" + refDrID;
cmd = new OleDbCommand(sql, acccon);
cmd.Parameters.AddWithValue("@month", month);
cmd.Parameters.AddWithValue("@year", year);
rs = cmd.ExecuteReader();
while (rs.Read())
{
data = Convert.ToInt32(rs[0]);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
return data;
}
I am passing month and year values like this ,Where I am doing mistake ?
int month = dateTimePickerMonth.Value.Month;
int year = dateTimePickerMonth.Value.Year;
A: There is mistake in your query, please do like this,
string sql = "Select d.DoctorID From Doctor_Master d,Patient_registration p where d.LastName + ' ' + d.FirstName = '" + DrName + "' AND datepart("m",p.[RegDate])=@month AND datepart("yyyy",p.[RegDate])=@year AND p.DoctorID=" + refDrID;
Note: You have to enclosed date interval with "" in DatePart function in ms access and only single m for month. If you didn't enclosed yyyy and m with "", system supposed that yyyy and m are parameter and expected value for these parameter.
If you execute your query in Ms-Aceess sql view then it will show this
message "Enter Paremeter Value".
A: There is a error in your Query,
see there is no equal to sign for lastname column
where d.LastName + ' ' + d.FirstName = '
A: I think you need to check 3 issues
*
*Check this int month = dateTimePickerMonth.Value.Month; int year = dateTimePickerMonth.Value.Year; values are not null or empty
*The date and time is a datetime datatype , so why you assign this value in integer ? So It's converted to different format .
*And your d.LastName column value is null , If you give the empty values ,then try
this way
d.LastName = '"+ string.Empty + " ',.. .....
Do check these conditions and try again .
A: Or Simply Make Correction in string
sql = "Select d.DoctorID From Doctor_Master d,Patient_registration p where d.LastName + ' ' + d.FirstName = '" + DrName + "' AND Format(p.[RegDate],mm)=@month AND Format(p.[RegDate],'yyyy')=@year AND p.DoctorID=" + refDrID;
| |
doc_23529545
|
A: DTM do not support ecommerce tracking nativly as other Tag Management System do (TealiumIQ for example).
To include ecommerce or advanced ecommerce library you have to setup the require in the GA tool pageCode. Something like:
ga('dtm_ga_standard.require', 'ec');
To use it you have to create custom third party tag in the correct pageLoad rule in order to setup advanced ecommerce tracking, something like:
ga('dtm_ga_standard.ec:setAction', 'purchase', {
id: s_orderid,
affiliation: s_orderid,
revenue: order_total,
tax: '0',
shipping: pageViewData.shipment_cost,
coupon: ''
});
ga('dtm_ga_standard.send', 'pageview');
Be sure to prevent in the tool custom page code the standard page view using the commend:
return false
When the ecommerce page load rule is running.
Claudio.
| |
doc_23529546
|
<a id="myBtn" class="ui-link">
<span class="number"> </span>
<span class="button "> </span>
</a>
I want dynamically to insert some content into <span class="number">
var content = 99;
$('number').html(content);
but nothing change.
So what I need to do insert value into span that resulted node looks like this
<span class="number">99</span>
A: You are not using . to get class selector. Use $('.number') instead of $('number')
$('.number').html(content);
OR
$('.number').text(content);
A: insert text using class
var content = 99;
$('.number').html(content);
A: Try this:
$('.number').html(content);
You are referring to a wrong element. You can also do this:
$('.number').text(content);
| |
doc_23529547
|
No route matches {:action=>"confirm", :controller=>"locations"}
This is what I have in the view.
<%= form_for(@location, :url => { :action => :confirm }) do |f| %>
<% end %>
And I think my routes file is set up correctly.
Finder::Application.routes.draw do
resources :locations do
member do
post :confirm
end
end
root :to => 'locations/index'
end
Any ideas?
Updated:
Ran rake routes and get what I think is correct.
confirm_location POST /locations/:id/confirm(.:format) {:action=>"confirm", :controller=>"locations"}
A: You can debug your routes easily in the future by running $ rake routes and looking at the output. ;)
I think what is happening is that your post :confirm isn't registering the route you're expecting. In the guides, match and it's brethren accept a string as a URL segment like so:
resources :locations do
member do
post 'confirm'
end
end
Note that "confirm" is now a string instead of a symbol.
If this doesn't help, run $ rake routes and tack the output onto your question.
Update
After seeing your rake output, I think that you just need to specify the POST method on your form_for:
<%= form_for(@location, :url => { :action => :confirm }, :method => :post) do |f| %>
<% end %>
You can also make this more readable using that helper method that Rails defines:
<%= form_for(@location, :url => confirm_location_path(@location), :method => :post) do |f| %>
<% end %>
A: Did you define the confirm action in your LocationsController?
A: Try adding a :method => :post to your form_for
<%= form_for(@location, :url => { :action => :confirm }, :method => :post) do |f| %>
<% end %>
A: Make sure that form_for doesn't sneak in a hidden field with _method=put if you have declared the route as accepting only post in your routes file.
| |
doc_23529548
|
def checkbox_status(self):
checked=self.driver.find_element_by_xpath('//span[contains(text(), "Dell")]/parent::span').is_selected()
return checked
HTML
<div class="a-checkbox a-checkbox-fancy s-navigation-checkbox">
<label>
<input type="checkbox" name="" value="" checked="">
<i class="a-icon a-icon-checkbox"></i>
<span class="a-label a-checkbox-label">
<span class="a-size-base a-color-base a-text-bold">Dell</span>
</span>
</label>
</div>
A: We can try with get attribute. That works fine for me:
def status():
element =driver.find_element_by_xpath('//span[contains(text(), "Dell")]/ancestor::label/input')
if element.get_attribute('checked') :
return True
else:
return False
A: You can use is_selected method that returns a boolean
To verify or get selection status, we can use two mechanisms
1.driver.find_element_by_id("privacypolicy").is_selected();
This will return ‘true’ if the checkbox is selected, false if it is not selected.
2.driver.find_element_by_id("privacypolicy").get_attribute("checked");
This will return ‘true’ if the checkbox is selected. But will return NoneType if checkbox is not selected.
for more information click on this link.
A: The problem is that your XPath is pointing to a SPAN instead of an INPUT. The INPUT is the checkbox here. If you switch your XPath to point to the INPUT, it should work just fine.
def checkbox_status(self):
return self.driver.find_element_by_xpath('//input/following::span[.='Dell'][1]').is_selected()
XPath explanation
//input/following::span[.='Dell'][1]
^ find an INPUT
^ that is followed by a SPAN
^ that contains the text "Dell"
^ return only the nearest one
NOTE: I combined the two lines of code since there's no need here to assign the element to a variable and then return that variable. Just return the result of the find.
To answer DebanjanB's question from the comments about the [1] in the XPath I'm using. Here's a simple demo. I start with the HTML
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
If I use the XPath //ul/li, it returns all 3 LIs. If I add a [1] to the XPath to give //ul/li[1], now it returns only the closest LI. This is useful when looking up or down the DOM. In some instances it isn't necessary because you can just use .find_element() (singular) but I've found that in IE this doesn't always work as expected. I haven't fully tested and documented the differences but I think it's basically that in some browsers if the position isn't in the XPath, it will return a collection where the first element is the closest element but in IE it will return the same collection but the first element is at the TOP of the DOM rather than the closest. After figuring that out the hard way, I started just putting the [1] inside the XPath and it seems to work consistently (at least on the browsers that I maintain).
The [1] I'm using is a alias for position(). You can read more about it on MDN.
A: I have used is_displayed() instead of is_selected() to assert the status of the checkbox. It is working fine.
def checkbox_status(self):
checked=self.driver.find_element_by_xpath('//span[contains(text(), "Dell")]/parent::span/parent::label/input[@checked]').is_displayed()
return checked
| |
doc_23529549
|
How to do this?
A: It is possible uninstall this feature using the feature manager available in WSO2 Identity Server.
*
*Go to 'Configure' -> 'Features' menu.
*Select the 'Installed Features' tab which will list down the installed features.
*Select the 'Passive STS' feature and click 'Uninstall'. This will start a wizard with a couple of steps.
*Restart the server.
This will remove the Passive STS features and users will not be able to connect to PassiveSTS to retrieve tokens.
P.S. - If you go to STS configuration page, you will still notice a "Passive STS Configuration" link which will lead to an empty page. But this is not a critical issue because the management console related activities are available only for administrative users.
Also this bug has been already fixed in the trunk and it will be available in the next release.
Hope this helps.
*
*Thilina
| |
doc_23529550
|
long mbind(void *addr, unsigned long len, int mode, const unsigned long *nodemask,
unsigned long maxnode, unsigned flags);
Currently, I have something like this:
mbind(0x0,4611686018424767488,MPOL_BIND,nodemask,maxnode,MPOL_MF_MOVE);
From the specs it's still unclear to me what to put and how to put for nodemask and maxnode.
A: nodemask is a pointer to a bitmask of the allowed NUMA nodes. The bitmask is an array of unsigned long elements with each array element holding as many bits as the size of unsigned long int on the particular architecture allows. Unless your program is running on a really big NUMA system, a single unsigned long variable should suffice.
maxnode gives the number of significant bits in nodemask. The kernel rounds internally the size to a multiple of sizeof(unsigned long) but only uses maxnode bits.
There are many examples and libraries around that allow you to create and conveniently manipulate bitmasks without having to fiddle with bit operations yourself. You can utilise libnuma. It doesn't allow you to set the MPOL_MF_MOVE policy but includes functions for the creation and manipulation of nodemasks.
A terrible and very unportable Linux pro-tip: The existing macros that deal with the CPU affinity masks, namely CPU_ZERO / CPU_SET / CPU_CLR and the associated data structure cpu_set_t can also be used for NUMA nodemasks. The reason for that is that (1) both are implemented as arrays of unsigned long and (2) there are usually less NUMA nodes than logical CPUs, therefore cpu_set_t should have enough bits to be able to represent all NUMA nodes on the system.
Side note: 4611686018424767488 should probably be suffixed with LL.
| |
doc_23529551
|
something like below
public static void SetLicence1()
{
Console.WriteLine("Setting Aspose Licence in Thread1 ");
Console.WriteLine(SetAsposeLicense());
}
public static void SetLicence2()
{
Console.WriteLine("Setting Aspose Licence in Thread2 ");
Console.WriteLine(SetAsposeLicense());
}
public static bool SetAsposeLicense()
{
try
{
//Declare Mutex variable:
using (Mutex mutex = new System.Threading.Mutex(false, "Test"))
{
mutex.WaitOne(TimeSpan.FromSeconds(5));
var objLic = new License();
objLic.SetLicense(@"C:\Nivedita\License\Aspose.Cells.lic");
mutex.ReleaseMutex();
}
return true;
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
return false;
}
}
}
public class TestClass
{
public static void Main()
{
Thread tid1 = new Thread(new ThreadStart(ThreadClass.SetLicence1));
Thread tid2 = new Thread(new ThreadStart(ThreadClass.SetLicence2));
tid1.Start();
tid2.Start();
Console.Read();
}
}
This piece of code is working perfectly fine. But here my question is that is there any chance for the WaitOne() method can gets stuck in or across the processes and the mutex object doesnt get released? Although I have used mutex.ReleaseMutex().
A: First of all it's not quite clear what your intention is. If you just want to make sure that the licence can't be set simultaneously by two threads, you need something like this:
static object s_lock = new object();
public static bool SetAsposeLicense()
{
try
{
lock (s_lock)
{
var objLic = new License();
objLic.SetLicense(@"C:\Nivedita\License\Aspose.Cells.lic");
}
return true;
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
return false;
}
}
You notice that there is not 5 seconds timeout here. If you want to wait for 5 seconds and set the license regardless if the other thread has finished (basically what your code in the question does), instead of messing with mutex, you better do this (but I have a hard time understanding, why would you want this):
private static object s_lock = new object();
public static bool SetAsposeLicense()
{
if (Monitor.TryEnter(s_lock, TimeSpan.FromSeconds(5)))
{
try
{
return SetLicenseInternal();
}
finally
{
Monitor.Exit(s_lock);
}
}
return SetLicenseInternal();
}
public static bool SetLicenseInternal()
{
try
{
var objLic = new License();
objLic.SetLicense(@"C:\Nivedita\License\Aspose.Cells.lic");
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
return false;
}
}
Using the Monitor object is more "native" approach than using mutex and it fits more here, since you don't need cross-process.
As far as Mutex go, it's a wrapper against system Mutex object surfaced to .NET. Named Mutexes are system-wide and visible across process. When you create a .NET Mutex object and supply a name, if the system Mutex with this name does not exist, it's created and wrapped into the .NET object that you get. If the system Mutex with this name was already created before, then this existing Mutex gets wrapped and returned as your new .NET Mutex object.
I don't think that you should use Mutexes in your scenario.
A: WaitOne will throw an AbandondMutexException if the process that was holding it exits without releasing it. Even with a try/finally block it is still possible for this to happen if you stop debugging in the wrong place in visual studio or use task manager to end the process, so you should handle this case either relocking the mutex or exiting the application. Note that the call to release will also throw if the lock wasn't acquired due to the thrown exception.
A: EDIT: I've since learned this answer is incorrect. zespri explains below.
There is no chance of mutex not being released because it is disposed as soon as the using block ends. Nothing else can ever see mutex because it's scoped to the method. Realise that you have two, independant Mutex objects here, one in Thread1 and one in Thread2. This is simply incorrect usage of Mutex.
If you need a Mutex, try this instead:
private static Mutex mutex = new Mutex(false, "Test");
public static bool SetAsposeLicense()
{
try
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(5))
{
throw new TimeoutException("Aspose license registration timed out.");
}
try
{
var objLic = new License();
objLic.SetLicense(@"C:\Nivedita\License\Aspose.Cells.lic");
return true;
}
finally
{
mutex.ReleaseMutex();
}
}
catch(Exception ex)
{
Console.WriteLine(ex.StackTrace);
return false;
}
}
Changes:
*
*Make mutex a class member so that all threads can see the same Mutex.
*Check whether mutex was released, or whether it timed out.
*Add a nested try/finally block to ensure mutex is released if setting the license throws an exception. The nesting is required because ReleaseMetux() can only be called by the thread that successfully called WaitOne().
| |
doc_23529552
|
@Value("${azure.storage.connection-string}")
private String connectionString;
I am using JUnit4 . When this test runs, the connectionString property is null.
@TestPropertySource(locations="classpath:/application-test.yml")
@Slf4j
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
public class BlobServiceTest {
@Autowired
private ObjectMapper objectMapper;
private BlobService blobServiceSpy;
@Before
public void setup() {
blobServiceSpy = Mockito.spy(new BlobService(objectMapper));
}
@Test
public void testGetExampleBlob() {
String stubFileId = UUID.randomUUID().toString();
PdfBlob pdfBlob = null;
try {
pdfBlob = blobServiceSpy.downloadBlobContent(stubFileId);
} catch (JsonProcessingException e) {
log.error("Test failed.", e);
Assert.fail();
}
Assert.assertNotNull("PDF blob was null.", pdfBlob);
}
}
There is some kind of answer in this question, but it is very unclear, and the answer needs more info.
This worked but it seems like a "hack":
public class BlobServiceTest {
@Value("${azure.storage.containerName}")
private String containerName;
@Value("${azure.storage.connection-string}")
private String connectionString;
@Autowired
private ObjectMapper objectMapper;
private BlobService blobServiceSpy;
@Before
public void setup() {
blobServiceSpy = Mockito.spy(new BlobService(objectMapper));
//TODO not sure why, but had to setup connectionString property this way
blobServiceSpy.containerName = this.containerName;
blobServiceSpy.connectionString = this.connectionString;
}
Why doesn't SpringBootTest wire up those values for me when I create the Spy object?
A: When you use new to create your BlobService spring doesn't know about it an therefore doesn't inject your properties. Try to @Autowire your blob service and then wrap it in the spy.
| |
doc_23529553
|
*
*Server1(winserver2016): Webapplication1 on IIS port 80 + 443, Webapplication2 Apache port 9000 + 9001
*Server2(ubuntu16.4): Rocketchat snap, OpenVPN
*2 Domain controllers (winserver2016) and a purchased dns record from godaddy domain.co.uk.
I cannot for the life of me figure out how to redirect HTTPS requests to the internal servers via port 443 on the router tried a reverse proxy in IIS 10 with aarp and rewrite (nothing) I tried using subdomains on godaddy but it just redirects to to the IPaddress:port. tried adding subdomains in DNS nothing still the same response 404
Essentially if I point port 80 and 443 at rocket chat it works and I get SSL via caddy but if I try to connect any other services on those ports I get nothing returned. If I connect rocket chat on ports 3000 and 8443 for example I get no SSL and the https site for it doesn't work
I am ready to try a reverse proxy on another Linux deploy in a min and see how that goes but I suspect it will be the same result.
All of these servers run on Hyper-V on 2 win10 boxes.
A: If you are trying to redirect based on source IP, You might have to use policy routes in the firewall to control the behavior depending on the source of the packet. I'd check to see if your firewall or router has such abilities. Cheap routers tend to use basic static routing
If that doesn't help, you might also need to have a separate reverse proxy web server in place. The configuration is a little tricky in apache...You could put the following inside a virtual host block if you wanted to route based on sub-directory:
<Proxy balancer://myset>
# xxx.xxx.xxx.xxx is your server that will be behind the proxy
BalancerMember http://xxx.xxx.xxx.xxx/subdirectoryName/
ProxySet lbmethod=bytraffic
</Proxy>
ProxyPreservehost On
ProxyPass "/subdirectoryName/" "balancer://myset/"
ProxyPassReverse "/subdirectoryName/" "balancer://myset/"
Not sure if this what would work exactly for subdomains, but I'd try something like this.
| |
doc_23529554
|
function SomeThing(window, document) {
var self = this;
self.window = window;
self.document = document;
if (!self.window.sessionStorage.getItem('page-reloaded')) {
self.window.sessionStorage.setItem('page-reloaded', true);
self.window.location.reload(true); // PROBLEM ON THIS LINE
return;
}
}
my mock test looks like this:
beforeEach(function() {
mockWindowObj = {
'location': {
'href': '',
'search': '?hello=world',
'pathname': '/some/path',
'replace': function () {},
'reload': jasmine.createSpy()
}
};
spyOn(mockWindowObj.location, 'reload').and.callFake(function(){}); ;
some = new SomeThing(mockWindowObj, mockDocumentObj);
});
When I run a test I get this error:
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
{
"message": "Some of your tests did a full page reload!",
"str": "Some of your tests did a full page reload!"
}
If I comment out the line window.location.reload(true) all of my test run fine and pass. I'm sort of new to unit tests and I'm not sure how to get around this. Any help would be very much appreciated. Thanks in advance.
A: Your posted code cannot be what you actually ran. The line containing self.window.sessionStorage.getItem would have to fail since you did not define sessionStorage on your mock.
I guess the SomeThing function is being called with window pointing to the real window object. That explains what you observe.
| |
doc_23529555
|
Problem is active resource mapping apis/ instead of api/
Below is my code for model => app/model/api.rb
class Api < ActiveResource::Base
self.site = "https://myapp/resource"
self.format = :json
self.element_name = "api"
end
Code in app/controllers/api_controller.rb
@api = Api.get(:responce, :key => "key", :userId =>'1')
The above code always give 404 error, when I check the logs, resource is hitting https://myapp/resource/**apis**/responce.json?key=key&userId=1
Where it must hit resource URL as https://myapp/resource/**api**/responce.json
A: The self.element_name = "api" is fixing the pluralization when you are doing a find(:first) or similar. What you need is self.collection_name = "api". That should fix the URL it is creating.
| |
doc_23529556
|
The guide suggest:
body,
h1,
h2,
h3,
h4,
p,
li,
figure,
figcaption,
blockquote,
dl,
dd {
margin: 0;
}
Isn't it the same as this?
*{
margin: 0;
}
Why should I use the first one?
A: With * {...} you reset / modify all possible tags. With div, p { ... } you will reset / modify only div, p tags.
A: Generally removing all default styles from all elements is not what you want. Some default styles just works fine and it's easier to let them be there :)
A: It's not the same. Let me try to explain.
The linked guide suggests resetting elements. The author wants to define their own margins on each of the elements.
Example 1:
*,
*::before,
*::after {
box-sizing: border-box;
}
This removes the box-sizing from the defined elements, meaning all elements and all ::before and ::after elements). Learn more about the ::before pseudo-element: https://developer.mozilla.org/en-US/docs/Web/CSS/::before
Example 2:
Furthermore, the guide suggests removing the default margin from a list of elements, not all elements as the * {} would do:
body,
h1,
h2,
h3,
h4,
p,
figure,
blockquote,
dl,
dd {
margin: 0;
}
Learn more about default values for various elements: https://www.w3schools.com/cssref/css_default_values.asp
Your 2nd code block is resetting margins on everything:
* {
margin: 0;
}
This removes the (default) margin from all elements. You could also overwrite the margin of elements defined before.
And, this is why CSS is named CSS, cascading stylesheets. Styles cascade ... several different style sheets can be active for a single document or element at the same time.
A: Because they aren't the same.
The list of elements in the above CSS snippet aren't all the HTML tags. For starters, the video tag isn't added, so it's not equivalent to *, which would encompass all of the (visual) HTML elements.
Here is a resource that shows all the tags.
| |
doc_23529557
|
Please find the error below:
XML Parsing Error: no element found Location: moz-nullprincipal:{1a2c8133-f48f-4707-90f3-1a2b2f2d62e2} Line Number 1, Column 1:
^
this is my javascript function:
function Update(Id) {
$.ajax({
type: "GET",
url: ROOT_URL + "/sevice/udates.svc/Update?Id=" + Id,
success: function(response) {
},
async: false
});
}
A: It's a known FireFox bug.
https://bugzilla.mozilla.org/show_bug.cgi?id=547718
to quick fix this , you maybe can return an response with html structure(but no content).
A: I fixed the problem by setting mimeType to "text/html"
A: The ajax call expects XML back (perhaps due to bad guessing) and tries to parse it and fails if nothing is returned or it is not valid XML..
Use the dataType option to specify the format of the response.
From the comments it looks like some browsers cannot handle an no-content response. So, a workaround for such cases might be to return something from your service (even a single space).
A: I've come across an alternative cause of this - might help someone.
If you make a $.ajax request (in my case a PUT request) that returns a 200 header but no body content I've seen this same XML Parsing error message occur - even when the dataType is set to json.
(At least) two solutions work:
*
*Make all API PUT requests return some content, or
*Return a 204 'No Content' header instead (what I ended up doing)
A: async is also part of options. Also specify the dataType as xml
function Update(Id) {
$.ajax({
type: "GET",
async: false,
dataType: "XML",
url: ROOT_URL + "/sevice/udates.svc/Update?Id=" + Id,
success: function(response) {
}
});
}
A: You need to send html document to the output (the output udates.svc in your case) . If you use ASP.NET, you could do the following:
Response.Clear();
Response.Write("<html xmlns=”http://www.w3.org/1999/xhtml”>");
Response.Write("<head><title></title></head>");
Response.Write("<body>");
Response.Write("your output");
Response.Write("</body>");
Response.Write("</html>");
Response.ContentType = "text/HTML";
Response.End();
| |
doc_23529558
|
For example:
Thats what i get when i try to autocomplete axios methods, i would like to return all avaliable methods of axios for example get, post and etc...
But my VS Code just doesnt autocomplete anything.
Here is the Javascript related extensions i have installed:
*
*JavaScript and TypeScript Nightly
*Babel Javascript
What i need to do to get this working?
A: SOLVED
SOURCE:
https://codeolives.com/2019/09/18/vs-code-why-javascript-intellisense-is-not-working/
Somehow my buitin extesion "TypeScript and JavaScript Language Features" was disabled, to autocompletion works this extension had to be enabled
Go to:
extensions sidebar tab > Filter icon > Built-in
Search for "typescript" and enable "TypeScript and JavaScript Language Features"
This part isnt in the source i linked above, but you need it too:
Make sure you have this on your settings.json file:
"[javascript]": {
"editor.defaultFormatter": "vscode.typescript-language-features",
},
| |
doc_23529559
|
Is there an error in the code or an alternate way of doing this?
Sub AddBorders()
With Range("A:B").FormatConditions.Add(Type:=xlExpression, Formula1:="=A1<>A2")
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
End With
End Sub
A: It seems that it is not xlEdgeBottom it is just xlBottom. So change the line:
With .Borders(xlEdgeBottom)
to
With .Borders(xlBottom)
and it worked for me
A: In addition to using xlBottom instead of xlEdgeBottom, another possible of cause of this error is having applied more than three conditional formats to the same range. I was having the same issue, and this is what resolved it for me.
The MSDN documentation on the Add method states:
You cannot define more than three conditional formats for a range. Use the Modify method to modify an existing conditional format, or use the Delete method to delete an existing format before adding a new one.
| |
doc_23529560
|
Error in xyz.coords(x = x, y = y, z = z, xlab = xlabel, ylab = ylabel, : 'x', 'y' and 'z' lengths differ
The code entered was as follows:
x <- rbinom(1000, 8, 0.5) y <- rbinom(1000, 8, 0.5) K <- c(rep(0:8,times = 9), rep(0:8, each = 9)) k <- matrix(k, ncol=2, byrow = FALSE) z <- k[,1]+k[,2] cdf <- rep(0.0, times = 81) for (i in 1:81) {cdf[i] <- sum(x+y <= z[i])/1000}
scatterplot3d(k[,1], k[,2], cdf, highlight.3d = TRUE, col.axis ="blue", main="Plotting Bivariate CDF", pch = 20, ylab = "Values of y", xlab = "Values of x", zlab = "CDF of x+y")
Does anyone have any advice on how to fix this error - I'm pretty confused.
| |
doc_23529561
|
Sidekiq works perfectly on my development environment. I can see the worker queue and it all processing correctly.
However when I publish to production I get on all ActiveJob requests.
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Here is my production setup:
AWS
*
*Redis - ElastiCache : *.cache.amazonaws.com:6379
*EC2 - ElasticBeanstalk
*Mysqsl - RDS
*Ruby - Ruby 2.1 (Passenger Standalone)
Sideqik Gem installed - Config
redis_url = Rails.env.production? ? 'redis://*.cache.amazonaws.com:6379' : 'redis://127.0.0.1:6379'
Sidekiq.configure_server do |config|
config.redis = { url: redis_url }
end
Sidekiq.configure_client do |config|
config.redis = { url: redis_url }
end
MYSQL2 Gemfile
gem 'mysql2'
Sideqik Stats on Prod
Everything is processed except ActiveJob requests.
--- !ruby/object:Sidekiq::Stats
stats:
:processed: 18
:failed: 15
:scheduled_size: 0
:retry_size: 0
:dead_size: 0
:processes_size: 1
:default_queue_latency: 0
:workers_size: 0
:enqueued: 3
Database YML
default: &default
adapter: mysql2
encoding: utf8mb4
pool: 5
username: root
password:
socket: /tmp/mysql.sock
production:
<<: *default
database: <%= ENV['RDS_DB_NAME'] %>
username: <%= ENV['RDS_USERNAME'] %>
password: <%= ENV['RDS_PASSWORD'] %>
host: <%= ENV['RDS_HOSTNAME'] %>
port: <%= ENV['RDS_PORT'] %>
pool: 25
ElasticBeanstalk Sidekiq Config
## .ebextensions/sidekiq.config
commands:
create_post_dir:
command: "mkdir /opt/elasticbeanstalk/hooks/appdeploy/post"
ignoreErrors: true
files:
"/opt/elasticbeanstalk/hooks/appdeploy/post/50_restart_sidekiq":
mode: "000777"
content: |
cd /var/app/current
if [ -f /var/app/support/pids/sidekiq.pid ]
then
kill -TERM `cat /var/app/support/pids/sidekiq.pid`
rm -rf /var/app/support/pids/sidekiq.pid
fi
. /opt/elasticbeanstalk/support/envvars.d/sysenv
sleep 10
bundle exec sidekiq \
-e production \
-P /var/app/support/pids/sidekiq.pid \
-L /var/app/support/logs/sidekiq.log \
-q default mailers \
-d
"/opt/elasticbeanstalk/hooks/appdeploy/pre/03_mute_sidekiq":
mode: "000777"
content: |
if [ -f /var/app/support/pids/sidekiq.pid ]
then
kill -USR1 `cat /var/app/support/pids/sidekiq.pid`
fi
The ActiveJob
class ActivitiesJob < ActiveJob::Base
queue_as :default
def perform(activity)
Activity.create(
team_id: activity[:team_id],
account_id: activity[:account_id],
entity: activity[:entity] || nil,
entity_id: activity[:entity_id] || nil,
description: activity[:description],
activity_type: activity[:activity_type].nil? ? nil : activity[:activity_type]
);
end
end
Would like to get any opinion on why I would be getting a Socket error.
| |
doc_23529562
|
I have no probleme creating posts with images, but when I try to update a post, post changed info are updated bu not the image.
I have tried several posibilities from different tutorials without success
Thanks in advance
Here is my code:
controller
public function create(){
if(!$this->session->userdata('logged_in'))
{
redirect('users/login');
}
$data['title'] = 'Create Post';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
if($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
}
else
{
$slug = url_title($this->input->post('title'));
$post_image = $this->upload_image();
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'post_image' => $post_image
);
//$this->post_model->create_post($post_image);
$this->post_model->create_post($data);
// Set message
$this->session->set_flashdata('post_created', 'Your post has been created successfully!');
redirect('posts');
}
}
public function edit($slug)
{
$data['post'] = $this->post_model->get_posts($slug);
// Check if logged user has created this post
if($this->session->userdata('user_id') != $this->post_model->get_posts($slug)['user_id'])
{
redirect('posts');
}
$data['categories'] = $this->category_model->get_categories();
if(empty($data['post']))
{
show_404();
}
$data['title'] = 'Edit Post';
$this->load->view('templates/header');
$this->load->view('posts/edit', $data);
$this->load->view('templates/footer');
}
public function update()
{
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$id=$this->input->post("id");
$slug = url_title($this->input->post('title'));
if( $_FILES['userfile']['name']!="" )
{
$post_image = $this->upload_image();
}
else
{
$post_image=$this->input->post('old');
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'post_image' => $post_image
);
//$this->post_model->update_post($post_image);
$this->post_model->update_post($data,$id);
// Set message
$this->session->set_flashdata('post_updated', 'Your post has been updated successfully!');
redirect('posts');
}
public function upload_image()
{
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
}
else
{
$upload_data=$this->upload->data();
$post_image=$upload_data['file_name'];
}
return $post_image;
}
model:
public function create_post($data)
{
return $this->db->insert('posts', $data);
}
public function update_post($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
view (edit view):
<?php echo form_open('posts/update'); ?>
<input type="hidden" name="id" value="<?php echo $post['id']; ?>">
<input type="hidden" id="old" name="old" value="<?php echo $post['post_image'] ?>">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="Add Title" value="<?php echo $post['title']; ?>">
</div>
<div class="form-group">
<label>Body</label>
<textarea id="editor1" class="form-control" name="body" placeholder="Add Body"><?php echo $post['body']; ?></textarea>
</div>
<div class="form-group">
<label>Change Image</label>
<input class="form-control" type="file" name="userfile" size="20">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
A: I'm not sure how anything is uploading as do_upload() doesn't declare the the name of the file field. In this case I suppose it is userfile e.g. do_upload('userfile').
Consider doing something with you file uploads error variable as this should have uncovered your error rather quickly.
EDIT:
My bad, apparently do_upload() default file name parameter for upload is userfile. My guess now as to why it isn't working is that your "update" form, doesn't use form_open_multipart!
Please note: you can also move your redirect function back to login to the controllers constructor. This will eliminate some lines of duplicate code.
Also if you are looking for an easy way to get the errors of the upload function you can do the following:
private function upload_image()
{
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$this->load->library('upload', $config);
if(!$this->upload->do_upload())
{
throw new Exception($this->upload->display_errors());
//$errors = array('error' => $this->upload->display_errors());
//$post_image = 'noimage.jpg';
}
else
{
$upload_data=$this->upload->data();
$post_image=$upload_data['file_name'];
}
return $post_image;
}
Usage:
try {
$this->upload_image();
} catch (Exception $e) {
show_error($e->getMessage());
}
| |
doc_23529563
|
I would like to understand what each part file signifies?
The files have the following naming, /part0000, part0001, part0002
Code to create a line based RDD flatmap that I used to output these files
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
@Override
public Iterable<String> call(String x) {
return Lists.newArrayList(NEWSPACE.split(x));
}
});
My assumption was that this is creating a DStream of RDD's with each RDD= 1 line, and hence should create 1 part file.
A: An DStream is a collection of RDDs over time. Each RDD is composed of partitions of data distributed across the cluster of Spark workers.
In this illustration, each colored line represents a stream of data. When it's bounded in an rdd, it's a partition of the RDD. The RDD is composed by the data collected at each time interval, represented here by the blue box.
DStream.saveAsTextFile will create a file for the RDD created at interval (bluc box) each part-file corresponds to the piece of the colored line bounded by such RDD (colored line within blue blox).
In a distributed file system, like hdfs, the fs will abstract out the partitioning, presenting you with a single logical file, or 1 file per RDD.
When you use the local file system, those part-files will the explicit as you are seeing.
(*) Credits for the image: Spark presentation at Devoxx 2014 by Andy Petrella and Gerard Maas (me)
| |
doc_23529564
|
The purpose of this is to wait that for one specific timestamp, we wait that we receive every item that we are expecting, then push the notification further once we are "synchronized" with all items.
Currently, we have a Dictionary<DateTime, TimeSlot> to store the non-synchronized TimeSlot(TimeSlot = list of all items we received for a specific timestamp).
//Let's assume that this method is not called concurrently, and only once per "MyItem"
public void HandleItemReceived(DateTime timestamp, MyItem item){
TimeSlot slot;
//_pendingTimeSlot is a Dictionary<DateTime,TimeSlot>
if(!_pendingTimeSlot.TryGetValue(timestamp, out slot)){
slot = new TimeSlot(timestamp);
_pendingTimeSlot.Add(timestamp,slot );
//Sometimes we don't receive all the items for one timestamps, which may leads to some ghost-incomplete TimeSlot
if(_pendingTimeSlot.Count>_capacity){
TimeSlot oldestTimeSlot = _pendingTimeSlot.OrderBy(t=>t.Key).Select(t=>t.Value).First();
_pendingTimeSlot.Remove(oldestTimeSlot.TimeStamp);
//Additional work here to log/handle this case
}
}
slot.HandleItemReceived(item);
if(slot.IsComplete){
PushTimeSlotSyncronized(slot);
_pendingTimeSlot.Remove(slot.TimeStamp);
}
}
We have severals instances of this "Synchronizer" in parallels for differents group of items.
It's working fine, except when the system is under heavy loads, we have more incomplete TimeSlot, and the application uses a lot more CPU. The profiler seems to indicate that the Compare of the LINQ query is taking a lot of time(most of the time). So I'm trying to find some structure to hold those references(replace the dictionary)
Here are some metrics:
*
*We have several(variable, but between 10 to 20) instances of this Synchronizer
*The current maximum capacity(_capacity) of the synchronizer is 500 items
*The shortest interval that we can have between two different timestamp is 100ms(so 10 new Dictionary entry per seconds for each Synchronizer)(most case are more 1 item/second)
*For each timestamp, we expect to receive 300-500 items.
So we will do, for one Synchronizer, per second(worst case):
*
*1 Add
*500 Get
*3-5 Sorts
What would be my best move? I thought to the SortedDictionary But I didn't find any documentation showing me how to take the first element according to the key.
A: The first thing you can try is eliminating the OrderBy - all you need is the minimum key, no need to sort for getting that:
if (_pendingTimeSlot.Count > _capacity) {
// No Enumerable.Min(DateTime), so doing it manually
var oldestTimeStamp = DateTime.MaxValue;
foreach (var key in _pendingTimeSlot.Keys)
if (oldestTimeStamp > key) oldestTimestamp = key;
_pendingTimeSlot.Remove(oldestTimeStamp);
//Additional work here to log/handle this case
}
What about SortedDictionary, it is an option for sure, although it will consume much more memory. Since it's sorted, you can use simply sortedDictionary.First() to take the key value pair with the minimum key (hence the oldest element in your case).
UPDATE: Here is a hybrid approach using dictionary for fast lookups and ordered double linked list for the other scenarios.
class MyItem
{
// ...
}
class TimeSlot
{
public readonly DateTime TimeStamp;
public TimeSlot(DateTime timeStamp)
{
TimeStamp = timeStamp;
// ...
}
public bool IsComplete = false;
public void HandleItemReceived(MyItem item)
{
// ...
}
// Dedicated members
public TimeSlot PrevPending, NextPending;
}
class Synhronizer
{
const int _capacity = 500;
Dictionary<DateTime, TimeSlot> pendingSlotMap = new Dictionary<DateTime, TimeSlot>(_capacity + 1);
TimeSlot firstPending, lastPending;
//Let's assume that this method is not called concurrently, and only once per "MyItem"
public void HandleItemReceived(DateTime timeStamp, MyItem item)
{
TimeSlot slot;
if (!pendingSlotMap.TryGetValue(timeStamp, out slot))
{
slot = new TimeSlot(timeStamp);
Add(slot);
//Sometimes we don't receive all the items for one timestamps, which may leads to some ghost-incomplete TimeSlot
if (pendingSlotMap.Count > _capacity)
{
// Remove the oldest, which in this case is the first
var oldestSlot = firstPending;
Remove(oldestSlot);
//Additional work here to log/handle this case
}
}
slot.HandleItemReceived(item);
if (slot.IsComplete)
{
PushTimeSlotSyncronized(slot);
Remove(slot);
}
}
void Add(TimeSlot slot)
{
pendingSlotMap.Add(slot.TimeStamp, slot);
// Starting from the end, search for a first slot having TimeStamp < slot.TimeStamp
// If the TimeStamps almost come in order, this is O(1) op.
var after = lastPending;
while (after != null && after.TimeStamp > slot.TimeStamp)
after = after.PrevPending;
// Insert the new slot after the found one (if any).
if (after != null)
{
slot.PrevPending = after;
slot.NextPending = after.NextPending;
after.NextPending = slot;
if (slot.NextPending == null) lastPending = slot;
}
else
{
if (firstPending == null)
firstPending = lastPending = slot;
else
{
slot.NextPending = firstPending;
firstPending.PrevPending = slot;
firstPending = slot;
}
}
}
void Remove(TimeSlot slot)
{
pendingSlotMap.Remove(slot.TimeStamp);
if (slot.NextPending != null)
slot.NextPending.PrevPending = slot.PrevPending;
else
lastPending = slot.PrevPending;
if (slot.PrevPending != null)
slot.PrevPending.NextPending = slot.NextPending;
else
firstPending = slot;
slot.PrevPending = slot.NextPending = null;
}
void PushTimeSlotSyncronized(TimeSlot slot)
{
// ...
}
}
Some additional usages:
Iterating from oldest to newest:
for (var slot = firstPending; slot != null; slot = slot.NextPending)
{
// do something
}
Iterating from oldest to newest and removing items based on a criteria:
for (TimeSlot slot = firstPending, nextSlot; slot != null; slot = nextSlot)
{
nextSlot = slot.NextPending;
if (ShouldRemove(slot))
Remove(slot);
}
Same for reverse scenarios, but using lastPending and PrevPending members instead.
A: Here is simple sample. The insert method in a list eliminates swapping elements.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Data> inputs = new List<Data>() {
new Data() { date = DateTime.Parse("10/22/15 6:00AM"), data = "abc"},
new Data() { date = DateTime.Parse("10/22/15 4:00AM"), data = "def"},
new Data() { date = DateTime.Parse("10/22/15 6:30AM"), data = "ghi"},
new Data() { date = DateTime.Parse("10/22/15 12:00AM"), data = "jkl"},
new Data() { date = DateTime.Parse("10/22/15 3:00AM"), data = "mno"},
new Data() { date = DateTime.Parse("10/22/15 2:00AM"), data = "pqr"},
};
Data data = new Data();
foreach (Data input in inputs)
{
data.Add(input);
}
}
}
public class Data
{
public static List<Data> sortedData = new List<Data>();
public DateTime date { get; set; }
public string data { get; set;}
public void Add(Data newData)
{
if(sortedData.Count == 0)
{
sortedData.Add(newData);
}
else
{
Boolean added = false;
for(int index = sortedData.Count - 1; index >= 0; index--)
{
if(newData.date > sortedData[index].date)
{
sortedData.Insert(index + 1, newData);
added = true;
break;
}
}
if (added == false)
{
sortedData.Insert(0, newData);
}
}
}
}
}
| |
doc_23529565
|
I have a model that has nested classes and one of the nested classes its self references a class that is linked at the parent level (which is entirely possible, its similar I guess to normalisation).
So, for example you might have a class structure
`
class-A
-> String
-> class-b
-> class-c
-> String
-> class-b
-> String
-> class-d
-> String
-> String
`
In the above structure, class-b models a set of data that is present as an attribute on both class-A and class-c. It seems to me that this is impossible because "class-b" would need to have definitions for 2 different positions in the structure. Is this correct, is this a limitation on the Bindy format?
thanks
Paul
| |
doc_23529566
|
guard 'coffeescript', :input => 'src/javascripts', :output => 'public/javascripts'
guard 'shell' do
watch( %r{^public/.+\.(js|css)$} ) do |m|
puts m.inspect
if m[1] == 'js'
puts 'a js is new!'
else
puts 'a css is new!'
end
puts %x{ echo #{File.mtime(m[0])} }
end
end
Which seems to output 'a js is new' twice if I edit a coffeescript file. With debug on it seems to run after
13:39:23 - DEBUG - Hook :run_on_changes_begin executed for Guard::CoffeeScript
13:39:23 - INFO - Compile src/javascripts/blah.coffee
13:39:23 - INFO - 01:39:23 PM Successfully generated public/javascripts/blah.js
["public/javascripts/blah.js", "js"]
a js is new!
and
13:39:23 - DEBUG - Hook :run_on_changes_end executed for Guard::CoffeeScript
["public/javascripts/blah.js", "js"]
a js is new!
It does seem to only fire once if I edit the blah.js file directly. I was a little confused by how hooks work, can I key into a hook from another guard? Should I just run this code in a callback in the coffeescript guard? I was trying to use groups and only do the shell part if I was in a group and didn't want to have to repeat the coffee guard in the case where I would use a callback instead.
Any thoughts on how I can stop triggering the shell guard twice when the coffe one fires?
A: Prior to Guard 1.0.0, new files created and updated from a Guard plugin did not trigger a subsequent file change for other plugins. This was a problem for example with the CoffeeScript and LiveReload plugins: When a JavaScript file has been updated, then LiveReload did not reload the file. As a workaround I added some manual file trigger code. With the Listen gem this limitation has been removed, thus the CoffeeScript plugin triggers file changes twice.
I removed it on my master branch. Can you please give it a try before I release a new gem? You can do this easily by using my master branch by adding:
gem 'guard-coffeescript', :github => 'netzpirat/guard-coffeescript', :branch => 'master'
to your Gemfile. I'll release a new gem asap when it works fine.
| |
doc_23529567
|
I have the following code:
-Stream of topic1:
KStream<Long, byte[]> events = builder.stream("topic1", Consumed.with(Serdes.Long(), Serdes.ByteArray()));
-Table of topic2:
KTable<Long, byte[]> table = builder.table("topic2",
Consumed.with(Serdes.Long(), Serdes.ByteArray()));
When I produce with producer from topic1, everything is produced fine. The values for topic1 and topic2 are different, I want to consume the produced record from first topics producer with this stream "events" and after that append this events to the seconds topic table and save the state of the second topic value for the same key (Key is long, it's the same number for the first and second topic). In other words, I want to join stream with the table based on the same key and update table.
My code:
StoreBuilder<KeyValueStore<Long, byte[]>> store = Stores
.keyValueStoreBuilder(Stores.persistentKeyValueStore(STORE_TOPIC2), Serdes.Long(), Serdes.ByteArray())
.withLoggingEnabled(new HashMap<>());
builder.addStateStore(store);
events.join(table, KeyValue::new, Joined.with(Serdes.Long(), Serdes.ByteArray(), Serdes.ByteArray()))
.transform(Update::new, STORE_TOPIC2)
.to("topic2", Produced.with(Serdes.Long(), Serdes.ByteArray()));
On the last line I produce the joined events to the topic2, but nothing is produced on this topic, my transformer "Update" looks like this:
private static class Update implements Transformer<Long, KeyValue<byte[], byte[]>, KeyValue<Long, byte[]>> {
private KeyValueStore<Long, byte[]> store1;
@Override
@SuppressWarnings("unchecked")
public void init(ProcessorContext context) {
store1 = (KeyValueStore<Long, byte[]>) context.getStateStore(store);
}
@Override
public KeyValue<Long, byte[]> transform(final Long key, final KeyValue<byte[], byte[]> updates) {
System.out.println("Inside event transformer for key: " + key);
System.out.println("Last produced graph: " + store.get(key));
CustomClass c = null;
try {
c = deserializeModel(store.get(key));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (c == null) {
c = new CustomClass(...);
}
try {
return KeyValue.pair(companyKey, serializeModel(companyNetwork));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
| |
doc_23529568
|
I am trying to run a Javascript program that integrates ReactJS. It worked for a while and every time I would type "npm start" it would automatically bring up the webpage template in the browser. Now it gives me the following error(s):
jMBP:project javen$ npm start
> react-box@0.1.0 start /Users/javen/Desktop/project
> node scripts/start.js
internal/modules/cjs/loader.js:583
throw err;
^
Error: Cannot find module 'react-dev-utils/prompt'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/Users/sland/Desktop/project/scripts/start.js:20:14)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react-box@0.1.0 start: `node scripts/start.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react-box@0.1.0 start 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! /Users/javen/.npm/_logs/2018-09-27T01_24_06_237Z-debug.log
I have the following installed:
node -v: v10.9.0
npm -v: 6.4.1
I have tried the following:
npm install --save-dev react-dev-utils
npm install -g npm@latest
rm -rf node_modules
npm install //this threw a lot of errors
In the package.json file, for react-dev-utils it says, "react-dev-utils": "^5.0.2" Also, I do not know if this matters, but in the process of trying fixing this, a package-lock.json file has shown up in my project folder. The "prompt" var the error is referring to is the start.js folder: var prompt = require('react-dev-utils/prompt');
I have read that downgrading to an older version of node can sometimes work. If this is the case, which version is best, and how do I do this? Any advice appreciated.
A: I think npm install --save-dev react-dev-utils commands generally solves the issue. If not then updating your configs to match the latest create-react-app will fix this issue.
| |
doc_23529569
|
Based on "Display total customers reviews and ratings average in WooCommerce" answer code, which gets the product average rating this way:
echo products_rating_average_html();
How to can I get the average rating for each product individually… for example if the product have 4 or 5 reviews it get the average rating for them (For every product)
I also would like to get the comment review for every product to put them in the table as well…
A: This will give the avarage rating of given product id
$rating = get_post_meta( $product_id, '_wc_average_rating', true );
You can use this in loop of product this will give you a raw number of avrage rating without any html
For getting latest comment you can use below add this code in functions.php and then call this action where you want to display latest comment pass current product object as argument
function display_product_review($product_id) {
$product = wc_get_product( $product_id );
$comments = get_approved_comments( $product->id );
$product_link = '/product/' . $product->post->post_name . "/#tab-reviews/";
if ( !empty ($comments) ) {
echo $comments[0]->comment_content . '<br><a href="'. $product_link . '">Read more reviews...</a>';
} else {
echo "There are no reviews for this product yet. Would you like to <a href='" . $product_link ."'>add your own review</a>?";
}
}
add_action('get_latest_review','display_product_review');
Calling of action
do_action('get_latest_review',$product);
A: Have a look to this answer thread, where you'll see that you can use WC_Product methods like:
*
*get_average_rating()
*get_rating_counts()…
Here is a complete example:
1) Get the products required related data (customizable):
$products_data = []; // Initializing
$products = wc_get_products( ['limit' => -1] ); // Get all WC_Product objects
// Loop through products -- Preparing data to be displayed
foreach ( $products as $product ) {
$product_id = $product->get_id();
// 1. Product data as product name …
$products_data[$product_id]['name'] = $product->get_name();
// 2. Average rating and rating count
$products_data[$product_id]['rating'] = (float) $product->get_average_rating();
$products_data[$product_id]['count'] = (int) $product->get_rating_count();
// 3. Reviews -- Loop though product reviews
foreach( get_approved_comments( $product_id ) as $review ) {
if( $review->comment_type === 'review' ) {
$products_data[$product_id]['reviews'][] = (object) [
'author' => $review->comment_author,
'email' => $review->comment_author_email,
'date' => strtotime($review->comment_date),
'content' => $review->comment_content,
];
}
}
}
2) Customizable display in a table:
echo '<table class="products-reviews-ratings"><tr>
<th>'.__("ID").'</th>
<th>'.__("Name").'</th>
<th>'.__("Rating").'</th>
<th>'.__("count").'</th>
<th style="text-align:center">'.__("Reviews (author, date and content)").'</th>
</tr>';
foreach ($products_data as $product_id => $data){
echo '<tr>
<td>'.$product_id.'</td>
<td>'.$data['name'].'</td>
<td>'.$data['rating'].'</td>
<td>'.$data['count'].'</td>
<td style="text-align:center">';
if( isset($data['reviews']) && $data['reviews'] > 0 ) {
echo '<table>';
// Loop through reviews
foreach ($data['reviews'] as $review ){
echo '<tr>
<td><a href="mailto:'.$review->email.'">'.$review->author.'</a></td>
<td>'.date( 'Y-m-d', $review->date ).'</td>
<td>'.$review->content.'</td>
</tr>';
}
echo '</table>';
} else {
_e('No reviews yet');
}
echo '</td></tr>';
}
echo '</table>';
You will get something like:
| |
doc_23529570
|
ERROR:root:Exception while sending command.
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/py4j/java_gateway.py", line 1207, in send_command
raise Py4JNetworkError("Answer from Java side is empty")
py4j.protocol.Py4JNetworkError: Answer from Java side is empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/py4j/java_gateway.py", line 1033, in send_command
response = connection.send_command(command)
File "/usr/local/lib/python3.7/site-packages/py4j/java_gateway.py", line 1212, in send_command
"Error while receiving", e, proto.ERROR_ON_RECEIVE)
py4j.protocol.Py4JNetworkError: Error while receiving
My pyspark code :
spark = SparkSession \
.builder \
.appName("Segments") \
.master("spark://xx.xxx.x.xxx:7077") \
.config("spark.executor.memory", "14g") \
.config("spark.cores.max", 1) \
.config("spark.driver.memory", "20g") \
.config("spark.network.timeout", 100000000) \
.config("spark.driver.extraClassPath", "/app/jars/mysql-connector-java-8.0.19.jar") \
.config("spark.executor.extraClassPath", "/app/jars/mysql-connector-java-8.0.19.jar") \
.getOrCreate()
Here xx.xxx.x.xxx is my spark kubernetes server. Anyone have any idea about why this error is coming or there are any other method to create spark session on docker with spark kubernetes.
| |
doc_23529571
|
<InnerElement
ref={myRef}
onClick={() => {
console.log(myRef.current?.offsetTop);
}}
/>
But it doesn't take into account if the element is inside of a div that is scrolled. If that parent div is scrolling, the value of myRef.current?.offsetTop will remain the same
Is there a way to get the absolute position of that ref in the viewport?
A: Use getBoundingClientRect() in combination with the window's scroll position:
getBoundingClientRect().y + window.scrollY
A: getboundingclientrect() Does it solve your problem!
| |
doc_23529572
|
How to set the specific position the element will occupy in the diagram? How to set the size of the element?
I notice we have a left, right, top and bottom properties in the diagram object, which we can initialize adding a new diagram object to the diagram:
var position = String.Format("l={0};r={1};t={2};b={3};", 1000, 1000, 5000, 5000);
var diaObject = (DiagramObject)rootDiagram.DiagramObjects.AddNew(position, string.Empty);
But no matter which values I use for the "coordinates", my hyperlink always appear on top left, one over the other, and all of them with the same size.
A: You're specifying r=l=1000 and b=t=5000. This will result in a size of 0x0 at which point I'd guess EA will revert to defaults. Try setting r to 1500 and b to 6500.
| |
doc_23529573
|
I have this regex function with which I want to get all the values in a string if they start with a hash sign. But I couldn't get it to work if a substring is at the end of the string and nothing fallows it. I've tried to remove the first "$" but it didn't work. It works when I append one space to the string but as I'm going to modify the function to ignore spaces I don't want to do it anymore.
For example if the string is:
a="#title1 #title2 #title3"
The result is:
{"title1","title2"}
But I want it to be:
{"title1","title2","title3"}
| |
doc_23529574
|
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Tick struct {
Query string `json:"query"`
}
func main() {
data := &Tick{Query: "https://ratesjson.fxcm.com/DataDisplayer?&callback=Tick"}
buf := new(bytes.Buffer)
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
_ = enc.Encode(data)
fmt.Println(string(buf.Tick()))
fmt.Println("Done")
}
Anyone know why this is invalid json or why this can not be parsed? Or point out the fix how to make this work?
package main
import (
"log"
"fmt"
"net/http"
"bytes"
"io/ioutil"
"github.com/pquerna/ffjson/ffjson"
)
type MsgRatesArray struct {
RateQuote []MsgRateQuoteJson `json:"Rates"`
}
type MsgRateQuoteJson struct {
SymbolName string `json:"Symbol"`
SymbolBid int64 `json:"Bid"`
SymbolAsk int64 `json:"Ask"`
SymbolSpread int64 `json:"Spread"`
SymbolPT string `json:"ProductType"`
}
var respBytes []byte
func main() {
var msg MsgRatesArray
response,err := http.Get("https://ratesjson.fxcm.com/DataDisplayer?&callback=Tick")
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
respBytes, err := ioutil.ReadAll(response.Body)
jsonBytes := respBytes[bytes.Index(respBytes, []byte("{")):bytes.LastIndex(respBytes, []byte("}"))+1]
jsonString := string(jsonBytes)
fmt.Println(jsonString)
err = ffjson.Unmarshal(jsonBytes, &msg)
if err != nil {
panic(err)
}
}
A: Do your own http request to get the json, then strip out the non json stuff (everything before the first { and after the last }:
response,err := http.Get("https://ratesjson.fxcm.com/DataDisplayer?&callback=Tick")
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
respBytes, err := ioutil.ReadAll(response.Body)
jsonBytes := respBytes[bytes.Index(respBytes, []byte("{")):bytes.LastIndex(respBytes, []byte("}"))+1]
jsonString := string(jsonBytes)
fmt.Println(jsonString)
https://play.golang.org/p/JyibZ3g6UA
| |
doc_23529575
|
I don't have a model for Department.
In IRB, I can do this successfully:
p = Product.new
But when I do this:
d = Department.new
It throws,
NameError: uninitialized constant Department
Is that happening because the Rails model for Department isn't there?
If you already have the table, how do you create the model (do I have to generate and run rake db:migrate)?
A: yes error is due to not having a Department class or model. You can just create a department.rb and inherited from active record in your app/models directory with your favourite editor. for example with vim you can do
vim app/models/department.rb
edit the above file to have following
class Department < ActiveRecord::Base
end
and then reload the irb session with reload!
A: Rails follow Convention over Configuration also the ActiveRecord follows the ORM (Object Relational Mapping) and according to it :
All the models in the Rails application has a Singular class name with a plural name in the database . For ex : In your case ,
Department model will refer to departments table in the database , where you have the departments table but not a model Department in your Rails application .
By default, Active Record uses some naming conventions to find out how
the mapping between models and database tables should be created.
Rails will pluralize your class names to find the respective database
table. So, for a class Book, you should have a database table called
books. The Rails pluralization mechanisms are very powerful, being
capable to pluralize (and singularize) both regular and irregular
words.
Now , when you try to initialize the Department model in irb like
$ > d=Department.new
What this will do is will search a class name as Department in your app/models directory , if it finds this class it will relate it to the similar departments table in the database and will initialize this object.
It will obviously throw an error as you haven't declared any Class as Department in your app/models/Department.rb .
So , what you need to do now is to declare a class name as Department in your models directory according to the @shani's answer :
class Department < ActiveRecord::Base
end
| |
doc_23529576
|
Currently I'm making a chat application using JavaFX, MQTT and Mysql.
I want to make an userlist (which user are online)
I tried this so that a new user would send a message through a special topic, and all will be "secretely" subscribing this topic it'll receive the message (using callback) and call the method insertingMysql() and updatingList(). But somehow it does not work.
This is where I give the username
public static void logging(String username) throws MqttException {
if(username != null && !username.isEmpty()) {
MysqlDatabase.insertingMysql(username);
window.close();
}
}
This is to add ListView
public static void addItem(String item) {
userList.getItems().add(item);
}
This is the part where I have problems with (I think)
public class MysqlDatabase {
static String topic_body = "chat";;
static String topic_ext = "userList";
static MqttCallback sqlCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable thrwbl) {
}
@Override
public void messageArrived(String string, MqttMessage mm) throws Exception {
String username = new String(mm.getPayload());
System.out.println(username); // Checking
updatingList();
}
@Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
}
};
public static void sqlConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Connected");
}
public static void mqttConnection(String username) throws MqttException {
MqttClient sqlClient = new MqttClient("tcp://iot.eclipse.org:1883", username);
sqlClient.connect();
sqlClient.subscribe(topic_body + topic_ext + "#");
sqlClient.setCallback(sqlCallback);
MqttMessage sqlMessage = new MqttMessage();
sqlMessage.setPayload((username).getBytes());
sqlClient.publish(topic_body + "userlist", sqlMessage);
}
public static void insertingMysql(String username) throws MqttException {
sqlConnection();
String host = "jdbc:mysql://localhost/test";
String user = "root";
String password = "";
try {
Connection connect = DriverManager.getConnection(host, user, password);
PreparedStatement statement = (PreparedStatement) connect.prepareStatement("INSERT INTO chat_test(username)VALUES(?)");
statement.setString(1, username);
statement.executeUpdate();
statement.close();
System.out.println("Inserted to database!");
mqttConnection(username);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
public static void updatingList() {
sqlConnection();
String host = "jdbc:mysql://localhost/test";
String user = "root";
String password = "";
try {
Connection connect = DriverManager.getConnection(host, user, password);
PreparedStatement statement = (PreparedStatement) connect.prepareStatement("SELECT * FROM chat_test");
ResultSet rs = statement.executeQuery();
while(rs.next()) {
String uName = rs.getString("username");
System.out.println("Username: " + uName);
JavaFXChat.addItem(uName);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
}
A: There are 2 options here:
*
*Database triggers. This is code that runs on the Database server when ever a table is changed. Normally these triggers are SQL statements but this blog (https://patternbuffer.wordpress.com/2012/09/14/triggering-shell-script-from-mysql/) post seams to talk about a plugin to support running a script that could send a MQTT message announcing the new user coming online.
*Use MQTT messages and the Last Will and Testament feature. A users would publish a message to known topic then they come online, they would publish a similar message when going offline. The LWT can be used to automatically publish the offline message if the connetion drops due to problem. (details of LWT can be found here http://www.hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament
| |
doc_23529577
|
A: You can call the linux command 'id' and redirect the output to a log file this way you will always know who invoked the script.
A: You can identify the process id of the Perl script's parent process with getppid. Then you can parse ps output or examine the /proc/<parent-pid> virtual file system to identify the parent.
Update: for your specific problem, wanting your Perl script to do something special if it was invoked by a certain bash script, it might be easier to set a special environment variable in the script. For example:
# special bash script
export SPECIAL=1
perl my_script.pl
# my_script.pl
...
do_something();
if ($ENV{SPECIAL}) {
print "Called from the special bash script\n";
send_email();
} else {
print "Not called from special bash script\n";
}
| |
doc_23529578
|
http://2.bp.blogspot.com/-yRuz5FO7T9k/TvM0yUAXQ5I/AAAAAAAAM0Y/uLB3oG6R8OI/s523/mapsmania.gif
The user must still be able to interact with the map, so I can't just put a "paper looking" div on top of the map and set opacity to some low number.
Any ideas how to achieve this? Preferably with css.
A: this screenshot is taken from http://www.ubilabs.net/kontakt
It's a simple map which is covered by a <div/> with a semi-transparent background-image(http://www.ubilabs.net/images/map_overlay.png)
To be able to interact with the map the pointer-events-style of this div is set to none
| |
doc_23529579
|
def fetch_frame(self):
context = zmq.Context()
footage_socket = context.socket(zmq.REP)
footage_socket.bind('tcp://*:5555')
while True:
frame = footage_socket.recv_string()
frame = frame.encode()
img = base64.b64decode(frame)
npimg = np.fromstring(img, dtype=np.uint8)
source = cv2.imdecode(npimg, 1)
Unfortunately, it is throwing the following error :
zmq.error.ZMQError: Operation cannot be accomplished in current state
What is the proper way to retrieve image using zmq?
UPDATE:
Following is the traceback :
File "/home/receive/main.py", line 77, in <module>
main()
File "/home/receive/main.py", line 73, in main
ci.fetch_frame()
File "/home/receive/main.py", line 59, in fetch_frame
frame = footage_socket.recv_string()
File "/home/.local/lib/python3.8/site-packages/zmq/sugar/socket.py", line 608, in recv_string
msg = self.recv(flags=flags)
File "zmq/backend/cython/socket.pyx", line 791, in zmq.backend.cython.socket.Socket.recv
File "zmq/backend/cython/socket.pyx", line 827, in zmq.backend.cython.socket.Socket.recv
File "zmq/backend/cython/socket.pyx", line 191, in zmq.backend.cython.socket._recv_copy
File "zmq/backend/cython/socket.pyx", line 186, in zmq.backend.cython.socket._recv_copy
File "zmq/backend/cython/checkrc.pxd", line 26, in zmq.backend.cython.checkrc._check_rc
zmq.error.ZMQError: Operation cannot be accomplished in current state
A:
Q : "ZMQError: Operation cannot be accomplished in current state"
The core reason is, that your code violated ZeroMQ REQ/REP documented properties.
Asking REP-instance to .send()-ed message before a REQ-instance has already "asked" its counterparty first, the API has to throw such error.
Similarly, if trying to .recv() a message on the REQ-side, before it has first "asked" by a .send() the REP-side ( to reply ), the API has to throw such error.
SOLUTION ?
In a case no other interaction is needed, a PUSH/PULL Scalable Formal Communication Pattern Archetype, where PUSH-side will .send() & the PULL-side will .recv(), is IMHO the best way ahead.
You might like to read more tips and links about this in this.
| |
doc_23529580
|
<index num="1">
<item key="0" xPos="100" yPos="214"/>
<item key="14" xPos="100" yPos="250"/>
<item key="28" xPos="100" yPos="286"/>
</index>
<index num="2">
<item key="146" xPos="100" yPos="134"/>
<item key="149" xPos="100" yPos="170"/>
</index>
<index num="3">
<item key="234" xPos="100" yPos="134"/>
</index>
i want use kissXML to parse this file
ie.
if num=1 only parse key= 0、14、28 and put them into an NSArray keyArray
if num=2 only parse key= 146、149 and put them into an NSArray keyArray
my code:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"xml"];
NSError* error = nil;
NSString *xmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
DDXMLDocument *xmlDoc = [[DDXMLDocument alloc]initWithXMLString:xmlString options:0 error:&error];
if (error) {
NSLog(@"%@",[error localizedDescription]);
}
xmlString = nil;
NSArray* resultNodes_1 = nil;
resultNodes_1 = [xmlDoc nodesForXPath:@"//index" error:&error];
NSArray* resultNodes = nil;
resultNodes = [xmlDoc nodesForXPath:@"//item" error:&error];
for(DDXMLElement* resultElement_1 in resultNodes_1)
{
NSString* keyVal_1 = [[resultElement_1 attributeForName:@"num"] stringValue];
NSMutableArray *key_1 = [[NSMutableArray alloc]init];
[key_1 addObject:keyVal_1];
[resultElement_1 childCount];
// NSLog(@"index: %d",[resultElement_1 childCount]);
if ([keyVal_1 isEqual:@"1"]) {
for(DDXMLElement* resultElement in resultNodes)
{
NSString* keyVal = [[resultElement attributeForName:@"key"] stringValue];
NSMutableArray *keyArray = [[NSMutableArray alloc]init];
[keyArray addObject:keyVal];
NSString* xPosVal = [[resultElement attributeForName:@"xPos"] stringValue];
NSMutableArray *xPosArray = [[NSMutableArray alloc]init];
[xPosArray addObject:xPosVal];
NSString* yPosVal = [[resultElement attributeForName:@"yPos"] stringValue];
NSMutableArray *yPosArray = [[NSMutableArray alloc]init];
[yPosArray addObject:yPosVal];
NSLog(@"key的值为:%@",keyVal);
}
}
}
from my code i want the result was key ----0、14、28
but the result is: key----0、14、28、146、149、234 print all key value
help me,plese
A: If you're going to go to the trouble of using xpath to do this anyway, you could just build a complete xpath expression and gather the data that way.
For example,
[xmlDoc nodesForXPath:@"//index[@num="2"]/item" error:&error];
Will return just the item nodes under index where num is 2.
So, you could build this path by using:
NSString *xpathPattern=
[NSString stringWithFormat: @"//index[@num=\"%d\"]/item", desiredValue];
NSArray* resultNodes = nil;
resultNodes = [xmlDoc nodesForXPath: xpathPattern error:&error];
And pass your desired value to that. At this point, you now have just:
<item key="0" xPos="100" yPos="214"/>
<item key="14" xPos="100" yPos="250"/>
<item key="28" xPos="100" yPos="286"/>
If you send in desiredValue = 1, and you can then pull out the key, xPos, and yPos as you have already defined in your inner loop.
| |
doc_23529581
|
[DataContract]
[Serializable]
public abstract class DimensionEntity
{
[DataMember(Order = 1)]
private readonly Date effectiveDatespan;
...
}
And the following derived class:
[DataContract]
[Serializable]
public class ClearingSite : DimensionEntity
{
[DataMember(Order = 1)]
private readonly string code;
...
}
When I serialize an instance of ClearingSite as follows:
model.Add(typeof(ClearingSite), true);
model.Serialize(ms, clearingSite);
I can see that only the code member of ClearingSite is serialized; the value of the base class' effectiveDatespan member is not serialized.
Two notes:
*
*I can see that the BaseType member of the added ProtoBuf.Meta.MetaType is set to null, causing the effectiveDatespan member to not be serialized; if I compile the model, instead, its BaseType member is correctly set to DimensionEntity (though it fails later on as the members are private readonly and thus not accessible by a compiled model);
*Of course I can declare ClearingSite as a known type of DimensionEntity, but I can't see why this would be required: I am not serializing a DimensionEntity, I'm serializing (and de-serializing) a ClearingSite, and furthermore the DataContractSerializer does not require me to add KnownType to DimensionEntity if I'm serializing a ClearingSite.
From other answers from Marc, it looks like Protobuf would require the KnownType (or ProtoInclude) attribute in order to get the "all-important field-number" (quote), but that seems to not be the case, as the CompiledModel works totally fine without ProtoInclude.
Note that I'm striving to use System.Runtime.Serialization attributes only, as I'm trying to keep my object model unaware of serializers down the road.
A: ProtoInclude, or an equivalent, is definitely required. If something is happening oddly with the compiled version, then that is a bug and I can investigate.
If you don't want to add non-BCL attributes to your type, this can be done at runtime:
RuntimeTypeModel.Default[typeof(BaseType)]
.AddSubClass(.....);
(or somethig like that - I'm not at a PC)
| |
doc_23529582
|
const fs = require('fs')
const { google } = require('googleapis')
const GOOGLE_API_FOLDER_ID = '1WONK0L9hDlNTfWKEYV1eyZXiXIw-yXAE'
const keyFile = 'D:\\AppEscritorio\\salud\\config.json'
const scopes = ['https://www.googleapis.com/auth/drive']
const auth = new google.auth.GoogleAuth({
keyFile,
scopes
})
const driveService = google.drive({
version: 'v3',
auth
})
async function subirImagen() {
try {
const fileMetadatafolder = {
name: 'nuevo folder',
parents: [GOOGLE_API_FOLDER_ID],
mimeType: 'application/vnd.google-apps.folder',
}
const file = await driveService.files.create({
resource: fileMetadatafolder,
fields: 'id'
})
console.log(file.data.id)
const fileMetaDataImg = {
'name': 'snowplace.png',
'parents': [file.data.id]
}
console.log(fd)
const media = {
mimeType: 'image/pmg',
body:fs.createReadStream('D:\\Users\\RJHR\\OneDrive\\Imágenes\\5x7.PNG')
}
const response = await driveService.files.create({
resource: fileMetaDataImg,
media: media,
field: 'id'
})
//return
console.log(response.data.id)
} catch (err) {
console.log('Upload file error', err)
}
}
subirImagen()
module.exports = { subirImagen }
when importing the function upload Imagen and run it from another achivo creates everything but the file with size 0 bit
as in the picture
displays the id of the folder and the created file
id folder and file
when running it on console con node google.js it raise it correctly
execute and print id
output
someone could explain this behavior, I clarify that it is the same code for both cases
this is the repositorye of de code https://github.com/Rafahur03/electron-salud.git
| |
doc_23529583
|
$list=array();
$stack=array();
in a for loop:
$list[]=array('something');
$stack[]=& end($list); //errors: Only variables should be assigned by reference
what am i doing wrong here? thanks for help.
A: Edited
$stack[] = &$list[count($list)-1]; //> Assuming numeric index incremental
or
end($list);
$stack[] = &$list[key($list)];
A: Objects will be always passed by reference in PHP 5.
EDITED
But if array is not a class then
$element = array();
$list[] = &$element;
$stack[] = &$element;
| |
doc_23529584
|
Some of this images used in my toolbar menu items as icon. I want to change the <item /> to be com.joanzapata.iconify.widget.IconTextView can i make that ?
I can add any item to my menu programmatically but this will make a big change in my code. Can any one help me to do that?
A: In your menu layout you should put something like :
<item
android:id="@+id/action_add"
android:title="@string/add"
app:showAsAction="ifRoom"
tools:visible="true" />
| |
doc_23529585
|
When I try to import a Grails project though (which is a Subversion repository), it is painfully slow, before it finally gives up:
The command 'C:\Program Files\Java\jdk1.6.0_45\bin\javaw.exe (4 Sep
2014 12:10:28)' was terminated because it didn't produce new output
for some time.
See details for the output produced so far.
If you think the command simply needed more time, you can increase the
time limit in the Grails preferences page.
See menu Windows >> Preferences >> Grails >> Launch Command:
C:\Program Files\Java\jdk1.6.0_45\bin\javaw.exe (4 Sep 2014 12:10:28)
---- System.out ---- | Loading Grails 2.1.4 | Configuring classpath | Downloading:
C:\Users\607534885\Software\grails-2.1.4\plugins\database-migration-1.3.2.pom
| Downloading:
C:\Users\607534885\Software\grails-2.1.4\lib\org.liquibase\liquibase-core\ivy-2.0.5.xml
| Downloading:
C:\Users\607534885\Software\grails-2.1.4\plugins\jquery-1.8.3.pom
---- System.err ----
Terminating process: Timeout: no new output for 180000 milliseconds
------System.out:----------- | Loading Grails 2.1.4 | Configuring classpath | Downloading:
C:\Users\607534885\Software\grails-2.1.4\plugins\database-migration-1.3.2.pom
| Downloading:
C:\Users\607534885\Software\grails-2.1.4\lib\org.liquibase\liquibase-core\ivy-2.0.5.xml
| Downloading:
C:\Users\607534885\Software\grails-2.1.4\plugins\jquery-1.8.3.pom
------System.err:-----------
Terminating process: Timeout: no new output for 180000 milliseconds
Why is Grails proving to be so slow? Or is this an issue with something else?
A: Figured it out. Rather pointless question in the end. We have an aggressive firewall in work and I simply needed to use a wifi connection instead as importing the project for the first time required third party software to be installed. Simples in the end.
| |
doc_23529586
|
/my_stereo/left/camera_info
/my_stereo/left/image_raw
/my_stereo/right/camera_info
/my_stereo/right/image_raw
/my_stereo_both/parameter_descriptions
/my_stereo_both/parameter_updates
/my_stereo_l/parameter_descriptions
/my_stereo_l/parameter_updates
/my_stereo_r/parameter_descriptions
How can I do this? Any help is truly appreciated!
A: You can use:
http://wiki.ros.org/stereo_image_proc
You can change the publish topic name according to the documentation.
A: This tutorial provides an example, how exactly to publish the images.
I'm struggling with the disparity topic and posted a question here.
According to the already mentioned tutorial from 2016, the stereo_image_proc node was supposed to do a lot of job, but it looks like that it doesn't exist in ROS2 version. There are two nodes: disparity_node and point_cloud_node.
| |
doc_23529587
|
A: It sounds like what you are seeing is the cached screenshot the iOS system is making of your app just before it puts it into the background.
This is handled automatically, and you do have the opportunity to intercept this.
Check out this answer, you can put an image over your app just as it's entering the background, this will be cached and used to relaunch the app.
A: Looking at the screenshots in the App Store of the application you mention, it looks like there's just a UIImageView at the back of the view hierarchy for the main menu. You can change this by assigning a UIImage object to its image property.
A: Suppose you want to change one or more view's background images, depending on the application launch.
Save an int x = 0 into NSUserDefaults. On each application launch increment it by 1. When you are to present a view, check that int and set a background image like this:
switch(x%3){// %3 just to make it a bit random
case 0://set this image;
break;
case 1://set that image
break;
//and so on
}
A: add background_0.png, background_1.png, background_2.png, background_3.png etc to your project.
#define max_image_number 3
Add the following to your viewDidLoad method:
-(void)viewDidLoad {
[super viewDidLoad];
[self updatedBackgroundImage];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBackgroundImage) name:UIApplicationWillEnterForegroundNotification object:nil];
}
-(void) updateBackgroundImage{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults integerForKey:@"imageNumber"]) {
[defaults setInteger:0 forKey:@"imageNumber"];
}
int i = [defaults integerForKey:@"imageNumber"];
myUIimageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"background_%d.png",i]];
i++;
if (i > max_image_number) {
[defaults setInteger:0 forKey:@"imageNumber"];
}else{
[defaults setInteger:i forKey:@"imageNumber"];
}
...
}
The above will update the image when the viewController is first loaded and also when it returns from running in the background. I assume this is what was missing for you :).
Remember to stop listening for the notification in the viewDidUnload method and you should be set.
| |
doc_23529588
|
A: The files and directories within a repository determine the languages that make up the repository. You can view a repository's languages to get a quick overview of the repository.
GitHub uses the open source Linguist library to determine file languages for syntax highlighting and repository statistics. Language statistics will update after you push changes to your default branch (which is usually master).
This is your project:
In your case, there are 1 CSS file and 1 JS file, so you can open an issue here regarding the misidentification your repo.
If you want to change the repo languages you can read the How to Change Repo Language in GitHub article.
| |
doc_23529589
|
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
I was hoping/expecting that whenever Android launched my app and created my custom Application object, it would always start my SplashActivity. However, some of my users have encountered launches where one of my "internal" activities which have no intent-filter are started. I believe that activity was typically the last activity used in a previous invocation of the app. I have not been able to reproduce the issue myself. However, is there some scenario where Android will launch my app, creating my custom Application object, but starting one of my internal activities that has no intent-filter. Under what circumstances will Android do so?
To easily reproduce the scenario where Android application launch starts an activity that has no intent-filter, first open your application to any such activity. Press the Home button. Then using Android Device Monitor (DDMS) to find the process that is running your application and stop/kill that process. Then launch your app. Android will create your Application object but will start/restore the activity that was last displayed instead of the starting the one with the MAIN LAUNCHER intent-filter.
A: Android can kill the OS process hosting your app at any time. Usually this happens when your app has been in the background for a while (ie: the user navigated away from your app to go do something else). This happens all the time.
When the user then returns to your app, Android creates a new OS process for the app, and creates a new instance of the Activity that was on the top of the stack (ie: the Activity that was showing on screen before the app was pushed to the background).
If you don't want this to happen, you can add the following attribute to the <activity> declaration for SplashActivity:
android:clearTaskOnLaunch="true"
This will force Android to always restart your app from the beginning if your user returns to it. However, this might make your users complain, because if the user is using your app, then takes a phone call, then returns to your app, it will start from the beginning again.
It is better if you detect the problem yourself, and redirect to the SplashActivity only when necessary (ie: when your app needs to be initialized because the process has been killed and restarted). To do this, declare a static variable named initialized in SplashActivity that you set to true when your SplashActivity has successfully initialized the app. In every other Activity, do this in onCreate():
super.onCreate(savedInstanceState);
if (!SplashActivity.initialized) {
// Android killed my process, need to redirect the user to `SplashActivity`
redirectIntent = new Intent(this, SplashActivity.class);
startActivity(redirectIntent);
finish();
return;
}
A: This happens when the application is still "alive".
When you exit an application, Android does not kill it. It will remain there until the memory is needed.
In this case, when the use re-launches it he will get the last Activity.
A: Can you try adding
android:clearTaskOnLaunch
for the root activity in your manifest file.
| |
doc_23529590
|
For example in the matrix below, there are convex connections between faces 1 and 2, 1 and 3, 2 and 3 and so on.
1 2 3 4 5 6
1 [[ 0. 1. 1. 0. 0. 0.]
2 [ 0. 0. 1. 1. 1. 1.]
3 [ 0. 0. 0. 0. 0. 0.]
4 [ 0. 0. 0. 0. 1. 0.]
5 [ 0. 0. 0. 0. 0. 0.]
6 [ 0. 0. 0. 0. 0. 0.]]
Id like to be able to record how many concave and convex connections each face has.
i.e. Face 1 has: 0 concave and 2 convex connections
Possibly even record which faces they are connected to.
i.e. Face 1 has: 0 concave and 2 convex (2, 3) connections
So far I have tried using np.nonzero() to return the indices of the 1's. However this returns the indices in a format which doesn't seem to be very easy to work with (a separate array for the row and column indices:
(array([ 0, 0, 1, 1, 1, 1, 3]), array([ 1, 2, 2, 3, 4, 5,
4]))
Can anyone help me with an easier way to carry out this task? Thanks
A: try this:
import numpy as np
a=np.matrix([[0,1,1,0,0,0],
[ 0,0,1,1,1,1],
[ 0,0,0,0,0,0],
[ 0,0,0,0,1,0],
[ 0,0,0,0,0,0],
[ 0,0,0,0,0,0]]).astype(float)
concave={}
convex={}
for i,j in zip(np.nonzero(a)[0]+1,np.nonzero(a)[1]+1):
if j > i :
if i not in convex.keys():
convex[i]=[]
if j not in convex.keys():
convex[j]=[]
convex[i].append(j)
convex[j].append(i)
else :
if i not in concave.keys():
concave[i]=[]
if j not in concave.keys():
concave[j]=[]
concave[i].append(j)
concave[j].append(i)
print 'concave relations : {} and number of relations is {}'.format(concave,sum(len(v) for v in concave.values()))
print 'convex relations : {} and number of relations is {}'.format(convex,sum(len(v) for v in convex.values()))
gives the result :
concave relations : {} and number of relations is 0
convex relations : {1: [2, 3], 2: [1, 3, 4, 5, 6], 3: [1, 2], 4: [2, 5], 5: [2, 4], 6: [2]} and number of relations is 14
where the dictionary key is the name of the face and key values are it's connections.
Logic is :
for every non-zero pair (i,j)
*
*if i>j then j is the concave connection of face i & i is the concave connection of face j
*if j>i then j is the convex connection of face i & i is the convex connection of face j
A: import numpy as np
A = np.array([[0, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
convex = np.triu(A, 1) # upper triangle
concave = np.tril(A, -1) # lower triangle
convex_indices = list(zip(np.nonzero(convex)[0] + 1, np.nonzero(convex)[1] + 1))
concave_indices = list(zip(np.nonzero(concave)[0] + 1, np.nonzero(concave)[1] + 1))
num_convex = len(convex_indices)
num_concave = len(concave_indices)
print('There are {} convex connections between faces: {}'.format(num_convex, ', '.join(str(e) for e in convex_indices)))
print('There are {} concave connections between faces: {}'.format(num_concave, ', '.join(str(e) for e in concave_indices)))
# will print:
# There are 7 convex connections between faces: (1, 2), (1, 3), (2, 3), (2, 4), (2, 5), (2, 6), (4, 5)
# There are 0 concave connections between faces:
| |
doc_23529591
|
i keep getting this warning when i try to build th project
warning: conditional expression of distinct Objective-C types 'UIImage*' and 'UIButton*' lacks a cast
is there any thing i can do about it?
#import "avTouchController.h"
#include "CALevelMeter.h"
// amount to skip on rewind or fast forward
#define SKIP_TIME 1.0
// amount to play between skips
#define SKIP_INTERVAL .2
@implementation avTouchController
@synthesize fileName;
@synthesize playButton;
@synthesize ffwButton;
@synthesize rewButton;
@synthesize volumeSlider;
@synthesize progressBar;
@synthesize currentTime;
@synthesize duration;
@synthesize lvlMeter_in;
@synthesize updateTimer;
@synthesize player;
@synthesize inBackground;
void RouteChangeListener( void * inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void * inData);
-(void)updateCurrentTimeForPlayer:(AVAudioPlayer *)p
{
currentTime.text = [NSString stringWithFormat:@"%d:%02d", (int)p.currentTime / 60, (int)p.currentTime % 60, nil];
progressBar.value = p.currentTime;
}
- (void)updateCurrentTime
{
[self updateCurrentTimeForPlayer:self.player];
}
- (void)updateViewForPlayerState:(AVAudioPlayer *)p
{
[self updateCurrentTimeForPlayer:p];
if (updateTimer)
[updateTimer invalidate];
if (p.playing)
{
[playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal];
[lvlMeter_in setPlayer:p];
updateTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateCurrentTime) userInfo:p repeats:YES];
}
else
{
[playButton setImage:((p.playing == YES) ? pauseBtnBG : playBtnBG) forState:UIControlStateNormal];
[lvlMeter_in setPlayer:nil];
updateTimer = nil;
}
}
- (void)updateViewForPlayerStateInBackground:(AVAudioPlayer *)p
{
[self updateCurrentTimeForPlayer:p];
if (p.playing)
{
[playButton setImage:((p.playing == YES) ? rewButton : playBtnBG) forState:UIControlStateNormal]; (this is where i have problems)
}
else
{
[playButton setImage:((p.playing == YES) ? rewButton : playBtnBG) forState:UIControlStateNormal];
}
}
-(void)updateViewForPlayerInfo:(AVAudioPlayer*)p
{
duration.text = [NSString stringWithFormat:@"%d:%02d", (int)p.duration / 60, (int)p.duration % 60, nil];
progressBar.maximumValue = p.duration;
volumeSlider.value = p.volume;
}
- (void)rewind
{
AVAudioPlayer *p = rewTimer.userInfo;
p.currentTime-= SKIP_TIME;
[self updateCurrentTimeForPlayer:p];
}
- (void)ffwd
{
AVAudioPlayer *p = ffwTimer.userInfo;
p.currentTime+= SKIP_TIME;
[self updateCurrentTimeForPlayer:p];
}
- (void)awakeFromNib
{
// Make the array to store our AVAudioPlayer objects
soundFiles = [[NSMutableArray alloc] initWithCapacity:3];
playBtnBG = [[UIImage imageNamed:@"play.png"] retain];
pauseBtnBG = [[UIImage imageNamed:@"pause.png"] retain];
rewButton = [[UIImage imageNamed:@"rewind.png"] retain];
[playButton setImage:playBtnBG forState:UIControlStateNormal];
[self registerForBackgroundNotifications];
updateTimer = nil;
rewTimer = nil;
ffwTimer = nil;
duration.adjustsFontSizeToFitWidth = YES;
currentTime.adjustsFontSizeToFitWidth = YES;
progressBar.minimumValue = 0.0;
// Load the array with the sample file
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"My Song" ofType:@"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
if (self.player)
{
fileName.text = [NSString stringWithFormat: @"%@ (%d ch.)", [[player.url relativePath] lastPathComponent], player.numberOfChannels, nil];
[self updateViewForPlayerInfo:player];
[self updateViewForPlayerState:player];
player.numberOfLoops = 0;
player.delegate = self;
}
OSStatus result = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (result)
NSLog(@"Error initializing audio session! %d", result);
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError)
NSLog(@"Error setting category! %d", setCategoryError);
result = AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, RouteChangeListener, self);
if (result)
NSLog(@"Could not add property listener! %d", result);
[fileURL release];
}
-(void)pausePlaybackForPlayer:(AVAudioPlayer*)p
{
[p pause];
[self updateViewForPlayerState:p];
}
-(void)startPlaybackForPlayer:(AVAudioPlayer*)p
{
if ([p play])
{
[self updateViewForPlayerState:p];
}
else
NSLog(@"Could not play %@\n", p.url);
}
- (IBAction)playButtonPressed:(UIButton *)sender
{
if (player.playing == YES)
[self pausePlaybackForPlayer: player];
else
[self startPlaybackForPlayer: player];
}
- (IBAction)rewButtonPressed:(UIButton *)sender
{
if (rewTimer) [rewTimer invalidate];
rewTimer = [NSTimer scheduledTimerWithTimeInterval:SKIP_INTERVAL target:self selector:@selector(rewind) userInfo:player repeats:YES];
}
- (IBAction)rewButtonReleased:(UIButton *)sender
{
if (rewTimer) [rewTimer invalidate];
rewTimer = nil;
}
- (IBAction)ffwButtonPressed:(UIButton *)sender
{
if (ffwTimer) [ffwTimer invalidate];
ffwTimer = [NSTimer scheduledTimerWithTimeInterval:SKIP_INTERVAL target:self selector:@selector(ffwd) userInfo:player repeats:YES];
}
- (IBAction)ffwButtonReleased:(UIButton *)sender
{
if (ffwTimer) [ffwTimer invalidate];
ffwTimer = nil;
}
- (IBAction)volumeSliderMoved:(UISlider *)sender
{
player.volume = [sender value];
}
- (IBAction)progressSliderMoved:(UISlider *)sender
{
player.currentTime = sender.value;
[self updateCurrentTimeForPlayer:player];
}
- (void)dealloc
{
[super dealloc];
[fileName release];
[playButton release];
[ffwButton release];
[rewButton release];
[volumeSlider release];
[progressBar release];
[currentTime release];
[duration release];
[lvlMeter_in release];
[updateTimer release];
[player release];
[playBtnBG release];
[pauseBtnBG release];
}
#pragma mark AudioSession handlers
void RouteChangeListener( void * inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void * inData)
{
avTouchController* This = (avTouchController*)inClientData;
if (inID == kAudioSessionProperty_AudioRouteChange) {
CFDictionaryRef routeDict = (CFDictionaryRef)inData;
NSNumber* reasonValue = (NSNumber*)CFDictionaryGetValue(routeDict, CFSTR(kAudioSession_AudioRouteChangeKey_Reason));
int reason = [reasonValue intValue];
if (reason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
[This pausePlaybackForPlayer:This.player];
}
}
}
#pragma mark AVAudioPlayer delegate methods
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)p successfully:(BOOL)flag
{
if (flag == NO)
NSLog(@"Playback finished unsuccessfully");
[p setCurrentTime:0.];
[self updateViewForPlayerState:p];
}
- (void)playerDecodeErrorDidOccur:(AVAudioPlayer *)p error:(NSError *)error
{
NSLog(@"ERROR IN DECODE: %@\n", error);
}
// we will only get these notifications if playback was interrupted
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)p
{
NSLog(@"Interruption begin. Updating UI for new state");
// the object has already been paused, we just need to update UI
if (inBackground)
{
[self updateViewForPlayerStateInBackground:p];
}
else
{
[self updateViewForPlayerState:p];
}
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)p
{
NSLog(@"Interruption ended. Resuming playback");
[self startPlaybackForPlayer:p];
}
#pragma mark background notifications
- (void)registerForBackgroundNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(setInBackgroundFlag)
name:UIApplicationWillResignActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearInBackgroundFlag)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
- (void)setInBackgroundFlag
{
inBackground = true;
}
- (void)clearInBackgroundFlag
{
inBackground = false;
}
@end
EDIT: I have already tried RewBtnBG but it says not declared in this scope. Any thing to fix that?
A: [playButton setImage:((p.playing == YES) ? rewButton : playBtnBG) forState:UIControlStateNormal];
newButton is a UIButton and playBtnBG is a UIImage I guess. Possibly you really wanted (guesssing from your naming conventions for other images).
[playButton setImage:((p.playing == YES) ? rewBtnBG : playBtnBG) forState:UIControlStateNormal];
| |
doc_23529592
|
import java.io.IOException;
public class Sample {
public static void main(String[] args) throws IOException {
int b = 3;
int c = 5;
char mov;
while(b != c) {
System.out.println("Your next move?");
mov = (char)System.in.read();
System.out.println(mov);
}
}
}
and the output:
Your next move?
b
b
Your next move?
Your next move?
Your next move?
why Your next move? is printed 3 times in a row without other codes in while loop be executed?
| |
doc_23529593
|
When I instantiate the map using the default color palette, it loads very quickly in IE 11 and Edge. Here is the fiddle.
However, when I define a custom color palette using the colors property of the highcharts object or setting the color property in the map data, the colors do not appear until regions are hovered over. Also, the legend indicates all regions are black despite the custom color palette. Here is the fiddle.
$(function () {
var md = mapData[0].data;
$('#container').highcharts('Map', {
title : { text : 'COCOMs' },
colors: ["#6cc2c8ff", "#3a784cff",
"#c4b9c9ff", "#d3eafaff",
"#afd5acff", "#e4cf8cff"],
series: jQuery.map(md, function(element, index) {
var seriesElement = {
type: 'map',
joinBy: 'name',
name: element.name,
data: new Array({name:element.name, value:index}),
mapData: new Array(element),
_colorIndex: index
};
return seriesElement;
})
});
});
Something different happens in Chrome and FireFox, but it still does not seem right.
What am I doing wrong?
| |
doc_23529594
|
I'm tired of doing the same old crap and want to learn something new but every time I sit and look at things to learn...I get overloaded with information. from c# to python..ruby to groovy and 10's of frameworks. where should a guy start?
And If I pick one, I dont want to just pick a book and read page to page while typing code proved in the book. So should I plan out my little project first?
Are there any de facto projects that one can try to implement while learning a new language. These projects would try to cover all aspects to the related domain (web/standalone).
what did you do when you learned your second language?
A: Start with the HelloWorlds of a few languages and see where that takes you. The only real way to start, is to start!
A: You might take a look at CodeKata and see if it's what you're after. They're not really very big projects, but they're good practice.
I usually try to write a Sudoku Solver as my first "real" project in a new language. Once I can do that, I feel pretty confident that I have the basics of the language under control.
A: One way to work with some standard problems is to use Project Euler: http://projecteuler.net/
This is a series of mathematical problems that require programming to solve, some of which can be quite challenging. People use all kinds of languages for this (you can see a language breakdown on the site). However, you need to be into maths somewhat.
A: Here are some things that I find help when learning a new language (and they may not work for you):
*
*Get a spec. You will make mistakes, and so you need to know how to use things properly, not how a tutorial might say.
*Start it small. What counts as 'small' to you depends on your prior programming experience. Console applications are good because they're simple and let you get familiar with the language without having to deal with a graphical framework.
*Have a defined goal. It could be something like writing a simple calculator, a puzzle solver, or some exercises - Project Euler is a common favorite, but I also enjoy the Candian Computing Competition problems - I find they tend to be less abstract than Project Euler.
*Learn the language's paradigm. Don't try to do something the language isn't meant to do. This is one of the most important bits - if you try to code Lisp in C, you will know only pain. If you are learning Erlang, use the process model, or else you really aren't learning the language. It's important not to try to force the language to do things it can't, or else you won't enjoy it. You will find this tough, especially given that you're a Java programmer who's been indoctrinated with The One True Object-Oriented Way (tip: it's not).
A: By far, the language that I have learned the most from is lisp. Pick up ANSI Common Lisp or On Lisp by Paul Graham. Read, eval, print, learn.
A: Mini web servers and strange twitter clients seem to be the rage. And, as you know, writing a blogging platform is the new "Hello, World"
I like to dive in to precision when I'm picking up a new language, for instance, what do I have to learn about the language in order to handle unicode? How can I handle localization? What does IPC look like ... how do I manage threads? Usually helps me write more serious things faster.
A: The way I learn a new language is to port the programs I've already coded into the new language
A: IMHO, it's always easier to pick up a new language or framework if you have a real problem you want to solve while learning. Try to find an interesting, non-trivial problem either at work or just a personal itch you want to scratch then dive in and start using the tool you want to learn. Writing "Hello, World!" for the umpteenth time will only get you so far.
A: I would recommend a code kata as Bill the Lizard did. This has been very successful for me recently. I've been ASP.NET/C# developer but had to learn Ruby on Rails for a recent project.
Because I was already doing a code kata to learn the keyboard shortcuts is Visual Studio, I had a project I could duplicate in a new language without having to make decisions about how I'd develop it. I already had the solution. At this point it was just about translating it into a new language.
I think that gave me a better jump on getting into Ruby because I could make associations with what I had already done in C# and close the knowledge gap between the two languages.
A: I became bored of Java with database applications myself as well.
I watched this iPhone course in Stanford University and became excited about Objective-C and iPhone programming
you can find video of all the lectures link text
| |
doc_23529595
|
for example :
start_date = 2011-09-01
end_date = 2011-09-15
Now it should give the out put
2011-09-03
2011-09-04
2011-09-10
2011-09-11
Any help really appreciate.
A: >>> import datetime
>>> start = datetime.datetime.strptime("2011-09-01", "%Y-%m-%d")
>>> end = datetime.datetime.strptime("2011-09-15", "%Y-%m-%d")
>>> while start <= end:
... if start.weekday() in (5, 6):
... print start.strftime("%Y-%m-%d")
... start += datetime.timedelta(days=1)
...
2011-09-03
2011-09-04
2011-09-10
2011-09-11
>>>
A: Well, I think this should work:
from datetime import datetime, timedelta
def daterange(start_date, end_date):
for n in range((end_date - start_date).days):
yield start_date + timedelta(n)
start_date = '2011-09-01'
end_date = '2011-09-15'
format = '%Y-%m-%d'
start_date_object = datetime.strptime(start_date, format)
end_date_object = datetime.strptime(end_date, format)
for day in daterange(start_date_object, end_date_object):
if day.weekday() in [5, 6]:
print day.strftime(format)
| |
doc_23529596
|
I do this
nomy_gctoo.col_metadata_df
And get this
Empty DataFrame
Columns: []
Index: [REP.A001_A375_24H_X1_B22:A03, REP.A001_A375_24H_X1_B22:A04, REP.A001_A375_24H_X1_B22:A05, REP.A001_A375_24H_X1_B22:A06, REP.A001_A375_24H_X1_B22:A07, REP.A001_A375_24H_X1_B22:A08, REP.A001_A375_24H_X1_B22:A08, ...]
How i can get array of index names?
A: Try .index:
arr = nomy_gctoo.col_metadata_df.index
L = nomy_gctoo.col_metadata_df.index.tolist()
| |
doc_23529597
|
def checkPrice():
old_price = 0.0
current_price = soup.find("div", class_="fund-price").get_text()
current_price = (current_price.lstrip("€"))
current_price = float(current_price[0:4])
print("old price is: ", old_price)
print("current price is: ", current_price)
if(current_price != old_price):
old_price = current_price
sendEmail()
while(True):
checkPrice()
time.sleep(3600)
A: You're setting old_price back to 0 every time checkPrice is called. The function doesn't "remember" values from previous invocations.
Instead, you could:
*
*make it a parameter that gets passed and returned, keep track of it in the calling function.
*turn it into a generator, which keeps track of its internal state.
*make a class and store the price as an instance variable.
Option 1 is the simplest:
def checkPrice(old_price):
current_price = soup.find("div", class_="fund-price").get_text()
current_price = (current_price.lstrip("€"))
current_price = float(current_price[0:4])
print("old price is: ", old_price)
print("current price is: ", current_price)
if(current_price != old_price):
sendEmail()
return current_price
price = 0.0
while(True):
price = checkPrice(price)
time.sleep(3600)
| |
doc_23529598
|
SELECT DISTINCT * FROM registrants WHERE (paid='Y' AND course_id = '$course_info[0]' AND course_date = '$course_info[1]')
Can anyone tell me what is doing that?
Here is the rest of the code!!!
We want to get the results of the registrants that have paid. But when you generate the report it gives us the same; lets say 8 registrants once, then two times, then three and so on and so on until it shows each registrant at least 8 times
$course_report = $_POST['course_report'];
$course_info = explode('~',$course_report);
$course_info[0]; // course_id
$course_info[1]; // course_date
$select = "SELECT DISTINCT * FROM registrants WHERE (paid='Y' AND course_id = '$course_info[0]' AND course_date = '$course_info[1]')";
$result = mysql_query($select);
while($row = mysql_fetch_assoc($result))
{
$course = $row['course'];
$coursedate = $row['course_date'];
$export = mysql_query($select);
$fields = mysql_num_fields($export);
// Get header
for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . "\t";
}
// Get rows
while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
A: You're selecting all columns from the table even though you're only filtering on three. Chances are that one of your columns has different data for each registrant. What do you want to be distinct? If you just want those three columns, then SELECT DISTINCT PAID, COURSE_ID, COURSE_DATE instead of all columns.
| |
doc_23529599
|
A: Do not automatically add knowledge about what a user prefers to generate a toolbar. Having a dynamically generated toolbar is confusing for users. It's fine if your configuration bar makes suggestions dynamically (i.e. suggesting buttons), but changing the layout itself is evil.
A: I think a toolbar makes a good aesthetic, but if you merely want to seperate parts of the app then a Tab bar makes more sense for usability.
With the advent of tabbed browsing, every user understands the tab concept.
A: Sure. Firefox has something similar in their 'Bookmarks Toolbar'.
Peachtree Accounting also has a toolbar like this, as do many others.
Tabbing is OK as long as there aren't too many.
Would be real good if the user could personalize the toolbar themselves. Sometimes I don't only want places I frequent, but screens that I use occasionally that are hard to find through menus or whatnot.
A: To me, this looks like a job for a menu with a MRU list, or support 'Add to Favorites'.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.