text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Make Selectable True for only given date range in React Big Calendar I am using React Big Calendar. By Default selectable true make the whole calendar selectable but I want to make only selectable true of given time and change the background color of that time range in the calendar. I am not willing to create event. Just make selectable true of given times.
Thanks
A: I found a solution that may help you to disable some dates , in my case , I needed to disable unavailability events, so I used selectable="ignoreEvents"
`<BigCalendar
selectable="ignoreEvents"
localizer={localizer}
events={events}
views={allViews}
step={60}
showMultiDayTimes
defaultDate={new Date()}
defaultView={BigCalendar.Views.WEEK}
style={{height: "90vh" }}
resources={resourceMap}
resourceIdAccessor="resourceId"
resourceTitleAccessor="resourceTitle"
onSelectSlot={this.handleSelect}
eventPropGetter={(this.eventStyleGetter)}
/>`
use eventPropGetter to style you events
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53184562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to hook api calls in another application I am trying to hook the ExtTextOut and DrawTextExt GDI method calls of another application.
I know that I need to Use GetProcAddress to find the address of those methods in gdi32.dll, and overwrite the address in the process I want to hook with the address of my function. Then in my function I do what I need, then call the original function.
I want to make this hook functionality available to .net applications, and apparently this is do-able by creating an 'intermediate' unmanaged dll that does the hooking, and is capable of firing a event on the .net side, so that the new function can bet written in the managed environment. I'm just not sure how to implement this. Does anyone have any code samples or links to information?
A: I would recommend Microsoft's Detours (C++ x86 only) or EasyHook (C++ & C#, x86/x64).
http://easyhook.codeplex.com/
I've used it before, works pretty well. You have to pass a function or address and where you want it redirected to, and you can have all calls (for all processes or a specific one) sent into your function. The tutorials cover most of the basics, but I can edit code into this answer if you'd like.
A bit of trivia is that it also works the other way. Pass a pointer to your function and you can redirect calls into external code. Makes for some interesting integration with old apps or closed-source ones.
A: You can use Deviare API Hook, use DeviareCSharpConsole that is a tool that is in the package that let you hook any API and see parameter values in a treeview-like control.
The only trick that it needs in Windows7 is to be load as admin, I reported.
A: How I Built a Working Poker Bot has samples of injecting code and hooking gdi events.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3464366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Jasper Report graph in iReport repeating I have a line graph in iReport which is incrementally repeating in every page, that is, if the graph has 30 x/y pairs (this is dynamic), the report will have 30 pages, of which the first will have just one value, the 2nd two values, and so on. Only the last one will contain the complete graph.
Questions "chart repeat many time" and "Problem with charting using JasperReport" and "How to print the grand total only in the last page of a very long report?" did not solve my problem. I understand that putting the chart in the Detail section makes the chart repeat, but putting it in the Summary, Footer, lastPageFooter, Title, etc. sections makes it display only one value. Same when I put it in the Detail section and use <printWhenExpression>.
My code:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="nodes-allarmipersistenti" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<field name="day" class="java.lang.Number"/>
<field name="month" class="java.lang.String"/>
<field name="year" class="java.lang.String"/>
<field name="dsunita" class="java.lang.String"/>
<field name="valueNumber" class="java.lang.Number"/>
<field name="logo" class="java.lang.String"/>
<field name="today" class="java.lang.String"/>
<field name="option" class="java.lang.String"/>
<title>
<band height="89">
<staticText>
<reportElement mode="Opaque" x="0" y="67" width="424" height="22" backcolor="#CCFFFF"/>
<textElement textAlignment="Right" verticalAlignment="Middle" markup="none">
<font size="10" isBold="true" pdfFontName="Helvetica-Bold" isPdfEmbedded="true"/>
</textElement>
<text><![CDATA[GRAFICO PARAMETRO]]></text>
</staticText>
<staticText>
<reportElement x="600" y="0" width="100" height="38"/>
<textElement verticalAlignment="Middle"/>
<text><![CDATA[Stampato in data]]></text>
</staticText>
<textField>
<reportElement x="700" y="0" width="102" height="38"/>
<textElement textAlignment="Right" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{today}]]></textFieldExpression>
</textField>
<image>
<reportElement x="0" y="0" width="100" height="67"/>
<imageExpression><![CDATA[$F{logo}]]></imageExpression>
</image>
<staticText>
<reportElement x="700" y="38" width="102" height="29"/>
<textElement textAlignment="Right"/>
<text><![CDATA[MaRe - Telecontrollo]]></text>
</staticText>
<textField>
<reportElement mode="Opaque" x="424" y="67" width="378" height="22" backcolor="#CCFFFF"/>
<textElement verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[' ' + $F{option}]]></textFieldExpression>
</textField>
</band>
</title>
<lastPageFooter>
<band height="387" splitType="Stretch">
<xyLineChart>
<chart evaluationTime="Page">
<reportElement x="0" y="0" width="802" height="387"/>
<chartTitle/>
<chartSubtitle/>
<chartLegend/>
</chart>
<xyDataset>
<dataset incrementType="Report"/>
<xySeries>
<seriesExpression><![CDATA["Unità " + $F{dsunita}]]></seriesExpression>
<xValueExpression><![CDATA[$F{day}]]></xValueExpression>
<yValueExpression><![CDATA[$F{valueNumber}]]></yValueExpression>
</xySeries>
</xyDataset>
<linePlot>
<plot/>
</linePlot>
</xyLineChart>
</band>
</lastPageFooter>
</jasperReport>
Datasource here is a JRBeanCollectionDataSource.
A: Putting it in the Detail band is wrong (as you noticed). Putting it in the Title or Summary will work. Your choice of evaluationTime="Page" doesn't look right. Try changing this to evaluationTime="Report"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9564001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I use two different custom UITableViewCell subclasses in a single table? How to I properly display to different UITableViewCell subclasses within the same UITableView?
I am using the storyboard for this question. I am trying to use two different subclasses of UITableView cell in a single table. The idea that TTTextFieldCells know how to show a text box and TTPickerCells know how to present a UIPicker to the user. There the protocol TTTableViewCell specifies a single selector: [setCellDetails (NSDictionary*) cellDetails] Each UITableViewCell subclass knows what to do with the cellDetails Dictionary to setup the cell.
-(NSArray *)tableData {
if (!_tableData) {
_tableData =
@[ // Sections
@{ // Section Details
kSectionName:@"Scout Information"
,kRows:@[ // Rows
@{// Cell Details
kBoundProperty:self.scoutName
,kReuseIdentifier:kTextFieldCell
,kLabel:@"Name"
,kPlaceholderValue:@"Scout's Name"
}
,@{
kReuseIdentifier:@"TTPickerCell"
,kLabel:@"Type"
,kPlaceholderValue:@"Cadet, Junior, etc..."
}
,@{
kBoundProperty:self.yearsScouting
,kReuseIdentifier:kTextFieldCell
,kLabel:@"Years"
,kPlaceholderValue:@"Years of Experience"
,kKeyboardStyle:@(UIKeyboardTypeNumberPad)
}
]
}
,@{ // Section Details
kSectionName:@"Parent Information"
,kRows:@[
@{
kBoundProperty:self.parentName
,kReuseIdentifier:kTextFieldCell
,kLabel:@"Name"
,kPlaceholderValue:@"Parents's Name"
}
]
}
];
}
return _tableData;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// Line A
[self.tableView registerClass:[TTTextFieldCell class] forCellReuseIdentifier:@"TTTextFieldCell"];
// Line B
[self.tableView registerClass:[TTPickerCell class] forCellReuseIdentifier:@"TTPickerCell"];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row];
NSString* reuseIdentifier = cellDetails[kReuseIdentifier];
// Line C
UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
[cell setCellDetails:cellDetails];
return cell;
}
Now, here is the question. If I comment out line A and B, then the TTTextFieldCells are displayed correctly. But Line C will fail because it is attempting to call the TTTextFieldCell init with a TTPickerCell object, and failing because the TTPickerCell object doesn't have the same properties. If I uncomment Line A and B then the cell styles default to UITableViewCellStyleDefault and they don't display the custom controls. Oddly, if I comment out Line A, and uncomment line B, then the TTTextFieldCells look great, but the TTPickerCells default to UITableViewCellStyleDefault.
It seems that if I do not register a class, dequeue will return an instance of the first prototype cell class. If I register the class then the cell defaults to UITableViewCellStyleDefault.
Also of note, the initWithStyle:reuseIdentifier: selectors only get called if the class is registered.
So, how to I properly display to different UITableViewCell subclasses within the same UITableView? Do I have to forgo using the storyboard to design the cell?
Thank you in advance.
A: You do not want to be calling tableView registerClass:... inside of cellForRowAtIndexPath. Instead, you should be registering your classes/nibs a single time. This is often done in the controller's viewDidLoad method. Your cellForRowAtIndexPath implementation can then look something like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row];
NSString *reuseIdentifier = (/*some condition*/ ? @"TTTextFieldCell" : @"TTPickerCell");
UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
[cell setCellDetails:cellDetails];
return cell;
}
EDIT: I should mention dequeueReusableCellWithIdentifier always returns a cell from iOS 6 on. If you are targeting an earlier version of iOS you need to account for creating cells in the even this method returns nil.
A: Ok, this is what I found to be the answer.
*
*Do not register the class for the reuse identifier. Comment out lines A and B.
*Do not copy and paste prototype cells, unless you take great care to review the IBOutlets. The pasted prototype cell doesn't care what UITableViewCell subclass you assign it too, it doesn't validate the IBOutlets are present.
Fixed up #2 and all was well.
Doh!
A: I used 2 types of cells loaded from NIB and NSMutable array with my objects, objects have texts, titles and imagens that i want to use in cells. In method cellForRowAtIndexPath... u put content from objects to cell. U can init without nib.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (your condition){
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass1" owner:self options:nil];
CellClass1 *cell = (CellClass1 *)[topLevelObjects objectAtIndex:0];
}else{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass2" owner:self options:nil];
CellClass2 *cell = (CellClass2 *)[topLevelObjects objectAtIndex:0];}
//get your content for cell at array or your own estructure
Content *content = [contents objectAtIndex:indexPath.row];
cell.description.text = content.description;
return cell;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20690037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: static interfaces in c# Sorry it's possibly a duplicate but in the other static interface they mention generics which I am not using.
I wanted a quick and simple logger for my app I though I could avoid a singleton using a static element.
I would have like to keep the interface so that later I could change to another logging package. The interface being for me (I may be wrong here) a way to implement a "facade" feature.
I have the feeling I am overlooking something.
A gentle push in the right direction would be greatly appreciated. (Hope it's a bit clearer)
public interface Ilogger
{
void Log(string data, out DateTime datetime, out string uid);
}
public class Logger : Ilogger
{
private static TraceSource AppTrace = new TraceSource("RD", SourceLevels.All);
static Logger ()
{
AppTrace.Listeners.Clear();
AppTrace.Listeners.Add(new DelimitedListTraceListener("RD.log"));
}
static void Log(string data, out DateTime datetime, out string uid)
{
datetime = DateTime.Now;
uid = Guid.NewGuid().ToString();
AppTrace.TraceInformation(datetime + ";" + uid + ";" + data);
}
}
A: You want to combine a singleton with a facade. Sort of a service locator. i.e. create a singleton that got the same methods as your interface and then assign the interface to the facade as the singleton.
I've blogged about it.
A: C# does not support static inheritance or static interface implementation. static variables are just a form of a Singleton either way you look at it - just go with a Singleton or better use a DI container to inject the logger dependency.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6945127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eigen SparseLU factorize too slow In my code, SparseLU.factorize() takes 1'20" to execute. How to speed it up? Or, are there any inappropriate steps slowing it down in my code?
Here is the code:
Eigen::SparseMatrix<double> F(verticesNum, verticesNum); // verticesNum is about 34918
// reserve space for non-zero elements in sparse matrix
F.reserve(Eigen::VectorXi::Constant(verticesNum, 20));
// build matrix operator
for (int i = 0; i < vertices->size(); i++)
{
// ... some algorithm
}
// build solver for matrix
Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solver;
// tailor solver to matrix
solver.analyzePattern(F);
solver.factorize(F);
Thank you!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62387748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to proxy requests in docker swagger ui I'm using Swagger UI using its docker version. The Try it out button is not working as expected from the Web UI because there's a problem with cors. I'm running the UI from localhost and doing requests to another domain. I have read this other question How to avoid CORS errors ("Failed to fetch" or "Server not found or an error occurred") when making requests from Swagger Editor? but I cannot do any of the solutions it says.
I'm not sure if it's posible to setup a proxy on the docker container as SwaggerHub does, like, instead of the Try it out request be resolved on the browser, resolve it on the docker container.
Do you know if that is posible?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72200046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Actionscript show button after amount of time Hi i'm loading a FLV into a blank video holder and would like to display a button when the video reaches a certain point. Is this at all possible?
A: You didn't specify the version of actionscript in use, so I'll assume you're using as3.
You could
*
*use cue points embedded in the flv (added when creating the flv)
*if you're using the FLVPlayer component, use cue points created with actionscript
*use a regular Timer
If you don't have access to the creating-the-flv-part, the simplest (and the most inaccurate, but I would assume that displaying a button doesn't need to be millisecond-level-accurate) solution would be number three. If the user has no control over the playback (i.e. pause, rewind) and the video isn't being streamed over network, just start/stop a timer with the playback. If the user can pause and rewind the video, you'll have to also stop and adjust the timer every time the user does so. If the video is being streamed over network, you'll have to take any buffering pauses into account, too.
A: You can add cuepoint and listen for them with:
_Player.AddEventListener(MetadataEvent.CUE_POINT, PlayerCuePoint);
function PlayerCuePoint(e:MetadataEvent):void
{
_Button.visible = true;
}
Or you could check the progress like this:
const BUTTON_TIME:Number = 10; //Time in seconds
_Player.AddEventListener(VideoEvent.PLAYHEAD_UPDATE, PlayerPlayheadUpdate);
function PlayerPlayheadUpdate(e:VideoEvent):void
{
if(_Player.playheadTime >= BUTTON_TIME)
_Button.visible = true;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/649916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Meaning of command ls -lt | wc -l My friend just passed me this command to count the number of files in a directory:
$ ls -lt | wc -l
Can someone please help me flush out the meaning of this command? I know that ls is to list all the files. But what does -lt mean?
Also, I get a different count if I use ls | wc -l with no -lt option. Why is that the case?
A: You'll want to get familiar with the "man (manual) pages":
$ man ls
In this case you'll see:
-l (The lowercase letter ``ell''.) List in long format. (See below.) If
the output is to a terminal, a total sum for all the file sizes is
output on a line before the long listing.
-t Sort by time modified (most recently modified first) before sorting the
operands by lexicographical order.
Another way you can see the effect of the options is to run ls without piping to the wc command. Compare
$ ls
with
$ ls -l
and
$ ls -lt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20851413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: building android project produces make error 2 I have recently purchased a book to assist in my development of C++ for Android which contained some code samples. However, when I come to build some of the sample code, I receive the following error:
C:\ndk\android-ndk-r9\ndk-build.cmd all
"Compile++ : Chapter10 <= Chapter10.cpp
process_begin: CreateProcess(NULL, C:/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.7/prebuilt/windows/bin/arm-linux-androideabi-g++ -MMD -MP -MF ./obj/local/armeabi/objs/Chapter10/Chapter10.o.d -fno-exceptions -fno-rtti -Ijni -IC:/ndk/android-ndk-r9/sources/android/native_app_glue -IC:/ndk/android-ndk-r9/sources/cxx-stl/stlport/stlport -IC:/ndk/android-ndk-r9/sources/cxx-stl//gabi++/include -Ijni -DANDROID -Wa,--noexecstack -Wformat -Werror=format-security -frtti -c jni/Chapter10.cpp -o ./obj/local/armeabi/objs/Chapter10/Chapter10.o, ...) failed.
make (e=2): The system cannot find the file specified.
make: *** [obj/local/armeabi/objs/Chapter10/Chapter10.o] Error 2
The make file is as shown below:
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_ARM_MODE := arm
LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_MODULE := Chapter10
LOCAL_SRC_FILES := Chapter10.cpp \
(Other cpp Files . . . )
LOCAL_LDLIBS := -llog -landroid -lEGL -lGLESv2 -lOpenSLES
LOCAL_STATIC_LIBRARIES := android_native_app_glue
include $(BUILD_SHARED_LIBRARY)
$(call import-module,android/native_app_glue)
The Application.mk file is as below:
APP_PLATFORM := android-9
APP_STL := stlport_static
NDK_TOOLCHAIN_VERSION := 4.7
This was compiled using ADT v22.2.1 and Android NDK r9 on a Windows 7 Machine.
The NDK was installed to 'C:\ndk\android-ndk-r9\'.
A: Android NDK r9 contains the following toolchains:
*
*arm-linux-androideabi-4.6
*arm-linux-androideabi-4.8
*arm-linux-androideabi-clang3.2
*arm-linux-androideabi-clang3.3
*llvm-3.2
*llvm-3.3
*mipsel-linux-android-4.6
*mipsel-linux-android-4.8
*mipsel-linux-android-clang3.2
*mipsel-linux-android-clang3.3
*x86-4.6
*x86-4.8
*x86-clang3.2
*x86-clang3.3
There is no toolchain for gcc 4.7. However, your Application.mk contains the line:
NDK_TOOLCHAIN_VERSION := 4.7
Which tells the NDK to look for the 4.7 toolchain. And it fails.
So, the solution to your problem is changing the NDK_TOOLCHAIN_VERSION variable to 4.6, 4.8, clang3.2, clang3.3, or just clang (which will use the most recent version of Clang available in the NDK).
A: Check your project path if is contain spaces and non-english characters.
I moved my project into somewhere without spaces, re-build it and works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19477500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Error message converting pandas dataframe integers to datetime I was trying to convert dates into datetime since they were given to me in YYYYMMDD format on my HW. The date was already indexed for a previous problem so I wrote out:
df.reset_index()
df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')
This is the error message I ended up getting:
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in
get_loc(self, key, method, tolerance)
3079 try:
-> 3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'DATE'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
<ipython-input-291-e5a2ae2efa46> in <module>
1 df.reset_index()
----> 2 df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')
3 #df.set_index('DATE',inplace=True)
4 #df.resample('A').apply(lambda x: x[x<0].count())
~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
3022 if self.columns.nlevels > 1:
3023 return self._getitem_multilevel(key)
-> 3024 indexer = self.columns.get_loc(key)
3025 if is_integer(indexer):
3026 indexer = [indexer]
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
3080 return self._engine.get_loc(casted_key)
3081 except KeyError as err:
-> 3082 raise KeyError(key) from err
3083
3084 if tolerance is not None:
KeyError: 'DATE'
Very confused since I pretty much literally used this datetime line for a different problem without any issue. Is there anything I can do to fix this? thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69692598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simplest way of integrating Angular-created elements with D3 I'm playing around with different ways of integrating D3 and Angular, in the context of learning both of these frameworks, and am hoping for some input:
My client application receives a JSON array of nodes and an array of edges from my server.
The central component of the client is a graph visualization implemented as a D3 force-directed layout: For each node in the nodes array, a (SVG) circle element is added to this visualization, and lines between these circles are added for each edge in the edges array.
Of course, D3's selection.data( ) makes it trivial to add these elements and bind each to the data it represents, but the graph visualization is only part of a much larger application: I need to create different types of elements representing these same nodes and edges in different parts of the application (which D3 has nothing to do with), and I'd like to keep all of these elements bound to a single dataset.
My primary goal is minimizing code complexity, and - although I've fallen in love with the simplicity and elegance of D3's data-binding functionality - I've arrived at the tentative conclusion that using it in one part of the application while using Angular to do the same in other parts is creating unnecessary complexity, and that the simplest approach would be to use Angular to handle the data-binding/element-creation
In other words, instead of using selection.data( ).enter( ).append( ) to create SVG elements, I'm thinking I should do so using a ng-repeat="node in nodes", perhaps creating each as a custom directive to allow for custom functionality. Having done so, I would then need to get these elements "into" D3, i.e. managed by its force-directed layout.
Is my reasoning here sound? In particular, I'm worried that I'm overlooking complications this will create with regard to object constancy, which is an important requirement as nodes will be entering, exiting and moving about the screen constantly and I need these transitions to be smooth. How would you recommend I go about integrating my angular-created elements into D3 (more precisely, getting them into my force.nodes{ } and force.links( ) arrays) to avoid any such complications?
Finally, I'm also considering a strategy that I'm hoping might give me the best of both worlds: I could use D3 to create my SVG elements and bind them to their respective datum, but rather than executing that code in the link function of visualization directive (as I've been doing, and as all the Angular/D3 tutorials I've found do), I could run it in the compile function, and do something like this:
d3.select('SVG')
.selectAll('.node')
.data('nodeDataArray')
.enter( )
.append('circle')
.attr("class", "node-icon"); //...other attributes/styles etc
where node-icon is the normalized name of a directive with a restrict property that includes C. If this runs in the compile method, angular should then compile all of these directives as normal, adding any additional functionality / interfaces with other directives (etc.), the same way it does with any other type of element. Right?
This is the option I'm most attracted to intuitively - are there any pitfalls of it I might be overlooking, which might make the former strategy preferable?
A: I have been pondering pretty much the same problem for a while and come to the following conclusion.
The simplest way to integrate Angular created elements with d3 is to add the directives with .attr and then .call the compile service on the d3 generated elements. Like this:
mySvg.selectAll("circle")
.data(scope.nodes)
.enter()
.append("circle")
.attr("tooltip-append-to-body", true)
.attr("tooltip", function(d){
return d.name;
})
.call(function(){
$compile(this[0].parentNode)(scope);
});
Here is a Plunker.
I think the idea of generating elements with Angular ngRepeat rather than d3 is working against the frameworks. D3 does not expect to be handed a bunch of elements. It wants to be handed data - almost always an array. It then has a stack of excellent functions to convert that data into various SVG or HTML elements. Let it do that.
It seems from this quote...
D3 makes it trivial to add elements and bind each to the data it represents, but the graph visualization is only part of a much larger application: I need to create different types of elements representing these same nodes and edges in different parts of the application (which D3 has nothing to do with), and I'd like to keep all of these elements bound to a single dataset.
... you are implying that generating elements with d3 somehow prevents you from binding the same data to different parts of the application. I can't see why. Just have d3 generate elements from a scope array (as is done in the linked Plunker). Then use the same dataset wherever you want in the usual Angular way. Other parts of the application can update the dataset and a $watch callback can re-render the d3 graphic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23231587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Cannot make child element the same height as parent element IE I am trying to make a child element of a table cell take on the table cell's height and width using CSS. Here is the html:
<tr>
<td>
<div class="yellowDiv"></div>
</td>
<td></td>
<td></td>
<td></td>
</tr>
Here is the CSS I'm using:
table tbody tr td:nth-child(1){
position: relative;
}
table tbody tr td div.yellowDiv{
position: absolute;
top: 0;
bottom: 0;
width: 100%;
background: yellow;
}
The above code renders properly in Chrome, but not in IE (only concerned with IE 9 and 10). I have also tried setting display: table-cell; for the div element but to no avail. I have also tried setting the height of the div element to be 100% but that has not worked either.
A: Absolutey-positioned elements are no longer part of the layout. They have their own layout context. Therefore they cannot know how big their parent element is.
You need to use JavaScript to solve this or consider why you need absolute positioning at all.
You can use:
.yellowDiv {
background-color:#ffff00;
height:100%;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19989430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android imageview over another imageview I want an icon (ImageView) over another ImageView. When I tried, the icon is hiding behind the white image. In my code below, first image view is for the white box and another image view is for the icon.
<RelativeLayout
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp">
<ImageView
android:id="@+id/button_menu"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:padding="5dp"
android:src="@drawable/ic_menu"
android:background="@drawable/button_white_rounded"
android:elevation="4dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:tint="@color/colorText"/>
<ImageView
android:id="@+id/warning_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="@drawable/ic_warning_circle"/>
</RelativeLayout>
I want the orange icon in screenshot over the white box. How can I bring it on the white box image?
A: <RelativeLayout
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp">
<ImageView
android:id="@+id/warning_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="@drawable/ic_warning_circle"/>
<ImageView
android:id="@+id/button_menu"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:padding="5dp"
android:src="@drawable/ic_menu"
android:background="@drawable/button_white_rounded"
android:elevation="4dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:tint="@color/colorText"/>
</RelativeLayout>
A: The layout_align [Top|Bottom|Left|Right] attribute in RelativeLayout is used to align views based on their respective x and y values within the margin. The second ImageView will now be aligned to the top, bottom, left, and right of the first ImageView based on the margins. Padding is ignored in the alignment.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white" >
<ImageView
android:id="@+id/inside_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginTop="5dip"
android:src="@drawable/frame" />
<ImageView
android:id="@+id/outside_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/inside_imageview"
android:layout_alignBottom="@id/inside_imageview"
android:layout_alignLeft="@id/inside_imageview"
android:layout_alignRight="@id/inside_imageview"
android:scaleType="fitXY" />
</RelativeLayout>
A: Your code is perfect but either you have to remove android:elevation from button_menu or you have to add android:elevation in warning_circle.
I have updated my answer based on @MikeM. suggestion for use RelativeLayout instead of ConstraintLayout
Solution 1:
<RelativeLayout
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp">
<ImageView
android:id="@+id/button_menu"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:background="@drawable/button_white_rounded"
android:padding="5dp"
android:scaleType="fitXY"
android:src="@drawable/ic_menu"
android:tint="@color/colorText"
tools:src="@tools:sample/avatars" />
<ImageView
android:id="@+id/warning_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:src="@drawable/ic_warning_circle"
tools:src="@tools:sample/avatars" />
</RelativeLayout>
Solution 2:
<RelativeLayout
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp">
<ImageView
android:id="@+id/button_menu"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:background="@drawable/button_white_rounded"
android:elevation="4dp"
android:padding="5dp"
android:scaleType="fitXY"
android:src="@drawable/ic_menu"
android:tint="@color/colorText"
tools:src="@tools:sample/avatars" />
<ImageView
android:id="@+id/warning_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:elevation="4dp"
android:src="@drawable/ic_warning_circle"
tools:src="@tools:sample/avatars" />
</RelativeLayout>
A: You can use FrameLayout to achieve this.. here is an example, you can modify this according to your need. In warning icon image view add gravity as bottom|end and in menu icon image view add margin of 10dp when using FrameLayout.
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp">
<ImageView
android:id="@+id/button_menu"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_margin="10dp"
android:padding="5dp"
android:src="@drawable/ic_menu"
android:background="@drawable/button_white_rounded"
android:elevation="4dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:tint="@color/colorText"/>
<ImageView
android:id="@+id/warning_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:src="@drawable/ic_warning_circle"/>
</FrameLayout>
A: <RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp">
<ImageView
android:layout_centerInParent="true"
android:id="@+id/warning_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:src="@drawable/ic_launcher_background"/>
<ImageView
android:id="@+id/button_menu"
android:layout_width="44dp"
android:layout_height="44dp"
android:padding="5dp"
android:layout_marginRight="-20dp"
android:layout_marginBottom="-20dp"
android:layout_alignRight="@+id/warning_circle"
android:layout_alignBottom="@+id/warning_circle"
android:src="@drawable/ic_menu_gallery"
android:background="@color/colorAccent"
android:elevation="4dp"
android:scaleType="fitXY"
android:adjustViewBounds="true"/>
</RelativeLayout>
Use this way!!
We have a concept of layers in relative layout!
Vertically down views are on the top most layer.
A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/download" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/download_img" />
</RelativeLayout>
</RelativeLayout>
A: You could try to search any ready-to-use solutions for badges like ImageBadgeView.
Or try to play with BadgeDrawable from material lib.
I'd prefer to use ViewOverlay for such purposes and just add few rows of code:
button_menu.post {
val drawable = ContextCompat.getDrawable(context, R.drawable.ic_warning_circle)
drawable.setBounds(
button_menu.width - drawable.intrinsicWidth,
button_menu.height - drawable.intrinsicHeight,
button_menu.width,
button_menu.height
)
button_menu.overlay.add(drawable)
}
In this way you would reduce amount of containers in your xml layout and make it more readable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58946988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Sharepoint 2007 File Upload , Page cannot be Displayed Having a bit of strange Sharepoint 2007 issue , especially for a Monday.
Here's the scenario: Users within organisation cannot upload files to ANY doc Lib.
User is able to click upload, browse, select the file without any problems. As soon as he/she clicks OK, they immediately get a standard IE error : Page cannot be displayed.
The MOSS Server is setup in a DMZ where it is Internet accessible. When accessing it from the Internet (which I'm doing), the uploading works fine. It's only when users who are in the organisation try to upload anything, they get the error. Users within the organistaion also access the site using the Internet IP as no direct route exists between Internal Network and DMZ.
We have a LINUX Firewall involved (Yuck, I know), and clients also have Norton AV.
I suspect some kind of networking issue, or maybe the AV. Any ideas?
A: Ok. The issue was related to intermittant connectivity loss. All fixed now
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3448190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Issue constructing a has_many relation with scope using multiple join tables I have a tag system on multiple models that are linked together.
The system works like this:
*
*A Top has many Middles
*A Middle has many Lows
*Tops, Middles and Lows have many Tags
*A tag associated to Top level is supposed to qualify every Middle and Low associated to it.
*Same goes for a tag that would be associated to a Middle, every Low associated to it would 'inherit' from the tags.
This mechanic is not on a database level, in the end in what concerns the database, Tops, Middles and Lows all have their own tag collection, and i initially implemented instance methods on each model so that when you call, for example, low_instance.all_tags, it concatenates the tag collections of it's parent Middles, and the one of its Top.
Here is what the models look like:
# ______________________________
# / \
# (1) (*)
# [Top] (1) __ (*) [Middle] (*) __ (*) [Low]
# (*) (*) (*)
# \_______________ | ______________/
# |
# *
# [Tags]
class Low < ApplicationRecord
has_many :low_tags, dependent: :destroy
has_many :tags, through: :low_tags
has_many :middle_foos, dependent: :destroy
has_many :middles, through: :middle_foos
end
class Middle < ApplicationRecord
belongs_to :top
has_many :middle_tags, dependent: :destroy
has_many :tags, through: :middle_tags
has_many :middle_lows, dependent: :destroy
has_many :lows, through: :middle_lows
end
class Top < ApplicationRecord
has_many :middles, dependent: :destroy
has_many :lows, dependent: :destroy
has_many :top_tags, dependent: :destroy
has_many :tags, through: :top_tags
end
### Join tables
class MiddleLow < ApplicationRecord
belongs_to :middle
belongs_to :low
end
class LowTag < ApplicationRecord
belongs_to :low
belongs_to :tag
end
class MiddleTag < ApplicationRecord
belongs_to :middle
belongs_to :tag
end
class TopTag < ApplicationRecord
belongs_to :top
belongs_to :tag
end
That actually works like a charm. The issue is that i want to be able to search my Lows with the awesome Ransack gem and using the full tag collection of a Low (its self tags, plus the ones inherited from the parent Middles and Top)
Problem: Ransack only works with ActiveRecord::Relations. So from Ransack's point of view, i can only search my Lows using their self-tags and not the full inherited collection as this does not exist on the database level.
The initial solution to this problem i wanted to implement is to add a "copy" full tag collection on the database level that updates with the rest and that i could use to search with Ransack.
But I'm sure i don't have to add anything to the database as all the info is already here in the join tables and i kind of don't want to duplicate that info which is not super cool i think and would make the code base less understandable.
I have seen potential solutions using has many with scopes like so:
has_many :all_tags, ->(low) {
unscope(.........).
left_joins(..........).
where(.........)
# Returs self tags (Low) + tags from associated Middles + tags from the Top
}
I'm pretty sure this would be the best solution, but I'm really not good when it comes to database querying especially with so much models and join tables. I get confused and can't seem to find what to put in that scope so that i get this full collection of tags.
So if anybody has a clue about that, any help would be greatly appreciated!
By the way, using Rails 6.1 and Ruby 2.7
A: So found the solution to the query I wanted to construct in the end.
The scope looks like following:
has_many :full_tags, lambda { |low|
where_clause = 'top_tags.top_id = ? or low_tags.low_id = ?'
where_args = [low.top_id, low.id]
if low.middles.any?
where_clause += ' or middle_tags.zone_id IN ?'
where_args << low.middle_ids
end
unscope(where: :low_id)
.left_joins(:middle_tags, :top_tags, :low_tags)
.where(where_clause, *where_args).distinct
}, class_name: 'Tag'
Calling xxx.full_tags on any instance of low returns the whole collection of tags from every middle it belongs to , plus those from the top it belongs to, plus its own tags, and the distinct makes it a unique collection.
That being said, that didn't fully fixed my problem because the whole purpose was to pass this scoped has_many relation as an attribute used by the Ransack gem to filter out my Low models, out of their full inherited collection of tags.
Big disappointment it was when i discovered that Ransack performs eager loading when it comes to search on associations:
Rails does not support Eager Loading on scoped associations
So i ended up implementing a whole other solution for my tagging system. But hey, i learned a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74318087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EnterpriseLibrary Error I'm receiving reports of a rare and intermittent error in our live environment. I have been unsuccessful in my attempts to reproduce it, and the error itself is a slight mystery. Add to that, it seems to be something involving Enterprise Library tracing (we're using version 5.0) - all in all, a bit of a pain. This is happening on Windows Sever 2008, application is on .Net Framework 4.0 (WPF).
The error message and the stack trace follow:
ArgumentNullException: Value cannot be null. Parameter name: category
<StackTrace>
Server stack trace:
at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry.BuildCategoriesCollection(String category)
at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceMessage(String message, String entryTitle, TraceEventType eventType)
at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceEndMessage(String entryTitle)
at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.Dispose()
at TestApplication.ViewModelTest.<UpdateUsers>d__1a.MoveNext()
Exception rethrown at [0]:
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.<SetException>b__1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
</StackTrace>
Can anyone shed any light on what might be causing this?
EDIT:
I'm not modifying LogEntry.BuildCategoriesCollection. The input to the method BuildCategoriesCollection(String category) is null.
The UpdateUsers method is as follows:
async void UpdateUsers()
{
Processing = true;
using (traceMgr.StartTrace("Trace"))
using (var engine = new EngineClient())
{
Users = new List<UserMasterDataModel> { _blankUser };
var users = await engine.GetPossibleTagsTask(SelectedOutcomeId, _queue.SystemCd, _queue.QueueCd);
Users.AddRange(users);
}
if (SelectedUser != _blankUser)
{
// If null user selected then initialize to the case's tag, otherwise try to find the previously selected UserName
var userNameToFind = SelectedUser == null ? _details.TagTo : SelectedUser.UserName;
SelectedUser = Users.FirstOrDefault(user => user.UserName == userNameToFind) ?? _blankUser;
OnPropertyChanged("SelectedUser");
}
}
A: This problem seem to be a known bug for E-Lib in previous versions too.
Known as: Unhandled exception when using the logging AB from multiple threads.
"The underlying issue is that in .NET 2.0 RTM a parent thread's operation stack was shared with its children if such a stack existed by the time the children were created."
Read more here:
http://entlib.codeplex.com/workitem/9592
Hard to suggest a generic solution to this as it is very depends on the architecture of your app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13016383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: android jni from static to non static methods I am trying to refactor some android jni code. It was initially setup to use static variables in JNI and static calls on the android side. I would like to change that to improve compatibility with other code.
current method signatures
static jclass main_activity;
static jmethodID on_init;
static jmethodID on_update;
static jmethodID on_render;
static jmethodID on_exit;
static jmethodID on_get_input;
these bindings were setup in the beginning of the code like this:
main_activity = (jclass)((*mEnv)->NewGlobalRef(mEnv, cls));
on_init = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
"on_native_init","()V");
on_update = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
"on_native_update","()V");
on_render = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
"on_native_render","()V");
on_exit = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
"on_native_exit", "()V");
Then later in the code they would be used like this:
void Android_JNI_SwapEGLwindow(void)
{
JNIEnv *a_env = get_android_jni_env();
(*mEnv)->CallStaticVoidMethod(a_env, main_activity, on_update);
}
Since this project is currently setup to store the main activity and the function addresses as a static reference with only the call to get_android_jni_env(); allowing me access to get the current android jni environment.
How can I restructure this code to be able to get an instance instead of holding on to a static reference?
A: Just add one static method as "getInstance()" to retreive the object of class main_activity, then you can use the object to call non-static methods.
jmethodID midGetInstance = (*env)->GetStaticMethodID(env, main_activity_class, "getInstance", "()Lcom/package/yourapp/MainActivity;");
jobject main_activity_obj = (*env)->CallStaticObjectMethod(env, main_activity_class, midGetInstance);
...NewGlobalRef(main_activity_obj);
where main_activity_class is the same of your original jclass main_activity.
On Java side, you need
onCreate(...) {mInstance = this;...}
public static MainActivity getInstance() {return mInstance;}
Then you can use main_acitivty_obj to access the non-static methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32644064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Send form data to Firebase The problem is that when I run this my real-time database is not updating and there are no errors coming or showing.
function writeData() {
firebase.database().ref("user").set( {
Email: document.getElementById("help").value,
Price: document.getElementById("price1").value,
Desc: document.getElementById("Pdesc").value,
}
);
}
<form>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Enter Product name</label>
<input type="text" class="form-control" id="help" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Product Price</label>
<input type="number" class="form-control" id="price1">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Product description</label>
<input type="text" class="form-control" id="Pdesc">
</div>
<!-- <div class="mb-3">
<label for="exampleInputPassword1" id="upProgess" class="form-label">Upload a file</label>
<input type="file" class="form-control" id="namebox">
</div> -->
<button type="submit" onclick="writeData()" class="btn btn-lg btn-success">Upload</button>
</form>
A: First, check your realtime firebase, sometimes if you use free, your realtime firebase has expired (for 1 month).
You can print it by inputting a simple value, for example:
If nothing happens, then check your project's API, library, or expiration date.
Solution:
Create a new project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68692499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $uibModal not loading correct content on first click I'm working in ServiceNow and am trying to use $uibModal to open up a modal window that holds an embedded widget. The modal opens fine on the first click, but every click after that requires two clicks for the modal to load the correct content. I've read on a few sites that it's because of the template cache doesn't clear and some people suggested not using the script tags, but I'm not sure how to get uibModal to work without the script tags in ServiceNow. Has anyone run into this? Would love to get some suggestions on how to fix this.
Here's my client script:
c.onWidget2 = function(template, task) {
c.taskName = task.short_description;
c.modalInstance = $uibModal.open({
templateUrl: template,
scope: $scope,
size: 'lg'
});
spUtil.get('hrj_task_activity_scoped', {
sys_id: task.sys_id,
table: 'sn_hr_core_task',
recordInfo: task.taskInfo
}).then(function(response) {
c.newTask2 = response;
});
};
//closeModal for the "x"
c.closeModal = function() {
c.modalInstance.close();
};
And here's my HTML:
<div class="card" ng-click="c.onWidget2('newTask2',task);"></div>
<script>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h4 class="panel-title pull-left">{{c.taskName}}</h4>
<span ng-click="c.closeModal()"><i class="fa fa-times pull-right"></i></span>
</div>
<sp-widget widget="c.newTask2" options="c.newTaskOptions"></sp-widget>
</div>
</script>
A: problem here is "directive in modal", like in this thread:
Integrating directive in Angular UI Modal
The solution would be to load the directive after the modal is rendered:
c.onWidget2 = function(template, task) {
c.taskName = task.short_description;
var initWidget = spUtil.get('hrj_task_activity_scoped', {
sys_id: task.sys_id,
table: 'sn_hr_core_task',
recordInfo: task.taskInfo
}).then(function(response) {
c.newTask2 = response;
});
c.modalInstance = $uibModal.open({
templateUrl: template,
scope: $scope,
size: 'lg'
}).rendered.then(initWidget);
};
//closeModal for the "x"
c.closeModal = function() {
c.modalInstance.close();
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53842681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fatal error: Class ‘mysqli’ not found in C:\xampp\htdocs\code\query.php I’m in the middle of E10-4 from 'Learning PHP, MySQL & JavaScript' by Robin Nixon. I have enjoyed the book until two days ago when I got to exercise 10-4 where I was asked to run the following php program:
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if (!$result) die($conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
echo 'Author: ' . $result->fetch_assoc()['author'] . '<br>';
$result->data_seek($j);
echo 'Title: ' . $result->fetch_assoc()['title'] . '<br>';
$result->data_seek($j);
echo 'Category: ' . $result->fetch_assoc()['category'] . '<br>';
$result->data_seek($j);
echo 'Year: ' . $result->fetch_assoc()['year'] . '<br>';
$result->data_seek($j);
echo 'ISBN: ' . $result->fetch_assoc()['isbn'] . '<br><br>';
}
$result->close();
$conn->close();
?>
I get the two following error messages:
*
*Fatal error: Class ‘mysqli’ not found in
C:\xampp\htdocs\code\query.php
*PHP Fatal error: Class ‘mysqli’ not found in C:\xampp\htdocs\code\query.php
I’m running the following systems:
*
*Windows 7 Home Premium
*PHP 5.6.8
*XAMPP Control Panel v3.2.1
*Apache 2.4.12
*Database client version: libmysql - mysqlnd 5.0.11-dev -
*PHP extension: mysqli
I have searched stackoverflow and found a few posts about similar problems but could not pull any information out to solve the problem. I’m new to programming but the responses where over my head. I really have enjoyed this book but this Fatal error is keeping me from doing some great stuff with php and I'm not sure what I can do if I don't get past this issue. I'm sure it is simple to fix. Thanks for your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31362103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is this labeled javaScript continue not working? I am using this code to weather some circles are overlapping:
iCantThinkOfAGoodLabelName:
x = genX(radius);
y = genY(radius);
for(i in circles) {
var thisCircle = circles[i];
if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
continue;
} else { //Overlap
continue iCantThinkOfAGoodLabelName; //<- Line 256
}
thisCircle = [];
}
But when the continue statement is reached, chrome's developer console gives me this: client.html:256 Uncaught SyntaxError: Undefined label 'iCantThinkOfAGoodLabelName'
A: Because iCantThinkOfAGoodLabelName: needs to be right before the loop.
iCantThinkOfAGoodLabelName:
for (blah; blah; blah)
..
I think what you want is a function..
function iCantThinkOfAGoodFunctionName() {
var x = genX(radius),
y = genY(radius);
for (i in circles) {
var thisCircle = circles[i];
if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
continue;
} else { //Overlap
iCantThinkOfAGoodFunctionName();
}
thisCircle = [];
}
}
A: There should not be any statement between a label name and associated loop.
x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
for(i in circles) {
fixes it.
A: The label should come immediately before the loop
x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
for(i in circles) {
A: I recently had this issue and I resolved it by using all lowercase in the loop's label in version v0.8.x of Node.js.
Using labelname: vs. iCantThinkOfAGoodLabelName: might help you.
Others have correctly corrected you on the location of the label. It should be immediately before the for loop.
The Mozilla Developer Network on labels advises to avoid using labels, and instead prefer calling functions or throwing an error. You might rethink your strategy on using them, if possible.
Example of calling a function depending on result:
var i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
// we want to ignore and continue
} else {
// do work with these variables from inside the doWork function
// (scoped to whatever scope `this` for loop is in)
doWork.call(this, i, j);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6393648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: error using result returned from angular service (undefined) So I have two variables in my Typescript class:
private myServiceSubscription: Subscription;
myVar: myDto[] = [];
In the ctor:
this.myServiceSubscription = this.deliveryPointService
.getPostalAddresses()
.subscribe(result => console.log(result));
I can see the expected result returned from the service in the console log (a list with two items)
However, if I use another subscribe instead:
.subscribe(result => this.myVar);
and (outside the subscribe):
console.log(this.myVar[0]);
then I notice this.myVar is undefined.
Why does console.log(result) show the right result, but this.myVar does not?
This is in angular 4.
A: Right now, you don't do anything with the result of your service method. You have to assign the returned item to your variable:
.subscribe(result => {
this.myVar = result;
console.log(this.myVar);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50002782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to prompt message box in remote computer where application is running as service? I have an C++ MFC application running in master machine that installs update from a server in remote computers through an agent service. This service takes care of authorization in remote machines before update. Now, I need to prompt the currently active user in remote machines for confirmation. AfxMessagebox or MessageBox in the service context doesn't show up any window in remote machines. Is there a way to achieve this?
A: Look at WTSSendMessage():
Displays a message box on the client desktop of a specified Remote Desktop Services session.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56422163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Push Data from a WCF Service to Website I have the following scenario, and I would like to know if there is a solution to achieve such thing:
I have a WCF service that is running in a backend server, and it does bulk data processing, like inserting records into DB, and I would like to have this service send a message or notification once a record has done processing to a webpage (ASP.NET Page), where this page should be listening to these messages and display a progress with the finished tasks at real-time.
Note: The WCF service is separate from the webpage; This means that the WCF service process starts when another WCF service calls it in the backend server, so the web-page should only 'listen' to the updates that comes from WCF service.
Through my research, I have come up with SignalR, can this technology help me build a solution for such a scenario, or maybe there is some other way to achieve it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19265609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to collect activity information from network-attached storage (NAS) devices? My goal is to be able to generate a report about the users that have accessed a particular folder on any file share. This includes Windows file servers, Unix/Linux file servers, and NAS devices (CIFS/SMB/NFS).
*
*For Windows, this isn't too complicated because it has built-in functionality that supports this (see: http://blogs.splunk.com/2013/07/08/audit-file-access-and-change-in-windows).
*I'm assuming that there is similar built-in functionality for unix/linux shares.
*So this leaves the question of whether something like this is possible for NAS devices (CIFS/SMB/NFS).
I'm thinking that something like this is possible because of some tools that I see are available, such as what is available at http://www.imperva.com/products/fsc_file-activity-monitoring.html.
So my question is the following: Is it possible to collect file share activity information from NAS devices? If so, how do I collect this information? For example, if there were APIs to support this, it would be most useful.
A: Is your NAS running SAMBA? If so will the Samba log files or smbstatus command solve your need? See https://askubuntu.com/questions/89288/how-can-i-monitor-my-samba-traffic
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21785390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wordpress - How to extract the first video embed from post content and place it in different area? I am trying to build a wordpress theme which extracts the first embedded video out of the content of the post and features it on top of the page.
So for example, I am trying to go from this:
<div id="main-post-content">
<div class="embedded-video">
<iframe src="...">
</div>
<p>Post content</p>
<p>Post content</p>
</div>
To this:
<div id="big-featured-area">
<div class="embedded-video">
<iframe src="...">
</div>
</div>
<div id="main-post-content">
<p>Post content</p>
<p>Post content</p>
</div>
So the important things I am trying to accomplish are:
1) Finding the first embedded video within the post content.
2) Placing that first video in the above featured area.
3) Filtering that first video out of the content (so that it doesn't appear twice on the page).
So far I am simply using the get_post_custom() function to get the first embed code within the post and copy it into the featured area. I am having problems with number 3 though (filtering out the first video from the post content). I could just hide the first embedded video with CSS, but it doesn't feel right to me. I feel like I need to filter the video out of the content completely. Am I right or wrong about this?
I have also had ideas about using the oembed filters in wordpress but I can't seem to get my head round how to implement them.
Let me know what you think is the best way of doing this is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35975590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: using JSON to get data from MYSQL to Java i'm trying for days to get this working.. but i still fail.
<?php
$province = $_POST['test'];
$dbhost = 'localhost';
$dbname = 'news';
$dblogin = 'root';
$dbpass = '';
function dbConnect() {
global $dbhost;
global $dbname;
global $dblogin;
global $dbpw;
$db = mysql_connect($dbhost, $dblogin, $dbpw) or die("could not
connect to database: ".mysql_error());
mysql_select_db($dbname) or die("could not select database");
return $db;
}
function dbClose($db) {
mysql_close($db);
}
// basis code ^^
$db = dbConnect();
$query = "SELECT title FROM news_google_us";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
;}
?>
i get this as response:
{"title":"Obama and GOP in Deal on Tax Cuts - New York Times"}{"title":"WikiLeaks Founder Warns About More Dispatches - New York Times"}{"title":"S. Korea to make islands near N. Korea fortresses - Jerusalem Post"}{"title":"9th Circuit judges explore narrow routes to reinstate gay marriage - Los Angeles Times"}{"title":"Killing of Iranian Scientist Overshadows 6-Nation Nuclear Talks - BusinessWeek"}{"title":"Schwarzenegger proposal rebuffed - San Jose Mercury News"}{"title":"WikiLeaks list of 'critical' sites: Is it a 'menu for terrorists'? - Christian Science Monitor"}{"title":"Big moments in the Concorde's history - BusinessWeek"}{"title":"Citigroup Stake Is Sold for About $10.5 Billion as US Unwinds Investment - Bloomberg"}{"title":"Jets Vs. Patriots: New England In Full-On Kobra Kai Mode...No Mercy - SB Nation"}{"title":"Obama, GOP cut deal to extend tax cuts - USA Today"}
I use Jquery to get the data:
$.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);
}});
$.getJSON('mysql-query.php', function(data) {
alert(data);
});
I've tried a stripped version
<?
$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['descrtiption'])) {
$stmt = $pdo->prepare("SELECT description FROM news_BBC_sport WHERE name = ? ORDER BY description");
// $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['descrtiption']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r(phpinfo());
echo "</pre>";
}
echo json_encode($rows);
?>
tried this one
I've tried a stripped version
<?
$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "";
$pdo = new PDO($dsn, $username, $password);
$rows = array();
if(isset($_GET['descrtiption'])) {
$stmt = $pdo->prepare("SELECT description FROM news_BBC_sport WHERE name = ? ORDER BY description");
// $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
$stmt->execute(array($_GET['descrtiption']));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r(phpinfo());
echo "</pre>";
}
echo json_encode($rows);
?>
tried this one
http://www.phpclasses.org/package/4369-PHP-Generate-JSON-representation-from-MySQL-queries.html
I'm using firebug to check what's wrong. I get this:
parse error
syntax error JSON parse
(shows json data)
I've tried like everything, but i still get this error. I'm using a XAMPP server on OSX.
A: You first attempt is almost right, just don't echo each row, collect the result then echo:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$rows[] = $row;
}
echo json_encode($rows);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4530613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: While installing yolov3 using conda on window10 getting error Solving environment: failed When I am trying to install yolov3 on windows10 using Conda, getting following error:
(base) D:\aaa\yolo>conda env create -f yolo.yml
Collecting package metadata (repodata.json): done
Solving environment: failed ResolvePackageNotFound:
vc==14.1=h0510ff6_3
vs2015_runtime==15.5.2=3
How do I solve this issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63136555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a Spring bean that cannot be autowired I have a class A that extends B, which implements C. Currently, A takes B has an input argument and is the only defined bean that is an implementation of C, so it gets autowired whenever C is needed.
Without changing the ALL of the places where C is needed or the class structure of A/B/C, I need make B a defined bean so the same instance can be re-used. The problem is then I have 2 implementations of C (A and B). Is there a way to mark B so that it cannot be autowired?
Current:
<bean id="A" class="A">
<constructor-arg>
<bean class="B">
</constructor-arg>
</bean>
Wanted (so same instance of B can be used elsewhere):
<!-- TODO: Somehow mark B so it cannot be autowired -->
<bean id="B" class="B"/>
<bean id="A" class="A">
<constructor-arg ref="B">
</bean>
<bean id="Foo" class="Foo">
<constructor-arg ref="B">
</bean>
A: If you want to eliminate a bean from autowiring, then you can set autowire-candidate attribute of that bean tag to false.
For example consider your case(Here I am setting B bean's autowire-candidate attribute to false)
<bean id="B" class="B" autowire-candidate="false"/>
<bean id="A" class="A">
<constructor-arg ref="B">
</bean>
<bean id="Foo" class="Foo">
<constructor-arg ref="B">
</bean>
A: You could use qualifiers attached to @Autowired.
E.g., if you want to wire the bean with id B, you can do the following:
@Autowired
@Qualifier("B")
private C c;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20478155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using NSTrackingArea in an NSView that is unattached to a window? Basically, I want an "invisible" NSView covering my entire screen. I will add an NSTrackingArea to that, so that I get global mouse events as my cursor moves about the screen.
-(void)setTrackingArea
{
view = [[NSView alloc] initWithFrame:[NSScreen currentScreenForPoint:[NSEvent mouseLocation]].frame];
NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[NSScreen currentScreenForPoint:[NSEvent mouseLocation]].frame options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways owner:view userInfo:nil];
[view addTrackingArea:area];
[area release];
//[[window contentView] addSubview:view];
//I don't want to add the view to a window, as all tutorials say.
}
- (void)mouseExited:(NSEvent *)theEvent
{
NSLog(@"Exit"); //Never firing
}
Is this possible? Using NSViews and NSTracking Areas without a window?
A: Using an invisible view is definitely not something you want to do. Look into the addGlobalMonitorForEventsMatchingMask:: class method on NSEvent.
For example, here's how you would add a monitor for a movement of the mouse:
[NSEvent addGlobalMonitorForEventsMatchingMask:NSMouseMovedMask handler:^(NSEvent *mouseMovedEvent) {
//do something with that event
}];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9885503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Implementing File Uploads From Angular to Flask I am trying to implement file uploading for my Web tool. The front end is developed using angular and the back end is using flask. Following tutorials on the flask website I have set up the following flask app:
from flask import Flask, request
from werkzeug import secure_filename
import os
UPLOAD_FOLDER = '/home/openstack/Documents/Confmrg/bcknd/uploads'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/uploader' , methods = ['GET' , 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
filename = secure_filename(f.filename)
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File Uploaded'
if __name__ == '__main__':
app.run(debug = True)
I run this and the web server is hosted on http://localhost:5000
So on my angular component html I place the following:
<form action="http://localhost:5000/uploader" method="POST" enctype = "multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
However when I run the angular web page, and test it by uploading a file and clicking submit, nothing happens. There is no error, and nothing is output in the console. I must be missing something, could someone point me in the right direction?
A: Form onSubmit handler
To answer your immediate question, what's happening is input type submit in Angular calls the onSubmit method of the form (instead of submitting the form like in plain HTML). And because you don't have a handler for onSubmit in your class, nothing is happening.
For a quick test, follow this link to create a simple onSubmit handler method to test that your submit button works.
Here's a Stackblitz example which logs to console when you click the submit button: https://stackblitz.com/edit/angular-uy481f
File upload
To make file upload work, you would need to make a few things. This touches the component class, creating a new service and injecting it, and updating your form to bind it to the class.
*
*Create a proper Angular form. Here's an example.
*Create a method that will handle the onSubmit() of the form.
*Create a service that will handle Http calls to upload files.
*Inject the service into your class, and call the file upload method of that class.
As you can see, there's a lot involved in making this work unlike having a simple post form in the template. As such, it will be too much for a single answer.
But hopefully, the initial paragraph answered your question and the rest of the answer pointed you in the right direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59249745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to bypass code if criteria don't match? The code works when the criteria exists. I get an error when the criteria doesn't exist.
' Define constants.
Const srcName As String = "wfm_rawdata"
Const srcFirst As String = "D2" ' Location for Group
Const dstName As String = "bond_insurance"
Const dstFirst As String = "A2" ' do not change the 'A' (entire row).
'This function will transfer rows from one worksheet to another worksheet
' if the value = specified critiera
' Define workbook.
Dim wb As Workbook: Set wb = ActiveWorkbook ' Workbook containing this code.
' Define Source Range
Dim LastRow As Long
Dim srg As Range
' Define worksheet and column am working on and
' getting the range of last used cell using(LastRow)
With wb.Worksheets(srcName).Range(srcFirst)
LastRow = .Offset(.Worksheet.Rows.Count - .Row).End(xlUp).Row
Set srg = .Resize(LastRow - .Row + 1, 10)
End With
'Combine' critical cells into a range.
Dim brg As Range ' Built Range --> Range in the new sheet
Dim cel As Range ' Current Cell Range --> Range in the current sheet(rawdata)
'for every cell in group within wfm_rawdata sheet if the value = GO
For Each cel In srg.Cells
If cel.Value = "BOND INSURANCE" Then
' If the range in the new sheet have nothing then
' add specific criteria from the group in wfm_rawdata
If brg Is Nothing Then
Set brg = cel
' if there is range in there combine the new and
' old range together using -> Union function
Else
Set brg = Union(brg, cel)
End If
End If
Next cel
Application.ScreenUpdating = False
' Copy and delete critical rows of Source Range.
With wb.Worksheets(dstName).Range(dstFirst)
.Resize(.Worksheet.Rows.Count - .Row + 1, _
.Worksheet.Columns.Count).clear
Set brg = brg.EntireRow ' 'Convert' cells into rows.
brg.Copy .Offset ' Copy. 'Offset' because range is in 'With'.
brg.Delete ' Delete.
End With
How can I use a Boolean or other function to bypass the above code if the criteria doesn't exist?
For example if criteria "dog" exists then run the code and if it doesn't exist bypass the code.
I use this code to run three modules with code similar to the top code.
Sub master()
Call report1
Call report2
Call report3
End Sub
A: One you've assigned srg you can use Match() to check whether it contains any instances of the term you're interested in:
'...
'...
' Define worksheet and column am working on and getting the range of last used cell using(LastRow)
With wb.Worksheets(srcName).Range(srcFirst)
LastRow = .Offset(.Worksheet.Rows.Count - .Row).End(xlUp).Row
Set srg = .Resize(LastRow - .Row + 1, 10)
End With
'Exit if "BOND INSURANCE" is not found in `srg`
If IsError(Application.Match("BOND INSURANCE", srg, 0)) Then Exit Sub
'...
'...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71226311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Keep client connected to WebSocket in react native and express server I have a react native application where i have two users using the app (customer and restaurant)
So on checkout I connect the customer to websocket on the express server and once the order is placed i send a message to the restaurant which is supposed to be connected to websocket all time.
However, sometimes the restaurant is disconnected somehow, so I am trying to keep the restaurant connected, and if disconnected then reconnect again automatically.
In react native restaurant side implementation i have the following code :
this is useWebSocketLite hook to handle connection, send, receive messages and retry connection to server when closed:
function useWebSocketLite({ socketUrl, retry: defaultRetry = 3, retryInterval = 1000 }) {
const [data, setData] = useState();
const [send, setSend] = useState(() => () => undefined);
const [retry, setRetry] = useState(defaultRetry);
const [readyState, setReadyState] = useState(false);
useEffect(() => {
const ws = new WebSocket(socketUrl);
ws.onopen = () => {
setReadyState(true);
setSend(() => {
return (data) => {
try {
const d = JSON.stringify(data);
ws.send(d);
return true;
} catch (err) {
return false;
}
};
});
ws.onmessage = (event) => {
const msg = formatMessage(event.data);
setData({ message: msg, timestamp: getTimestamp() });
};
};
ws.onclose = () => {
setReadyState(false);
if (retry > 0) {
setTimeout(() => {
setRetry((retry) => retry - 1);
}, retryInterval);
}
};
return () => {
ws.close();
};
}, [retry]);
return { send, data, readyState };
}
So based on this, every-time the connection is closed, the connection will retry again.
Besides, when a restaurant launches the app the following code will be implemented:
const ws = useWebSocketLite({
socketUrl: `wss://${url}/id=${user.user_id}&role=restaurant`
});
This useEffect to establish the connection:
useEffect(() => {
if (ws.readyState === true) {
setConnectionOpen(true);
}
}, [ws.readyState]);
and this useEffect to handle incoming messages
useEffect(() => {
if (ws.data) {
const message = ws.data;
//dispatch...
}
}, [ws.data]);
Express server implementation:
This is the code where i handle socket connections and messages in express server:
var webSockets = {}
function setupWebSocket(server) {
server.on('connection', (socket, req) => {
if (req) {
var clientId = req.url
let regexReplace = /[\[\]/]/g
let regex = /([^=#&]+)=([^?&#]*)/g,
params = {},
match;
while ((match = regex.exec(clientId))) {
params[decodeURIComponent(match[1]).replace(regexReplace, '')] = decodeURIComponent(match[2])
}
if (params.role === 'restaurant') {
webSockets[params.id] = socket
}
}
socket.on('message', data => {
let sData = JSON.parse(JSON.parse(data))
let {id, data} = sData.data
sendToClient(id, 'order', data)
})
socket.on('error', (err) => {
console.log(err)
})
socket.on('close', (code, req) => {
var clientId = req.url
let regexReplace = /[\[\]/]/g
let regex = /([^=#&]+)=([^?&#]*)/g,
params = {},
match;
while ((match = regex.exec(clientId))) {
params[decodeURIComponent(match[1]).replace(regexReplace, '')] = decodeURIComponent(match[2])
}
if (params.role === 'restaurant') {
delete webSockets[clientId]
console.log(`${webSockets[clientId]} disconnected with code ${code} !`);
}
});
});
// sends a message to a specific client
const sendToClient = (clientId, type, data = {}) => {
const payload = { type, data }
const messageToSend = JSON.stringify({ error: false, message: payload })
if (webSockets[clientId]) {
webSockets[clientId].send(messageToSend)
console.log(`${clientId} client notified with this order`)
} else {
console.log(`${clientId} websocket client is not connected.`)
}
}
}
So most of the time I get 13 websocket client is not connected. which means the restaurant has already been deleted from the webSockets object and its connection already closed.
Apologise for long question and hope someone can help me regarding this.
A: First of all, you should know that this is not a good practice of websockets, where you are forcing the client (the restaurant) to be connected.
Whatever, at the current state of your code, there is an illogical behavior: at the end of the useEffect of your “useWebSocketLite” function, you are closing the socket connection:
return () => {
ws.close();
};
Knowing that the useEffect hook is called twice: after the first render of the component, and then after every change of the dependencies (the “retry” state in your case); Your code can be ridden like so: everytime the “retry” state changes, we will close the socket! So for me that is why you got the client disconnected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70766805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't generate a new migration in Rails I am trying to generate a new migration to add an Index to a table field with the following :
$ rails generate migration AddIndexToUserEmail
Though, unexpectedly I get the following message
C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-core-3.0.2/lib/rspec/core/formatters/b
ase_formatter.rb:1:in <top (required)>': uninitialized constant
RSpec::Support (NameError)
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
ib/rspec/legacy_formatters.rb:24:inrequire'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
ib/rspec/legacy_formatters.rb:24:in block in <top (required)>'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
ib/rspec/legacy_formatters.rb:13:ineach'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
ib/rspec/legacy_formatters.rb:13:in <top (required)>'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
me.rb:81:inrequire'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
me.rb:81:in rescue in block in require'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
me.rb:66:inblock in require'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
me.rb:59:in each'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
me.rb:59:inrequire'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:13
2:in require'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.1/lib/rails/comman
ds.rb:43:inrequire'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.1/lib/rails/comman
ds.rb:43:in <top (required)>'
from bin/rails:4:inrequire'
from bin/rails:4:in `'
I am not sure what has to be understood here as I had same Constant Unitinialized error when trying to do tests with RSPEC (before I found the right setup).
Though this is a different context here
A: Seems the problem was coming from the following gem:
gem "rspec-legacy_formatters", :group => [:development, :test]
Not sure why I added it to the gem file. I removed it and did a
$ bundle install
which solved the problem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24727191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regex Expression that matches a pattern except for specific matches I'm trying to extract Names from a HTML Response using a RegEx. So far I'm able to do so except I'm getting more than I need, I want to NOT match specific strings such as "Date" or "Today".
Here is my regex:
<li class="rcbItem">([^:()]{1,20})<\/li>
And here is a portion of the HTML response against which I'm running the pattern:
<div class="rcbSlide" style="z-index:6000;">
<div id="ctl07_ddInspector_DropDown" class="RadComboBoxDropDown RadComboBoxDropDown_Default " style="float:left;display:none;">
<div class="rcbScroll rcbWidth" style="width:100%;">
<ul class="rcbList" style="list-style:none;margin:0;padding:0;zoom:1;">
<li class="rcbItem">...Default Inspector (if any)</li>
<li class="rcbItem">Andy Schene</li>
<li class="rcbItem">gilberto hubner</li>
<li class="rcbItem">Jim Tinner</li>
<li class="rcbItem">Kenneth Donovan</li>
<li class="rcbItem">RENTAL REG INSPECTORS</li>
<li class="rcbItem">Rob Barker</li>
<li class="rcbItem">Robert Costello</li>
<li class="rcbItem">Ryan BalFour</li>
<li class="rcbItem">Sean Angeley</li>
<li class="rcbItem">Krissy King</li>
</ul>
</div>
</div>
</div>
<input id="ctl07_ddInspector_ClientState" name="ctl07_ddInspector_ClientState" type="hidden" />
</div>
<span id="ctl07_lblInspector" class="pnlData"/>
</td>
</tr>
<tr>
<td>
<span id="ctl07_lblSetDefaultLabel" class="pnlLabelLight">Set Default</span>
</td>
<td>
<div id="ctl07_ddSetDefault" class="RadComboBox RadComboBox_Default pnlDD" style="width:175px;">
<table summary="combobox" border="0" style="border-width:0;border-collapse:collapse;table-layout:fixed;width:100%">
<tr class="rcbReadOnly">
<td class="rcbInputCell rcbInputCellLeft" style="margin-top:-1px;margin-bottom:-1px;width:100%;">
<input name="ctl07$ddSetDefault" type="text" class="rcbInput radPreventDecorate" id="ctl07_ddSetDefault_Input" value="Next Day (Default)" style="display: block;" readonly="readonly" />
</td>
<td class="rcbArrowCell rcbArrowCellRight" style="margin-top:-1px;margin-bottom:-1px;">
<a id="ctl07_ddSetDefault_Arrow" style="overflow: hidden;display: block;position: relative;outline: none;">select</a>
</td>
</tr>
</table>
<div class="rcbSlide" style="z-index:6000;">
<div id="ctl07_ddSetDefault_DropDown" class="RadComboBoxDropDown RadComboBoxDropDown_Default " style="float:left;display:none;">
<div class="rcbScroll rcbWidth" style="width:100%;">
<ul class="rcbList" style="list-style:none;margin:0;padding:0;zoom:1;">
<li class="rcbItem">Next Day (Default)</li>
<li class="rcbItem">Today</li>
<li class="rcbItem">Specified Date</li>
<li class="rcbItem">Next Available (Insp Cap)</li>
<li class="rcbItem">No Specified Date</li>
</ul>
</div>
</div>
</div>
I'm aware of negative lookaheads and this other post: Regex that matches a pattern and doesn't match specific words. But I can't make that work for me. The following still brings back the unwanted matches:
<li class="rcbItem">((?!Date$)[^:()]{1,20})<\/li>
A: *
*You don't want Date$ because the $ means "This is the very end of the string."
*Since your examples show that the unwanted strings containing "Date" have it appearing right before </li>, you want to put your negative lookaround right there, not earlier.
*Now, since you want to be looking backward to find Date, you want a lookbehind, not a lookahead. (add < in the middle of your ?!)
This ends up looking like:
<li class="rcbItem">([^:()]{1,20})(?<!Date)<\/li>
If you're also trying to remove "Today" entries, then make it Today|Date:
<li class="rcbItem">([^:()]{1,20})(?<!Today|Date)<\/li>
P.S.: Do you really need to check for all that whitespace at the beginning?
A: As the location of 'Date' or 'Today' is not fixed,
so here is my suggestion:
string[] filter = {"date","today"};
var result = Regex.Matches(yourhtml,"(?i) <li class=\"rcbItem\">([^:()]{1,20})<\/li>")
.Cast<Match>()
.Where(m=>!filter.Any(f=>m.Groups[1].Value.ToLower().Contains(f)));
A: You cannot use the $ because it indicates the end of the entire string.
Try this one:
<li class="rcbItem">((?!(.)*(Date|Today))[^:()]{1,20})<\/li>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45247487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can a stack allocated Rust buffer be accessed through C++? In order to avoid head allocations, and since I know the maximum MTU of an ethernet packet, I created a small buffer: [u8, MAX_BYTES_TRANSPORT] in Rust, that C++ should fill for me:
pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> std::result::Result<(), &str> {
let mut buffer: [u8; MAX_BYTES_TRANSPORT] = [0; MAX_BYTES_TRANSPORT];
//number of bytes written in buffer in the C++ side
let written_size: *mut size_t = std::ptr::null_mut::<size_t>();
let r = unsafe{openvpn_client_receive_just(
buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client)};
So, the function openvpn_client_receive_just, which is a C++ function with C interface, should write to this buffer. Is this safe? I couldn't find information about a stack allocated Rust buffer being used in C++
This is the function:
uint8_t openvpn_client_receive_just(
uint8_t *buffer, size_t buffer_size, size_t *written_size, OpenVPNSocket *client)
A:
Can a stack allocated buffer be accessed through C++?
Yes.
From the type-system perspective there is no difference between statically allocated, stack allocated, or heap allocated: the C signature only takes pointer and size, and cares little where that pointer points to.
Is this safe?
Most likely.
As long as the C function is correctly written and respects the bounds of the buffer, this will be safe. If it doesn't, well, that's a bug.
One could argue that it's better to have a heap-allocated buffer, but honestly once one starts writing out of bounds, overwriting arbitrary stack bytes or overwriting arbitrary heap bytes are both bad, and have undefined behavior.
For extra security, you could use a heap allocated nested between 2 guard pages. Using OS specific facilities, you could allocate 3 contiguous OS pages (typically 4KB each on x86), then mark the first and last as read-only and put your buffer in the middle one. Then any (close) write before or after the buffer would be caught by the OS. Larger jumps, though, wouldn't... so it's a lot of effort for a mitigation.
Is your code safe?
You most likely need to know how many bytes were written, so using a null pointer is strange.
I'd expect to see:
let mut written: size_t = 0;
let written_size = &mut written as *mut _;
And yes, that's once again a pointer to a stack variable, just like you would in C.
A note on style. Your Rust code is unusual in that you use fully typed variables and full paths, a more idiomatic style would be:
// Result is implicitly in scope.
pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> Result<(), &str) {
let mut buffer = [0u8; MAX_BYTES_TRANSPORT];
let mut written: size_t = 0;
let written_size = &mut written as *mut _;
// Safety:
// <enumerate preconditions to safely call the function here, and why they are met>
let result = unsafe {
openvpn_client_receive_just(
buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client)
};
translate_openvpn_error(result)?;
let buffer = &buffer[0..written];
f(buffer);
Ok(())
}
I did annotate the type for written, to help along inference, but strictly speaking it should not be necessary.
Also, I like to preface every unsafe call I make with the list of pre-conditions that make it safe, and for each why they are met. It helps me audit my unsafe code later on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66503106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compare count of characters with a constant value, then execute next statement I have a PowerShell script where I get the count of certain string from a file, then go to next step or execute next step only if the string count is 30.
I do have the code for getting the count of the string, as well the code for executing the next step. The only thing missing is to incorporate if statement.
To get the count of string, I am using the following:
$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches
To do the next step, I am using following;
"d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm%
How to include if condition in between above two codes, so that last command will follow, only if the count of the string is more than 30?
A: First off, don't use $Matches for anything user-defined - it's an automatic variable.
With that out of the way: since Select-String may return multiple lines, you should sort them by length and test the length of the longest one:
$FileContent = Get-Content "YourFile.txt"
$LongestMatch = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches |Sort-Object {$_.Line.Length} |Select-Object -Last 1
if($LongestMatch.Line.Length -gt 30){
# We found a match in a string longer than 30 chars!
# run plink here!
}
A: This may be too simplistic. I feel like there is something I must have missed in the question.
$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches
if ($Matches -eq 30) {
& "d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm%
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39691048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Better way to combine tables than multiple joins? I have two dfs, df1 and df2. I need to combine the dfs in a way that might require multiple left joins, but I have a feeling there's a better way to do this.
df1 is a table of locations and people (id numbers) associated with them, it looks like this.
location person1 person2 person3 ... personn
1 12 450 2 ... 90
2 23 218 4 ... 3
3 1000 274 937 ... 318
.... ... ... ... ... ...
1350 1 41 10 ... 101
df2 contains information about the people. It looks like this:
person year action
1 2020 a
2 2020 a
3 2020 b
4 2020 c
1000 2020 a
1 2019 c
2 2019 b
3 2019 a
4 2019 c
... ... ...
1000 2019 b
Ideally, I'd like the combined dataset to look like this:
location year action_a_count action_b_count action_c_count ... action_n_count
1 2020 1 0 0 ... ...
2 2020 0 1 1 ... ...
3 2020 1 0 0 ... ...
1350 2020 1 0 0 ... ...
1 2019 0 1 0 ... ...
2 2019 0 1 1 ... ...
3 2019 0 1 0 ... ...
1350 2019 0 0 1 ... ...
... ... ... ... ... ... ...
Right now my instinct is to do a series of left joins to get the actions for each person into df1, then figure out a way to count them.
A: You could restructure df1 to have 2 columns, location and person. That would simplify the subsequent operations.
df1_new = df1.melt(id_vars='location',
value_vars=df1.columns[1:],
value_name='person')
df1_new = df1_new.drop('variable', axis=1)
Now you can join df2 and df1_new
combined = df2.join(df1_new.set_index('person'), on='person', how='left')
Then create a pivot table
combined.pivot_table(index=['location', 'year'], columns='action', aggfunc='count')
After the pivot table is created, you can rename the columns however you'd like.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61328734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where should logic go for deciding which SQL query to execute I have a DAO with a method CommitmentListDAO.getListByOwnerBadge that returns an arraylist of commitment items against a supervisor badge (database field OWNED_BY)
String SQL_VIEW_LIST_BY_SUPERVISOR = SELECT_QUERY +
" WHERE c.OWNED_BY = ? " +
" ORDER BY p.PROGRAM_NAME";
Now, I want to add a pull down on my web form to allow the user to choose between Owned By or Tasked To
I'll need to add a WHERE c.TASKED_TO = ? clause in the DAO.
Do I perform the logic for which field to search on within the DAO - say a passed in parameter of the pulldown (Never the request object) and rename the method to getListByBadge(String whichField, String badge) or should my CommitmentListForm class have this logic and then make the appropriate call to either getListByOwnerBadge or getListByTaskeToBadge
A: I would go with a DAO on it with two different methods to clearly differentiate what the call does.
The point of a DAO is to hide the SQL implementation details. You should always consider a question like this from the standpoint of, "What if I switched to a different persistence mechanism, like HBase?" The HBase implementation may not store this in a way that simply differentiates by a field name. The DAO should make it possible to hide that detail, thus the different methods.
Just my opinion, of course. :)
A: I would determine the logic in your controller and separate the two SQL queries into getListByOwnerBadge or getListByTaskeToBadge. That way you avoid having a method that "does it all" and could quickly get out of hand. Furthermore, other developers who choose to use the "does it all" method will have to inspect the method's internals to see what valid Strings can be passed in, whereas an explicit method call makes it obvious as to what the method is accomplishing.
A: I think that the second solution is better. Keep DAO as simple as it is possible. No logic, no flags. Create 2 simple methods and make decision in form which one to call. Or even create yet another layer between form and DAO that decides which DAO method to call.
A: To summarize:
From @McStretch - The logic for which to call goes in your controller.
From @rfreak - The query methods themselves go in the DAO
Here's an example:
//Controller
CommitmentListAction {
updateForm(...){
List<CommitmentItem> commitmentItems;
if (formUsesOwnedBy){
commitmentItems = CommitmentItemDAO.getListByOwnerBadge(...);
} else {
commitmentItems = CommitmentItemDAO.getListByTaskeToBadge(...);
}
// Do stuff with commitmentItems.
}
// DAO
getListByOwnerBadge(...){
String SQL_VIEW_LIST_BY_SUPERVISOR = SELECT_QUERY +
" WHERE c.OWNED_BY = ? " +
" ORDER BY p.PROGRAM_NAME"
return doQuery(SQL_VIEW_LIST_BY_SUPERVISOR); // Performs the actual query
}
getListByTaskeToBadge(...){
String SQL_VIEW_LIST_BY_TASKED_TO = SELECT_QUERY +
" WHERE c.TASKED_TO = ? " +
" ORDER BY p.PROGRAM_NAME"
return doQuery(SQL_VIEW_LIST_BY_TASKED_TO); // Performs the actual query
}
If you're going to have many different views of the CommitmetItems or many different criteria, consider passing in the criteria to the DAO. But only do this at the time when it appears there is an excessive number of getListBy[blah] methods polluting the DAO.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4795744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gitlab CI Runner slow to complete job I've been using the GitLab CI runner on Windows for a couple of years now, and am wondering why it takes a long time between when the compile has actually completed before GitLab deems that the job has completed.
Here's a few screen grabs to show what I'm talking about. This one shows that the compilation is complete:
MSBuild is complete, so the build stage is complete. The 31 second time is the time it took MSBuild to finish, but there was another minute or so of getting packages from NuGet and Bower and NPM before that. Here's a picture of the current job running time:
But then GitLab sits with the 3 dots for another two minutes or so before it decides the job has actually succeeded:
I turned on CI_DEBUG_TRACE but it didn't show much that seemed useful to me. I've also played around with caching and artifacts but turned them off because the artifacts were too big and it didn't significantly change the build time. Here's the .gitlab-ci.yml file:
stages:
- build
- test
before_script:
- '.nuget\\nuget.exe restore <name>.sln'
- 'call bower install'
- 'call npm install'
- 'call gulp'
cache:
build:
stage: build
dependencies: []
script:
- '"C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe" <name>.sln /t:ReBuild /p:Configuration=Release'
retry: 2
test:
stage: test
dependencies: []
script:
- '"C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe" <name>.sln /t:ReBuild /p:Configuration=Release'
- ".\\packages\\xunit.runner.console.2.3.1\\tools\\net452\\xunit.console.exe UnitTest\\bin\\Release\\UnitTest.dll"
retry: 2
A couple of minutes doesn't seem too bad except it's happening with each stage in the pipeline, so it adds up quickly.
In the past that 2-minute delay didn't happen, but I don't know what might have changed or what I might have done to cause it. The runner is the latest version.
Any ideas or suggestions?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50070902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Access: Combining multiple rows into one, but show text I am trying to form a single row from multiple rows by using GROUP BY in my SQL statement.
Problem is, the raw data I am working with contains data that I do not need, and all the fields are populated with text strings.
For example,
ID COURSE
01 Baking 101
01 Driving 102
01 Writing 101
02 Baking 102
02 Writing 101
I don't need 'Writing', only 'Baking' and 'Driving'. So I'd like my data to turn up like this:
ID Baking Driving
01 Baking 101 Driving 102
02 Baking 102 -
I am selecting records by seeing if they contain the relevant keywords, because my raw data source contains the course history of all courses, not just the ones that I am concerned with. And the spelling of the courses can vary for the same course.
As of now, I am using a IIf statement to return a 1 if the keyword is present and a 0 if the keyword isn't. I then Sum it and GROUP BY my ID (Personal identifier). So my table turns out a bit like this.
ID Course1 Course2 Course3 Course4 Course5
01 1 0 0 1 0
02 0 1 1 0 0
What I would like is for my query to display the record IF the record contains a certain keyword, while still grouping and truncating all related records into a single row.
A GROUP BY function can't do that (afaik) because it doesn't know how to handle text strings (i.e. it doesn't know which record to display), which is why I am using an IIf to generate a number then Sum to allow GROUP BY. Is there a way for me to perhaps convert the number back into the text (i.e. the text that satisfies my IIf statement)
I apologise for not being able to provide an actual sample of the data, but it's corporate data that I can't share unfortunately.
Edit:
What I mean when I say the spelling varies is something like this:
1.Baking 101 Cse
2.Baking 101 Course
3.Baking-101 Cse
So as of now, my SELECT statement is something like this
SELECT Courses.CourseName,
Sumiif((Courses.CourseName Like "*Baking*",1,0) AS BAKING
FROM Courses
GROUP BY Courses.PersID
This is quite a bit simplified, because I have more than 1 course to handle.
So the problem I am facing is that I want to display the actual data in the field, and not the result of my IIf function. i.e. instead of a 1, I want to see the name of the course. However, I also need to group by my primary key, which requires that I use an aggregate function. I am not aware of an aggregate function that can do this with strings.
A: Consider a table or query like:
+----------+------------+---------------+
| CourseID | CourseName | CourseSection |
+----------+------------+---------------+
| 01 | Baking | 101 |
| 01 | Driving | 102 |
| 01 | Writing | 101 |
| 02 | Baking | 102 |
| 02 | Writing | 101 |
+----------+------------+---------------+
And query:
TRANSFORM First(Courses.CourseSection) AS FirstOfCourseSection
SELECT Courses.CourseID
FROM Courses
WHERE (((Courses.CourseName)<>"Writing"))
GROUP BY Courses.CourseID
PIVOT Courses.CourseName;
Output:
+----------+--------+---------+
| CourseID | Baking | Driving |
+----------+--------+---------+
| 01 | 101 | 102 |
| 02 | 102 | |
+----------+--------+---------+
If your course names are less consistent for spelling and the name and section are actually in one field but the section suffix is consistent, then emulate a crosstab like:
SELECT Courses.CourseID, Max(IIf(InStr([CourseName],"Baking")>0,Right([CourseName],3),Null)) AS Baking,
Max(IIf(InStr([CourseName],"Driving")>0,Right([CourseName],3),Null)) AS Driving
FROM Courses
GROUP BY Courses.CourseID;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47160734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to download a file from the server using a POST request or a more secure method without using a GET request for iOS application. I do not want to use asihttp methods so is there a way to download a file from the server without having to use a get request? How to use a post request to download the file from the server?
A: Since the OP wants the answer regardless, I will use PHP for this.
iOS client side:
NSString *phpURLString = [NSString stringWithFormat:@"%@/getFile.php", serverAddress];
NSURL *phpURL = [NSURL URLWithString:phpURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:phpURL];
NSString *post = [NSString stringWithFormat:@"filePath=%@", filePath];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]:
For the PHP side:
<?php
$filePath = htmlspecialchars($_POST['filePath']);
$fileData = file_get_contents($filePath);
echo $fileData;
?>
This is very basic. Also for the iOS side you would want to wrap that entire request in a code block that is run asynchronously in the background. You could use GCD for that. Once you have the file as responseData in iOS you can save the file to the local container and then do many things with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11770183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Populating Tabs WinForms Goes Undetected without User View This might just be a small quirk. But I've built a small windows form application with multiple tabs.
I have a feature that allows users to "load" the entries in each of the tabs by opening a json file. This lets them avoid manually inserting the data. At the same time, I have a "check" to make sure that all required fields have been populated.
What I've found is that even if the load process is successfully populating all the right fields, the user still needs to select each tab (even though they are already filled), in order to avoid hitting the flag.
Hopefully, this makes sense. Right now, my work around is to have the program flip through each tab automatically upon "load", but it seems strange that winforms can't detect a text box has been filled unless the tab is viewed.
Any advice?
A: Some events only fire when the control is visible. This sounds like what you should do is decouple the text entries from the control and store them in another object which fires off the filled events then do data binding to those entries.
This has the nice benefit of decoupling the UI from the data storage (always a nice thing) as well as freeing you from the vagaries of the .net UI system (both winforms and wpf have 'interesting' quirks like the above which assume specific behavior preferences).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27724673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: About linux kernel module Does the kernel module need a linux kernel to finish the compilation ?
Can I compile a kernel module without kernel ?
What I mean is: copy the needed kernel header, manually write makefile or manually compile. and without using the kernel building system.
A: Lovespring,
You will need a copy of the kernel source or kernel headers for the kernel you are attempting to compile against. The kernel source is generally not installed with the system by default.
Typically, you can pull down a copy of the kernel source through whatever package/repository manager your have.
A: You may not need an installed kernel, but you will definitely need a copy of the source to be able to compile your module.
A:
Does the kernel module need a linux kernel to finish the compilation ?
Can I compile a kernel module without kernel ?
Yes, you can have single Makefile for your module source code. It still needs to find the kernel headers and some basic build tools.
you do not need to have the kernel sources, and you do not need to recompile the kernel.
Page #94 of this chapter may help:
http://www.linuxfordevices.com/files/misc/newnes_embedded_linux_ch7.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4867278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ggplot2 density of circular data I have a data set where x represents day of year (say birthdays) and I want to create a density graph of this.
Further, since I have some grouping information (say boys or girls), I want to use the capabilities of ggplot2 to make a density plot.
Easy enough at first:
require(ggplot2); require(dplyr)
bdays <- data.frame(gender = sample(c('M', 'F'), 100, replace = T), bday = sample(1:365, 100, replace = T))
bdays %>% ggplot(aes(x = bday)) + geom_density(aes(color = factor(gender)))
However, this gives a poor estimate because of edge effects.
I want to apply the fact that I can use circular coordinates so that 365 + 1 = 1 -- one day after December 31st is January 1st.
I know that the circular package provides this functionality, but I haven't had any success implementing it using a stat_function() call.
It's particularly useful for me to use ggplot2 because I want to be able to use facets, aes calls, etc.
Also, for clarification, I would like something that looks like geom_density -- I am not looking for a polar plot like the one shown at: Circular density plot using ggplot2.
A: To remove the edge effects you could stack three copies of the data, create the density estimate, and then show the density only for the middle copy of data. That will guarantee "wrap around" continuity of the density function from one edge to the other.
Below is an example comparing your original plot with the new version. I've used the adjust parameter to set the same bandwidth between the two plots. Note also that in the circularized version, you'll need to renormalize the densities if you want them to add to 1:
set.seed(105)
bdays <- data.frame(gender = sample(c('M', 'F'), 100, replace = T), bday = sample(1:365, 100, replace = T))
# Stack three copies of the data, with adjusted values of bday
bdays = bind_rows(bdays, bdays, bdays)
bdays$bday = bdays$bday + rep(c(0,365,365*2),each=100)
# Function to adjust bandwidth of density plot
# Source: http://stackoverflow.com/a/24986121/496488
bw = function(b,x) b/bw.nrd0(x)
# New "circularized" version of plot
bdays %>% ggplot(aes(x = bday)) +
geom_density(aes(color = factor(gender)), adjust=bw(10, bdays$bday[1:100])) +
coord_cartesian(xlim=c(365, 365+365+1), expand=0) +
scale_x_continuous(breaks=seq(366+89, 366+365, 90), labels=seq(366+89, 366+365, 90)-365) +
scale_y_continuous(limits=c(0,0.0016))
ggtitle("Circularized")
# Original plot
ggplot(bdays[1:100,], aes(x = bday)) +
geom_density(aes(color = factor(gender)), adjust=bw(30, bdays$bday[1:100])) +
scale_x_continuous(breaks=seq(90,360,90), expand=c(0,0)) +
ggtitle("Not Circularized")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36266402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Slow threading performance on Linux on ARM9 When I write a simple application, running for 10 minutes, that starts 10 threads once (pthreads), each sleeping for 1 ms in a loop (not doing anything else) the CPU is used ca. 44% (top reports that). It is a ARM9 CPU with 450 MHz, Linux 2.6.37 is used as OS. There is no other program running, it tried out different kernel configs (Dynamic Ticks, Soft/Hard IRQ, High Resolution Timer, ..., ..., ...), different priorities (up to 99) but the numbers stay the same. /usr/bin/time -v shows ca. 5'200'000 voluntary context switches and ca. 3 minutes are spent in Kernel space. Sleepin in each thread for ca. 5 ms and the CPU utilization goes down to ca. 9% which is IMO still crazy (40'500'000 cycles to safe some registers). clock_nanosleep was used for sleeping (CLOCK_REALTIME/CLOCK_MONOTONIC did not change anything).
I'm aware that a full context switch is expensive on ARM9 because caches have to be cleared. But a simple thread switch, or switch to the OS shouldn't be that expensive IMHO (address space remains the same, no cache/TLB flushing required). Is this common or should I try to find the bottleneck in the kernel?
A: You're busily waking up and going back to sleep at 100uS intervals -- 10 threads, 1ms, that's 100uS on average. And keep in mind that you have two context switches for each of those 100uS intervals, so you have a context switch every 50uS on average, or 20,000 times per second.
Perhaps that's the answer you're looking for?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10152497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to import an old Excel file with extension.xls? I have a file from SAS that is exported as an older Excel .xls file. I would like to import this file into python 3.5.
when I do:
import pandas as pd
Filewant = pd.read_excel("Filepath\\\Filename.xls")
I get a bunch of error messages culminating in
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'<html xm'
if I open up the file and manually save it in a current .xlsx file and us the same command line using:
Filewant =pd.read_excel("Filepath\\Filename\.xlsx")
then the file is imported into Python properly. However, I want the process to be more automated so I don't to have to manually save the file to .xlsx format to make it work.
A: SAS tech support told me that this won't work and that I'll need to convert the .xls SAS output into a .xlsx file:
Unfortunately, the MSOffice2K destination creates an HTML file even though it uses the .XLS extension here which allows the file to be opened with excel.
You can use VBScript to convert the file to .XLSX, however, there is no way to do this using the MSoffice2K destination.
A: The error message tells you the problem. found b'<html xm' Your file is an HTML file and not an XLS file. This was commonly done with "old" SAS since it did not support writing XLS files, but Excel did support reading HTML files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40476327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Azure Logic App: Azure DevOps "When A Work Item Is Closed" trigger not firing at times I have automated some processes for when work items are closed in Azure DevOps (Boards) but on occasion the Azure Logic App is not triggered. I know this cause I have a different logic app that checks the counts between closed work items and my data warehouse and the newly closed work item is missing. I have check and the Logic App was just never triggered. There is nothing for that day the work item was closed. If I were to update the work item from closed to not closed (save) then back to closed (save) the Logic App is triggered fine. Has anyone else run into this? Is this a flaw in the Azure DevOps or Azure Logic App or Azure itself where it hiccups and just doesn't fire the event or see an event has been fired? I would expect this to be process to be seamless and work 100% of the time.
Question update:
I have several Azure Logic Apps that use the Azure Devops "When A Work Item Is Closed" Trigger connector. Several because we have different Project Names and Types I want to trigger the "When A Work Item Is Closed" event. The recurrence of the logic apps was every 3 minutes but I have since updated them to be every 1 hour. A handful of the logic apps are again failing on what would be the recurrence trigger time. And it continually fails every hour thereafter.
enter image description here
When reviewing the Output links of the failure the message states "BadGateway", InnerError "500", and Error Message "Unknown error occurred"
This is happening with a few of the logic apps. All my logics apps are in the same subscription and the same resource group using the same API Connection and SQL Database connections.
A: I deleted my logic app, and re-deployed it and the Logic App is executing as expected and the Trigger history (where it was showing Failed previously) shows as either Skipped (nothing to do) or Succeeded.
Strange that only a handful of my Logic Apps were failing, but this fixed my issue at this time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70336948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: SQLite and Android Exception I am facing problem in android application i want to create database with following script.
CREATE TABLE IF NOT EXISTS events (
_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
source_device_id INT,
timestamp INT NOT NULL,
processed BOOLEAN DEFAULT FALSE,
event_type TINYINT NOT NULL,
payload BLOB);
CREATE INDEX IF NOT EXISTS events_unprocessed ON events (processed, _id);
and my android code is
public void onCreate(SQLiteDatabase db) {
InputStream schemaStream = context.getResources().openRawResource(R.raw.logdb_schema);
Scanner schemaScanner = new Scanner(schemaStream, "UTF-8");
schemaScanner.useDelimiter(";");
Log.i(TAG, "Creating database");
try {
db.beginTransaction();
while (schemaScanner.hasNext()) {
String statement = schemaScanner.next();
Log.d(TAG, "Creating database: " + statement);
db.execSQL(statement);
}
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
}
}
Its not working its generating run-time exception:
android.database.sqlite.SQLiteException: not an error:
A: I had this problem because of whitespace after the last semicolon in my schema. My java code was executing that whitespace as a separate query.
On Froyo it complains, on Ice Cream Sandwich it doesn't cause a problem.
A: My guess would that you are using a BOOLEAN & TINYINT type which are not supported. You need to use INTEGER instead
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7882580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fix cx_Oracle: DLL load failed? There are so many related questions that I have gone through which made me wonder how come this is such a prevalent issue? Anyways, I am trying to use cx_Oracle module.
I have the :
instant client: instantclient-basic-win32-11.1.0.6.0.zip
python - 3.4
cx_Oracle - cx_Oracle-5.2-11g.win32-py3.4.exe
I have set up Path as well as the ORACLE_HOME variables. Why is that I still get this error?
Edit: I tried installing cx_oracle again, but this time through install command on the setup.py instead of the .exe. I got an error distutils.errors.DistutilsSetupError: cannot locate Oracle include files in C:\oracle\client
C:\Oracle\Client is where my instant client resides that's where my path and Oracle_Home point to. Any idea how to overcome this problem?
A: Well, I figured out how to fix it.
*
*The Oracle Instant Client version I had should be instantclient-basic-nt-11.2.0.4.0.zip
*Oracle Home is not needed at all
*When mentioning the path of instant client in the path variable, it should be the last if any other oracle client is already available in the machine.
Once I fixed these, it just worked like a charm!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31134947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is this activity designed with cardviews? I am trying to design a layout similar to the one on the left image .
I thought this was a layout with one cardview for each section. However, I tried to put more than one cardview inside a LinearLayout orientation vertical and I only see one.
Why is that? Are cardviews are just meant to be used on RecyclerViews lists? If so, how can I achieve a layout design like these?
A: Reference for CardView. It is just a RelativeLayout with a rounded corners and a drop shadow. So yes, the image was probably an image of a layout designed with CardViews. At the same time, it could also just be a layout that was custom built and a shadow drawn behind it, if that developer wanted to do the work themselves. You can easily replicate the layout by creating this in xml, I can provide an example if necessary.
The CardView is not JUST designed for RecyclerView's but looks really good in a RecyclerView as the layout that is inflated IF a CardView layout makes sense to use. Again, it's just a RelativeLayout with extra features (rounded edges, and shadow)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34053533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Is there a static alternative of format!()? This is what I'm trying to do:
fn foo() -> &'static str {
let x = "Jeff";
return &format!("Hello, {}", x);
}
I understand that it's not possible, since format!() makes a String in heap, while the result of foo is expected to be in static memory. Is there a similar macro/function, which would work like this:
fn foo() -> &'static str {
let x = "Jeff";
return static_format!("Hello, {...}", x);
}
Here, {...} is a five-bytes placeholder for world. The macro static_format! should allocate Hello, {...} in static, fill it up with arguments, and return it. Or maybe something else is possible, to simplify the process of formatting-and-returning static strings?
A: I read your question and some of the comments as @sirdarius suggested you can use const_format for fancy formatting or simply use concat! from the standard library.
You mention that const_format requires everything to be const and that's not suitable for your case. Unfortunately, that's not possible. If you don't know the shape of the thing at compile time you cannot use it at compile time because it simply does not exist yet. Adding another str to the end of &str requires heap allocation due to the unknown size of the the runtime str you are planning to use.
I hope this made compile time vs runtime a little more clearer for you
A: The only way to satisfy the signature of foo() and return a dynamic string is by leaking it:
fn foo() -> &'static str {
let x = "Jeff";
return Box::leak(format!("Hello, {}", x).into_boxed_str());
}
Caveat emptor: the return &'static str will never be freed, so this is only usable in cases where foo() is known to be called a fixed and small number of times, such as at program startup.
A: Depending on your use case, once_cell may be what you are looking for. It provides the generic Lazy<T> type that can be used to lazily initialize global data. Since the data is initialized at runtime, said initialization can do things that are impossible with compile time initialization.
Your function could be written like this:
use once_cell::sync::Lazy;
fn foo() -> &'static str {
static VALUE: Lazy<String> = Lazy::new(|| {
let x = "Jeff";
format!("Hello, {}", x)
});
&VALUE
}
or, if the name can be a static too, you can move it outside of the function:
use once_cell::sync::Lazy;
static NAME: &str = "Jeff";
fn foo() -> &'static str {
static VALUE: Lazy<String> = Lazy::new(|| {
format!("Hello, {}", NAME)
});
&VALUE
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70825018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to refresh AWS temporary credentials from within an app running in EC2 We have a java app that runs within an EC2. This uses AWS SDK to interact with AWS services. The app uses the default credentials provider which in turn uses the temporary tokens from the EC2.
The problem is that this temporary token expires after a while and all subsequent AWS SDK calls fail. How can we refresh this temporary credentials so that the app can use the new valid credentials?
A: InstanceProfileCredentialsProvider retrieves credentials as needed; a client using it should never see a credentials timeout exception.
This implies that either (1) you are explicitly setting instance profile credentials on the client that is timing out, or (2) there is something else in the provider chain that is providing limited-time credentials.
Or, I suppose, you might be using an extremely old version of the SDK. I don't know at what point they added automatic refresh; according to git blame, the fetcher variable was last changed 13 months ago. But I've been using instance credentials with long-running processes for much longer than that.
A: This article may help you.
If you really need to get a new credentials, the following example shows pseudocode for how to use temporary security credentials if you're using an AWS SDK:
assumeRoleResult = AssumeRole(role-arn);
tempCredentials = new SessionAWSCredentials(
assumeRoleResult.AccessKeyId,
assumeRoleResult.SecretAccessKey,
assumeRoleResult.SessionToken);
s3Request = CreateAmazonS3Client(tempCredentials);
Read further info about temporary credentials in this docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65469023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I "move" an object from one table to another using OpenJPA? I have two tables, that share the same definition. I commonly insert new objects into one of these tables, let's call it Table1. From time to time, I want to move one entry from Table1 to the other table (Table2).
How can I achieve this using the OpenJPA Framework? The object is clearly bound to one table ...
@Entity
@Table(name="TRACKING")
public class TrackingEntry {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="LASTNAME")
private String lastName;
@Column(name="FIRSTNAME")
private String firstName;
// rest omitted
}
Any Ideas besides using an "on delete" trigger on database level? (I'd like to hold this logic in code only).
A: Well, I cannot think of a "one-step solution".
Your entities are inherently linked to a table. So, one solution could be to define a secondary entity class linked to your secondary table.
This secondary class could inherit from the first one to ensure compatibility, and you could provide a copy constructor that receives an instance of the parent and copies all attributes every time you want to move a record. Then you could delete the original record from the original table by deleting the original entity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6040969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with labels using library Charts with UIKit in XCode 12 Hell my friends.I'm developing an app which has to show several charts using UIKit and the library Charts. I've been requested to use both things.
I have two arrays with correct data Ciudades y Precios.
Ciudades is String type and Precios Double type. I'v been reading how to use Charts library for hours but it seems that I dont understand how to use it because the chart I get it's not the one I excpected to. I need a chart with the cities on x label but they are not showed as you can see in the picture.
This is my code
class BarChartViewController: UIViewController, ChartViewDelegate {
@IBOutlet weak var barChartView: BarChartView!
var nombres: [String]!
var precios: [Double]!
override func viewDidLoad() {
super.viewDidLoad()
barChartView.delegate = self
nombres = eventos.devolverNombre()
print(nombres)
precios = eventos.devolverPrecios()
setChart(dataPoints: nombres, values: precios)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "Es necesario añadir datos."
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
if dataEntry != nil {
dataEntries.append(dataEntry)}
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: "PRECIOS POR EVENTO")
let chartData = BarChartData(dataSet: chartDataSet)
chartDataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)]
chartDataSet.colors = ChartColorTemplates.colorful()
barChartView.data = chartData
barChartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
return self.nombres[Int(index)] })
let labelCount = nombres.count
print(labelCount)
barChartView.xAxis.setLabelCount(labelCount, force: true)
barChartView.xAxis.labelRotationAngle = 90
barChartView.xAxis.centerAxisLabelsEnabled = true
barChartView.xAxis.labelPosition = .bottom
barChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 10)
barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0, easingOption: .easeInBounce)
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74919222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Could not read the Interrupt Priority after vTaskStartScheduler() I want to use NVIC_GetPriority(DMA1_Channel4_IRQn) function with FreeRtos. I can use this function before the vTaskStartScheduler(); but, when I call NVIC_GetPriority(DMA1_Channel4_IRQn) function after vTaskStartScheduler();, it does not work do you have any suggestion?
#include <FreeRTOS.h>
#include <queue.h>
#include <task.h>
/* -- */
static void vTest_NVIC( void *pvParameters )
{
tprintf("\r\nTask Started...");
/* -- */
while(1) {
/* -- */
taskENTER_CRITICAL();
tprintf("\r\npriority= %d",NVIC_GetPriority(DMA1_Channel4_IRQn));
taskEXIT_CRITICAL();
vTaskDelay(3000);;
}
}
int main()
{
portBASE_TYPE xReturn;
/* -- */
xReturn = xTaskCreate ( vTest_NVIC, ( const signed portCHAR * const )"Test_NVIC", configMINIMAL_STACK_SIZE<<4, NULL, tskIDLE_PRIORITY, NULL );
if( xReturn != pdPASS ) {
tprintf("\n\rTest_NVIC initilisation problem.\n\r");
}
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_SetPriorityGrouping(3);
/* DMA1 Channel4 interrupt setting */
NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 11;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
tprintf("\r\npriority= %d",NVIC_GetPriority(DMA1_Channel4_IRQn));
/* Now all the tasks have been started - start the scheduler. */
vTaskStartScheduler();
The output of the program is like that.
priority= 11
Task Started...
Do you have any suggestions to read interrupt priority aftevTaskStartScheduler() start? Thanks from now.
A: I don’t know what microcontroller you’re using, but sometimes printf use interrupts to send characters through the UART and the like, if you make it a critical section that means the interrupt will never fire. Comment out the critical section lines to see if that’s the case.
Another possibility is that you have the MPU (memory protection unit) enabled, and it is not allowing access to the NVIC registers from a user task. AFAIK FreeRTOS has support for the MPU in Cortex-M microcontrollers, check if that is enabled in your case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53745655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Random encryption of string in C# I wanted to encrypt a string value with this method.
public string EncryptString(string inputString)
{
MemoryStream memStream = null;
try
{
byte[] key = { };
byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
string encryptKey = "aXb2uy4z";
key = Encoding.UTF8.GetBytes(encryptKey);
byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
memStream = new MemoryStream();
ICryptoTransform transform = provider.CreateEncryptor(key, IV);
CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.FlushFinalBlock();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return Convert.ToBase64String(memStream.ToArray());
}
The thing I want to do is that the encrypted string will always be random. Any one know how to do it? Please help.
A: Here is the code:
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int i = 0; i < r.Next(100); i++) sb.Append((char)r.Next(65, 255));
string s = sb.ToString();
Make sure you store the string or you won't be able to decrypt
A: If you want some random value for your encryption (for example a salt value, to make the usage of rainbow tables impossible), i always use Guids. They are unique and "random".
Be sure to keep your salt, because you will need it later, for example, if you want to proof wether a password is correct:
PASSWORD + SALT --encryption--> Hash
If you forget the salt, you will not be able to build the same Hash again.
If you want to encrypt passwords, you algorithm is not very useful. I would take the following code-snippet from SO: sha-256 hash in C#
Just be sure, that you pass password + hash to the method, to get your encrypted value with some random "touch".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28230974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: `ngc` failed with angular material2 I'm trying to build a Angular 4 Universal App, following this guide. However, it failed when I called ngc to generate NgModuleNgFactory, I got this error:
Error: Compilation failed. Resource file not found: /home/poi/Projects/solomon/src/app/module/archive/~@angular/material/theming
at ModuleResolutionHostAdapter.readResource (/home/poi/Projects/solomon/node_modules/@angular/compiler-cli/src/compiler_host.js:370:19)
at CompilerHost.loadResource (/home/poi/Projects/solomon/node_modules/@angular/compiler-cli/src/compiler_host.js:243:85)
at Object.get (/home/poi/Projects/solomon/node_modules/@angular/compiler/bundles/compiler.umd.js:24640:107)
at DirectiveNormalizer._fetch (/home/poi/Projects/solomon/node_modules/@angular/compiler/bundles/compiler.umd.js:13297:45)
at /home/poi/Projects/solomon/node_modules/@angular/compiler/bundles/compiler.umd.js:13426:53
at Array.map (native)
at DirectiveNormalizer._loadMissingExternalStylesheets (/home/poi/Projects/solomon/node_modules/@angular/compiler/bundles/compiler.umd.js:13426:14)
at /home/poi/Projects/solomon/node_modules/@angular/compiler/bundles/compiler.umd.js:13429:26
at process._tickCallback (internal/process/next_tick.js:109:7)
at Module.runMain (module.js:607:11)
Compilation failed
It looks like the compiler is trying to asscess a non-exist file /home/poi/Projects/solomon/src/app/module/archive/~@angular/material/theming, I imported ~@angular/material/theming in my scss following guide.
So how to talk where the compiler the file is? :(
FYI, the version of @angular/material is 2.0.0-beta.5, while @angular/compiler and @angular/compiler-cli are both 4.1.2.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44023734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: html5/javascript means can not protect source codes? I am learning html5/css3/javascript.
But I have found that the samples on the web disclose their source codes.
Does this mean html5/javascript can not protect source codes?
Welcome any comments.
A: All of those (HTML, CSS, JavaScript) work on the client side, always have, they are part of the presentation layer and the web browsers have always been capable of displaying the source code for what's presented to the user.
So no, you can't have closed-source projects that are solely based upon HTML, CSS and/or JavaScript
A: You can't really protect JavaScript since it has be run by the browser.
There are tools to obfuscate JavaScript but it's trivial to reverse the process.
A: One of the things that really irritates me about JavaScript is the fact that it is non-compiled. One way you can help combat this is by using a minifier before you deploy your source. Here is a good one for CSS and Javascript:
http://aspnet.codeplex.com/releases/view/40584
Another way you can manipulate the Document Object Model (DOM) without using Javascript is the use Silverlight/Flash or a Java/DOM API like:
http://www-archive.mozilla.org/projects/blackwood/dom/
You can also try using an obfuscator but usually minification does a fair job of obfuscation. Please don't rely on JavaScript to enforce secuity for your site since Javascript can be easily hacked. It is okay to use JavaScript to help the user find his/her way, but all client side Javascript validation must be followed up with Server Side validation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6147272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cannot convert the value of parameter 'Date' to the type 'System.DateTime'.' I use EntityDataSource , i get an error conversion after i format my date
like that :DataFormatString="{0:dd/MM/yyyy}"
[EntityDataSourceValidationException: Error while setting property 'fromDate': 'Cannot convert the value of parameter 'fromDate' to the type 'System.DateTime'.'.]
Microsoft.AspNet.EntityDataSource.EntityDataSourceView.ConvertProperties(IDictionary values, PropertyDescriptorCollection propertyDescriptors, ParameterCollection referenceParameters, Dictionary`2 convertedValues) +737
Microsoft.AspNet.EntityDataSource.EntityDataSourceView.ExecuteDelete(IDictionary keys, IDictionary oldValues) +383
System.Web.UI.DataSourceView.Delete(IDictionary keys, IDictionary oldValues, DataSourceViewOperationCallback callback) +84
Telerik.Web.UI.GridTableView.PerformDelete(GridEditableItem editedItem, Boolean suppressRebind) +228
Telerik.Web.UI.GridCommandEventArgs.ExecuteCommand(Object source) +2417
Telerik.Web.UI.RadGrid.OnBubbleEvent(Object source, EventArgs e) +91
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
My aspx:
<telerik:GridDateTimeColumn HeaderText="تاريخ البداية" UniqueName="fromDate" SortExpression="fromDate" DataField="fromDate" DataFormatString="{0:dd/MM/yyyy}"></telerik:GridDateTimeColumn>
Note : fromDate of type Date in sqlserver db
A: Try that:
<telerik:GridBoundColumn DataField="fromDate" DataType="System.DateTime" HeaderText="تاريخ البداية"
UniqueName="fromDate" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30211974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: d3.js: Multiple Series Line Chart With this code as a starting point: https://bl.ocks.org/d3noob/15e4f2a49d0d25468e76ab6717cd95e7 I'm attempting to make a simple line graph with multiple data series. Per @wasserholz suggestion, I've added a complete MVP: https://github.com/djmcmath/d3-fail-mvp
The data parsing portion seems to be working correctly, in that I'm creating a map with 5 elements, each of which is a "sailing date" and array of values associated with that date. This is the variable named "group_by_sailing_date".
The axes appear to be reasonable: For the X-axis, I'm taking the "since_midnight" value, pulling the extents, and formatting it as a time. The Y-axis, similarly, is just the extents of the "margin" value. I get this -- so far so good:
Next, I want to add some lines to my chart. My thinking is that I iterate through the map, and for each of the map elements, I add the element as data to a series. What I get is a gigantic "Nothing Happens" though. No lines, no errors, just "Gosh, your data looks great, but I'm going to ignore it."
//line generator?
var valueline = d3.line()
.x(function(d) { return x(d.since_midnight); })
.y(function(d) { return y(d.margin); });
group_by_sailing_date.forEach(function (s) {
svg_summ.append("path")
.data(s)
.attr("stroke", "steelblue")
.attr("stroke-width", "3px")
.attr("d", valueline);
});
I feel like I'm missing something really fundamental here, but I'm drawing a complete blank (pun intended, ha ha ha). Help?
A: Following the rules of selection within d3.js (https://bost.ocks.org/mike/selection/) the code should look something like this:
svg_summ.selectAll("path")
.data(group_by_sailing_date)
.enter()
.append("path")
.attr("stroke", "steelblue")
.attr("fill", "none")
.attr("stroke-width", "1px")
.attr("d", (d) => valueline(d));
A: Ok, I've made it work, but I don't know why. I removed the .data(s) line, and changed "valueline" to "valueline(s)". No idea why this works. Technically, it's all good, but I'd be thrilled if someone could help me understand what this code actually means.
group_by_sailing_date.forEach(function (s) {
svg_summ.append("path")
.attr("stroke", "steelblue")
.attr("fill", "none")
.attr("stroke-width", "1px")
.attr("d", valueline(s));
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73756011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where is the API documentation for boto3 resources? I have learned that boto3 offers two levels of abstraction: a low-level API called client that is a thin wrapper around the AWS HTTP API, and a high-level client called resource that offers real Python objects. My question is, where is the API documentation for the resource API?
I found this:
https://boto3.readthedocs.io/en/stable/reference/services/ec2.html#client
But that describes the client API, and there's not a 1-to-1 mapping to the resource API. For example, enumerating instances is called describe_instances() on the client object, and it is called instances.all() on the resource object.
Next I found this:
http://boto3.readthedocs.io/en/stable/reference/core/resources.html?highlight=resource
This describes a set of base classes and factory methods, but it doesn't describe the API for a specific service like EC2.
At runtime, I printed out an object of interest and found that it is a boto3.resources.factory.ec2.ServiceResource, but searching the boto3 documentation doesn't show me any human-readable documentation for this resource.
Is there an API document that explains what all of the different Python classes are, and what properties/methods they have? I can print this out at runtime, e.g. print(dir(ec2)) but this is a pretty tedious way to discover the API.
A:
Thanks @jordanm for answering in the comments. I'm expanding into a more detailed answer.
The client documentation contains a section called "Service Resource" that I had not noticed before.
Highlighted the service resource in the table of contents:
Clicking this heading shows me the methods and properties of an EC2 resource instance.
A: Hope this answer is useful to some even though its late.
Use these two links accordingly
Consider the 1st one as the Main reference. This is the link provided in the other answer
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#service-resource
Main reference
The 2nd one provides a more detailed view on the methods and attributes available for a particular resource like instance,image,VPC etc
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html
^this is almost the same link -- all options below the service-resource provide detailed info on that particular resource such as instance,image etc.,
common resources
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49177491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Add 1 year to the current date in a batch file Hi couldnt find anything here to help out with this one.
My company has a set of client folders that require a set of subfolders to be created at the end of each financial year. This is required to be a 2 digit representation of the year (ie - 14 Folder1 [for 2014] and so on).
I have a batch file that creates the folders every year, but have to modify the year every time. I am looking to schedule an auto mated solution, but i am stuck trying to add 1 additional year to the date. (as the folders need to be created at the end of the financial year, not calender year).
I am looking for a way to add 1 year to the current date. Here is my batch file so far. Any ideas anyone?
set YEAR= %DATE:~-2% + %DATE:~-2%
for /f "delims=|" %%s in ('dir /ad/b') do md "%%s\%YEAR% Folder1"
for /f "delims=|" %%s in ('dir /ad/b') do md "%%s\%YEAR% Folder2"
for /f "delims=|" %%s in ('dir /ad/b') do md "%%s\%YEAR% Folder3"
A: Like this :
set /a YEAR=%DATE:~-2% + 1
A: set /a YEAR=1%DATE:~-2%+1
set YEAR= %DATE:~-2%%YEAR:~-2%
This is assuming that you want 1415 for the 2014-2015 financial year.
Are you aware that your construct will yield a Space before the string? Spaces are significant in string-assignments - on both sides of the =.
It's safer to use
set "YEAR=%DATE:~-2%%YEAR:~-2%"
for instance - the rabbit's ears in this format ensure that trailing spaces are omitted (that can cause chaos)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24520398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the exact protocol differences between Azure AD "classic", ADFS "3.0" & B2C This answer describes the difference between MSAL and ADAL in various use cases and contexts (mobile, non mobile)
What are the exact protocol differences between these implementations?
A: Azure AD is available both through ADAL which uses the Azure AD v1 Endpoint and through MSAL which uses the Azure AD v2 Endpoint.
Azure AD B2C is accessible via the v2 endpoint but requires that a policy be indicated.
There are several differences between these. Your best bet is to compare the docs between the protocols/tokens of each:
*
*v1 endpoint - protocol doc & token doc
*v2 endpoint - protocol doc & token doc
*B2C - protocol doc & token doc
Just to name a few differences:
*
*v2 endpoint adds an extra v2.0 to the authorization and token endpoint URLs, https://login.microsoftonline.com/common/oauth2/**v2.0**/authorize
*v1 has a resource query parameter in the request to the authorization endpoint, v2 and B2C don't, it puts the resources as extra values in the existing scope query parameter. B2C has the extra p query string parameter
*The token has several differences including the value of the issuer and the name of some of the basic claims.
*v2 doesn't support the on-behalf-of flow yet. See v2 limitations doc as there are other protocol limitations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43019064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sub report text fields right alignment not working on jasper master report at run time I set right alignment in sub report text fields. Its showing in preview report but when I run this report from java then sub report text fields right alignment are not working.
Here is my java code
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection("jdbc:sqlserver://XYZ-BD-BBI01;user=abc;password=1234;database=myDataTables");
String report="C:\\Users/mainReport.jrxml";
JasperDesign jd = JRXmlLoader.load(report);
String sql = "select * from Report where ReportID = " + reportID;
JRDesignQuery query = new JRDesignQuery();
query.setText(sql);
jd.setQuery(query);
JasperReport jr = JasperCompileManager.compileReport(jd);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ReportID",1211);
JasperPrint jp1 = JasperFillManager.fillReport(jr, parameters, conn);
JasperViewer.viewReport(jp1, false);
}catch (Exception ex) {
ex.printStackTrace();
}
This is the current output
And I want this output
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35939141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding attributes to form labels in Django 1.5 I have some code that looks like:
#form.html
<form action="/form-action" method="post">
{{form.faction.label_tag}}
{{form.faction}}<br />
{{form.character_name.label_tag}}
{{form.character_name}}
</form>
#form.py
class CharacterForm(forms.Form):
FACTION_CHOICES = (
('Sith', 'Sith Empire'),
('Republic', 'Republic Alliance')
)
faction = forms.ChoiceField(choices=FACTION_CHOICES)
character_name = forms.CharField(max_length=100)
However I would like have a specified class on the label tag on the html output. I know I could do:
<form action="/form-action" method="post">
<label for="id_faction" class="foo">{{form.faction.label}}:</label>
{{form.faction}}<br />
<label for="id_character_name" class="bar">{{form.character_name.label}}:</label>
{{form.character_name}}
</form>
I previously used Rails and you can do something along the lines of:
<%= f.label :field, class: "baz" %>
and was hoping there was just as easy of a solution in django. I thought using form.field-name.label_tag(attrs={'class':'custom-class-name'}) was going to work out but alas I am stuck. Any insight is appreciated.
A: For this i always use widget_tweaks
*
*Install it : pip install django-widget-tweaks .
*Add 'widget_tweaks' to INSTALLED_APPS in settings.py after django apps and just before your apps.
*Add {% load widget_tweaks %} to the top of the template you will customise.
Now to add a class for a field "name" of form1 do :
{{ form1.name|add_class:"baz" }}
or add 2 and more
{{ form1.name|add_class:"baz baz2 baz3" }}
which will add class ="baz baz2 baz3" to your field html output
You can also add attributes :
{{ form1.name|attr:"size:200"|attr:"color:blue"}}
and combine the two ^^
{{ form1.name|add_class:"baz baz2 baz3"|attr:"size:200"|attr:"color:blue"}}
You can also test field type for an adapted output by including snippets according to type. it's what i do.
Go consult the docs of widget_tweaks
it works for me on Django 1.6 and 1.7
Hope it will help you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26261657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Anyone know of a good tutorial for Facebook authentication? I'm linking my app to Facebook, and would like people to log in with their Facebook account, but I can't figure out how to do this. I had read up on Facebook Connect, but it seems that that's not used any more - but every tutorial I can find seems to refer to it. When I try to follow them, it doesn't work, because the interface has changed.
So, can anyone direct me to a tutorial or guide to doing this the new way?
Basically, what I want to do is this:
A user who is signed into Facebook and comes to my webpage is automatically logged in to my app (with the usual Facebook 'granting permission' windows etc), or can sign in with their Facebook account if they're not already logged in.
I then want to use Facebook to link users with their friends who are also registered on my site, so they can share things.
I would also like to have access to Facebook comments made on wall posts from my site - so the comment stream for a particular post can be seen on my site as well as on Facebook, and comments can be made on either.
If anyone can point me in the right direction (or even tell me what I should be typing in to Google!) I'd be very grateful.
Thanks.
A: Some sample apps that do many of the things you speak of are shown here. The Graph API is probably your best bet right now for delivering the content and access you need and there are numerous tutorials online for how to use it, including the Facebook Developers site itself.
A: You will find good Tuts on ThinkDiff, e.g.
http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/
http://thinkdiff.net/facebook/graph-api-iframe-base-facebook-application-development-php-sdk-3-0/
A: I know this is an older question, but the current method for authentication is OAuth 2.0.
Facebook provides a pretty good outline of what steps are necessary in this Reference:
https://developers.facebook.com/docs/authentication/client-side/
This example allows the authentication to occur entirely in Javascript on the client side so that you can request a potential user to authenticate via Facebook and then confirm access to your application.
If the user is already logged in, only the access confirmation for your application is performed.
If the user is already logged in and access has already been granted, the user is not required to login, or reconfirm access.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5438270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Aurelia custom binding with Parent resolver not injecting correct container Using a Parent.of resolver on a custom binding behavior does not work.
The DI container received by the resolver is the root container. This stops it from finding the correct parent to inject.
Using a custom attribute with the same Parent.of decoration works as expected.
An HTML snippet:
<form cs-validate-context="login">
<div class="ui two column grid">
<label class="column" t="branchcode"></label>
<div class="form-group ui input column">
<input type="text" t="[placeholder]branchcode" value.bind="branchcode & csValid" cs-valid="x">
</div>
The cs-validate-context gets injected correctly with Parent.of resolver into the attribute, cs-valid, but not the custom binding, csValid.
Is this expected or is it a matter of RT*M ?
A: An aurelia attribute do get the correct parent injected.
So I used it instead of the aurelia binding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37229388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I implement session expiry based on users inactivity in django framework? I am using django request.session.set_expiry() to expire session for a logged in user. But it expires session even though user is active.
if user is not None:
login(request, user)
request.session.set_expiry(60)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54477802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Post API using Ratpack and Groovy giving 405 Error and RxJava methods not working I am building an API using Ratpack and Groovy. The POST API is always giving:
405-Method not Found Error
This is a snippet from POST Endpoint Handler. In this code, promiseSingle, then, observe, map, doOnNext, doOnError, etc.
RxJAVA functions are not working. Is there any reason why RxJava methods are not working?
saveJsonAsData(context, id)
.promiseSingle()
.then { Data updateddata ->
context.response.headers
.add(HttpHeaderNames.LOCATION, "/api/save/${updateddata.id}/${updateddata.value}")
context.response.status(HttpResponseStatus.CREATED.code())
.send()
}
}
protected Observable<Data> saveJsonAsData(GroovyContext context, String id) {
context.request.body.observe()
.map { TypedData typedData -> extractData(context, typedData) }
.doOnNext { Data data ->
data.id = id
validatorWrapper.validate(data)
}
.flatMap(data.&save as Func1)
.doOnError { Throwable throwable -> log.error("Error saving data", throwable) }
}
A: The issue is not so much with Rx as it is with the usage of the Context.
You should try to keep the response handling logic within your Handler, that is don't pass the Context around, rather get the objects you need and pass them to your services.
As an example
path('myendpoint') { MyRxService service ->
byMethod {
get {
// do something when request is GET
}
post {
request.body.map { typedData ->
extractItem(typeData) // extract your item from the request first
}.flatMap { item ->
service.saveJsonAsItemLocation(item).promiseSingle() // then once it's extracted pass the item to your "saveJsonAsItemLocation" method
}.then { ItemLocationStore updatedItem ->
response.headers.add(HttpHeaderNames.LOCATION, "/itemloc/v1/save/${updatedItem.tcin}/${updatedItem.store}")
context.response.status(HttpResponseStatus.CREATED.code()).send()
}
}
}
}
My guess is that you have something like this:
get {
// get stuff
}
post {
// post stuff
}
The reason this doesn't work is that Ratpack doesn't use Routing Table for handling incoming requests, instead it uses chain delegation. The get {} binds to root path and GET http method and post {} binds to root path and POST http method. Because get {} matches the path, Ratpack considers the handler matched and since the handler is for GET it considers it a 405.
There are chain methods available that binds regardless of HTTP Method such as all {} and path {}. Chain#all will handle all paths and methods where as Chain#path(String) matches against specific path.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37634964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Seeding random number generators in parallel programs I am studing the multiprocessing module of Python.
I have two cases:
Ex. 1
def Foo(nbr_iter):
for step in xrange(int(nbr_iter)) :
print random.uniform(0,1)
...
from multiprocessing import Pool
if __name__ == "__main__":
...
pool = Pool(processes=nmr_parallel_block)
pool.map(Foo, nbr_trial_per_process)
Ex 2. (using numpy)
def Foo_np(nbr_iter):
np.random.seed()
print np.random.uniform(0,1,nbr_iter)
In both cases the random number generators are seeded in their forked processes.
Why do I have to do the seeding explicitly in the numpy example, but not in the Python example?
A: numpy 1.17 just introduced [quoting] "..three strategies implemented that can be used to produce repeatable pseudo-random numbers across multiple processes (local or distributed).."
the 1st strategy is using a SeedSequence object. There are many parent / child options there, but for our case, if you want the same generated random numbers, but different at each run:
(python3, printing 3 random numbers from 4 processes)
from numpy.random import SeedSequence, default_rng
from multiprocessing import Pool
def rng_mp(rng):
return [ rng.random() for i in range(3) ]
seed_sequence = SeedSequence()
n_proc = 4
pool = Pool(processes=n_proc)
pool.map(rng_mp, [ default_rng(seed_sequence) for i in range(n_proc) ])
# 2 different runs
[[0.2825724770857644, 0.6465318335272593, 0.4620869345284885],
[0.2825724770857644, 0.6465318335272593, 0.4620869345284885],
[0.2825724770857644, 0.6465318335272593, 0.4620869345284885],
[0.2825724770857644, 0.6465318335272593, 0.4620869345284885]]
[[0.04503760429109904, 0.2137916986051025, 0.8947678672387492],
[0.04503760429109904, 0.2137916986051025, 0.8947678672387492],
[0.04503760429109904, 0.2137916986051025, 0.8947678672387492],
[0.04503760429109904, 0.2137916986051025, 0.8947678672387492]]
If you want the same result for reproducing purposes, you can simply reseed numpy with the same seed (17):
import numpy as np
from multiprocessing import Pool
def rng_mp(seed):
np.random.seed(seed)
return [ np.random.rand() for i in range(3) ]
n_proc = 4
pool = Pool(processes=n_proc)
pool.map(rng_mp, [17] * n_proc)
# same results each run:
[[0.2946650026871097, 0.5305867556052941, 0.19152078694749486],
[0.2946650026871097, 0.5305867556052941, 0.19152078694749486],
[0.2946650026871097, 0.5305867556052941, 0.19152078694749486],
[0.2946650026871097, 0.5305867556052941, 0.19152078694749486]]
A: If no seed is provided explicitly, numpy.random will seed itself using an OS-dependent source of randomness. Usually it will use /dev/urandom on Unix-based systems (or some Windows equivalent), but if this is not available for some reason then it will seed itself from the wall clock. Since self-seeding occurs at the time when a new subprocess forks, it is possible for multiple subprocesses to inherit the same seed if they forked at the same time, leading to identical random variates being produced by different subprocesses.
Often this correlates with the number of concurrent threads you are running. For example:
import numpy as np
import random
from multiprocessing import Pool
def Foo_np(seed=None):
# np.random.seed(seed)
return np.random.uniform(0, 1, 5)
pool = Pool(processes=8)
print np.array(pool.map(Foo_np, xrange(20)))
# [[ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.64672339 0.99851749 0.8873984 0.42734339 0.67158796]
# [ 0.64672339 0.99851749 0.8873984 0.42734339 0.67158796]
# [ 0.64672339 0.99851749 0.8873984 0.42734339 0.67158796]
# [ 0.64672339 0.99851749 0.8873984 0.42734339 0.67158796]
# [ 0.64672339 0.99851749 0.8873984 0.42734339 0.67158796]
# [ 0.11283279 0.28180632 0.28365286 0.51190168 0.62864241]
# [ 0.11283279 0.28180632 0.28365286 0.51190168 0.62864241]
# [ 0.28917586 0.40997875 0.06308188 0.71512199 0.47386047]
# [ 0.11283279 0.28180632 0.28365286 0.51190168 0.62864241]
# [ 0.64672339 0.99851749 0.8873984 0.42734339 0.67158796]
# [ 0.11283279 0.28180632 0.28365286 0.51190168 0.62864241]
# [ 0.14463001 0.80273208 0.5559258 0.55629762 0.78814652] <-
# [ 0.11283279 0.28180632 0.28365286 0.51190168 0.62864241]]
You can see that groups of up to 8 threads simultaneously forked with the same seed, giving me identical random sequences (I've marked the first group with arrows).
Calling np.random.seed() within a subprocess forces the thread-local RNG instance to seed itself again from /dev/urandom or the wall clock, which will (probably) prevent you from seeing identical output from multiple subprocesses. Best practice is to explicitly pass a different seed (or numpy.random.RandomState instance) to each subprocess, e.g.:
def Foo_np(seed=None):
local_state = np.random.RandomState(seed)
print local_state.uniform(0, 1, 5)
pool.map(Foo_np, range(20))
I'm not entirely sure what underlies the differences between random and numpy.random in this respect (perhaps it has slightly different rules for selecting a source of randomness to self-seed with compared to numpy.random?). I would still recommend explicitly passing a seed or a random.Random instance to each subprocess to be on the safe side. You could also use the .jumpahead() method of random.Random which is designed for shuffling the states of Random instances in multithreaded programs.
A: Here is a nice blog post that will explains the way numpy.random works.
If you use np.random.rand() it will takes the seed created when you imported the np.random module. So you need to create a new seed at each thread manually (cf examples in the blog post for example).
The python random module does not have this issue and automatically generates different seed for each thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29854398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: IE not clearing subsequent floats I'm trying to get two divs to float to opposite sides of the page, with text flowing between them. The top of the second (left-aligned) div should be even with the bottom of the first (right-aligned) div. The code below works fine in FF, Chrome, Opera, etc. fine, but they do not clear properly in IE. Both divs appear at the top of the text.
If I move the left-aligned div low enough within the text, it works fine in IE, but that's not really a sustainable solution.
I've found multiple pages on IE CSS float bugs, but I haven't found anything speaking directly to this.
CSS
div {
width: 200px;
margin-top: 10px;
border-style: solid;
border-width: 1px;
position: relative;
}
.wrapper {
width: 600px;
border-color: #FF0000;
}
.right {
float: right;
border-color: #00FF00;
}
.left {
float: left;
clear: both;
border-color: #0000FF;
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" href="float.css" />
</head>
<body>
<div class="wrapper">
<div class="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla pretium tempor leo. Vivamus mi risus, dapibus ac,
consectetur quis, pellentesque eget, sem.
</div>
<div class="left">
Proin malesuada. Ut vel lorem. Cras rhoncus nisl accumsan
turpis tristique consequat. Sed lacinia ligula at nibh.
Morbi in quam. Morbi commodo nibh.
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla pretium tempor leo. Vivamus mi risus,
dapibus ac, consectetur quis, pellentesque eget, sem.
Maecenas est dui, imperdiet nec, fermentum ut,
pretium a, orci. Quisque hendrerit interdum orci.
Nulla sit amet risus non enim ultrices bibendum.
Aenean arcu purus, rhoncus at, vestibulum vel,
volutpat et, nunc. Integer eget risus eget purus viverra
congue.</p>
<p>Nullam vel libero ut purus semper ullamcorper.
Pellentesque mattis tincidunt odio. Nullam pulvinar
orci at dolor. Sed volutpat eros ac elit.
Praesent porttitor libero sed felis. Vivamus lobortis
pellentesque diam.
Proin laoreet massa ac metus. Integer faucibus lorem
molestie nibh. Integer id massa. Integer ligula ipsum,
pellentesque id, interdum at, pretium eget, orci.
Proin malesuada. Ut vel lorem.</p>
</div>
</body>
</html>
A: IE7 and IE6 have a variety of problems with elements that have both float and clear on them. In IE7, using clear on an element with float only clears the float below other floats floated in the same direction.
A modified version of the easyclearing fix may do the trick, but don't get your hopes up. See this page for details: New clearing method needed for IE7?.
Bottom line is that you're probably not going to get this to work in IE6/7 without cheating: moving the div down in the text, embedding the divs in paragraphs, etc.
A: I'm fairly sure this is one of those rare bugs in ie6 that doesn't have a pure CSS solution.
Try using the ie7 javascript - it may fix the problem for you: http://code.google.com/p/ie7-js/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/795161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is causing my site to load and add "#" at the end? I think there might be something in my .htaccess file that is causing my page to load and then "bounce" back to the top adding # at the end of my domain, like this: example.com/#
Here is my htaccess file:
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
# Start Category Redirects
Redirect permanent /check-out-this-page-tration http://example.com/this-page/
Redirect permanent /rewards http://example.com/example-reward-coupons-page/
Redirect permanent /p-photo-entries http://example.com/2012-contest-photos/
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<files *.html>
SetOutputFilter DEFLATE
</files>
# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]
# END WordPress
Any ideas on what I should remove or change?
A: URL fragments are used by the client (a web browser) to help determine how to handle the content that it's trying to display.
This can be anchors to jump to a certain part of a page, or used by javascript to send information between other scripts. This is not your htaccess file as fragments are never sent to the server (where your htaccess file lives).
Try selectively removing javascript (especially scripts that you load from 3rd party sites that share links like "Add To Any"), otherwise make sure you have no links in your content that look like this:
some/path/file.html#
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16186302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Routers in versions 3.4.X Since I upgraded from version 3.3.3 to version 3.4 I'm have problems with routers:
File "/urls.py", line 23, in
urlpatterns = router.urls
File "~/Library/Python/2.7/lib/python/site-packages/rest_framework/routers.py", line 81, in urls
self._urls = self.get_urls()
File "~/Library/Python/2.7/lib/python/site-packages/rest_framework/routers.py", line 358, in get_urls
view = self.get_api_root_view(api_urls=urls)
TypeError: get_api_root_view() got an unexpected keyword argument 'api_urls'
A: You likely have overridden get_api_root_view without providing the api_url argument since it's already part of DRF: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/routers.py#L292
A: I had the same error. I found I had an older version of drf-extensions. I have a feeling drf-extensions overrides the get_api_root_view method, and when it's not in sync with your version of Django Rest Framework, this can cause a problem (ie. drf-extensions is passing a parameter that DRF no longer expects, but in previous versions was acceptable).
If it's not drf-extensions specifically, it's probably something else that's overriding get_api_root_view as Linovia suggested.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39120364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: multi language site and search engines I'm developing a site for a company that has clients from all over the world and the site will be served in two languages: Italian (local) and English.
Once a visitor visits the site I check the IP, if its coming from Italy I show the site in Italian , if it's not I show it in English. Of course they will have the option to manually override the language.
What exactly happens when the search engine bots inspect the site to index the pages?
*
*usually the crawlers always have USA based IPs
*even if the crawlers "click" on the "change language" link to show Italian pages since they can't accept cookies (and so sessions) I can't keep the language set or keep trace of what has been chosen
So the question is , how can you handle this situation in a way that search engines scan both the languages and also index them?
A: Google actually has an article in their Webmaster guidelines on this subject. You may want to take a look, as they specifically address the issues you have raised: http://www.google.com/support/webmasters/bin/answer.py?answer=182192
A: I'd use subdomains:
eng.mysite.com/whatever
it.mysite.com/whatever
Then have a sitemap which points to the home page of each of those language subdomains, and they should all be crawled just fine.
A: You can use the following approach:
*
*Scan the Accept-Language header ($_SERVER['HTTP_ACCEPT_LANGUAGE']) for languages that the user agent prefers. This is usually more reliable than checking the IP address for their country.
*Check the User-Agent header ($_SERVER['HTTP_USER_AGENT']) to see if the request comes from a search engine, such as "Googlebot" and "Yahoo! Slurp".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6740380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I fix this Python ModuleNotFoundError I am trying to figure out what is causing this file called builder.py to not run on mac even though it runs on windows. Code:
import cffi
import glob
import platform
# relative to build dir
LIB_BASE = '../libs/'
# compiling libraries statically to get a single binary
EXTRA_SRC = [LIB_BASE + 'subhook/subhook.c']
pltsysname = {'Windows': 'win32', 'Darwin': 'osx', 'Linux': 'elf'}
pltsrc = pltsysname[platform.system()]
pltsrc = LIB_BASE + 'plthook/plthook_{}.c'.format(pltsrc)
# EXTRA_SRC.append(pltsrc) # disabled until it is actually useful
LIBDIRS = []
if platform.system() == 'Windows':
LIBDIRS.append('../libs/SDL/lib/x86/')
CDEFS = 'generated internals SDL XDL subhook xternPython'.split()
def readfile(name):
with open(name, 'r') as f:
content = f.read()
return content
def build():
ffibuilder = cffi.FFI()
for fname in CDEFS:
ffibuilder.cdef(readfile('cdefs/{}.h'.format(fname)))
ffibuilder.embedding_api('uint32_t kickstart();')
ffibuilder.embedding_init_code(readfile('remote.py'))
ffibuilder.set_source(
'_remote', readfile('cdefs/remote.c'), sources=EXTRA_SRC,
libraries=['SDL2'], library_dirs=LIBDIRS,
define_macros=[('SUBHOOK_STATIC', None)])
ffibuilder.compile(tmpdir='build', target='remote.bin')
if __name__ == '__main__':
build()
When ever I run it I expect it to run but instead it comes up with the following error:
Traceback (most recent call last):
File "/Users/alexanderlee/Desktop/sbpe-1.6.1/builder.py", line 1, in <module>
import cffi
ModuleNotFoundError: No module named 'cffi'
>>>
How do I fix it?
A: It's probably because you only installed cffi on your Windows, so you probably need to install it on your Mac also.
You can follow rules on the docs:
pip install cffi
A: cffi is a third-party module. It's installed on your Windows computer but not on your Mac.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54032375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Mysql C++ Driver - Get prepared statement query after created I use prepared statements quite heavily in my c++ application. The problem that I'm having is that when a mysql query throws an error (i.e. foreign key constraint),
I would like to somehow be able to get that query so I can debug.
Here is a small code example from MysqlWrapper.cpp
(A class that I have written that wraps the C++ Driver)
long MysqlWrapper::Insert(sql::PreparedStatement *stmt)
{
try
{
stmt->execute();
...
//return inserted id
}
catch(sql::SQLException &ex)
{
// How can I get the query being executed by stmt?
}
}
A: Prepared statements are not worth the problems at MySQL, they are not much faster than classic SQL statements. They are not compiled as in other RDBMS.
I think in this case it would be better to use a batch insert instead of a prepared statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17752138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Get objects outside an array of objects I have a bit of a complex mix of objects and arrays and I was looking for way to flatten the arrays so it's less complex when I try to render it.
Basically I have some input fields and there's an option to add custom fields with custom label and value, but the way it's stored in DB the label is customLabel and the value is the array of all the custom fields that were added
const keyTerms = [
{label: 'pre-set label', value: 'some value'},
{label: 'pre-set label', value: 'some value'},
{label: 'customLabel', value: [{}, {}]}
];
In my React component I'm mapping through that array to display the objects, but when I hit the object that has an array as a value, I get an error since the component is expecting an string instead of an array
{keyTerms.map(keyTerm => <Component keyTerm={KeyTerm} />}
Inside the Component I tried to check if keyTerm.value is an array to map through it
Array.isArray(keyTerm.value)
? keyTerm.value.map(ele => (
<>
<Label>{keyTerm.label}</Label>
<Description>{keyTerm.value}</Description>
</>
))
: (
<>
<Label>{keyTerm.label}</Label>
<Description>{keyTerm.value}</Description>
</>
)
But that solution didn't work, it's passing the first check and always going to the else block then throwing this error:
Uncaught Error: Objects are not valid as a React child (found: object with keys {label, description, __typename}). If you meant to render a collection of children, use an array instead.
Is there a way to take the objects from inside the third object value array and put them in the outside array?
A: Try the code below: (however it may be worth it to create a reusable component out of the label/description fields so it’s not duplicated)
Array.isArray(keyTerm.value)
? keyTerm.value.map(ele => (
<>
<Label>{ele.label}</Label>
<Description>{ele.value}</Description>
</>
))
: (
<>
<Label>{keyTerm.label}</Label>
<Description>{keyTerm.value}</Description>
</>
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65365335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Homework Sales calculator Yesterday I submitted this problem, got terrific responses but my code still didn't work. I modified my code based on another student's code that works, but my code still won't calculate but it validates in javascript. Any suggestions. This homework is due TONIGHT!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4 /loose.dtd">
<html>
<head>
<title>Price Calculator</title>
<script type="text/javascript">
function fixOrder() {
const TAX = 0.975;
var numPrice;
var total;
var tax;
numPrice = parseFloat(document.getElementById("cost").value, 10);
tax = parseFloat(document.getElementById("tax").value, 10);
total = parseFloat(document.getElementById("total").value, 10);
numPrice = numPrice * TAX;
total = numPrice;
total = document.getElementById("total").value = "$" + total.toFixed(2);
if (isNaN(numPrice)) {
alert("Sorry,you must enter a numeric value to place order");
numPrice = 0;
}
}
</script>
</head>
<body bgcolor="#00f3F1">
<h1 align="left">Price Calculator</h1>
<form name="form" id="form">
<p>Price: <input type="text" id="cost" name="cost" value="" onchange=
"fixOrder" /></p>
<p>Tax: <input type="text" id="tax" name="tax" value="" onchange=
"fixOrder" /></p>
<p>Total: <input type="text" id="total" name="total" value="" disabled=
"disabled" /></p>
</form>
</body>
</html>
A: You need to change the onchange to
fixOrder()
A: JS Fiddle
Your onchange event is onchange="fixOrder" which is not really doing anything. If you change it to fixOrder() you will call the function fixOrder when the change event is fired.
Furthermore:
*
*I don't think const is a reserved word in JavaScript. I don't think JS has constants. You should change that line from const TAX to var TAX;
*Unlike parseInt, which takes two arguments (string and base/radix), parseFloat only takes one argument (string), so you can remove the , 10 from it
I imagine you want something like:
function fixOrder() {
var TAX = 0.0975;
var numPrice;
var total;
var tax;
numPrice = parseFloat(document.getElementById("cost").value);
tax = parseFloat(document.getElementById("tax").value);
total = parseFloat(document.getElementById("total").value);
numPrice = numPrice + (tax || numPrice * TAX);
total = numPrice;
var dec = new Number((total+'').split('.')[1]) || 0;
total = document.getElementById("total").value =
"$" + Number(parseInt(total)
+ '.'
+ Math.round(
( (dec+''.split('').reverse().join('') )/100 + '').split('').reverse().join('')
)).toFixed(2);
);
if (isNaN(numPrice)) {
alert("Sorry,you must enter a numeric value to place order");
numPrice = 0;
}
}
This will use the dollar amount of tax you enter, or if that doesn't exist, it will use the constant rate that you have supplied at the beginning (this was changed from .975 to .0975).
Also, notice the new calculation from total, we're taking the decimal part of the number, dividing it by 100 to get to two decimal places, reversing it back so it's in the proper order again, and then rounding it to the nearest 1 (cent).
HTML Body:
<h1 align="left">Price Calculator</h1>
<form name="form" id="form">
<p>Price: <input type="text" id="cost" name="cost" value="" onchange="fixOrder()" /></p>
<p>Tax: <input type="text" id="tax" name="tax" value="" onchange="fixOrder()" /></p>
<p>Total: <input type="text" id="total" name="total" value="" disabled="disabled" /></p>
</form>
A: When calling a function in JavasScript by an event, you need to mention the () after the name of the function you want to call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7705544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Starting shell from android app to run separate executable I want to start shell from android application because i want to run an executable file and pass few arguments and expect output.
I tried ProcessBuilder and process and run at runtime listening to their io stream but android app does not allowing me to start shell is this permission issue??
I am getting all the time
runCommand error: Error running exec(). Command: [su] Working Directory: null Environment: null
Is there a way to run shell as an interface between running app as a process and process will be started from shell?
Shed some light on this issue thanks
A: Actually, when you use the "su" hack what you are getting is a shell that runs as root (if the device has been modified to support that)
If you don't want a root shell but an ordinary one running as your application's userid, you could presumably run /system/bin/sh or whatever it is on your device instead of su.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7264968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ugly looking java data structure I've created the following structure which maps unique double values to one or more pairs of integers:
@SuppressWarnings("boxing")
private static final HashMap<Double, Integer[][]> rules =
new HashMap<Double, Integer[][]>() {
private static final long serialVersionUID = 1L;
{
put(-0.6, new Integer[][] { { 1, 3 } });
put(-0.3, new Integer[][] { { 2, 2 } });
put(0.0, new Integer[][] { { 2, 4 }, { 3, 3 }, { 4, 2 } });
put(0.3, new Integer[][] { { 4, 4 } });
put(0.6, new Integer[][] { { 5, 3 } });
}
};
Can I rewrite this so it's simpler - i.e not have to deal with warnings (serialVersionUID, boxing), and it being so verbose?
A: Using a class for the pairs of integers should be the first. Or is this a coincidence, that all arrays containing a bunch of pairs?
The second thing is, that these initialization-data could be read from a configuration-file.
Edit: As I looked again on this code, I realized that Doubles as keys in a Map is somewhat risky. If you produce Doubles as a result of an mathematical operation, it is not clear, if they will be equal for the computer (even if they are equal in a mathematical sense). Floating-point-numbers are represented as approximation in computers. Most likely you want to associate the values with the interval (example 0.0-0.3) and not the value itself. You may avoid trouble, if you always use the same constants as keys in the array. But in this case you could use an enum as well, and no new programmer runs into trouble, if he uses his calculated doubles as keys in the map.
A: Create another class to hold your pairs of integers, and store them using a list:
Map<Double,List<MyPair>>
Are these to be arbitrary pairs of integers, or will the represent something? If the latter, then name appropriately. New classes are cheap in Java, and good naming will reduce maintenance costs.
Edit: why are you creating an anonymous subclass of HashMap?
A: using a static initializer would be slightly better in my opinion, although it does nothing about the verbosity:
private static final Map<Double, int[][]> rules;
static {
rules = new HashMap<Double, int[][]>();
rules.put(-0.6, new int[][] { { 1, 3 } });
rules.put(-0.3, new int[][] { { 2, 2 } });
rules.put(0.0, new int[][] { { 2, 4 }, { 3, 3 }, { 4, 2 } });
rules.put(0.3, new int[][] { { 4, 4 } });
rules.put(0.6, new int[][] { { 5, 3 } });
}
Another option using a special Pair class and Arrays.asList:
class Pair<A, B> {
A a;
B b;
public Pair(A fst, B snd) {
}
// getters and setters here
}
private static final Map<Double, List<Pair<Integer, Integer>>> rules;
static {
rules = new HashMap<Double, List<Pair<Integer, Integer>>>();
rules.put(-0.6, Arrays.asList(new Pair(1, 3)));
rules.put(-0.3, Arrays.asList(new Pair(2, 2)));
rules.put(0.0, Arrays.asList(new Pair(2, 4), new Pair(3, 3), new Pair(4, 2));
// etc
}
A: Can you wrap a class around Integer[][] called, say Point?
That would make you have a
HashMap<Double, List<Point>>
A: I would start with a MultiValueMap. http://larvalabs.com/collections/.
This way you can do:
private static final MultiValueMap<Double, Integer[]> rules;
static {
MultiValueMap<Double, Integer[]> map = new MultiValueMap <Double, Integer[]>();
map.put(-0.6, new Integer[] { 1, 3 });
map.put(-0.3, new Integer[] { 2, 2 });
map.put(0.0, new Integer[] { 2, 4 }, new Integer[]{ 3, 3 }, new Integer[]{ 4, 2 } );
map.put(0.3, new Integer[] { 4, 4 } );
map.put(0.6, new Integer[] { 5, 3 } );
rules = map;
};
It looks also like you are aways using pairs of integers as the list of Keys. It would probably clean your interface up if you refered to that as a RulePair or some other specified object. Thus 'typing' your Integer array more specificially.
A: you could try also with a Builder; Java is not good as other languages for this kind of uses.. but here is FYI:
First shot
class RuleBuilder {
private Map<Double, Integer[][]> rules;
public RuleBuilder() {
rules = new HashMap<Double, Integer[][]>();
}
public RuleBuilder rule(double key, Integer[]... rows) {
rules.put(key, rows);
return this;
}
public Integer[] row(Integer... ints) {
return ints;
}
public Map<Double, Integer[][]> build() {
return rules;
}
}
sample usage:
private static final Map<Double, Integer[][]> rules =
new RuleBuilder() {{
rule(-0.6, row(1, 3));
rule(-0.3, row(2, 2));
rule(0.0, row(2, 4), row(3,3), row(4, 2));
rule(0.3, row(4, 4));
rule(0.6, row(5, 3));
}}.build();
Second shot
In order to elimate the final "build()" call and double brace init you could try with:
class RuleBuilder2 extends HashMap<Double, Integer[][]> {
public RuleBuilder2 rule(double key, Integer[]... rows) {
put(key, rows);
return this;
}
public Integer[] row(Integer... ints) {
return ints;
}
}
in this case the code is a little better:
private static final Map<Double, Integer[][]> rules2 =
new RuleBuilder2().
rule(-0.6, row(1, 3)).
rule(-0.3, row(2, 2)).
rule(0.0, row(2, 4), row(3,3), row(4, 2)).
rule(0.3, row(4, 4)).
rule(0.6, row(5, 3));
EDIT
Probably the names that I've used are not so meaningful; boxed/unboxed conversion is still a problem but this is a problem of Java
A: There's not much you can do here. The warnings have to be suppressed; in practice, you never have to worry about serialVersionUID unless you are in fact planning to serialize this object.
The boxing can (and probably should) be removed by using a typed collection as described in other answers here. To remove the boilerplate, you'll have to use a method. For example:
private static void put (double key, int x, int y) {
rules.put(key, new Point(x,y));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/772876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get snapshot from Sonatype I'm trying to get the snapshot release for atmosphere that is available for org.atmosphere and can't seem to get it...
<repositories>
<!-- Added to get the Atmosphere 1.1.0-SNAPSHOT, can be removed when 1.1.0 is released -->
<repository>
<id>oss.sonatype.org-snapshot</id>
<url>http://oss.sonatype.org/content/repositories/snapshots</url>
<releases><enabled>false</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
There are no atmosphere versions that appear to be picked up by adding the new repository.
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>1.1.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
I'm told by the primary atmosphere developer that this should work
A: Works fine for me. What error are you getting?
pom.xml
<?xml version="1.0"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>example</artifactId>
<version>1.0</version>
<repositories>
<!-- Added to get the Atmosphere 1.1.0-SNAPSHOT, can be removed when 1.1.0 is released -->
<repository>
<id>oss.sonatype.org-snapshot</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.atmosphere</groupId>
<artifactId>atmosphere-runtime</artifactId>
<version>1.1.0-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
Update
$ mvn dependency:tree
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building example 1.0
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ example ---
[INFO] org.example:example:jar:1.0
[INFO] \- org.atmosphere:atmosphere-runtime:jar:1.1.0-SNAPSHOT:compile
[INFO] +- org.atmosphere:atmosphere-compat-jbossweb:jar:1.1.0-SNAPSHOT:compile
[INFO] +- org.atmosphere:atmosphere-compat-tomcat:jar:1.1.0-SNAPSHOT:compile
[INFO] +- org.atmosphere:atmosphere-compat-tomcat7:jar:1.1.0-SNAPSHOT:compile
[INFO] \- eu.infomas:annotation-detector:jar:3.0.1:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.044s
[INFO] Finished at: Mon Apr 29 21:46:45 IST 2013
[INFO] Final Memory: 9M/301M
[INFO] ------------------------------------------------------------------------
A: Remove content of $HOME/.m2/repository/org/atmosphere/cpr and try again :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16286055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ImageIcon color issue when I fetch from assets in flutter I'm starting to learn flutter and at the moment, I'm trying to show an image from assets, but it's color going to change and I don't know why.
IconButton(
icon: ImageIcon(AssetImage("assets/icons/library.png")),
onPressed: (){
},
),
This is original red icon
And after fetching from assets it's looks like
A: I've used this before, the image must be of a PNG type, and it should be background is empty.
Or using it in another way, like this:
InkResponse(
icon: Image.asset("assets/icons/library.png",width: 30,height: 30,),
onTap: (){
},
),
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63155063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bot doesn't assign role in reaction role command So I've been trying to follow a tutorial on how to set up a reaction role command. Even though I do get the embed with the reactions that I wanted, when I react to it the bot doesn't assign the roles. After comparing the code to the tutorial I'm still not sure on what the problem here is.
This is the code:
module.exports = {
name: 'reactionrole',
description: "Sets up a reaction role message!",
async execute(message, args, Discord, client){
const channel = '851809318843187262';
const yellowTeamRole = message.guild.roles.cache.find(role => role.name === "2D simp");
const blueTeamRole = message.guild.roles.cache.find(role => role.name === "3D simp");
const yellowTeamEmoji = '<:wings:851814106146144326>';
const blueTeamEmoji = '<:crowshine:851814012290203680>';
let embed = new Discord.MessageEmbed()
.setColor('#e42643')
.setTitle('Choose a team to play on!')
.setDescription('Choosing a team will allow you to interact with your teammates!\n\n'
+ `${yellowTeamEmoji} for yellow team\n`
+ `${blueTeamEmoji} for blue team`);
let messageEmbed = await message.channel.send(embed);
messageEmbed.react(yellowTeamEmoji);
messageEmbed.react(blueTeamEmoji);
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id === channel) {
if (reaction.emoji.name === yellowTeamEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(yellowTeamRole);
}
if (reaction.emoji.name === blueTeamEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(blueTeamRole);
}
} else {
return;
}
});
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id === channel) {
if (reaction.emoji.name === yellowTeamEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(yellowTeamRole);
}
if (reaction.emoji.name === blueTeamEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(blueTeamRole);
}
} else {
return;
}
});
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68104365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: html img tag within button tag not picking up javascript applied to button tag I have a dynamic formset where the user can click a button to remove forms from the formset before clicking submit. I've achieved this by applying some javascript to the button tag. This is a django app.
My issue arises when I add a trash can icon as the button's image. The image itself is not clickable and dynamic (i.e. removing the form when clicked), but the button area around the image is. I would like the entire thing to be clickable.
When trying to click the trash icon itself, nothing happens, and the console logs this error:
Uncaught TypeError: Cannot set properties of null (setting 'checked') at HTMLButtonElement.removeIngredient
When tracing this error, I encounter the following in the chrome console sources tab:
This image corresponds with the javascript below
HTML
<button class="remove-button" id="remove-ingredient" type="submit"><img src="{% static 'inventory/trash-icon.png' %}"></button>
CSS
.remove-button {
border: none;
width: 100%;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
}
.remove-button img {
height: 20px;
width: 20px;
}
.remove-button:hover {
cursor: pointer;
}
Javascript
function removeBtnListener () {
const removeIngredientBtns = document.getElementsByClassName('remove-button')
for (let i = 0; i < removeIngredientBtns.length; i++) {
removeIngredientBtns[i].addEventListener('click', removeIngredient)
}
}
function removeIngredient (event) {
if (event) {
event.preventDefault()
}
let ingredientFormToBeRemoved = event.path[1]
let indexString = ingredientFormToBeRemoved.id
let array = indexString.split('-')
let indexNum = array[2]
let deleteCheckbox = document.getElementById(`id_ingredientquantity_set-${indexNum}-DELETE`)
deleteCheckbox.checked = true
ingredientFormToBeRemoved.setAttribute('class', 'hidden')
}
Here is an image of the formset. By clicking the area around the trash can icon (red outline), the form is removed. By clicking the trash can icon itself (green arrow), nothing happens.
Does anyone know how to make this work so the entire element removes the form properly when clicked?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72372640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Web App Multiple Google Accounts Error I am creating a web app using Google Apps Script, and have run into kind of a wall.
Sometimes the users using the web app use it while being logged in with multiple Google accounts. There is a known error that shows up when a user attempts to access a google web app while being logged in with multiple accounts: Can't log in to Google Apps Scripts
The known solutions are:
*
*Log out of all accounts and log in as just one.
*Use incognito mode, thus being logged in as just one user
*Use a separate browser for separate Google Accounts.
Unfortunately, none of these solutions are fitting for the current situation. I myself know how to deal with the error, but how do I programmatically inform the user of these solutions?
What I am trying to do is to intercept this error page, and put out my own error, that could instruct the user to log out of their other accounts. I am deploying the web app using Google Sites, but have not had any luck with it there.
Thanks for any help!
A: Check the Issue Tracker
Unexpected "authorization is required" error from google.script.run after installing Sheets add-on while logged into multiple gmail.com accounts
*
*Comment #114, has a workaround for add-ons
*Comment #117, has another workaround for add-ons
You haven't mentioned what you are trying to accomplish, but there may be a workaround there.
Another idea might be to make an intermediate page that will serve as a sort of "landing page" that can remind your users about this issue and then re-direct them to the Web App. If you use cookies or the local storage API, then you could have it redirect immediately if they have seen it within the last few days.
Current known status of the bug
I seem to remember seeing somewhere, though I can't find it now, that the Apps Script team were planning on starting work to fix this in 2021.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66780096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 'tags' parameter at Python Softlayer API call SoftLayer.VSManager.list_instances() not working as expected I am implementing a cloud bursting system with Softlayer instances and Slurm. But I got a problem with Python Softlayer API.
When I try to get a list of some specific instances with the API call SoftLayer.VSManager.list_instances() I use the parameter 'tags', since I tagged the instances to classify them. But it does not work as expected.
It is supposed to find instances whose 'tagReferences' field matches with the value of the parameter 'tags' you passed in the API call.
However, I get a list with all the nodes whose 'tagReferences' field is not empty. Whatever is the value I pass as 'tags' parameter.
I have the following nodes:
*
*hostname: 'node000' tags: 'slurm, node'
*hostname: 'node005' tags: 'test'
I run this script:
import os
import SoftLayer
os.environ["SL_USERNAME"] = "***"
os.environ["SL_API_KEY"] = "******"
client = SoftLayer.Client()
mgr = SoftLayer.VSManager(client)
for vsi in mgr.list_instances(tags = 'slurm'):
print vsi['hostname']
This is the output I get:
node000
node005
I tried passing different values as 'tags' parameter (see below), but I always get the same result shown above, even with the last one.
Set of values passed as 'tags' parameter:
slurm, node
slurm
node
test
random
Did I miss anything?
I wrote a ticket to Softlayer support team but they believe my script should work and they assured me that the tags feature does work. Even they told me explicitly to come here to ask because they have no idea of what is happening.
A: According the documentation of the method that you are using, you need to send a list of tags, so change the string by a list like this:
client = SoftLayer.Client()
mgr = SoftLayer.VSManager(client)
for vsi in mgr.list_instances(tags = ['mytag']):
print (vsi['hostname'])
Regards
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38723603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cheap reverse dns lookup Currently, I am running asp.net on a 4.0 Framework. I found one section of my code that is truly expensive for me to use. I currently get the IP Address and the reverse dns for users accessing my site, however, I am trying to keep performance in mind.
Is there a cheaper alternative to this?
return System.Net.Dns.GetHostEntry(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]).HostName;
A: Since the ServerVariables indexer returns a string, your code snippet calls the GetHostEntry string overload. Its documentation describes a three-step lookup algorithm, with two separate queries. The GetHostEntry IPAddress overload documentation doesn't describe any similar process, so perhaps it saves a query. Then again, it seems to provide the same info (all IP address and host names), so maybe it's the same, but just documented differently.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8862464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to sort and group by by it's count I have the following:
SELECT DISTINCT s.username, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.id
)
ORDER BY cnt DESC
Basically I have an instagram_item_viewer with the following structure:
id viewer_id item_id created
It tracks when a user has viewed an item and what time. So basically I wanted to find shops that has the most items viewed. I tried the query above and it executed fine, however it doesn't seem to give the appropriate data, it should have more count than what it is. What am I doing wrong?
A: First, with a group by statement, you don't need the DISTINCT clause. The grouping takes care of making your records distinct.
You may want to reconsider the order of your tables. Since you are interested in the shops, start there.
Select s.username, count(v.id)
From instagram_shop s
INNER JOIN instagram_shop_picture p ON p.shop_id = s.shop_id
INNER JOIN instagram_item_viewer v ON v.item_id = p.id
AND v.created >= '2014-08-01'
WHERE s.expirydate IS NULL
AND s.isLocked = 0
GROUP BY s.username
Give thata shot.
A: As mentioned by @Lennart, if you have a sample data it would be helpful. Because otherwise there will be assumptions.
Try run this to debug (this is not the answer yet)
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.username, p.id
)
ORDER BY cnt DESC
The problem here is the store and item viewer is too far apart (i.e. bridged via shop_picture). Thus shop_picture needs to be in the SELECT statement.
Your original query only gets the first shop_picture count for that store that is why it is less than expected
Ultimately if you still want to achieve your goal, you can expand my SQL above to
SELECT x.username, SUM(x.cnt) -- or COUNT(x.cnt) depending on what you want
FROM
(
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.username, p.id
)
ORDER BY cnt DESC
) x
GROUP BY x.username
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29024336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting the Image to display in a Custom ButtonImage Control c# I'm new to c# and i'm trying to create a ButtonImage Control. I've managed to get most of the code to work including TextAlignment and image resource selection, but the image won't display. I've tried adding TextImageRelation property as well as the ImageAlignment property to no effect - not even sure if I've done everything correctly. I've spent hours searching MSDN and the internet, please help, tnx. Heres the code:
namespace ImageButton
{
//[System.ComponentModel.DefaultBindingProperty("ButtonText")]
public partial class ImageButton : UserControl
{
private String name = "btn1";
private String btnText = "Button1";
private TextImageRelation textImage = TextImageRelation.Overlay;
private ContentAlignment alignmentValue = ContentAlignment.MiddleRight;
private ContentAlignment imageAlignmentValue = ContentAlignment.MiddleLeft;
public ImageButton()
{
InitializeComponent();
}
//
// Properties
//
[Description("Sets the Text Label"),
Category("Custom")]
public String ButtonText
{
get
{
return btnText;
}
set
{
btnText = value;
btn1.Text = btnText;
}
}
[Description("Sets the Button Image"),
Category("Custom")]
public Image Image
{
get;
set;
}
[Description("Specifies the relationship of text to Image."),
Category("Custom")]
public TextImageRelation TextImageRelation {
get{
return textImage;
}
set{
textImage =value;
btn1.TextImageRelation = textImage;
}
}
[Category("Custom"),
Description("Specifies the alignment of text.")]
public ContentAlignment TextAlignment
{
get
{
return alignmentValue;
}
set
{
alignmentValue = value;
btn1.TextAlign = alignmentValue;
//Invalidate();
}
}
[Category("Custom"),
Description("Specifies the alignment of text.")]
public ContentAlignment ImageAlignment
{
get
{
return imageAlignmentValue;
}
set
{
imageAlignmentValue = value;
btn1.ImageAlign = imageAlignmentValue;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
StringFormat style = new StringFormat();
style.Alignment = StringAlignment.Far;
switch (alignmentValue)
{
case ContentAlignment.MiddleLeft:
style.Alignment = StringAlignment.Near;
break;
case ContentAlignment.MiddleRight:
style.Alignment = StringAlignment.Far;
break;
case ContentAlignment.MiddleCenter:
style.Alignment = StringAlignment.Center;
break;
}
// Call the DrawString method of the System.Drawing class to write
// text. Text and ClientRectangle are properties inherited from
// Control.
e.Graphics.DrawString(
Text,
Font,
new SolidBrush(ForeColor),
ClientRectangle, style);
}
}
}
A: Solved:
instead of:
public Image Image{ get; set;}
as other ppl have suggested, I used
public Image Image{
get { return image; }
set
{
image = value;
btn1.Image = image;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11751582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make the PopupMenu appear at the selected Item of a TreeView in VB6 I hava a TreeView in VB6 that uses a PopupMenu when a Node is right clicked. As the VB6 PopupMenu defaults its position to the mouse coordinates the menu appears at the right place.
What I want to accomplish is that the Popupmenu appears at the right place too on a KeyDown event when a TreeView Node is selected. How can I do this?
A: You need to obtain coordinates of the item. For that you need to first obtain its handle. And when you get the rect, you must translate it to form coordinates.
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByRef lParam As Any) As Long
Private Declare Function MapWindowPoints Lib "user32.dll" (ByVal hwndFrom As Long, ByVal hwndTo As Long, ByRef lppt As Any, ByVal cPoints As Long) As Long
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type RECTF
Left As Single
Top As Single
Right As Single
Bottom As Single
End Type
Private Const TV_FIRST As Long = &H1100&
Private Const TVM_GETITEMRECT As Long = (TV_FIRST + 4)
Private Const TVM_GETNEXTITEM As Long = (TV_FIRST + 10)
Private Const TVGN_CARET As Long = &H9&
Private Function GetSelectedItemRect(ByVal tv As TreeView, ByRef outRect As RECTF) As Boolean
Dim hItem As Long
hItem = SendMessage(tv.hwnd, TVM_GETNEXTITEM, TVGN_CARET, ByVal 0&)
If hItem Then
Dim r As RECT
r.Left = hItem
If SendMessage(tv.hwnd, TVM_GETITEMRECT, 1, r) Then
MapWindowPoints tv.hwnd, Me.hwnd, r, 2
outRect.Left = Me.ScaleX(r.Left, vbPixels, Me.ScaleMode)
outRect.Top = Me.ScaleY(r.Top, vbPixels, Me.ScaleMode)
outRect.Right = Me.ScaleX(r.Right, vbPixels, Me.ScaleMode)
outRect.Bottom = Me.ScaleY(r.Bottom, vbPixels, Me.ScaleMode)
GetSelectedItemRect = True
End If
End If
End Function
Usage:
Dim r As RECT
If GetSelectedItemRect(TreeView1, r) Then
PopupMenu whatever, , r.Right, r.Top
End If
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6726632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Context with filtering for daterange is not working I am having a view that is working and properly returning results as long as I am not filtering for dates. As soon as I start to add a filter e.g. booking_time__range = (start_date, end_date) no results are returned in my template. I have no tried to find the error by myself for several days, now I need the wisdom of the crowd.
My Model:
from django.db import models
from django.utils import timezone
from users.models import Account
from organization.models import Organization, Office
class Booking(models.Model):
LOCATION_OPTIONS = (
('H', 'Home Office'),
('O', 'Office'),
('N', 'Not indicated'),
)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
office = models.ForeignKey(Office, on_delete=models.CASCADE)
booking_time = models.DateTimeField(default=timezone.now)
location = models.CharField(max_length=1, choices=LOCATION_OPTIONS)
class Meta:
unique_together = ('account', 'booking_time',)
My View:
def overview_view(request):
context = {}
if request.method == 'GET':
start_date = None
end_date = None
if request.is_ajax():
booking_times = request.GET.get('day')
start_date = datetime.strptime(booking_times, "%Y-%m-%d")
end_date = start_date + timedelta(days=4)
start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc)
end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc)
context['bookings']=Booking.objects.filter( Q(organization_id=request.user.organization_id), Q(booking_time__range = (start_date, end_date))
context['office'] = Office.objects.filter(organization_id__exact=request.user.organization_id)
return render(request, 'overview/overview.html', context)
return render(request, 'overview/overview.html', context)
Both start_date and end_date are datetime.datetime format. As soon as I remove Q(booking_time__range = (start_date, end_date) results will show. But I really need this filter.
My template:
<small>{{ office.office_name }}</small>
{% for booking in bookings %}
<div class="client-item">
<div class="client-text">
<p class="name">{{ booking.account.first_name }} {{ booking.account.last_name }}</p>
{% if booking.get_location_display == 'House' %}
<p class="sub-title"> {{ booking.get_location_display }}</p>
{% elif booking.get_location_display == 'Home' %}
<p class="sub-title"> {{ booking.get_location_display }}</p>
{% else %}
<p class="sub-title"> {{ booking.get_location_display }}</p>
{% endif %}
</div>
</div>
{% endfor %}
{% endfor %}
Thank you very much for your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66716716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is double tap still being picked up in this IOS code? Background
- I have a map (MapKit) with a callout (custom view added to an annotation view)
- I have managed to ensure that the "long press" gesture made over the callout view does not get picked up (see below, using "shouldReceiveTouch")
Issue
What I can't do is do the same thing (i.e. ignore) a double-click over the callout view, in that the MapKit map still somehow picks this up and zooms in. I've tried putting the Double Tap gesture in to trap it however it doesn't seem to be working.
Mapkit View Delegate Code
Setup of Gesture Recognisers
// Gesture Recogniser (Long Press)
let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
longPressGR.minimumPressDuration = 1
longPressGR.delegate = self
self.mapView.addGestureRecognizer(longPressGR)
// Gesture Recogniser (Double Tap)
let doubleTapGR = UITapGestureRecognizer(target: self, action: "doubleTapAction:")
doubleTapGR.numberOfTapsRequired = 2
doubleTapGR.delegate = self
self.mapView.addGestureRecognizer(doubleTapGR)
Implement the "shouldReceiveTouch" for UIGestureRecognizerDelegate
extension GCMapViewHelper : UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
guard let touchesView = touch.view else { fatalError("ERROR: Touch event received was nil") }
for annotation in self.mapView.selectedAnnotations {
if annotation is GCAnnotation {
let annotationView = self.mapView.viewForAnnotation(annotation)
if let annotationView = annotationView {
if (touchesView.isDescendantOfView(annotationView)) {
return false
}
}
}
}
return true
}
}
EDIT: It seems the issue is the double-tap gesture recognizer is NOT picking up the double tap...any ideas? i.e. this is not working..
doubleTapGR.numberOfTapsRequired = 2
EDIT 2 Here is a simplified view of the issue re code example:
With the code below in terms of what I see in the console output from print statements:
* "longPressAction" - This appears/works
* "tapAction" - This does NOT appear, even when I double tap over the MKMapView. So this is my isssue here.
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var mapview: MKMapView!
func longPressAction() {
print("longPressAction")
}
func tapAction() {
print("tapAction") // ** Not appearing in console **
}
override func viewDidLoad() {
super.viewDidLoad()
// Gesture Recogniser (Long Press)
let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction")
longPressGR.minimumPressDuration = 1
self.mapview.addGestureRecognizer(longPressGR)
let tapGR = UITapGestureRecognizer(target: self, action: "tapAction")
tapGR.numberOfTapsRequired = 2
self.mapview.addGestureRecognizer(tapGR)
//tapGR.requireGestureRecognizerToFail(longPressGR)
}
}
A: While it's not a direct answer to your question - I have a workaround for you.
If you add your gesture recognizers to your custom annotation view then you can capture both long press and double tap over the annotation view and any associated callout.
Some example code I wrote to try this:
import UIKit
import MapKit
class StarAnnotation : NSObject, MKAnnotation {
let title: String?
let coordinate: CLLocationCoordinate2D
init(title: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate
super.init()
}
}
class StarAnnotationView : MKAnnotationView, UIGestureRecognizerDelegate {
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
self.image = UIImage(named: "star")
// Gesture Recogniser (Long Press)
let longPressGR = UILongPressGestureRecognizer(target: self, action: "longPressAction:")
longPressGR.minimumPressDuration = 1
longPressGR.delegate = self
self.addGestureRecognizer(longPressGR)
// Gesture Recogniser (Double Tap)
let doubleTapGR = UITapGestureRecognizer(target: self, action: "doubleTapAction:")
doubleTapGR.numberOfTapsRequired = 2
doubleTapGR.delegate = self
self.addGestureRecognizer(doubleTapGR)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func doubleTapAction(recognizer: UITapGestureRecognizer) {
if recognizer.numberOfTapsRequired == 2 {
print("double tapped")
}
}
func longPressAction(recognizer: UILongPressGestureRecognizer) {
print("long pressed")
}
}
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
// set up map view and sample annotation
let operaHouseCoord = CLLocationCoordinate2D(latitude: -33.8587, longitude: 151.2148)
let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
let operaHouseAnnotation = StarAnnotation(title: "Opera House", coordinate: operaHouseCoord)
mapView.region = MKCoordinateRegion(center: operaHouseCoord, span: span)
mapView.delegate = self
mapView.addAnnotation(operaHouseAnnotation)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? StarAnnotation {
let identifier = "star"
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? StarAnnotationView {
dequeuedView.annotation = annotation
return dequeuedView
} else {
let view = StarAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
return view
}
}
return nil
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35697397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: about bounded boxes of objects i'm trying to compose a dataset for the detection of soccer players, ball etc.. in a soccer game, i'm using alexeyAB Darknet framework,
So in the labeling phase in each image there are at least 8 players a ball and other stuff, at some point it is logical to think about the fact that i will have enough instances per player, but not enough for the ball and the goalkeeper for example,
so can i only marking bounded boxes the ball and other things avoiding to do it with the players to not waste time?
A: If you are training the model on your own dataset, I would recommend limiting the number of labels/classes in your data to what you seek. For example if you only want your model to see balls, goal-posts and Not players, simply keep the classes as balls and goal-posts. (This reminds me of a classification problem where 0 stands for balls and 1 stands for goal-post). P.S you mentioned object detection and Not Localization, which is the purpose of the YOLO models.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61551560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I customize the arguments to a kubernetes system pod such as kube-apiserver in Kind? I want to customize the arguments to kube-apiserver so that I can inspect the requests being made, so that I can debug a failing request. However, I'm not sure what I need to modify. I know that kube-apiserver can't be being deployed with helm, because helm requires an API server in order to do its job. So it must be being deployed via some other bootstrapping method, but looking at the kind source code I can't figure out what that method is.
A: The kube-apiserver is configured with a static manifest file, which is stored in /etc/kubernetes/manifests/kube-apiserver.yaml.
So find out the ID of the container that is the Kubernetes control plane node in kind:
docker ps|grep cluster-control-plane
Get a shell in it:
docker exec -it 4aeedccce928 bash
Install an editor (e.g. emacs) and edit the aforementioned file to add/remove/replace the desired arguments:
apt-get update
apt-get install emacs-nox
emacs /etc/kubernetes/manifests/kube-apiserver.yaml
Kubernetes will detect the file change and automatically restart the server, which can be validated with:
ps -Afl|grep kube-apiserver
If it crashes on startup, you can find the logs using
apt-get install less
less /var/log/pods/kube-system_kube-apiserver-cluster-control-plane_*/*/*.log
If the container fails to start at all, there will not be any log file there - check the manifest file for syntax errors by referring to the Kubernetes documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60877242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django filter a prefetched queryset returning an empty list In my app I have some Users and Groups, that are related by a many to many relation through GroupMember.
class User(models.Model):
...
class Group(models.Model):
...
users = models.ManyToManyField(User, through='groups.GroupMember', related_name='groups')
class GroupMember(models.Model):
...
user = models.ForeignKey(User, related_name='group_members', on_delete=models.CASCADE)
group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE)
Now I am trying to build an endpoint that retrieves a list of user instances that are in any one of the groups that your user is in. So if user A and B are in group1, user A and C are in group2, and C and D are in group3, retrieving the users as A would return B and C (since those are in groups with A).
That filter part can be done in multiple ways, but the part where I am stuck is how to show which groups were the cause of the relation. I tried to use prefetch_related with a custom filter, to fetch only the groups that have user A in them, like this:
User.objects.exclude(id=user.id).annotate(
# Annotate the amount of groups related between the users
related_group_count=Count('groups', filter=Q(groups__users=user))
).filter(
# Only users that have at least 1 relation with this user
related_group_count__gt=0
).prefetch_related(
# Prefetch the specific groups to show
Prefetch('groups', User.groups.all(), to_attr='related_groups'),
)
The returned users will not have any related_groups, it will be an empty qs. When I include the request user (by removing the exclude part on the query), the groups will be available for that user, but still not any other. This is my current response (including the requesting user "A"):
{
"first_name": "A",
"related_groups": [
{
"name": "group1",
},
{
"name": "group2",
}
]
},
{
"first_name": "B",
"related_groups": []
},
{
"first_name": "C",
"related_groups": []
}
But I'm trying to achieve this:
{
"first_name": "B",
"related_groups": [
{
"name": "group1",
}
]
},
{
"first_name": "C",
"related_groups": [
{
"name": "group2",
}
]
}
The problem lies with the filter on the Prefetch queryset, but I can't figure out what I'm doing wrong or if this is even possible. I tried different way of filtering (also with Group.objects.filter(users=user)) or even annotating the group members, counting if the given user is in that group and filtering on that, but with no success...
Note: This only happens when filtering the prefetch as described above: User (is group member) -> Group -> User (group member). It looks like the filter is "overwriting" the user in the queryset with the initial user (A).
In my project I work with multiple group-like concepts, one of which has 2 different kind of members (lets say, in context of this question a second GroupMember type model, with an additional many to many relation in the group model to user). When using User (group member) -> Group -> User (other kind of member), the prefetch actually works as expected. This issue is only when prefetching using the same through-model in relation to the user.
A: I managed to get this to work, by using a separate queryset that gets the group ids. This way the prefetch filter will not use the requesting user id to filter, which resulted in empty lists for all other users.
group_ids = user.groups.values('pk')
User.objects.exclude(id=user.id).filter(
groups__in=group_ids
).prefetch_related(
Prefetch('groups', Group.objects.filter(id__in=group_ids), to_attr='related_groups'),
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65688505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Set fixed size of a QDialog without cutting text I currently set a QDialog to have a fixed size using the following code
dlg->setWindowModality(Qt::WindowModal);
dlg->setFixedSize(dlg->size());
Now as a result of this code whatever size I save my ui form in QT Designer. It sticks to that size.This however ends up being a issue in some systems and displays. Where my Qlabels begin to cut from the sides due to the shortage of space.I wanted to know what would be the proper way of doing this ? How would I determine which size would accommodate the layout on the form.The form itself has a horizontal layout which has multiple layouts in it ??
A: Try
dlg->adjustSize();
dlg->setFixedSize(dlg->sizeHint());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22542091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: R: Tabulate each column of a sparse matrix against a vector I have a logical sparse matrix, say m, (which can be any of Matrix, slam, or SparseM matrices if that makes things faster) that I want to do the following on:
for (col in 1:ncol(m)) {
print(table(m[ , col], logicalV)
}
where logicalV is a fixed logical vector of the same length as rows in m. Think of this as creating a confusion matrix per feature in the sparse m.
The dimensions I am dealing with for m are: (15 ~ 40K) x (75 ~ 125K). This makes just the step of accessing the columns m[ , col] really slow.
What I am looking for is a fast solution here. Any ideas?
Edit:
Based on the comments, here is an outline of what I am really trying to achieve. I have a bunch of feature selection metrics like information gain, binormal separation, etc. which are all functions of the confusion matrix (i.e. table(m[ , col], logicalV)) as they are functions of the counts of true positives / negatives and false positives / negatives. So for each column and logicalV, I need to know counts of both TRUE, both FALSE, and either TRUE. Does that help?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19427474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get n unique numbers uniformly from a given range? I have a integer range [0, Z). I need to obtain n (where n <= Z) random numbers from this range, but they have to be unique. So I know I can just code up rejection sampling to do this, but I'm wondering if there's a one line python function that can do this for me?
A: why not use random sampling without replacement
import numpy as np
n = 25
a = range(26)
out = np.random.choice(a, size=n, replace=False)
len(np.unique(out))
>>>25
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73640901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.