text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to validate an integer with regex I have the following regex to validate only for integers, ^\$?\d{0,10}(.(\d{0,2}))?$ While it correctly identifies 12 as a valid integer, it also validates $12 as a valid one. If, I remove the first $ from the regex it doesn't work either.
Thanks
A: Short Answer
using System;
using System.Text.RegularExpressions;
Console.WriteLine(Regex.IsMatch("1313123", @"^\d+$")); // true
That assumes we want to validate a simple integer.
Conversation
If we also want to include thousands grouping structures for one or more cultures or other numeric conventions, that will be more complicated. Consider these cases:
*
*10,000
*10 000
*100,00
*100,000
*-10
*+10
For a sense of the challenge, see the NumberFormatInfo properties here.
If we need to handle culture specific numeric conventions, it's probably best to leverage the Int64.TryParse() method instead of using Regex.
Sample Code
It's live here. The complete list of NumberStyles is here. We can add/remove the various NumberStyles until we find the set that we want.
using System;
using System.Text.RegularExpressions;
using System.Globalization;
public class Program
{
public static void Main()
{
Console.WriteLine(IsIntegerRegex("")); // false
Console.WriteLine(IsIntegerRegex("2342342")); // true
Console.WriteLine(IsInteger("1231231.12")); // false
Console.WriteLine(IsInteger("1231231")); // true
Console.WriteLine(IsInteger("1,231,231")); // true
}
private static bool IsIntegerRegex(string value)
{
const string regex = @"^\d+$";
return Regex.IsMatch(value, regex);
}
private static bool IsInteger(string value)
{
var culture = CultureInfo.CurrentCulture;
const NumberStyles style =
// NumberStyles.AllowDecimalPoint |
// NumberStyles.AllowTrailingWhite |
// NumberStyles.AllowLeadingWhite |
// NumberStyles.AllowLeadingSign |
NumberStyles.AllowThousands;
return Int64.TryParse(value, style, culture, out _);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48675824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Crashes with EXC_BAD_ACCESS with Garbage Collection after hours of running i have a app where several videos are being randomly displayed and everything was sweet and worked great. Since they program loops the same code over and over again I find it very odd that is just stops all of a sudden. What can the error message below be about?
But after many hours it crashes. The first time it ran for 13 hours before crash and tonight it crashed after 11 hours.
Process: CamRecorder [4695]
Path: /Users/wgv/Desktop/Fullscreeen/CamRecorder.app/Contents/MacOS/CamRecorder
Identifier: wgv.CamRecorder
Version: 1.0 (1)
Code Type: X86 (Native)
Parent Process: launchd [86]
Date/Time: 2011-03-01 02:21:03.509 +0100
OS Version: Mac OS X 10.6.6 (10J567)
Report Version: 6
Interval Since Last Report: 428620 sec
Crashes Since Last Report: 2
Per-App Interval Since Last Report: 257957 sec
Per-App Crashes Since Last Report: 2
Anonymous UUID: 4528D13C-54C9-413F-92D9-128D05272F57
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000fef6e1df
Crashed Thread: 0 Dispatch queue: com.apple.main-thread
Application Specific Information:
objc_msgSend() selector name: rectSetBeingDrawnForView:
objc[4695]: garbage collection is ON
Thread 0 Crashed: Dispatch queue: com.apple.main-thread
0 libobjc.A.dylib 0x93719ed7 objc_msgSend + 23
1 com.apple.AppKit 0x915ae95c -[NSView _recursiveDisplayRectIfNeededIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:topView:] + 4668
2 com.apple.AppKit 0x915ae95c -[NSView _recursiveDisplayRectIfNeededIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:topView:] + 4668
3 com.apple.AppKit 0x9164caa3 -[NSNextStepFrame _recursiveDisplayRectIfNeededIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:topView:] + 311
4 com.apple.AppKit 0x915a9ea2 -[NSView _displayRectIgnoringOpacity:isVisibleRect:rectIsVisibleRectForView:] + 3309
5 com.apple.AppKit 0x9150aa57 -[NSView displayIfNeeded] + 818
6 com.apple.AppKit 0x914be661 -[NSNextStepFrame displayIfNeeded] + 98
7 com.apple.AppKit 0x914d3d40 -[NSWindow displayIfNeeded] + 204
8 com.apple.AppKit 0x9150528a _handleWindowNeedsDisplay + 696
9 com.apple.CoreFoundation 0x91397e02 __CFRunLoopDoObservers + 1186
10 com.apple.CoreFoundation 0x91353d8d __CFRunLoopRun + 557
11 com.apple.CoreFoundation 0x91353464 CFRunLoopRunSpecific + 452
12 com.apple.CoreFoundation 0x91353291 CFRunLoopRunInMode + 97
13 com.apple.HIToolbox 0x9904e004 RunCurrentEventLoopInMode + 392
14 com.apple.HIToolbox 0x9904ddbb ReceiveNextEventCommon + 354
15 com.apple.HIToolbox 0x9904dc40 BlockUntilNextEventMatchingListInMode + 81
16 com.apple.AppKit 0x914db78d _DPSNextEvent + 847
17 com.apple.AppKit 0x914dafce -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 156
18 com.apple.AppKit 0x9149d247 -[NSApplication run] + 821
19 com.apple.AppKit 0x914952d9 NSApplicationMain + 574
20 wgv.CamRecorder 0x00001ff9 start + 53
Le Code
-(void)playMovie
{
NSError *error = nil;
NSString *pathString = [NSString stringWithFormat:@"/Users/Shared/Real/Movies"];
fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error: &error];
NSInteger lenghtOfArray = [fileList count];
NSInteger myNewFavoriteRandomNumber = arc4random() % lenghtOfArray;
NSString *fileName = [NSString stringWithFormat:@"%@",[fileList objectAtIndex:myNewFavoriteRandomNumber]];
fileName = [fileName stringByDeletingPathExtension];
NSString *fuckDS_Store = [NSString stringWithFormat:@"%@",[fileList objectAtIndex:myNewFavoriteRandomNumber]];
if([fuckDS_Store isEqualToString:@".DS_Store"])
{
[self playMovie];
}
else
{
if([lastPlayedVideo intValue] == myNewFavoriteRandomNumber)
{
if(lenghtOfArray > 3)
{
[self playMovie];
}
}
else if([lastPlayedVideo2 intValue] == myNewFavoriteRandomNumber)
{
if(lenghtOfArray > 3)
{
[self playMovie];
}
}
else
{
lastPlayedVideo2 = lastPlayedVideo;
lastPlayedVideo = [NSNumber numberWithInt:myNewFavoriteRandomNumber];
[textfield setStringValue:[fileList objectAtIndex:myNewFavoriteRandomNumber]];
NSError *cperror = nil;
NSString* stringMoviePath = [NSString stringWithFormat:@"/Users/Shared/Real/Movies/%@.mov",fileName];
QTMovie* movie = [[QTMovie alloc] initWithFile:stringMoviePath error:&cperror];
if(movie)
{
[movieViewLoop setMovie:movie];
[movieViewLoop play:@"yes"];
}
else
{
//[self playMovie];
[self performSelector:@selector(playMovie) withObject:@"Oki" afterDelay:1];
}
}
}
}
- (void)movieDidEnd:(NSNotification *)aNotification //Every time a movie has been played this is being run
{
if([blockLoop intValue] == 0)
{
[self playMovie];
}
}
A: The code that crashes is deeply nested in AppKit. The window is busy redrawing a part of it's view hierarchy. In this process it uses a (private) _NSDisplayOperation objects, that responds to the mentioned rectSetBeingDrawnForView: selector.
The stack trace looks like AppKit tries to message an erroneously collected display operation object. The crash has probably nothing at all to do with your code.
So, what can you do about it?
*
*File a bug
*Avoid garbage collection
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5152140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Send json data to Jupyter Notebook Frontend via Comm I want to send some arbitrary data to the Jupyter Notebook frontend.
According to http://jupyter-client.readthedocs.org/en/latest/messaging.html#opening-a-comm, the Comm protocol is a way to send custom message types without resorting to hacks like using execute_request msg_type.
On the Python side, I have
from ipykernel.comm import Comm
c=Comm()
#c.open()
#c.send(data={'foo':'bar'})
However, on the JavaScript side I get an error on initializing Comm():
Error: Class comm not found in registry at http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:12751:28 at Object.load_class (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:12736:16) at CommManager.comm_open (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:21802:37) at x.isFunction.i (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:89:5488) at Kernel._handle_iopub_message (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:23101:20) at Kernel._finish_ws_message (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:22936:29) at http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:22926:44
What does this error mean?
A: Figured it out - IPyWidgets notebook extension provides nice examples of how to do this: https://github.com/ipython/ipywidgets
On the JS side:
var comm_manager=Jupyter.notebook.kernel.comm_manager
var handle_msg=function(msg){
console.log('got msg');
console.log(msg)
}
comm_manager.register_target('myTarget', function(comm,msg){
console.log('opened comm');
console.log(msg);
// register callback
comm.on_msg(handle_msg)
})
Then in Python,
from ipykernel.comm import Comm
c=Comm(target_name='myTarget',data={})
c.send('hello')
The response in the browser console:
opened comm
VM4511:3 Object {parent_header: Object, msg_type: "comm_open", msg_id: "331ba915-0b45-4421-b869-7d9794d72113", content: Object, header: Object…}
VM4464:2 got msg
VM4464:2 Object {parent_header: Object, msg_type: "comm_msg", msg_id: "9fdc83c8-49c5-4629-aa43-7ddf92cb4f5e", content: Object, header: Object…}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33845775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Rails - How to avoid messy conditions in my views I'm still fairly new to rails and trying to learn its 'best practices'. I've noticed when I'm drawing up my views to display a report, my views are starting to look cluttered with if-else-then conditions. If there are some good ways to avoid such mess, please advise.
A: General advice would be to make sure that any domain logic exists in your models, rather than the view.
Also, extract mark-up into partials if your views are getting too long.
You might also want to look at the MVVM pattern: http://en.wikipedia.org/wiki/Model_View_ViewModel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6239287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calculate layout delta to store on an item I am trying to figure out how to calculate, then store the layout delta for a rendering programatically. The situation I'm in is that I have a rendering defined on my standard value. It's datasource is empty. I then have a process that creates an item based on that template, but I need to set the datasource on the rendering.
By default, the __Renderings field on the new item is blank (as is expected). So far, I've been able to get a RenderingReference to my rendering, detect that the datasource is blank, but I cannot for the life of me figure out how to set the datasource then store the correct delta in the __Renderings field on my item.
So far I have:
foreach (var device in new DeviceRecords(database).GetAll())
{
foreach (var rendering in myItem.Visualization.GetRenderings(device, false).Where(r => r.RenderingID == renderingId)
{
if (rendering.Settings.DataSource.IsNullOrEmpty())
{
var dataSourceItem = datasourceFolder.Add("Datasource name", dataSourceTemplate);
rendering.Settings.DataSource = dataSourceItem.ID.ToString();
using (new EditingContext(myItem)){
myItem[FieldIDs.LayoutField] == //????
}
}
}
}
My guess is I need to somehow invoke something in XmlDelta, but it looks like all of those methods want some Xml to work with, when all I have is the rendering item.
A: I wrote some code a while back that tried to extract data source information from Sitecore's XML deltas. I never tried updating it though, but this may work for you.
The class I used was Sitecore.Layouts.LayoutDefinition which is able to parse the XML and if I remember correctly it deals with the business of working out what the correct set of page controls is by combining the delta with the underlying template data. You can construct it like so:
string xml = LayoutField.GetFieldValue(item.Fields["__Renderings"]);
LayoutDefinition ld = LayoutDefinition.Parse(xml);
DeviceDefinition deviceDef = ld.GetDevice(deviceID);
foreach(RenderingDefinition renderingDef in deviceDef.GetRenderings(renderingID))
{
// do stuff with renderingDef.Datasource
}
So I think you can then use the API that LayoutDefinition, DeviceDefinition and RenderingDefinition provides to access the data. There's a bit more info on how I used this in the processImages() function in this blog post: https://jermdavis.wordpress.com/2014/05/19/custom-sitemap-filespart-three/
I think the missing step you're after is that you can modify the data this object stores (eg to set a data source for a particular rendering) and then use the ToXml() method to get back the revised data to store into your Renderings field?
You may be able to find more information by using something like Reflector or DotPeek to look inside the code for how something like the Layout Details dialog box modifies this data in the Sitecore UI.
-- Edited to add --
I did a bit more digging on this topic as I was interested in how to save the data again correctly. I wrote up what I discovered here: https://jermdavis.wordpress.com/2015/07/20/editing-layout-details/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30985914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding MIN and MAX of date column I am trying to find out min and max of application_date(Text data type)
application_date
01Jan2018
21Feb2018
18Mar2018
31Dec2017
15Jan2019
Column is of Text data type
From the data above Min date is 31Dec2017 ,Max date is 15Jan2019
A: SQL DEMO
Convert the text to DATE
SELECT to_date(application_date,'DDMONYYYY');
then
SELECT MAX(to_date(application_date,'DDMONYYYY')),
MIN(to_date(application_date,'DDMONYYYY'))
;
A: Try this:
select max(TO_DATE(application_date, 'DDMONYYYY')) max_date,
min(TO_DATE(application_date, 'DDMONYYYY')) min_date
from table1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54428287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL : how to check if a column value has all elements from a string array I have a table where a column called Phrase has a sentence.
For example :
ID | Phrase |
----+---------------+
1 | I can do it |
2 | Where is that |
I also have another table which has keywords. For example :
select keyword
from keywords
returns
ID | Keywords |
---+----------+
1 | I |
2 | can |
3 | do |
4 | it |
How can I can check if the phrase column for a given row has all matching keywords. Something like:
select *
from table
where phrase like '%I%'
and phrase like '%do%'
and phrase like '%can%'
and phrase like '%it%'
Thanks
A: It's a little bit tricky but by using String_Split it can be handled like this:
SELECT ph.Id,
ph.Phrase
FROM
(
SELECT Id,
Phrase,
value
FROM Phrases
CROSS APPLY STRING_SPLIT(Phrase, ' ')
) ph
LEFT JOIN Keywords keys
ON keys.Keyword = ph.value
GROUP BY ph.Id,
ph.Phrase
HAVING SUM( CASE
WHEN keys.Keyword IS NULL THEN
1
ELSE
0
END
) = 0;
A: You may try the following to get the phrase that contains all of the keywords listed in keyword table:
SELECT T.ID, T.Phrase
FROM table_name T JOIN keyword K
ON T.Phrase LIKE CONCAT('%',K.Keywords,'%')
GROUP BY T.ID, T.Phrase
HAVING COUNT(*) = (SELECT COUNT(*) FROM keyword)
See a demo.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73761876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compiling vsftpd 3.0.0 is failing I recently tried to compile vsftpd 3.0.0 but it fails due the following compile error:
gcc -c seccompsandbox.c -O2 -fPIE -fstack-protector --param=ssp-buffer-size=4 -Wall -W - Wshadow -Werror -Wformat-security -D_FORTIFY_SOURCE=2 -idirafter dummyinc
seccompsandbox.c:63: error: ‘O_DIRECTORY’ undeclared here (not in a function)
seccompsandbox.c:63: error: ‘O_CLOEXEC’ undeclared here (not in a function)
make: *** [seccompsandbox.o] Error 1
As I'm not very familar with the source and the environment I have no idea how to fix this. I imagine that it has something to do with the new seccomp filter sandbox. A Search on google showed me that the error is reproducible but no solution was submitted.
My linux kernel version is 2.6.32-5-amd64 and I'm using gcc version 4.4.5 (Debian 4.4.5-8)
Any ideas welcome.
(If you need additional information's don't hesitate to ask)
A: At least on Debian O_DIRECTORY and O_CLOEXEC are defined only if _GNU_SOURCE is defined.
Although _GNU_SOURCE is set for certain modules in the current vsftp release it is not set generally.
As a work around you might use the following patch:
diff -Naur vsftpd-3.0.0.orig/seccompsandbox.c vsftpd-3.0.0/seccompsandbox.c
--- vsftpd-3.0.0.orig/seccompsandbox.c 2012-04-05 00:41:51.000000000 +0200
+++ vsftpd-3.0.0/seccompsandbox.c 2012-06-30 15:25:52.000000000 +0200
@@ -11,7 +11,7 @@
#include "seccompsandbox.h"
#if defined(__linux__) && defined(__x86_64__)
-
+#define _GNU_SOURCE
#include "session.h"
#include "sysutil.h"
#include "tunables.h
Disclaimer: Applying this patch makes the current vsftp release compile, I have now clue wether the created binaries work correctly or not.
A: I'm using SLES 11 sp1 64bit, kernel 2.6.32, gcc ver 4.3.4; changing or removing FORTIFY_SOURCE made no difference, get same error. I'm not a c programmer - the flags O_DIRECTORY and O_CLOEXEC are in seccompsandbox.c:
static const int kOpenFlags =
O_CREAT|O_EXCL|O_APPEND|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_LARGEFILE;
It compiles if you remove them but that really fills me with confidence....
The vrf_findlibs.sh is also broken, I had to rejig the script so it found a 64bit version of libcap first or it keeps selecting the 32bit copy (the -lcap doesn't work either, says it isn't found):
# Look for libcap (capabilities)
if locate_library /lib64/libcap.so; then
echo "/lib64/libcap.so.2";
elif locate_library /lib/libcap.so.1; then
echo "/lib/libcap.so.1";
elif locate_library /lib/libcap.so.2; then
echo "/lib/libcap.so.2";
else
locate_library /usr/lib/libcap.so && echo "-lcap";
locate_library /lib/libcap.so && echo "-lcap";
locate_library /lib64/libcap.so && echo "-lcap";
fi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11088276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails 3.2 and yui compressor The Rails Guide on the asset pipeline says you can use the yui-compressor on CSS with:
config.assets.css_compressor = :yui
However, I see no sign that it is actually using it. For one, thing, it makes no difference whether or not I have the yui-compressor gem installed or not. For another, compressed output is the same whether I have that line or not.
I put a little debug line into actionpack-3.2.3/lib/sprockets/compressors.rb in the registered_css_compressor method, and this is the result when the css is compiled: #<Sass::Rails::CssCompressor:0x007fdef9f9fee0>
So it appears that the config line is not being honored. Has anyone actually used this option?
Update
Looking in sass-rails shows that the selection is overridden:
if app.config.assets.compress
app.config.sass.style = :compressed
app.config.assets.css_compressor = CssCompressor.new
end
If I comment that out, then it actually attempts to start the yui compressor... I'm still checking the output to see if it is correct.
A: It truly is a bug in rails. I created a patch and pull request to fix it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10673591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to call CreateProcess() in C# passing lpEnvironment I imported native CreateProcess into my C# project
for ICorDebug purposes http://msdn.microsoft.com/en-us/library/vstudio/ms232508(v=vs.100).aspx
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void CreateProcess([In, MarshalAs(UnmanagedType.LPWStr)] string lpApplicationName, [In, MarshalAs(UnmanagedType.LPWStr)] string lpCommandLine, [In] SECURITY_ATTRIBUTES lpProcessAttributes, [In] SECURITY_ATTRIBUTES lpThreadAttributes, [In] int bInheritHandles, [In] uint dwCreationFlags, [In] IntPtr lpEnvironment, [In, MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, [In] STARTUPINFO pStartupInfo, [In] PROCESS_INFORMATION pProcessInformation, [In] CorDebugCreateProcessFlags debuggingFlags, [MarshalAs(UnmanagedType.Interface)] out ICorDebugProcess ppProcess);
I call it trying to pass lpEnvironment this way
IntPtr intPtrEnv;
if (variables != string.Empty)
intPtrEnv = Marshal.StringToHGlobalUni(variables);
else
intPtrEnv = new IntPtr(0);
p_codebugger.CreateProcess(
exepath,
exepath,
null,
null,
1, // inherit handles
(UInt32)CreateProcessFlags.CREATE_NEW_CONSOLE,
intPtrEnv,
".",
si,
pi,
CorDebugCreateProcessFlags.DEBUG_NO_SPECIAL_OPTIONS,
out proc);
the variables string contains:
"COR_ENABLE_PROFILING=1\0COR_PROFILER=PROFILER_GUID\0COR_PROFILER_PATH=GetProfilerFullPat\0\0"
I GET an ERROR
Value Exceeded Allowable Range
Any suggestions how to pass the environment block from c# into the c++ dll?
A: Ok i managed to resolve my problem.
First i used StringBuilder instead of IntPtr.
To add a string "COR_ENABLE_PROFILING=1\0COR_PROFILER=PROFILER_GUID\0COR_PROFILER_PATH=GetProfilerFullPat\0\0"
i simply add("COR_ENABLE_PROFILING=1") and the increse the Stringbuilder lenght + 1 etc...;
the end should be incremented one more time lenght++ (this is the ansi encoding);
Second thing is to change and add marshalling into the imported method
Instead of [In] IntPtr lpEnvironment add [In, MarshalAs(UnmanagedType.LPStr)] StringBuilder lpEnvironment
A: There's no need to use P/Invoke for this, you can use the .Net Process.Start method directly from your C# code.
If you want to customize the process startup, pass environment variables etc, use one of the overloads that takes a ProcessStartInfo object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25353445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a standard in java for _ (underscore) in front of variable or class names? I have seen some programmers using _ (underscore) in front of class names, and others using it for local variables.
Does the Java standard require/suggest the use of _ (underscore) in front of an private instance variable or class name?
A: Many people (including myself) use _ in front of field names. The reason for this is to easily distinguish them from local variables. However in the ages of IDEs this is not so necessary since syntax highlighting shows this. Using an underscore in front of a class name is just wrong. By convention, class names start with an uppercase letter.
A: I think artifacts like these are pre-IDE and C++ vintage. Don't do it.
A: A lot of people is it for instance variables as it makes them stand out. Personally I hate it mainly because methods should, for the most part, be no more than 10 lines of code (I hardly ever go over 20). If you cannot see that a variable isn't local in under 10 lines then there is something wrong :-)
If you have 100 line methods and you don't declare all your variables at the top of the block that they are used in I can see why you would want to use _ to distinguish them... of course, as with most things, if it hurts then stop doing it!
A: It is a matter of personal taste.
Martin Fowler appears to like it. I don't care much for it - it breaks the reading pattern, and the information it conveys is already subtly told by color in your IDE.
I've experimented with using _ as the name of the variable holding the result to be returned by a method. It is very concise, but I've ended up thinking that the name result is better.
So, get your colleagues to agree on what you all like the most and then just do that.
A: if you want to follow best practice java , use the code convention outlined here http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
I.e., no underscore for private member variable names.
Tho, personally, i m not fussed either way, as long as consistency is applied.
A: Using _ before a variable helps in one case where if the developer wants to use a standard/key word as a variable name knowingly or unknowingly. It would not give a conflict if that has an additional character.
A: It seems to be a convention that states if an underscore is used as an initial character in the name of method, the method cannot be overridden.
For example, in context of JSP, _jspService() method cannot be overridden.
However, i dont find any document that states above convention.
A: I agree with the others here... It breaks the standard and doesn't really buy you anything if you just use a naming standard. If you need to know the difference between your class and local variables, try a naming convention like lVariableName where the l is used to indicate that it is local. To me this is unnecessary since the IDE highlighting is sufficient, but might be useful to some.
A: *
*Do not use _ when you use a modern LCD color monitor, with modern IDE like Eclipse, Netbeans, IntelliJ, Android Studio.
*Use _ when you need to use a old-style monochrome CRT monitor with only green or white text, or when you have difficulty to identify the color on LCD monitor.
*The consensus of your code collaborators overrides the above.
A: I am using _ in front of class name, if the class is package private. So in the IDE I have grouped all package private classes on top of the package and I see immediately, that these classes are not accessable from outside of the package.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1899683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: can't convert string[] to string in vhdl i am writing a code in vhdl and bump into this error
Assignment target incompatible with right side. Cannot convert 'dataArray' to 'STRING'
here is my code
entity instructionTranslator is
port(clk :in std_logic;
instructionCode :in std_logic_vector(4 downto 0);
instructionType:out std_logic_vector(1 downto 0) ;
data :out string (1 to 1)--here is data
);
end instructionTranslator;
.
.
.
architecture Translator of instructionTranslator is
type dataArray is array (0 to 13)of string(1 to 1);
process(clk) begin
data<=dataArray(1);
how should chooses special index of array in vhdl.
A: Here. I made it into an [MCVE] for you. This one compiles.
You declared a type dataArray.
You didn't then go on to declare a signal (or variable or constant) of that type.
Assigning a member of a type (which is something abstract) to a real signal obviously won't work.
Assigning a member of a signal (etc) of that type, however, ...
library ieee;
use ieee.std_logic_1164.all;
entity instructionTranslator is
port(clk :in std_logic;
instructionCode :in std_logic_vector(4 downto 0);
instructionType:out std_logic_vector(1 downto 0) ;
data :out string (1 to 1)--here is data
);
end instructionTranslator;
architecture Translator of instructionTranslator is
type dataArray is array (0 to 13)of string(1 to 1);
signal da : dataArray;
begin
process(clk) is
begin
data<=da(1);
end process;
end Translator;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48421071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does My Boolean variable Automatically switch? I have a program where players and enemies can attack each other in a loop and when health reaches zero, the bool isDead turns to true, and when both players or both enemies are dead then allDead(c1, c2) turns to true. When a character's isDead is true, then I skip their turn. But I've been setting breakpoints and I notice that the character's isDead automatically turn to true even though they still have health. I looked everything over and I just don't understand what I'm missing. isDead has been initialized to false and all the lines associated with the variable are meant to check if its true or false. Could someone please help point out what i'm missing? Thank you.
isDead Function
bool Character::isDead() {
if (dead = true)
return true;
}
Main
int main()
{
srand(time(NULL));
PlayerCharacter* p1 = new PlayerCharacter();
PlayerCharacter* p2 = new PlayerCharacter();
EnemyCharacter* e1 = new EnemyCharacter();
EnemyCharacter* e2 = new EnemyCharacter();
p1->printCharacter();
p2->printCharacter();
e1->printCharacter();
e2->printCharacter();
string enemyTarget, playerTarget;
list<Character*> players;
list<Character*> enemies;
players.push_back(p1);
players.push_back(p2);
enemies.push_back(e1);
enemies.push_back(e2);
list<Character*>::iterator PinsertIt = players.begin();
list<Character*>::iterator EinsertIt = enemies.begin();
for (; PinsertIt != players.end() && EinsertIt != enemies.end(); ++PinsertIt, ++EinsertIt)
{
listShuffle(players);
listShuffle(enemies);
if (*PinsertIt == p1)
{
if (!p1->isDead())////isDead switches to true when I reach this line
{
cout << "Player One. Choose your Target (1 or 2)" << endl;
cin >> playerTarget;
playerAttack(e1, e2, p1->currentWeapon, playerTarget);
}
else
{
cout << p1->firstName << " " << p1->lastName << " is dead" << endl;
}
}
else if (*PinsertIt == p2)
{
if (!p2->isDead())
{
cout << "Player Two. Choose your Target (1 or 2)" << endl;
cin >> playerTarget;
playerAttack(e1, e2, p2->currentWeapon, playerTarget);
}
else
{
cout << p2->firstName << " " << p2->lastName << " is dead" << endl;
}
}
if (*EinsertIt == e1)
{
if (!e1->isDead())
{
cout << "Enemy One ";
enemyAttack(p1, p2, e1->currentWeapon);
}
else
{
cout << e1->firstName << " " << e1->lastName << " is dead" << endl;
}
}
else if (*EinsertIt == e2)
{
if (!e2->isDead())
{
cout << "Enemy Two ";
enemyAttack(p1, p2, e2->currentWeapon);
}
else
{
cout << e2->firstName << " " << e2->lastName << " is dead" << endl;
}
}
if (allDead(p1, p2))
{
cout << "Game Over!" << endl;
}
else if (allDead(e1, e2))
{
cout << "You Win!" << endl;
}
}
system("pause");
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49718836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Avoid double typing class names in python This seems like a silly question but I haven't been able to come across the answer anywhere. Within my various packages I have a set of modules, usually each containing one class. When I want to create an instance of a class I have to refer to it twice:
Example:
package/obj.py:
class obj(object):
pass
file.py:
import package.obj
my_obj = package.obj.obj()
Is there a way to reorganize my code such that I don't have to type the name twice? Ideally I'd like to just have to type package.obj().
A: You can use from ... import ... statement:
from package.obj import obj
my_obj = obj()
A: Python is not Java. Feel free to put many classes into one file and then name the file according to the category:
import mypackage.image
this_image = image.png(...)
that_image = image.jpeg(....)
If your classes are so large you want them in separate files to ease the maintenance burden, that's fine, but you should not then inflict extra pain on your users (or yourself, if you use your own package ;). Gather your public classes in the package's __init__ file (or a category file, such as image) to present a fairly flat namespace:
mypackage's __init__.py (or image.py):
from _jpeg import jpeg
from _png import png
mypackage's _jpeg.py:
class jpeg(...):
...
mypackage's _png.py:
class png(...):
...
user code:
# if gathered in __init__
import mypackage
this_image = mypackage.png(...)
that_image = mypackage.jpeg(...)
or:
# if gathered in image.py
from mypackage import image
this_image = image.png(...)
that_image = image.jpeg(....)
A: Give your classes and modules meaningful names. That's the way. Name your module 'classes' and name your class 'MyClass'.
from package.classes import MyClass
myobj = MyClass()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19010969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: I'm missing a using directive or an assembly reference? I am having issues with the following code.
class AccountDB
{
public void DumpCustomers(TextWriter textWriter)
{
foreach (Customer c in _Customers)
{
textWriter.WriteLine("\t{0}", c);
foreach (Account a in c.Accounts)
{
textWriter.WriteLine("\t\t{0}", a.AccountType);
textWriter.WriteLine("\t\t\t{0,-20} : {1,13}", "Opening Balance", a.OpeningBalanceString);
foreach (ITransaction t in a.Transactions)
textWriter.WriteLine("\t\t\t{0,-20} : {1,13}", t.Description, t);
textWriter.WriteLine("\t\t\t{0,-20} : {1,13}", "Closing Balance", a);
}
}
}
}
class SavingsAccount : Account
{
public string AccountType
{
get { return "Savings Account"; }
}
}
class CreditAccount : Account
{
public string AccountType
{
get { return "Credit Account"; }
}
}
class Customer
{
private string _Name;
private List<Account> _Accounts = new List<Account>();
public string Name
{
get { return _Name; }
}
public ReadOnlyCollection<Account> Accounts
{
get { return _Accounts.AsReadOnly(); }
}
public Customer(string Name)
{
_Name = Name;
}
public void AddAccount(Account account)
{
if (!_Accounts.Contains(account))
{
_Accounts.Add(account);
account.RecordCustomer(this);
}
}
public override string ToString()
{
return _Name;
}
}
When the compiler attempts to access the AccountType string, I get the following error:
'Example_Namespace.Account' does not contain a definition for 'AccountType' and no extension method 'AccountType' accepting a first argument of type 'Example_Namespace.Account' could be found (are you missing a using directive or an assembly reference?)
I understand that something must be added to the Account class to allow the code to run (probably polymorphic), but I am unsure how to proceed further. I would greatly appreciate any help. Thanks :)
A: You should add AccountType property to Account class. There are two ways:
Making Account class abstract:
abstract class Account
{
public abstract string AccountType { get; }
}
class SavingsAccount : Account
{
public override string AccountType
{
get { return "Savings Account"; }
}
}
class CreditAccount : Account
{
public override string AccountType
{
get { return "Credit Account"; }
}
}
Or making AccountType property virtual:
class Account
{
public virtual string AccountType { get { return string.Empty; } }
}
class SavingsAccount : Account
{
public override string AccountType
{
get { return "Savings Account"; }
}
}
class CreditAccount : Account
{
public override string AccountType
{
get { return "Credit Account"; }
}
}
This would make sense if Account should be instantiated on its own and can provide a valid implementation for AccountType property. Otherwise you should go with the abstract class.
A: Well, you wrote:
foreach (Account a in c.Accounts)
{
textWriter.WriteLine("\t\t{0}", a.AccountType);
...
}
The problem is that you have defined the AccountType property in SavingsAccount and CreditAccount, the classes inherited from the Account class.
The error happens when a in c.Accounts is not a SavingsAccount or CreditAccount.
The solution would be adding the (virtual) AccountType property to the Account class, and overriding it in the child classes.
A: here:
foreach (Account a in c.Accounts)
You are making a of the account type.
here you are saying that saving account implements account.
class SavingsAccount : Account
{
public string AccountType
{
get { return "Savings Account"; }
}
}
SavingAccount is where the AccountType exists not in Account. Your base class of Account needs be like this.
public abstract class Account
{
public abstract string AccountType { get; }
}
and your saving account needs to be this:
public class SavingAccount : Account
{
public override string AccountType
{
get { return "Savings Account"; }
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23312934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot read property 'name' of null on default value I have a state in which i have
I had initialized my data state as null
For whole code visit
https://codeshare.io/5zMyXD
Calling aixos api request on componentDidMount
axios.post("http://localhost/axios1/index.php",data)
.then(res=>this.setState({data:res.data},
()=>console.log(this.state.data)))
Getting this on state
{id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
<input defaultValue={this.state.data.name} />
how to set these values in it's input like input for name input for fname
A: {id: "1", name: "vivek", fname: "modi", mobile: "9024555623", photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"}
fname: "modi"
id: "1"
mobile: "9024555623"
name: "vivek"
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
<input defaultValue={this.state.data.name} />
Just use name from state
as if the object you mentioned is state then you can directly access state keys from state
like
this.state.name || this.state.mobile
A: You need to show your code in order to get better help but
If you have a correct state you can change values like this:
<input type="text" name="fname" value={this.state.data.name}>
But your state is null and the code you showed has problem, you need to fill your state correctly, in your class you can write:
State={name:"test"}
And it will work fine. Hope this can help you
update now write this:
{this.state.data && this.state.data.name
&& ( < input defaultValue={this.state.data.name} /> )}
A: You can set like call your axios request through
componentDidMount(){
axios.post("http://localhost/axios1/index.php",data)
.then(res=>this.setState({data:res.data},
()=>console.log(this.state.data)))
}
Suppose you are getting this in your state
state={
data:{
id: "1",
name: "vivek",
fname: "modi",
mobile: "9024555623",
photo: "http://localhost/axios1/uploaded/student/rhinoslider-sprite.png"
}
}
and then render it as
render(){
const {name,fname} = this.state.data?this.state.data:"";
return(
<div>
<input defaultValue={this.state.name} />
<input defaultValue={this.state.fname} />
</div>
);
}
A: Change this in your code, line no 31
this.setState({res.data},()=>console.log(this.state))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58076863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VS Code - prettier settings not applied My settings from prettier are not applied. When I change some settings and save my file it has no effect.
In my Vidoe I enabled single quotes and disabled semicolon, but without any effect.
Vimeo Link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71555173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Image label for input file not clickable In IE7, IE8, IE9 the image label in the following code is not opening browse window on click:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Image label</title>
<!-- Bootstrap CSS Toolkit styles -->
</head>
<style type="text/css">
label{
display: inline-block;
}
label img{
pointer-events: none;
}
</style>
<body>
<form>
<label for="test">
<img src="http://anniekateshomeschoolreviews.com/wp-content/uploads/2015/05/Online-picture1-300x203.jpg">
</label>
<input type="file" id="test">
</form>
</body>
</html>
Is there any way of fixing this problem.
Any help would be greatly appreciated.
A: http://snook.ca/archives/javascript/using_images_as
check this out hope thiss will work
A: You can do it like this without setting id and label for. Position relative should be used to wrap this section as well.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Image label</title>
<!-- Bootstrap CSS Toolkit styles -->
</head>
<style type="text/css">
label{
display: inline-block;
}
label img{
pointer-events: none;
width: 100px;
height: 100px;
border-radius: 50%;
box-shadow: 0px 2px 4px rgba(0,0,0,0.2);
}
input[type="file"]{
position: absolute;
top: 5px;
left: 5px;
width: 108px;
height: 130px;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
</style>
<body>
<form>
<label>
<img src="http://anniekateshomeschoolreviews.com/wp-content/uploads/2015/05/Online-picture1-300x203.jpg">
</label>
<input type="file" id="test">
</form>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32139225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache LocationMatch: how to match again after internal redirect I have a apache LocationMatch with two sets of RewriteCond and RewriteRule. If the second set hits I want to start the LoactionMatch over again.
In my apache2 ( Apache/2.4.41 (Ubuntu) mod_wsgi/4.9.0 Python/3.8 configured) config I have something like this:
<LocationMatch ^/incoming-request$>
RewriteEngine On
RewriteCond /tmp/test-file -f
RewriteRule (.*) /some/service [QSA,L]
RewriteCond /file-associated-with-the-request -f
RewriteRule (.*) /myapp [L]
</LocationMatch>
Where myapp is a wsgi script which generates the /tmp/test-file and returns 301 redirect and Location: /incoming-request
/file-associated-with-the-request always exists.
So far so good.
If the /tmp/test-file does not exists then trigger the /myapp which then generates the /tmp/test-file. Then I want the LocationMatch to start over again so that the /some/service
is triggered as /tmp/test-file exists after the first loop. This does not happen.
If I curl http://localhost/incoming-request I get the /tmp/test-file generated, and I get the return from /myapp. So if I want to get the return from /some/service I have to run the curl again.
Is there a way to kind of loop over again in the LocationMatch so I dont have to do my request twice?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71662485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Twitter integration using oauth and twitter4j I want to integrate twitter in an android application and found many tutorials. Implemented 2 of them. But after implementing, when ran the application, I came to know that they use older version of twitter4J library.
Although plenty other tutorials are available but none of them is latest one.i.e. just 2-3 months older. I need a tutorial or example which uses latest twitter4J library version which is twitter4j-core-3.0.3.
My main aim is to allow user to post tweets on his/her account. But again, if user is not logged in then, I first need to ask for credentials. Also, if user clicks on logout button then I need some way to log the user out.
A: I found a good example which works well with twitter4j 3.0.3 on android. Others do not work.
http://hintdesk.com/how-to-tweet-in-twitter-within-android-client/
A: This is the working example from my code , i am using twitter4j and also you don't need to set any intent in manifest since i use webview instead of browser.
Place your consumer and secret key and you should be good to go
package com.example.mysituationtwittertest;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "XXXXXXXXXXXXXXXXXXX"; // place your
// cosumer
// key here
static String TWITTER_CONSUMER_SECRET = "XXXXXXXXXXXXXXXX"; // place
// your
// consumer
// secret
// here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://youdare";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button btnShareTwitter;
WebView myWebView;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// All UI elements
btnShareTwitter = (Button) findViewById(R.id.btnShareTwitter);
myWebView = (WebView) findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url != null && url.startsWith(TWITTER_CALLBACK_URL))
new AfterLoginTask().execute(url);
else
webView.loadUrl(url);
return true;
}
});
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnShareTwitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call login twitter function
new LoginTask().execute();
}
});
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
public void handleTwitterCallback(String url) {
Uri uri = Uri.parse(url);
// oAuth verifier
final String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
MainActivity.this.accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
// Update status
twitter4j.Status response = twitter
.updateStatus("XXXXXXXXXXXXXXXXX");
} catch (Exception e) {
e.printStackTrace();
}
}
class LoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
loginToTwitter();
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
myWebView.loadUrl(requestToken.getAuthenticationURL());
myWebView.setVisibility(View.VISIBLE);
myWebView.requestFocus(View.FOCUS_DOWN);
}
}
class AfterLoginTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
myWebView.clearHistory();
}
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
handleTwitterCallback(params[0]);
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
myWebView.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "Tweet Successful",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onBackPressed() {
if (myWebView.getVisibility() == View.VISIBLE) {
if (myWebView.canGoBack()) {
myWebView.goBack();
return;
} else {
myWebView.setVisibility(View.GONE);
return;
}
}
super.onBackPressed();
}
}
A: To illustrate my comment above, here is my final working MainActivity class.
Pretty similar to the code above, the differences are :
*
*the internal class OAuthAccessTokenTask, that includes the retrieval of the Oauth token and the user information
*its callback onRequestTokenRetrieved(Exception)
Also, note that to get this to work you must declare a callback url on your twitter app settings, even a phony one. It took me a few hours to figure out the way it works.
When you check the twitter4j documentation, the first pieces of code refer to a PIN code you have to get from an authorisation webpage. That's what happens when no callback url is set in your app. It's called PIN based authentication and you don't want to use it on a mobile :)
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "PutYourConsumerKeyHere"; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
private User user;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(
getApplicationContext(),
"Please enter status message",
Toast.LENGTH_SHORT
).show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
new OAuthAccessTokenTask().execute(verifier);
}
}
}
private class OAuthAccessTokenTask extends AsyncTask<String, Void, Exception>
{
@Override
protected Exception doInBackground(String... params) {
Exception toReturn = null;
try {
accessToken = twitter.getOAuthAccessToken(requestToken, params[0]);
user = twitter.showUser(accessToken.getUserId());
}
catch(TwitterException e) {
Log.e(MainActivity.class.getName(), "TwitterError: " + e.getErrorMessage());
toReturn = e;
}
catch(Exception e) {
Log.e(MainActivity.class.getName(), "Error: " + e.getMessage());
toReturn = e;
}
return toReturn;
}
@Override
protected void onPostExecute(Exception exception) {
onRequestTokenRetrieved(exception);
}
}
private void onRequestTokenRetrieved(Exception result) {
if (result != null) {
Toast.makeText(
this,
result.getMessage(),
Toast.LENGTH_LONG
).show();
}
else {
try {
// Shared Preferences
Editor editor = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
editor.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
editor.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
}
catch (Exception ex) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + ex.getMessage());
ex.printStackTrace();
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
});
thread.start();
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
A: I solved the problem. I made changes to the code I found in a tutorial to make it work. Copying the whole code here. Just replace with your ConsumerKey and ConsumerSecret.
You need to add twitter4j library to your project's libs folder.
AndroidManifest.xml :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.twitterconnect"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<!-- Permission - Internet Connect -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="t4jsample"
android:scheme="oauth" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java :
package com.androidhive.twitterconnect;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import com.androidhive.twitterconnect.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "PutYourConsumerKeyHere"; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = "PutYourConsumerSecretHere"; // place your consumer secret here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
final String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
// Get the access token
MainActivity.this.accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
e.printStackTrace();
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
AlertDialogManager.java :
package com.androidhive.twitterconnect;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* @param context - application context
* @param title - alert dialog title
* @param message - alert message
* @param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
ConnectionDetector.java :
package com.androidhive.twitterconnect;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
This is original code by Ravi Tamada. The changes I made are in MainActivity.java and AndroidManifest.xml files only.
A: Have you seen the sign-in-with-twitter github project, it is based on twitter4j and implements Twitter sign in for Android.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17499935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: JQuery select2 integration with Frontaccounting https://stackoverflow.com/questions/33993771/how-to-integrate-jquery-select2-with-frontaccounting/33994148#
Hi this is my first post. Here actually there is a similar post. I commented there. But few told me to go with separate question. So my question is a duplicate of the above link. I have not get a solution for this problem. Any solution for this one?.
A: Finally I found a solution for it. Just bring the jquery select to files to your frontaccounting and include it on header.inc than you have to do one more step into it. Goto Root_of_FA/company/0/js_cache/utilis.js and found the below line
window.scrollTo(0,0);if(!newwin){setFocus();}
}
}, false
around this will be line number : 27-36. than change it like the below one.
window.scrollTo(0,0);if(!newwin){setFocus();}
}
$(".combo").select2({
placeholder: "Select a state",
allowClear: true
});
},false
that's it. It will work for you. If you need more details, check Here.
KV codes Select2 and Frontaccounting
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34011702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MVC 4 View doesnt recognize model [EDIT]
@model LocationInfo (LocateIt.Models)
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
</div>
</body>
</html>
I just started working with MVC/NHibernate today by going through a little tutorial. Everything went fine until I tried to create a view out of my model through an ActionResult (Index). It seems that the view cant find the model and as I'm literally a Beginner I have no clue what to do.
Could you guys have a look at my code and tell me what I did wrong or at least give a clue?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LocateIt.Models
{
public class LocationInfo
{
public virtual int Id { get; set; }
public virtual string LocationName { get; set; }
public virtual string LocationDescription { get; set; }
public virtual string City { get; set; }
public virtual string Street { get; set; }
public virtual string HouseNumber { get; set; }
public virtual short PLZ { get; set; }
public virtual decimal Rating { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LocateIt.Models;
using LocateIt.Models.NHibernate;
namespace LocateIt.Controllers
{
public class LocationInfoController : Controller
{
LocationInfoRepository _repository;
public LocationInfoController()
{
_repository = new LocationInfoRepository();
}
public ActionResult Index()
{
IList<LocationInfo> LocationInfo = _repository.GetLocation("Oberhausen");
return View(LocationInfo);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Linq;
namespace LocateIt.Models.NHibernate
{
public class LocationInfoRepository
{
public IList<LocationInfo> GetLocation(string city)
{
using (ISession session = NHibernateHelper.OpenSession())
{
return session.Query<LocationInfo>().ToList();
}
}
public void Save(LocationInfo objLocationInfo)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(objLocationInfo);
transaction.Commit();
}
}
}
}
}
using NHibernate;
using NHibernate.Cfg;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LocateIt.Models.NHibernate
{
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var NHibernateConfig = new Configuration();
NHibernateConfig.Configure(HttpContext.Current.Server.MapPath(
@"Models\NHibernate\Configuration\hibernate.cfg.xml"));
NHibernateConfig.AddDirectory(new System.IO.DirectoryInfo(
HttpContext.Current.Server.MapPath(@"Models\NHibernate\Mappings")));
_sessionFactory = NHibernateConfig.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping
xmlns="urn:nhibernate-mapping-2.2"
assembly="MVC4_Using_NHB"
namespace="MVC4_Using_NHB"
auto-import="true">
<class name="MVC4_Using_NHB.Models.LocationInfo,MVC4_Using_NHB">
<id name="Id" access="property" column="Id" type="Int32">
<generator class="native"></generator>
</id>
<property name="LocationName" access="property"
column="LocationName" type="String"></property>
<property name="LocationDescription" access="property"
column="LocationDescription" type="String"></property>
<property name="City" access="property"
column="City" type="String"></property>
<property name="Street" access="property"
column="Street" type="String"></property>
<property name="HouseNumber" access="property"
column="HouseNumber" type="String"></property>
<property name="PLZ" access="property"
column="PLZ" type="Int16"></property>
<property name="Rating" access="property"
column="Rating" type="Int32"></property>
</class>
</hibernate-mapping>
A: You're sending an IList into your view. This will display a single item.
public ActionResult Index()
{
var info = _repository.GetLocation("Oberhausen").First();
return View(info);
}
If you really want a list (e.g., you're going to display a table or some such), keep your action as is and change your view to:
@model IList<LocateIt.ModelsLocationInfo>
A: I don't understand what the parentheses are doing in the model declaration. The syntax for @model should be:
@model Your.Namespace.ClassName
The in your code you use Model, not model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17255371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PayPal gateway has rejected request (#10413) I have migrated our Magento store 1.9 to 2.3. I have only one tax policy 10% for US California customers.
But I tried to make the payment with California address it came back to cart page with error.
PayPal gateway has rejected request. The totals of the cart item amounts do not match order amounts (#10413: Transaction refused because of an invalid
When I checked the code, it shows tax twice, but I couldn't find the where its coming from.
Is there any solution for that
A: Need to narrow down the issue first:
*
*Check if having class preference and plugins and observer events that override or being triggered while processing Paypal gateway.
*Also check if the issue still exists by removing tax policy 10% US California customers
Hope it helps, thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60561929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Here my code to insert multiple records in database on laravel. So, it doesn't work? anyone help me? I want to insert multiple records in a table at once submit into a database using eloquent laravel, so I have tried hard.
my code on controller
$x = $request->all();
$datas = DataAnak::create($x)->id_anak;
if ($datas != 0) {
foreach ($datas as $key => $value) {
$rows = [
'nama' => $request->nama_anak[$key],
'jenis_kelamin' => $request->gender_anak[$key],
'tempat_tgl_lahir' => $request->tmt[$key],
'tgl_baptis' => $request->baptis_anak[$key],
'tgl_sidi' => $request->sidi_anak[$key],
];
DataAnak::insert($rows);
}
}
my code on blade page
<tr>
<td><input type="text" class="form-control" name="nama_anak[]"></td>
<td><input type="text" class="form-control" name="gender_anak[]"></td>
<td><input type="text" class="form-control" name="tmt[]"></td>
<td><input type="text" class="form-control" name="baptis_anak[]"></td>
<td><input type="text" class="form-control" name="sidi_anak[]"></td>
<td class="text-center">
<button type="button" class="btn btn-danger row-del"><i class="fas fa-times"></i></button>
</td>
</tr>
A: Try this
$datas = $request->all();
$records = [];
foreach ($datas as $key => $value) {
$records[][$key] = $value;
}
DataAnak::insert($records);
A: why are you trying this complex way and that even not the eloquent way to insert data into database. you should do it like below
foreach($request->nama_anak as $key => $value){
DataAnak::create([
'nama_anak' => $request->nama_anak[$key],
'gender_anak' => $request->gender_anak[$key],
'tmt' => $request->tmt[$key],
'baptis_anak' => $request->baptis_anak[$key],
'sidi_anak' => $request->sidi_anak[$key],
]);
}
no need to take the inputs into another variable and create, loop, insert separately.
A: So I think your field is array, you need to loop it like this, and insert them at once:
$datas = $request->all();
$rows = array();
foreach ($datas as $key => $data) {
foreach($data as $index => $value) {
if ($key == 'nama_anak') $rows[$index]['nama'] = $value;
if ($key == 'gender_anak') $rows[$index]['jenis_kelamin'] = $value;
if ($key == 'tmt') $rows[$index]['tempat_tgl_lahir'] = $value;
if ($key == 'baptis_anak') $rows[$index]['tgl_baptis'] = $value;
if ($key == 'tgl_sidi') $rows[$index]['sidi_anak'] = $value;
}
}
DataAnak::insert($rows);
PS: If you have multiple records, don't insert/create them in loop. It will decrease the performance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59527522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: merge dynamic multidimensional arrays Sorry in advance if there is an answer for this, but I could not find exactly what I was looking for.
I currently have a reporting application that is returning data results into multi dimensional arrays from a database query. Each array is build off of the id field. I would like to be able to merge arrays into one where the id is the same.
For example here is a test result set. As you can see the user with an id of 1 currently has two results.
Array
(
[0] => Array
(
[AssessmentQuestion] => 1
[AssessmentAnswer] => 0
[id] => 1
)
[1] => Array
(
[AssessmentQuestion] => 2
[AssessmentAnswer] => 2
[id] => 1
)
)
Array
(
[0] => Array
(
[AssessmentQuestion] => 1
[AssessmentAnswer] => 1
[id] => 2
)
)
I would like the result set to look like this if the id's are the same.
Array
(
[0] => Array
(
[AssessmentQuestion] => 1
[AssessmentAnswer] => 0
[AssessmentQuestion] => 2
[AssessmentAnswer] => 2
[id] => 1
)
)
Thanks so much in advance.
Here are the queries I'm running. There's a custom function ArrayFunctions::captureArrayFromResult(), this is just capturing the array results.
The first query just grabs all active user entry ids, and then per id returns all the
assessment question information.
/**** COLLECT ALL ACTIVE USER ENTRY IDS ****/
$query = "SELECT DISTINCT ue.id
FROM user_entry ue
LEFT JOIN user_demographic_answers uda ON ue.id = uda.user_entry_id
LEFT JOIN user_assessment_answers uaa ON ue.id = uaa.user_entry_id
WHERE $condition
AND DATE(ue.datetime_finished) BETWEEN '{$this->reportDateRangeStart}' AND '{$this->reportDateRangeEnd}'";
$results = db_Query($query);
$this->reportUserEntryID = ArrayFunctions::captureArrayFromResult($results, "id", "id");
foreach($this->reportUserEntryID as $userID)
{
/**** COLLECT ASSESSMENT QUESTIONS ****/
$query = SELECT DISTINCT uaa.question_id as 'AssessmentQuestion', uaa.answer_value as 'AssessmentAnswer', ue.id
FROM user_assessment_answers uaa
LEFT JOIN report_field_options rfo ON uaa.question_id = rfo.assessment_question_id
LEFT JOIN user_entry ue ON uaa.user_entry_id = ue.id
WHERE ($condition)
AND DATE(ue.datetime_finished) BETWEEN '{$this->reportDateRangeStart}' AND '{$this->reportDateRangeEnd}'
AND ue.id IN ($userID)
ORDER BY uaa.question_id";
$results = db_Query($query);
$this->reportQuestionAssessmentAnswers = ArrayFunctions::captureArrayFromResult($results);
}
A: Short answer: it's not possible to do what you're asking for, as array keys must be unique.
I would suggest, during your combining logic, to create an array of AssesmentQuestions and AssesmentAnswers, e.g.:
Array
(
[0] => Array
(
[id] => 1,
[AssesmentQuestions] => Array
(
[0] => 1,
[1] => 2
),
[AssesmentAnswers] => Array
(
[0] => 0,
[1] => 2
)
)
)
A: You can use foreach loop to achieve this :
$main_arr = array
(
array
(
'AssessmentQuestion' => 1,
'AssessmentAnswer' => 0,
'id' => 1
),
array
(
'AssessmentQuestion' => 2,
'AssessmentAnswer' => 2,
'id'=> 1
),
array
(
'AssessmentQuestion' => 3,
'AssessmentAnswer' => 4,
'id' => 2
),
array
(
'AssessmentQuestion' => 5,
'AssessmentAnswer' => 6,
'id'=> 1
)
);
foreach ($main_arr as $arr) {
$new_arr[$arr['id']]['id'] = $arr['id'];
$new_arr[$arr['id']]['AssessmentQuestions'][] = $arr['AssessmentQuestion'];
$new_arr[$arr['id']]['AssessmentAnswers'][] = $arr['AssessmentAnswer'];
}
var_dump($new_arr);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18918093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send request query string from html? I am new to ASP.Net . I have created a blog , the post page displays all the post by using XSLT to transform the xml data of the blog. However, I am struggling to create a dedicated post page whenever user click on the desired article.
This is the xslt code to transform the xml data of the blog post to the home :
<xsl:for-each select="Posts/post">
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="post-preview">
<a href="Post.aspx">
<h2 class="post-title">
<xsl:value-of select="title"/>
</h2>
<h3 class="post-subtitle">
<xsl:value-of select="subtitle"/>
</h3>
</a>
<p class="post-meta">
Posted by
<xsl:value-of select="author"></xsl:value-of>
on <xsl:value-of select="date"/>
</p>
</div>
<hr/>
</div>
</div>
</div>
</xsl:for-each>>
This is the post page I want it to be when user click on the desired article :
However, I have hard time getting the response query string with the code I have setup in the page_load of post page.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["pid"] != null) { }
XmlDocument xml_doc = new XmlDocument();
postdata.DocumentSource = "~/Data/blog_post.xml";
postdata.TransformSource = "~/XSLT file/ViewCurrentPost.xslt";
System.Xml.Xsl.XsltArgumentList xslArg = new System.Xml.Xsl.XsltArgumentList();
xslArg.AddParam("_pid", "", Request.QueryString["pid"]);
postdata.TransformArgumentList = xslArg;
xml_doc.Load(MapPath("~/blog_posts.xml"));
}
This is the XSL file I have made in order to display the correct post :
<xsl:apply-templates select="Posts/post"/>
<xsl:for-each select ="Posts/post">
<xsl:if test="@pid=$_pid">
<!--Header-->
<header class="masthead" style="background-image: url('img/post-bg.jpg')">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="post-heading">
<h1>
<xsl:value-of select="title"/>
</h1>
<h2 class="subheading">
<xsl:value-of select="subtitle"/>
</h2>
<span class="meta">
Posted by
<xsl:value-of select="author"></xsl:value-of>
on <xsl:value-of select="date"/>
</span>
</div>
</div>
</div>
</div>
</header>
This is my blog post structure :
<Posts>
<post pid="pid2623">
<title>Test</title>
<description>Test</description>
<subtitle>Test</subtitle>
<date>7/29/2018 12:00:00 AM</date>
<author>est</author>
</post>
<Posts>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51578947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Safer way to get window scroll position To determine how much window has been scrolled, we have window.scrollY alias window.pageYOffset, but I feel they are not pefectly reliable, because you can simply do window.scrollY = 23401 and this value won't be replaced even after you scroll window to a new position. Same happens to pageYOffset too.
So is there any other property or method we can use to detect window scroll position?
A: use jQuery $(window).scrollTop()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36741902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ Problems with write array function I'm trying to write a function that will write an array (2D) to file. This is the code below:
#ifndef WRITE_FUNCTIONS_H_
#define WRITE_FUNCTIONS_H_
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void write_array(string name, int rows, int columns, double **array){
ofstream output;
output.open(name, ios::out);
for(int r = 0; r < rows; r++){
for(int c = 0; c < columns; c++){
output<<array[r][c]<<",";
}
output<<endl;
}
output.close();
}
#endif
When I try to run it in this program here:
#include <string>
#include <iostream>
#include "write_functions.h"
using namespace std;
int main(){
double **array = new double*[10];
for(int i = 0; i < 10; i++){
array[i] = new double[10];
}
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
array[i][j] = i + j;
}
}
string array_name="home/Plinth/Documents/Temp/array.txt";
write_array(array_name, 10, 10, array);
return(0);
}
It runs perfectly fine, without error or warning, but there is no file created. Did I write something improperly? Am I going about this the wrong way?
A: You're likely writing in an unexpected directory.
Try to fully specify the path like /home/... (note the first '/') or just write it to a local file like array.txt.
A: When handling file streams, I prefer using this idiom to detect errors early.
#include <iostream>
#include <fstream>
#include <cstring>
int main() {
std::ifstream input("no_such_file.txt");
if (!input) {
std::cerr << "Unable to open file 'no_such_file.txt': " << std::strerror(errno) << std::endl;
return 1;
}
// The file opened successfully, so carry on
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35707492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: fopen write with variable issue small project - stumped typing to get it working - if you have any ideas please let me know tku! This post program is requiring more words so here we go
<?php
$row = 1;
if (($handle = fopen("issue-heads-1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
if ($row == 2) {
$file = fopen($data[14], "w");
$write = '
<?php
include "/home/history/public_html/issue1.php";
echo \'<a class="prev" href="\' . $data[16] . \'">\';
?>
';
fwrite($file, $write);
fclose($file);
}
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
A: Quick guess - Try (untested):
$write = '
<?php
include "/home/history/public_html/issue1.php";
echo \'<a class="prev" href="' . $data[16] . '">\';
?>
';
It's just a bit tricky with the multiple quotes... think you might have lost track of which ones need escaping...
Hmmmm... so that didn't work... the next thing I would try is to construct the $write variable over several lines (hopefully making the job a bit easier, so perhaps easier to avoid error) - note that I also threw in a repeating filewrite to see what the output is:
$hF = fopen('__debug.log', "a"); //outside your loop
//inside loop
$hrf = $data[16];
$write = '<?php' + "\n";
$write .= 'include "/home/history/public_html/issue1.php";' + "\n";
$write .= "echo '<a class=\"prev\" href=\"";
$write .= $hrf;
$write .= "\">';" + "\n";
$write .= '?>';
fwrite($hF, $write);
and make sure to close the file before your script ends:
//outside the loop
fclose($hF);
A: Using a variable inside a write statement didn't work while inside a fopen statement. I ended up having to use ob_start to get it to work. Hat tip to gibberish for getting me on the right path.
<?php
ob_start();
include 'issue1.php';
$issueone = ob_get_contents();
ob_end_clean();
$row = 1;
if (($handle = fopen("issue-heads-1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle)) !== FALSE) {
$csv[] = $data;
}
fclose($handle);
}
$file = fopen($csv[$row][14], "w") or die("Unable to open file!");
fwrite($file, $issueone);
fwrite($file, "<a class=\"prev\" href=\"" . $csv[$row][16] . "\">");
fclose($file);
print "ok";
?>
A: If you have unique headers in your CSV
$headers = [];
while (false !== ($data = fgetcsv($handle))) {
if(empty($headers)){
$headers = $data; //["foo", "bar"] (for example)
continue; //skip to next iteration
}
//$data [1,2] (for example)
$row = array_combine($headers, $data);
//$row = ["foo"=>1,"bar"=>2] (for example)
}
Now you can use the text headers instead of 16 etc...
One thing to be careful of is array combine is very sensitive to the length of the arrays. That said if it errors you either have duplicate keys (array keys are unique) or you have either an extra , or a missing one for that line.
Array combine takes the first argument as the keys, and the second as the values and combines them into an associative array. This has the added benefit that the order of your CSV columns will not be important (which can be a big deal).
PS as I have no idea what your headers are, I will leave that part up to you. But lets say #16 is issues. Now you can simply do $row['issues'] just like a DB source etc...
Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55643261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Assigning StackElements without multiple for loops in C# I have 30 chocolates in a stack and I want to distribute it to 3 people
public class People
{
public int Id{get;set;
public Stack<Chocolate> chocolates{get;set;}
}
Stack<Chocolate> chocolateObjects;
List<People> peopleList;
How can we assign to three people in this example in the same for loop?
The first person should get first ten chocolates,
second person should get choclates from 11-20 and so on.
I have tried doing is:
People p = new People ();
foreach(var a in chocolateObjects)
{
Chocolate c= a.pop();
p.Chocolates.push(c);
}
The number of people and chocolates are also generic
A: I think you are looking to loop through each person, and give them upto 10 chocolates each
Stack<Chocolate> chocolateObjects = new Stack<Chocolate>();
List<People> peopleList = new List<People>()
{
new People(),
new People(),
new People(),
};
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
chocolateObjects.Push(new Chocolate());
foreach (var p in peopleList)
{
while (p.chocolates.Count < 10 && chocolateObjects.Count>0)
{
var a = chocolateObjects.Pop();
p.chocolates.Push(a);
}
Console.WriteLine(p.chocolates.Count());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67531389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Lightswitch Updating() method not saving any data in DB I am trying to save the entity data using General methods of lightswitch, which is Updating. Below is the following code. I am not able to figure out what I am missing. There is no error in the code or in the UI. Its just that nothing gets saved.
partial void viewFamilyProcessDatas_Updating(viewFamilyProcessData entity)
{
var AutoAddMissingListing = entity.AutoAddMissingListing;
var AutoAddOddLots = entity.AutoAddOddLots;
var DefaultFilterValue = entity.DefaultFilterValue;
var ExcludeZeroNumberOfUnits = entity.ExcludeZeroNumberOfUnits;
//objFamilyProcessData.FamilyID = entity.FamilyID;
var IgnoreForPricing = entity.IgnoreForPricing;
var LimitEndDate = entity.LimitEndDate;
var OffsetFromMaxAsAtDate = entity.OffsetFromMaxAsAtDate;
var PrefilterConstituents = entity.PrefilterConstituents;
var TimeDataExpires = entity.TimeDataExpires;
entity.AutoAddMissingListing = AutoAddMissingListing;
entity.AutoAddOddLots = AutoAddOddLots;
entity.DefaultFilterValue = DefaultFilterValue;
entity.ExcludeZeroNumberOfUnits = ExcludeZeroNumberOfUnits;
entity.IgnoreForPricing = IgnoreForPricing;
entity.LimitEndDate = LimitEndDate;
entity.OffsetFromMaxAsAtDate = OffsetFromMaxAsAtDate;
entity.PrefilterConstituents = PrefilterConstituents;
entity.TimeDataExpires = TimeDataExpires;
//this.DataWorkspace.SolaDBServerData.Details.DiscardChanges();
entity.Details.DiscardChanges();
}
A: The solution to this finally came to this:
partial void vwFamilyProcessDatas_Updating(vwFamilyProcessData entity)
{
if(entity.Details.EntityState.ToString() == "Modified")
{
var AutoAddMissingListing = entity.AutoAddMissingListing;
var AutoAddOddLots = entity.AutoAddOddLots;
var DefaultFilterValue = entity.DefaultFilterValue;
var ExcludeZeroNumberOfUnits = entity.ExcludeZeroNumberOfUnits;
var IgnoreForPricing = entity.IgnoreForPricing;
var LimitEndDate = entity.LimitEndDate;
var OffsetFromMaxAsAtDate = entity.OffsetFromMaxAsAtDate;
var PrefilterConstituents = entity.PrefilterConstituents;
var TimeDataExpires = entity.TimeDataExpires;
tblFamily objFamily = tblFamilies.Where(f => f.FamilyID == entity.FamilyID).Single();
objFamily.AutoAddMissingListing = AutoAddMissingListing;
objFamily.AutoAddOddLots = AutoAddOddLots;
objFamily.DefaultFilterValue = DefaultFilterValue;
objFamily.ExcludeZeroNumberOfUnits = ExcludeZeroNumberOfUnits;
objFamily.IgnoreForPricing = IgnoreForPricing;
objFamily.LimitEndDate = LimitEndDate;
objFamily.OffsetFromMaxAsAtDate = OffsetFromMaxAsAtDate;
objFamily.PrefilterConstituents = PrefilterConstituents;
objFamily.TimeDataExpires = TimeSpan.Parse(TimeDataExpires);
entity.Details.DiscardChanges();
}}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36441545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Online polynomial curve fitting in Simulink How to fit curves in Simulink and still generate the code?
I have a model of a sensor in Simulink, that returns vectors Pos_x and Pos_y. Each vector has size of 20x1, and their values change every one step time (1ms).
I am trying to calculate the coeffecients of the 3rd degree Polynomial y(x) = p1*x^3 + p2*x^2 + p3*x + p4 in Simulink, that fits the data.
I did not find any block in simulink that calculates the coeffecients, so I used a simple Matlab function
function [p1, p2, p3, p4] = fcn(x,y)
% f(x) = p1*x^3 + p2*x^2 + p3*x + p4
f = fit(x', y', 'Poly3'); % I have also tried "polyfit"
p1 = f.p1;
p2 = f.p2;
p3 = f.p3;
p4 = f.p4;
end
but I get the error:
Function 'fit' not supported for code generation.
1- so back to my qustion, How to fit curves in Simulink and still generate the code?
2- I am also open to any other suggestion
A: If possible, you can use directly the LSQCURVEFIT function using Levenberg-Marquardt - method, which is Coder-compatible, with some limitations - see it's documentation that describes the limitations in detail.
Under the hood FIT uses LSQCURVEFIT, but in a non-Coder-compatible way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68988980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: handlebar partial not displaying in materialize card? My group is making a chore chart project. we are stuck on how to get our partial(which is a dropdown with hardcoded users) to display in a card. we have displayed our dropdown above the card to see functionality, which it works. but when we place partial in card it does not...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69830987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: d3.js Multi-line graph with zoom : line error It is my version of "Multi-line graph 4: Toggle" from http://bl.ocks.org/d3noob/e99a762017060ce81c76 but I ran into some problems pls help.
At first the initial graph is correct,
*
*after the zooms, the line would become one which used data for both line and rotated.
I think it is the zoomed functions is not doing right, when I used "d.value" the browser would say "d. is not define"
Here are the codes:
// https://github.com/mbostock/d3/wiki/Ordinal-Scales#category10
var colors = d3.scale.category10();
var margin = {top: 20, right: 30, bottom: 80, left: 85},
width = 900 - margin.left - margin.right,
height = 570 - margin.top - margin.bottom;
// Kind of defining the length and the directions of the axis
var x = d3.scale.linear()
.range([0, width]);
// Since the origin is on the left corner, the y axis of the svg system points down
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.tickSize(-height)
.tickPadding(10) // Distance between axis and tick note
.tickSubdivide(true)
.tickFormat(d3.format(".0"))
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.tickPadding(10)
.tickSize(-width)
.tickSubdivide(true)
.tickFormat(d3.format(".3e")) // https://github.com/mbostock/d3/wiki/Formatting#d3_format
.orient("left");
var valueline = d3.svg.line()
.x(function(d) { return x(d.samples); })
.y(function(d) { return y(d.measurements); });
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([0.1, 50])
.on("zoom", zoomed);
// Adding svg canvas
var svg = d3.select("body").append("svg")
.call(zoom)
.attr("width", width + margin.left + margin.right )
.attr("height", height + margin.top + margin.bottom )
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get the data
data=[{"SAMPLES":"1","MEASUREMENTS":"2","ID":"ch1"},{"SAMPLES":"2","MEASUREMENTS":"3","ID":"ch1"},{"SAMPLES":"1","MEASUREMENTS":"4","ID":"ch2"},{"SAMPLES":"3","MEASUREMENTS":"5","ID":"ch1"},{"SAMPLES":"2","MEASUREMENTS":"6","ID":"ch2"}];
data.forEach(function(d) {
d.samples = +d.SAMPLES;
d.measurements = +d.MEASUREMENTS;
});
console.log(data);
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.samples; }));
y.domain([0, d3.max(data, function(d) { return d.measurements; })]);
// Creating X axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Drawing notations
svg.append("g")
.attr("class", "x axis")
.append("text")
.attr("class", "axis-label")
.attr("x", (width - margin.left)/2)
.attr("y", height + margin.top + 45)
.text('Samples');
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "y axis")
.append("text")
.attr("class", "axis-label")
.attr("transform", "rotate(-90)")
.attr("y", (-margin.left) + 10)
.attr("x", -height/2)
.text('Volts');
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
// Nest the entries by channel id (ID)
var dataNest = d3.nest()
.key(function(d) {return d.ID;})
.entries(data);
// set the colour scale
var color = d3.scale.category10();
// Auto spacing for the legend
legendSpace = width/dataNest.length;
// Loop through each IDs / key to draw the lines and the legend labels
dataNest.forEach(function(d,i) {
svg.append("path")
.attr("class", "line")
.attr("clip-path", "url(#clip)")
.style("stroke", function() { // Add the colours dynamically
return d.color = color(d.key);
})
.attr("id", 'tag'+d.key.replace(/\s+/g, '')) // assign ID
.attr("d", valueline(d.values))
.style("stroke", function(){return d.color = color(d.key);});
// Adding legends
svg.append("text")
// Setting coordinates and classes
.attr("x", (legendSpace/2)+i*legendSpace)
.attr("y", height + (margin.bottom/2)+ 5)
.attr("class", "legend")
// Setting colors
.style("fill",function(){
return d.color = color(d.key);
})
// Setting 'click' events
.on("click", function(){
// Determine if current line is visible
var active = d.active ? false : true,
newOpacity = active ? 0 : 1;
// Hide or show the elements based on the ID
d3.select("#tag"+d.key.replace(/\s+/g, ''))
.transition().duration(600)
.style("opacity", newOpacity);
// Update whether or not the elements are active
d.active = active;
})
.text(function() {
if (d.key == '28-00043b6ef8ff') {return "Inlet";}
if (d.key == '28-00043e9049ff') {return "Ambient";}
if (d.key == '28-00043e8defff') {return "Outlet";}
else {return d.key;}
})
})
// Zoom specific updates
function zoomed() {
svg.select(".x.axis")
.transition().duration(500)
.call(xAxis);
svg.select(".y.axis")
.transition().duration(500)
.call(yAxis);
svg.selectAll('path.line')
.transition().duration(500)
.attr('d', valueline(data));
}
body {
font: 12px Arial;
margin: 50px;
}
.axis path {
fill: none;
stroke: #bbb;
stroke-width: 2;
shape-rendering: crispEdges;
}
.axis text {
fill: #555;
}
.axis line {
fill: none;
stroke-width: 1;
stroke: #e7e7e7;
shape-rendering: crispEdges;
}
.axis .axis-label {
font-size: 14px;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.legend {
font-size: 16px;
font-weight: bold;
text-anchor: middle;
}
A: You need to bind your paths to your data, so you can call valueLine with the correct data for the path when zooming.
Use d3 data and enter functions when adding a new path:
// choose all .line objects and append a path which is not already binded
// by comparing its data to the current key
svg.selectAll(".line").data([d], function (d) {
return d.key;
})
.enter().append("path")
.attr("class", "line")
Then when you zoom, change the d attribute path by calling valueLine with the path's correct values:
svg.selectAll('path.line')
.transition().duration(500)
.attr('d', function(d) {
return valueline(d.values)
});
Plunker
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28914653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove chromium log in Android Studio (LogCat) When I open the webview Cordova (app in release mode) The logcat show these logs I/chromium: [INFO: CONSOLE(1)] source http://.....
How to remove these logs into my application "I/chromium: [INFO: CONSOLE(1)], in Android Studio (LogCat)? Thanks
A: It's possible.
Using Console APIs in WebView
Just override WebViewClient for your WebView like this:
val myWebView: WebView = findViewById(R.id.webview)
myWebView.webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
consoleMessage?.apply {
Log.d("MyApplication", "${message()} -- From line ${lineNumber()} of ${sourceId()}")
}
return true
}
}
A: @Volodymyr ans work for me. Just override onConsoleMessage on WebChromeClient (reference):
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
Log.d(TAG, "onConsoleMessage: "+ consoleMessage.message());
return true;
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55822617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can find the center point of svg bezier path in android I have convert svg path to bezier path by svgparser.
I have a text file in which we have all the world country svg path. I have draw all bezier path but now how I can get centre of each bezier curve.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class RegionViewClass extends MapView implements View.OnTouchListener {
Path mPath;
Paint mPaint;
Region mRegion;
Context mContext;
MapView mapView;
int p,q;
This is the svg path of 3 countries. how I can differentiate every path on touch Event.
String d = "M670.98,313.01l4.58-2.24l2.72-9.84l-0.12-12.08l15.58-16.82v-3.99l3.21-1.25l-0.12-4.61l-3.46-6.73l1.98-3.61l4.33,3.99l5.56,0.25v2.24l-1.73,1.87l0.37,1l2.97,0.12l0.62,3.36h0.87l2.23-3.99l1.11-10.46l3.71-2.62l0.12-3.61l-1.48-2.87l-2.35-0.12l-9.2,6.08l0.58,3.91l-6.46-0.02l-2.28-2.79l-1.24,0.16l0.42,3.88l-13.97-1l-8.66-3.86l-0.46-4.75l-5.77-3.58l-0.07-7.37l-3.96-4.53l-9.1,0.87l0.99,3.96l4.46,3.61l-7.71,15.78l-5.16,0.39l-0.85,1.9l5.08,4.7l-0.25,4.75l-5.19-0.08l-0.56,2.36l4.31-0.19l0.12,1.87l-3.09,1.62l1.98,3.74l3.83,1.25l2.35-1.74l1.11-3.11l1.36-0.62l1.61,1.62l-0.49,3.99l-1.11,1.87l0.25,3.24L670.98,313.01L670.98,313.01z" +
"M671.19,242.56l0.46,4.27l8.08,3.66l12.95,0.96l-0.49-3.13l-8.65-2.38l-7.34-4.37L671.19,242.56L671.19,242.56z\n" +
"M695.4,248.08l1.55,2.12l5.24,0.04l-0.53-2.9L695.4,248.08L695.4,248.08z\n"+"M781.68,324.4l-2.31,8.68l-12.53,4.23l-3.75-4.4l-1.82,0.5l3.4,13.12l5.09,0.57l6.79,2.57v2.57l3.11-0.57l4.53-6.27v-5.13l2.55-5.13l2.83,0.57l-3.4-7.13l-0.52-4.59L781.68,324.4L781.68,324.4z\n"+
"M473.88,227.49l-4.08-1.37l-16.98,3.19l-3.7,2.81l2.26,11.67l-6.75,0.27l-4.06,6.53l-9.67,2.32l0.03,4.75l31.85,24.35l5.43,0.46l18.11-14.15l-1.81-2.28l-3.4-0.46l-2.04-3.42v-14.15l-1.36-1.37l0.23-3.65l-3.62-3.65l-0.45-3.88l1.58-1.14l-0.68-4.11L473.88,227.49L473.88,227.49z\n";
;
public RegionViewClass(Context context) {
super(context);
this.mContext=context;
mPath = new Path();
mRegion=new Region();
mPath= SVGParser.parsePath(d);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(20);
RectF rectF = new RectF();
mPath.computeBounds(rectF, true);
mRegion.setPath(mPath, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom));
}
@Override
protected void onDraw(Canvas canvas) {
//canvas.drawPath(mPath, mPaint);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Point point = new Point();
point.x=event.getX();
point.y = event.getY();
invalidate();
if(mRegion.contains((int) point.x,(int) point.y)==true)
Toast.makeText(mContext, "inside", Toast.LENGTH_LONG).show();
Path selectedPath= mRegion.getBoundaryPath();
if (mPath==selectedPath){
Toast.makeText(mContext, "india", Toast.LENGTH_SHORT).show();
Log.e("", "" + selectedPath);
}
else
Toast.makeText(mContext, "outside", Toast.LENGTH_LONG).show();
return true;
}
/* private boolean contains(int i, int j) {
}*/
class Point {
float x, y;
@Override
public String toString() {
return x + ", " + y;
}
}
}
A: If you want to test which of the sub-paths in your path the user clicks on. You will need to separate them into separate path definitions. Then run the Region.contains() test on each of them individually.
A: Your given paths don't have bezier curves. And shouldn't as counties don't tend to define curved boundaries with each other (save a couple examples where we use longitude like the US Canada border has a curve, because Earth is curved).
But, if you want. The formula to calculate the centermost point in a bezier curve, is:
t = 0.5;
x = (1 - t) * (1 - t) * p[0].x + 2 * (1 - t) * t * p[1].x + t * t * p[2].x;
y = (1 - t) * (1 - t) * p[0].y + 2 * (1 - t) * t * p[1].y + t * t * p[2].y;
Which answers your first question. The answer to the proper question, how can you tell which touch is part of which path is a harder one, and given that you actually have a polygon the correct answer is to implement a path in polygon algorithm.
But, really what you want is something that works. Might I recommend a handle. Simply draw something at the center of the shape for each regional shape. Then when the person touches the screen, find the closest point, to that point. Most countries are vaguely roundish or typically not weirdly curved, so simply find the bounding region then do distance to the center point.
Divide up the paths for each country. Get a bounding box for the county. Check whether that touch is inside any bounding box. If it is, compare the closeness of that touch to the center of that bounding box for all countries whose hit box was hit by that touch.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28428785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: KeyboardAvoidingView not working with Expo I cannot seem to get the keyboard to push the content up in my React-Native Expo app. I am testing this from the expo App by publishing it from my development machine.
Try as I might, nothing seems to push the view up when the keyboard comes into focus, is there a specific order of components, or some property I am missing; I have included the versions, the render block and the style blocks I think which are relevant.
I am using the following versions (latest);
"expo": "^29.0.0",
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-29.0.0.tar.gz",
For the login page, the render code looks like the following;
render() {
return (
<SafeAreaView style={styles.flexContainer}>
<KeyboardAvoidingView
style={styles.flexContainer}
behavior="padding"
>
<Image style={styles.image} source={require('../../assets/images/backgroundWelcome.png')} role="presentation" />
<View style={styles.container}>
<View style={[styles.row, styles.border]}>
<TextInput
placeholder='Email'
style={styles.input}
onChangeText={(input) => this.setState({email: input})}
value={this.state.email}
/>
</View>
<View style={[styles.row, styles.border]}>
<TextInput
placeholder='Password'
style={styles.input}
secureTextEntry={true}
onChangeText={(input) => this.setState({password: input})}
value={this.state.password}
/>
</View>
<View style={styles.row}>
<StyledButton callback={this.handleLogin} title='Log In'/>
</View>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
These are the styles that are relevant;
root: {
flex: 1,
alignItems: 'center',
backgroundColor: '#fff',
},
flexContainer: {
flex: 1,
},
container: {
paddingHorizontal: 40,
paddingBottom: 22,
alignItems: 'center',
flex: -1
},
row: {
flexDirection: 'row',
marginVertical: 10,
},
A: I ultimately could not find a full solution to the above directly, but I did find a npm module called.
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
I then nested this inside a ScrollView and included the View and Form inside it.
<ScrollView
<KeyboardAwareScrollView>
<View>
<!-- stuff -->
<View
<KeyboardAwareScrollView>
<ScrollView>
The module can be found here;
react-native-keyboard-aware-scroll-view
At the time of writing appears a very popular module with ~30k downloads a week. I have no affiliation to this module, but it works for me.
A: I had the same issue adding flex: 1 to KeyboardAvoidingView fixed my problem:
<KeyboardAvoidingView style={{ flex: 1 }} behavior={"padding"} >
<ScrollView >
<Card>
<CardItem header bordered>
<Text>Personal Information</Text>
</CardItem>
<CardItem bordered>
<Body>
<Item floatingLabel style={styles.item}>
<Label>Full Name</Label>
<Input />
</Item>
<Item floatingLabel style={styles.item}>
<Label>Headline</Label>
<Input />
</Item>
<Item floatingLabel style={styles.item}>
<Label>Location</Label>
<Input />
</Item>
<Item floatingLabel style={styles.item}>
<Label>Email</Label>
<Input />
</Item>
<Item floatingLabel style={styles.item}>
<Label>Phone Number</Label>
<Input />
</Item>
<Item floatingLabel style={styles.item}>
<Label>Phone Number</Label>
<Input />
</Item>
<Item floatingLabel style={styles.item}>
<Label>Phone Number</Label>
<Input />
</Item>
</Body>
</CardItem>
</Card>
<ListItem>
<Left>
<Text>Make my Profile Public</Text>
</Left>
<Right>
<Switch value={this.state.publicProfileRadioValue}
onValueChange={(value) => this.setState({ publicProfileRadioValue: value })}
/>
</Right>
</ListItem>
</ScrollView>
</KeyboardAvoidingView>
A: Add minHeight property to the root view style.
<KeyboardAvoidingView
behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
style={styles.container}>
{//content }
</KeyboardAvoidingView>
minHeight: Math.round(Dimensions.get('window').height),
Do not forget to import Dimensions form react native
import { Dimensions } from 'react-native';
A: for anyone else who ran into this when testing on Android, make sure the element you want to be keyboard avoided also has flex: 1.
this will not work:
<KeyboardAvoidingView
behavior={Platform.OS == "ios" ? "padding" : "height"}
style={{ flex: 1 }}
>
<TextInput style={{ height: 300 }} />
</KeyboardAvoidingView>
this will:
<KeyboardAvoidingView
behavior={Platform.OS == "ios" ? "padding" : "height"}
style={{ flex: 1 }}
>
<TextInput style={{ flex: 1 }} />
</KeyboardAvoidingView>
without flex 1, the target element will not resize its height accordingly to avoid the keyboard
A: I could achieve the right behavior with this implementation:
*
*Removed KeyboardAvoidingView component.
*Added this to the app.json file:
"android": {
"softwareKeyboardLayoutMode": "pan"
}
Hope it works for you guys as well!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51857389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Issue running Net cmd but with no error (BAT file) I am trying to create a bat file that will run cmd as administrator, then execute net command as shown below:
runas /user:administrator cmd "net localgroup administrators mjordan /add"
The goal is to add whoever the current user is as a local administrator.
So the first part works like a charm, and asks for the admin password. Upon entering the admin PW however, I do not see said test user under the local admin group. My best guess is I made a syntax error. But oddly enough no errors show up and command-line exits as if it executed.
Also, how would I make this execute and add the current user to the local admin group (thinking in a %username% way)? Not sure I am using the proper terminology, but say the user logged on running this command is JSmith. How could I make it add without using his name so it works on any account rather than just JSmith
Do you guys notice any errors? ...I am fairly new to creating bat files, and am learning as much as I can, so i know i must have messed up somewhere. Also, any references or study help is appreciated! Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39884907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Plot of a potential temperature line using metpy I’m trying to plot a potential temperature line
that passes through the point located by the
temperature and pressure of an air parcel on a “skew T - lnp” chart.
As far as I understood, metpy provides two possibilities.
metpy.plots.plot_dry_adiabats and metpy.calc.dry_lapse.
The former directly plots the potential temperature line, the latter provides the array of values that can be plotted by metpy.plots.SkewT.ax.plot.
I’m trying to understand why the two methods give different results (at least with my code) as in the example below. The second one seems the correct one.
Both methods require the starting point of the line. Starting point that I have to place on the border of the chart.
To find the value of (T,p) I used sequentially
metpy.calc.potential_temperature and metpy.calc.temperature_from_potential_temperature.
My code to draw the lines is the following:
import matplotlib.pyplot as plt
import metpy.calc as mpcalc
from metpy.units import units
from metpy.plots import SkewT
import numpy as np
# coordinate of the target point
p_trg=900*units.hPa
T_trg=15*units.degC
fig = plt.figure(figsize=(9, 5))
skew = SkewT(fig, rotation=30)
skew.ax.set_xticks(range(-15,26,5))
skew.ax.set_yticks(range(600,1010,50))
skew.ax.set_ylim(1020, 600)
skew.ax.set_xlim(-10,27)
# potential temperature of the line
theta=mpcalc.potential_temperature(p_trg, T_trg)
# point on the border of the chart and on the potential temperature line
p_bord=skew.ax.get_ylim()[0]*units.hPa
T_bord=mpcalc.temperature_from_potential_temperature(p_bord,potential_temperature=theta)
# pressure values to be included in the line (first value on the border)
pressure_levels=np.append(p_bord.magnitude, np.array([1010,900,800,700,600]))*units.hPa
# plot the dry adiabat line
skew.plot_dry_adiabats(t0=[T_bord.magnitude]*T_bord.units,pressure=pressure_levels)
# privide the value of T at each pressur level and plot them
dry_lapse_T=mpcalc.dry_lapse(pressure=pressure_levels, temperature=T_bord,reference_pressure=p_bord)
skew.ax.plot(dry_lapse_T,pressure_levels)
Thanks for any help.
A: If you look at the code for SkewT.plot_dry_adiabats(), you can see that when calculating the dry adiabats the reference pressure is set to 1000 hPa. If you use that when doing your own calculation, the results then completely line up.
This could definitely be better documented. If being able to control that on the call to plot_dry_adiabats is important to you, feel free to open a feature request (or even better, contribute the enhancement yourself!).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74999470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GET request fails with JAX-RS: Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: text/html I'm building a sample client-server with JAX-RS using JEE7. I'm using Wildfly 10.1
I followed the guy in this video. Here is the code of the war that runs on the application server:
boundary package contains the service
package pl.devcrowd.virtual.business.chickens.boundary;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import pl.devcrowd.virtual.business.chickens.controls.ChickenStore;
import pl.devcrowd.virtual.business.chickens.entity.Chicken;
@Stateless
public class ChickenService {
@Inject
ChickenStore cs;
public List<Chicken> getAllChickens() {
return this.cs.all();
}
public void save(Chicken chicken) {
this.cs.save(chicken);
}
}
and the resource
package pl.devcrowd.virtual.business.chickens.boundary;
import java.util.List;
import javax.inject.Inject;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import pl.devcrowd.virtual.business.chickens.entity.Chicken;
@Path("chickens")
public class ChickensResource {
@Inject
ChickenService cs;
@GET
public List<Chicken> chickens() {
return cs.getAllChickens();
}
@POST
public void save(JsonObject chicken) {
String name = chicken.getString("name");
int age = chicken.getInt("age");
cs.save(new Chicken(name, age));
}
}
control package contains the store which is mostly useless in this example
package pl.devcrowd.virtual.business.chickens.controls;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import pl.devcrowd.virtual.business.chickens.entity.Chicken;
public class ChickenStore {
@PersistenceContext
EntityManager em;
public void save(Chicken chicken) {
em.merge(chicken);
}
public List<Chicken> all() {
return this.em
.createNamedQuery("all", Chicken.class)
.getResultList();
}
}
entity package contains the entity:
package pl.devcrowd.virtual.business.chickens.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@Entity
@NamedQuery(name="all", query = "SELECT c FROM Chicken C")
public class Chicken {
@Id
@GeneratedValue
private long id;
private String name;
private int age;
public Chicken() {}
public Chicken(String name, int age) {
this.name = name;
this.age = age;
}
}
The parent package contains the Jax-RS application class which I implemented, I hope correctly:
package pl.devcrowd.virtual.business;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import pl.devcrowd.virtual.business.chickens.boundary.ChickensResource;
/**
* Configures a JAX-RS endpoint. Delete this class, if you are not exposing
* JAX-RS resources in your application.
*
* @author airhacks.com
*/
@ApplicationPath("resources")
public class JAXRSConfiguration extends Application {
public Set<Class<?>> getClasses() {
return new HashSet<Class<?>>(Arrays.asList(ChickensResource.class));
}
}
Now i'm trying to do a GET request like this
RestClient get = RestClient.create().method("GET")
.host("http://localhost:8080/DevCrowd")
.path("resources/chickens");
GluonObservableList<Chicken> sample = DataProvider.retrieveList(
get.createListDataReader(Chicken.class));
System.out.println(sample);
where Chicken is
public class Chicken {
private String name;
private int age;
public Chicken(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
and I get the error:
05:59:17,019 ERROR [org.jboss.resteasy.resteasy_jaxrs.i18n] (default task-3) RESTEASY002005: Failed executing GET /chickens: org.jboss.resteasy.core.NoMessageBodyWriterFoundFailure: Could not find MessageBodyWriter for response object of type: java.util.ArrayList of media type: text/html
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:66)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:473)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:422)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:209)
at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:221)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
What am I doing wrong?
A: As far as I see the client calls for mediatype text/html. But the objectmapper does not know how to write html for an arraylist.
What kind of format do you expect xml or json?
@Path("chickens")
public class ChickensResource {
@Inject
ChickenService cs;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Chicken> chickens() {
return cs.getAllChickens();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void save(JsonObject chicken) {
String name = chicken.getString("name");
int age = chicken.getInt("age");
cs.save(new Chicken(name, age));
}
}
An other solution would be to set the right requested Content type in the Request:
GET Header:
Accept: application/json
POST Header:
Accept: application/json
Content-Type: application/json
The Accept header says in which format the response should be.
The Content-Type header says which format the request payload has.
Content Types:
HTML --> text/html
JSON --> application/json
XML --> application/xml
edit: I think the Post has the same issue. We now told the methods that they consume json as input data and return json as output data (produces).
But are those data really set in the request. can you please post how you construct the post.
To match those methods there need to be those two headers in the request:
Accept: application/json says which format the client expects.
This should match the @Produces in the service which sets the output format.
Content-Type: application/json this is the one I think is missing says in which format the POST payload is and this should match the server input @Consumes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43833220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does JqueryUI read data on your jquery request when downloading data? I have date picker and want my date picker to be able get below data that is available, no matter if a user select last year date. eg. 2019-12-04.
On my jquery request I can only get this year date, anyone who can help me to achieve such logic. The logic is below if perhaps I am not making a sense.
HTML:
<!---DatePicker for startDate and endDate ---->
<div class="d-flex justify-content-start">
<div class="col-xl-10.5 col-lg-10.5 col-md-10 col-sm-10.5 col-10.5">
<div class="input-daterange input-group" id="datepicker">
<input type="text" class="input-sm form-control" name="from" placeholder="startdate" />
<span class="input-group-addon">To</span>
<input type="text" class="input-sm form-control" placeholder="enddate" />
</div>
</div>
</div><br/>
<br/>
<br/>
Javascript:
// date functionality
$(document).ready(function() {
$('.input-daterange').datepicker({
dateFormat: "dd-mm-yy",
autoclose: true
});
});
//checking equality for channel fields on thingspeak.
$(function() {
$("#download").click(function(e) {
e.preventDefault();
var isTemperature = $('#temperature').is(':checked');
var isButtonState = $('#button_state').is(':checked');
if (isTemperature && isButtonState) {
window.open('https://api.thingspeak.com/channels/952961/feeds.csv?api_key=FDJCRN71YJM2R0FM&start=2020-01-06T00:00+02&end=2020-01-10T23:59+02:00&timezone=Africa/Johannesburg');
} else {
if (isTemperature) {
window.open('https://api.thingspeak.com/channels/952961/fields/1.csv?api_key=FDJCRN71YJM2R0FM&timezone=Africa/Johannesburg');
} else {
if (isButtonState) {
window.open('https://api.thingspeak.com/channels/952961/fields/8.csv?api_key=FDJCRN71YJM2R0FM&start=2020-01-06T00:00+02&end=2020-01-10T23:59+02:00&timezone=Africa/Johannesburg');
}
}
}
});
});
A: I made some attempts and finally got it working, but doing this logic below;
// date functionality
$(document).ready(function() {
var year = (new Date).getFullYear();
$('.input-daterange').datepicker({
format: "dd-mm-yyyy",
autoclose:true,
minDate: new Date(year, 0, 1),
maxDate:new Date(year, 11, 31)
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59645385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to change the order of a bar plot(two categorical variables) So I got stuck with this problem for a while and can't solve it even after extensive research and experimentation, please help me out here.
I was trying to plot the relationship between education level and general health, here is my code.
p <- ggplot(educa_genhlth, aes(x = educa, fill = genhlth)) +
geom_bar(position = "fill")
q <- p +
aes(stringr::str_wrap(educa, 10)) +
labs(title = "general health vs education background") +
xlab(NULL)
r <- q+
scale_fill_discrete(name="general health")
r
Note I wrote line aes(string::str_wrap(Educa, 10)) because the labels of x variable were too long and clogged over one another and makes it hard to read. I searched this function at the suggestion of another post on this website.
But, a new problem is that the bar doesn't follow a logical order, i.e. say from " Never attended school " to "College 4 years ...". It was organized, I assume, alphabetically. So I did some research and realized that I have to give order to the factor variable educa_health$educa. So I added another line of code
educa_genhlth$educa <- factor(educa_genhlth$educa,
ordered = TRUE,
c("Never attended school or only kindergarten",
"Grades 1 through 8 (Elementary)",
"Grades 9 though 11 (Some high school)",
"Grade 12 or GED (High school graduate)",
"College 1 year to 3 years (Some college or technical school)",
"College 4 years or more (College graduate)"))
p <- ggplot(educa_genhlth, aes(x = educa, fill = genhlth)) +
geom_bar(position = "fill")
q <- p +
aes(stringr::str_wrap(educa, 10)) +
labs(title = "general health vs education background") +
xlab(NULL)
r <- q +
scale_fill_discrete(name = "general health")
r
But it turned out it didn't change anything.
However, if I keep the line that give order to factor educa_health$educa but delete the part about wrap the string in line 4, I could however get the reorganized plot I want.(note that in order to see it more clearly I flip the plot horizontally by adding coord_flip())
educa_genhlth$educa <- factor(educa_genhlth$educa,
ordered = TRUE,
c("Never attended school or only kindergarten",
"Grades 1 through 8 (Elementary)",
"Grades 9 though 11 (Some high school)",
"Grade 12 or GED (High school graduate)",
"College 1 year to 3 years (Some college or technical school)",
"College 4 years or more (College graduate)"))
p <- ggplot(educa_genhlth, aes(x = educa, fill = genhlth)) +
geom_bar(position = "fill")
q <- p +
labs(title = "general health vs education background") +
xlab(NULL)
r <- q +
scale_fill_discrete(name = "general health") +
coord_flip()
r
I have absolutely at my wits' end. what I want is to keep the plot vertical, keep the labels readable and with a logical order I assigned. I really really appreciate if someone can tell me how to do it and why my original approach was ineffective.
Here is a small sample of my dataset:
structure(list(educa = structure(c(6L, 5L, 6L, 4L, 6L, 6L), .Label = c("Never attended school or only kindergarten",
"Grades 1 through 8 (Elementary)", "Grades 9 though 11 (Some high school)",
"Grade 12 or GED (High school graduate)", "College 1 year to 3 years (Some college or technical school)",
"College 4 years or more (College graduate)"), class = "factor"),
genhlth = structure(c(4L, 3L, 3L, 2L, 3L, 2L), .Label = c("Excellent",
"Very good", "Good", "Fair", "Poor"), class = "factor")), row.names = c(NA,
6L), class = "data.frame")
A: Assuming you've already ordered your educa in the desired order, you can use fct_relabel from the forcats package together with str_wrap, to change the factor labels in one step without converting it from character to factor again:
ggplot(educa_genhlth,
aes(x = forcats::fct_relabel(educa,
stringr::str_wrap,
width = 10),
fill = genhlth)) +
geom_bar(position = "fill") +
labs(title = "general health vs education background") +
xlab(NULL) +
scale_fill_discrete(name = "general health")
This approach also keeps the educa_genhlth$educa in the data frame in the original form, leaving you the flexibility to wrap it to other lengths in other plots.
A: The use of str_wrap reorder your factors. So you need first to wrap, and then reorder your factors:
educa_genhlth$educa <- stringr::str_wrap(educa_genhlth$educa,10)
educa_genhlth$educa <-factor(educa_genhlth$educa,ordered=TRUE,
stringr::str_wrap(c("Never attended school or only kindergarten",
"Grades 1 through 8 (Elementary)",
"Grades 9 though 11 (Some high school)",
"Grade 12 or GED (High school graduate)",
"College 1 year to 3 years (Some college or technical school)",
"College 4 years or more (College graduate)"),10))
p<-ggplot(educa_genhlth,aes(x=educa,fill=genhlth))+geom_bar(position="fill")
q<-p+aes(educa)+labs(title="general health vs education background")+xlab(NULL)
r<-q+scale_fill_discrete(name="general health")
r
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54504125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: dependencies without using maven I have two files
In project1 have a file named test.java:
public class test {
public static void main(String[] args) {
sayHello();
}
public static void sayHello() {
System.out.println("MyTest says hello!");
}}
In project2 have a file named test2.java:
public class test2
{
public static void main(String[] args)
{
sayHello();
}
public static void sayHello() {
System.out.println("MyTest2 says hello!");
}}
Here i need to link up the class file of test(which is in project 1) to test2(which is my project2) without using maven. how do i proceed?
A: if you are using eclipse then right click on project2>properties>java build path>projects> add project 1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19927308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Monitor CPU spikes of any process over X percent for Y seconds I would like to run a .NET console application on our Windows Server 2008 box, which monitors CPU usage every 2 seconds.
If any single application uses > 30% CPU, two times in a row, it should be logged.
I will execute "CheckCpu" every 2 seconds... but my problem is, how do I determine the CPU usage of each process? And, efficiently so that I don't bog down our server :)
Dim lStrProcessCurrent As List(Of String)
Dim lStrProcessPrevious As List(Of String)
Private Sub CheckCpu()
Dim pcc As New PerformanceCounterCategory("Process")
'Clear "Current" run
lStrProcessCurrent = New List(Of String)
For Each instance As String In pcc.GetInstanceNames
Using cnt As PerformanceCounter = New PerformanceCounter("Process", "ID Process", instance, True)
Dim processName As String = cnt.InstanceName
' ????? HOW TO DETERMINE CPU USAGE ????
Dim cpuUsage As Long = 31
If cpuUsage >= 30 Then
'Was over 30% in Previous check
If lStrProcessPrevious.Contains(processName) Then
LogCpuSpike(processName)
End If
lStrProcessCurrent.Add(processName)
End If
End Using
Next
'Update "Previous" run
lStrProcessPrevious = lStrProcessCurrent
End Sub
A: You could try something like the code below. Effectively, check the TotalProcessorTime for each process each time you call CheckCpu() and then subtract this from the previous run and divide by the total time that has elapsed between the two checks.
Sub Main()
Dim previousCheckTime As New DateTime
Dim previousProcessList As New List(Of ProcessInformation)
' Kick off an initial check
previousCheckTime = Now
previousProcessList = CheckCPU(previousProcessList, Nothing)
For i As Integer = 0 To 10
Threading.Thread.Sleep(1000)
previousProcessList = CheckCPU(previousProcessList, Now - previousCheckTime)
previousCheckTime = Now
For Each process As ProcessInformation In previousProcessList
Console.WriteLine(process.Id & " - " & Math.Round(process.CpuUsage, 2).ToString & "%")
Next
Console.WriteLine("-- Next check --")
Next
Console.ReadLine()
End Sub
Private Function CheckCPU(previousProcessList As List(Of ProcessInformation), timeSinceLastCheck As TimeSpan) As List(Of ProcessInformation)
Dim currentProcessList As New List(Of ProcessInformation)
For Each process As Process In Process.GetProcesses()
' Id = 0 is the system idle process so we don't check that
If process.Id <> 0 Then
' See if this process existed last time we checked
Dim cpuUsage As Double = -1
Dim previousProcess As ProcessInformation = previousProcessList.SingleOrDefault(Function(p) p.Id = process.Id)
' If it did then we can calculate the % of CPU time it has consumed
If previousProcess IsNot Nothing AndAlso timeSinceLastCheck <> Nothing Then
cpuUsage = ((process.TotalProcessorTime - previousProcess.TotalProcessorTime).Ticks / (Environment.ProcessorCount * timeSinceLastCheck.Ticks)) * 100
End If
' Add to the current process list
currentProcessList.Add(New ProcessInformation With {.Id = process.Id, .CpuUsage = cpuUsage, .TotalProcessorTime = process.TotalProcessorTime})
End If
Next
Return currentProcessList
End Function
Class ProcessInformation
Public Id As Integer
Public TotalProcessorTime As TimeSpan
Public CpuUsage As Double
End Class
In a production environment you should probably add some more checks because it is possible for a process to be killed between you calling GetProcesses() and then processing the list. If the process has gone away then you will get an error when you try to access the TotalProcessorTime property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28223595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Know g++ Version of Code blocks in Windows I am solving questions on Interviewstreet.com. They said they use C++ version g++ 4.6.3,C0x mode.
I am writing code on code blocks. So i want to know which version iam using in code blocks is it in C0x mode or C11 mode??
I have tried using g++ --version i got g++ TDM-2 mingw32 4.4.1.Can u tell me where i can get this kind of information.
what is the difference between C++ 0x and C++11??
A: You'll have to update the version of g++ to 4.6.3 (or later) if you want to use c++11 features. See this question and it's answers on how to do it for deb linux.
Then you'll have to pass --std=c++0x to the compiler in options. You should be able to easily find them in codeblocks.
what is the difference between C++ 0x and C++11??
c++0x is a synonym for c++11.
A: The command:
g++ --version
gives you the version of your g++ or mingw compiler. Since you got g++ TDM-2 mingw32 4.4.1 then your version is 4.4.1. If you want to use version 4.6.3 as in that web site, then you would have to update.
It wouldn't hurt to use a newer than 4.6.3 version of mingw, so please see here for the latest version. This page offers an windows installer for mingw.
After installation, you would have to configure CodeBlocks to use the newly installed compiler by looking into Compiler and debugger settings -> Toolchain executables tab and setting the paths for the compiler-related executables to the new ones.
Hope this helps.
EDIT:
Here is a small tutorial/example of what the CodeBlocks settings look like.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12597254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: clear() is not clearing textbox field in python selenium I am checking two validations by sending keys in file test1.py
# Check email is valid
find_account.enter_email('amit@')
find_account.click_search_button()
validation_invalid_email = find_account.get_validation_invalid_email()
self.assertEqual('Email should be valid.', validation_invalid_email, 'Invalid email validation is missing')
time.sleep(2)
# Check email id exists in database
find_account.enter_email('[email protected]')
find_account.click_search_button()
time.sleep(2)
error_message_prompt = find_account.get_error_message_prompt()
self.assertEqual('User not found!', error_message_prompt, 'Error message is missing')
time.sleep(3)
which takes reference from file testpage.py for entering values in email field
def enter_email(self, email):
self.driver.find_element_by_id(self.email_field_id).click()
self.driver.find_element_by_id(self.email_field_id).clear()
self.driver.find_element_by_id(self.email_field_id).send_keys(email)
But clear() does not works. Instead appends value to previous one in textbox field & hence test is failing.
I was trying with clear() only but that does not worked. Then I tried with click() then clear(), but this also not worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62730796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Data directly store to mysql database without any validation already set using php I am novice for the php and mysql. cuurrently I'm working on a registration system using php and mysql to storing the data. So I already connect the database, and I'm doing some validation for the form information the user fill in. I decided not to use html "required" function. But the validation is not working at all. Although the info fill in is empty, it doesn't display any error but it still can proceed to the next step and insert the info to the database. Any help would be appreciated,see whether where is going wrong...
here is my code.
<div id="content">
<form action="signup.php"method="POST">
<fieldset>
<legend>Sign up your Watevershit account to unlock more shit!</legend>
<p>
<label>
<span>Username :</span>
<input type="text"name="username">
</label>
</p>
<p><?php if(isset($errors['username1']) echo $errors['username1'])?></p>
<p>
<label>
<span>Password</span>
<input type="password"name="password">
</label>
</p>
<p><?php if(isset($errors['password1']) echo $errors['password1'])?></p>
<p>
<label>
<span>Confirm Password :</span><input type="password"name="password">
</label>
</p>
<p>
<label>
<span>Email:</span>
<input type="email"name="email">
</label>
</p>
<p><?php if(isset($errors['email1']) echo $errors['email1'])?></p>
<p>
<label>
<input type="submit"id="submit"value="Sign Up Now!">
</label>
</p>
<p>
<label>
<span><a href="login.html">Already member?Log in here</a></span>
</label>
</p>
</fieldset>
</form>
</div>
here is my php script which I do all the validation already,but it doesn't work and insert data to database although the form fill in nothing. So,what's wrong here ?
<?php
include ('config.php');
//declare variables
$username=$_POST['username'];
$password=$_POST['password'];
$email=$_POST['email'];
//define error variables
$usernameERR = $emailERR =$passwordERR="";
$username=$email=$password="";
//validation
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//not empty
//at least 3 characters long
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields"
}
if (strlen($username) <3 ) {
$errors['username2'] ="Username must at least 3 characrters long.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
if (strlen($password) < 8) {
$errors['password2'] = "Password must be 8 characrters long";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
if (strlen($email) < 12){
$errors['email2'] ="Email must at least 12 characrters long";
}
//check the errors
if(count($errors) == 0){
//redirect to sucess page
header('Location:login.html');
}
}
// if all correct,insert data to the database
$query="INSERT INTO user(Username,Password,Email) VALUES ('".$_POST['username']."','".$_POST['password']."','".$_POST['email']."')";
mysqli_query($con,$query);
?>
Any idea?
A: Try this..
<?php
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=$_POST['username'];
$password=$_POST['password'];
$email=$_POST['email'];
//not empty
//at least 3 characters long
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
if (strlen($username) <3 ) {
$errors['username2'] ="Username must at least 3 characrters long.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
if (strlen($password) < 8) {
$errors['password2'] = "Password must be 8 characrters long";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
if (strlen($email) < 12){
$errors['email2'] ="Email must at least 12 characrters long";
}
//check the errors
if(count($errors) == 0){
$query="INSERT INTO user(Username,Password,Email) VALUES ('".$_POST['username']."','".$_POST['password']."','".$_POST['email']."')";
mysqli_query($con,$query);
}
}
?>
<div id="content">
<form action="" method="POST">
<fieldset>
<legend>Sign up your Watevershit account to unlock more shit!</legend>
<p>
<label>
<span>Username :</span>
<input type="text"name="username">
</label>
</p>
<p><?php if(!empty($errors['username1'])) { echo $errors['username1']; } ?></p>
<p>
<label>
<span>Password</span>
<input type="password" name="password">
</label>
</p>
<p><?php if(!empty($errors['password1'])) { echo $errors['password1']; }?></p>
<p>
<label>
<span>Confirm Password :</span><input type="password"name="password">
</label>
</p>
<p>
<label>
<span>Email:</span>
<input type="email"name="email">
</label>
</p>
<p><?php if(!empty($errors['email1'])) { echo $errors['email1']; }?></p>
<p>
<label>
<input type="submit"id="submit"value="Sign Up Now!">
</label>
</p>
<p>
<label>
<span><a href="login.html">Already member?Log in here</a></span>
</label>
</p>
</fieldset>
</form>
</div>
A: Replace this block:
//check the errors
if(count($errors) == 0){
//redirect to sucess page
header('Location:login.html');
}
With this:
//check the errors
if(count($errors) > 0){
//redirect to sucess page
header('Location:login.html');
}
And also replace following line:
if ($_SERVER["REQUEST_METHOD"] == "POST"){
With:
if ($_POST){
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27519696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to redirect asp .net core API to external URL from angular SPA client Basically I am new to SSO. I have two websites www.angularwebsite.com which talks to a .net core web API.Using azure ad , I can authenticate myself and I am able to log into www.angularwebsite.com using an Authorisation header "Bearer ". So far this is working.
We have another website www.ecommercesite.com which is using SAML to authenticate Azure and it also works fine. Now how do I call this www.ecommercesite.com from my www.angularwebsite.com after authentication so that the tokens which I got by authenticating on www.angularwebsite.com is valid.
Basically I don''t know how/where to call the www.ecommercesite.com (in angular by window.location.href) or in .NET API core
My startup.cs in API CORE's classes are as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseSession();
app.UseMvc();
//How do redirect when I come from angular to www.ecommercesite.com
}
My snippet of ConfigureService is as follows:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions: null);
services.AddAuthorization(options =>
{
options.DefaultPolicy =
new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
All the references to where I looked point to SSO with SPA and .Net core aPI which I already got. I am not able to find **"what if I want to navigate to another website"**using the same token. Kindly direct me to right place, I can try it myself. I don't know how to do.Thank you
Regards,
Jaga
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62756612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: return key-value pair key based on key-value pair value date with sorting I have the follow list:
test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'}, {'date': '2022-02-17 10:07:25', 'name': 'bar'}, {'date': '2022-02-18 04:00:05', 'name': 'baz'}]
I want to return the name attached to the most recent date. baz in this example. I probably need to use this but I don't know how: .sort(key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'))
I tried something like this:
sorted_list = test.sort(key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'))
print(sorted_list[0])
I read that list methods work in-place so i'm wondering how I can use it in my case.
A: You can simply do this
test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'}, {'date': '2021-02-19 10:07:25', 'name': 'bar'}, {'date': '2022-02-18 04:00:05', 'name': 'baz'}]
sortedList = sorted(test, key=lambda x: datetime.strptime(x['date'], '%Y-%m-%d %H:%M:%S'), reverse=True)
print(sortedList[0]['name'])
> baz
A: Try this one
from datetime import datetime
test = [{'date': '2021-07-01 20:32:48', 'name': 'foo'},
{'date': '2022-02-17 10:07:25', 'name': 'bar'},
{'date': '2022-02-18 04:00:05', 'name': 'baz'}]
sorted_list = sorted(test, key=lambda d: datetime.strptime(d['date'], '%Y-%m-%d %H:%M:%S'), reverse=True)
print(sorted_list[0])
Output:
{'date': '2022-02-18 04:00:05', 'name': 'baz'}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71254274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make Fluro defined route parameters OPTIONAL in flutter? I have defined this route using Fluro.
exchange/:pair
There is a problem! I want :pair to be optional. If client types https://host:port/exchange/BNB_BTC everything goes fine. but assume the user is looking for https://host:port/exchange and he confronts with 404 error cause there is no such route/path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67003073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Session_id is visible in page source, is it ok? I'm sending the session_id with the javascript. The session_id is visible in source of the page like:
function startUpload(id){
var queryString = '&' + $('#new_doc_upload').serialize() + "&session_id=" + "01dfda2def225bae907b129d2ffb1";
$('#fileUpload').fileUploadSettings('scriptData',queryString);
$('#fileUpload').fileUploadStart();
}
Is it ok that the session_id is visible or can is it a security issue?
Thanks.
A: It's okay. It's probably not ideal, but anyone interested in hacking your sessions will look for it in the other places you might have put it anyway (cookies, etc.), so you're not lowering the bar much if at all. (Java EE stuff does this as a fallback if cookies don't work, appending ;jsessionid=xxx to every URL.)
The important thing is to ensure that it's difficult to hijack sessions, regardless of how the hacker got the session ID. (By binding the session to the source IP address and checking that at the server level on every request, using sane timeouts, and the various other techniques.)
A: I would argue that it's perfectly fine. My rationale is that PHP sends it in clear text and so does the browser when you use sessions. Here's what happens in the background when you make a web request:
> GET / HTTP/1.1
Host: example.com
Accept: */*
< HTTP/1.1 200 OK
< Date: Tue, 12 Jul 2011 07:00:26 GMT
< Server: Apache
< Set-Cookie: PHP_SESSID=2873fd75b29380bc9d775e43e41dc898; path=/; domain=example.com; secure
< P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"
< Vary: Accept-Encoding
< Content-Length: 5538
< Content-Type: text/html; charset=UTF-8
As you can see, I made a GET request and the server response with Set-Cookie: PHP_SESSID= followed by my session ID. Anyone that's "sniffing" the request who would be able to see the session ID in the JavaScript would be able to get it from the headers too. The only thing to worry about would be things like malicious browser plugins and other exploits that are not likely but can be avoided by properly securing your code.
I'd recommend that you look at http://phpsec.org/projects/guide/4.html for some tips and information on session hijacking.
A: I recently did this while working on a google earth plugin project. It didn't use the browser's cookies so I had to pass session variables in the url with javascript which grabbed it from the html. There are no security issues.
A: i think it is not severe issue but still is not properly coded.one should not let anyone know ids if possible.From your code it looks like you have encoded your id.you should add some more info in your encoding to make it more secure.
for an example
one can easily decode "encode(15)" but it is very difficult to decode "encode('php is great'.15.' codint language')";
A: No, I don't think it's ok. You're making the session_id easily accessible, which in turns makes session-hijacking attacks very easy (and likely).
If you need the session_id, there are some methods to mitigate the possibility of session hijacking, consider regenerating the session_id after the upload, or having a secondary check to validate the user.
If you're trying to prevent unauthorized uploads, I'd consider something a little different - perhaps generating a one-time unique string of characters that is associated with the user for the duration of the upload, but not the session_id itself. Too much risk in that, IMO.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6660477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Riverpod state update does not rebuild the widget I'm using StateProvider<List<String>> to keep track of user taps on the Tic Tac Toe board.
Actual board is a widget that extends ConsumerWidget and consists of tap-able GridView.
Within the onTap event of GridViews child - following is invoked to update the state:
ref.read(gameBoardStateProvider.notifier).state[index] = 'X';
For some reason this does not invoke widget rebuild event. Due to this I cannot see the 'X' in the GridView item which was tapped.
However, if I add additional "simple" StateProvider<int> and invoke it as well within the same onTap event then the widget gets rebuilt and I can see the 'X' in the GridView.
I am not even using or displaying this additional state provider but for some reason it invokes rebuild while my intended provided doesn't.
final gameBoardStateProvider = StateProvider<List<String>>((ref) => List.filled(9, '', growable: false));
final testStateProvider = StateProvider<int>((ref) => 0); //dummy state provider
class Board extends ConsumerWidget {
const Board({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final gameBoard = ref.watch(gameBoardStateProvider);
final testState = ref.watch(testStateProvider);
return Expanded(
child: Center(
child: GridView.builder(
itemCount: 9,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
shrinkWrap: true,
itemBuilder: ((BuildContext context, int index) {
return InkWell(
onTap: () {
//With this line only the widget does not get refreshed - and I do not see board refreshed with added 'X'
ref.read(gameBoardStateProvider.notifier).state[index] = 'X';
//??? If I add this line as well - for some reason the widget get refreshed - and I see board refreshed with added 'X'
ref.read(testStateProvider.notifier).state++;
},
child: Container(
decoration: BoxDecoration(border: Border.all(color: Colors.white)),
child: Center(
child: Text(gameBoard[index]),
),
),
);
}),
),
),
);
}
}
A: Once you do
ref.read(gameBoardStateProvider.notifier).state[index] = 'X'
Means changing a single variable. In order to update the UI, you need to provide a new list as State.
You can do it like
List<String> oldState = ref.read(gameBoardStateProvider);
oldState[index] = "X";
ref
.read(gameBoardStateProvider.notifier)
.update((state) => oldState.toList());
Or
List<String> oldState = ref.read(gameBoardStateProvider);
oldState[index] = "X";
ref.read(gameBoardStateProvider.notifier).state =
oldState.toList();
Why testStateProvider works:
Because it contains single int as State where gameBoardStateProvider contains List<String> as State.
Just updating single variable doesn't refresh ui on state_provider, You need to update the state to force a refresh
More about state_provider
You can also check change_notifier_provider
A: The reason the ""simple"" StateProvider triggers a rebuild and your actual doesn't is because you aren't reassigning its value.
StateProviders works like this:
*
*StateProvider is just a StateNotifierProvider that uses a simple implementation of a StateNotifier that exposes its get state and set state methods (and an additional update method);
*StateNotifier works like this: an actual state update consists of a reassignment. Whenever state gets reassigned it triggers its listeners (just like ChangeNotifier would do). See immutability patterns.
This means that, since you're exposing a List<String>, doing something like state[0] = "my new string will NOT trigger rebuilds. Only actions such as state = [... anotherList]; will do.
This is desirable, since StateNotifier pushes you to use immutable data, which is can be good pattern in the frontend world.
Instead, your int StateProvider will basically always trigger an update, since chances are that when you need to alter its state, you need to reassign its value.
For your use case you can do something like:
state[i] = 'x';
state = [...state];
This forces a re-assignment, and as such it will trigger the update.
Note: since you're implementing a tic-tac-toe, it is maybe desirable to handle mutable data for that grid. Try using a ChangeNotifier, implement some update logic (with notifiyListeners()) and exposing it with a ChangeNotifierProvider.
Riverpod actually advises against mutable patterns (i.e. against ChangeNotifiers), but, as there is no silver bullet in Computer Science, your use case might be different.
A: Big thanks to both Yeasin and venir for clarifying what it means to reassign the state and the difference between simple and complex types.
While keeping the initial StateProvider I've replaced
ref.read(gameBoardStateProvider.notifier).state[index] = 'X';
with
var dataList = ref.read(gameBoardStateProvider);
dataList[index] = 'X';
ref.read(gameBoardStateProvider.notifier).state = [...dataList];
And it works now - the state gets updated and the widget rebuilt.
I've also tried the StateNotifier approach and it also works - although it seems more convoluted to me :) I'm pasting the code bellow as it can maybe benefit someone else to see the example.
class GameBoardNotifier extends StateNotifier<List<String>> {
GameBoardNotifier() : super(List.filled(9, '', growable: false));
void updateBoardItem(String player, int index) {
state[index] = player;
state = [...state];
}
}
final gameBoardProvider = StateNotifierProvider<GameBoardNotifier, List<String>>((ref) => GameBoardNotifier());
class Board extends ConsumerWidget {
const Board({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final gameBoard = ref.watch(gameBoardProvider);
return Expanded(
child: Center(
child: GridView.builder(
itemCount: 9,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
shrinkWrap: true,
itemBuilder: ((BuildContext context, int index) {
return InkWell(
onTap: () {
ref.read(gameBoardProvider.notifier).updateBoardItem('X', index);
},
child: Container(
decoration: BoxDecoration(border: Border.all(color: Colors.white)),
child: Center(
child: Text(gameBoard[index]),
),
),
);
}),
),
),
);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73078012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: pull out data from array in localStorage I have a function that takes data from an input and saves it as data in an array during registration. Now I want another function to check during login if the data exists and if it matches. How can I do this using javascript only?
In short, I need a function that checks if the data entered by the user exists and if so, logs him in.
function saveData() {
let name, email, password;
name = document.getElementById("username").value;
email = document.getElementById("email").value;
password = document.getElementById("password").value;
let user_records = new Array();
user_records = JSON.parse(localStorage.getItem("users"))
? JSON.parse(localStorage.getItem("users"))
: [];
if (
user_records.some((v) => {
return v.email == email;
})
) {
alert("Email wykorzystany");
} else {
user_records.push({
name: name,
email: email,
password: password,
});
localStorage.setItem("users", JSON.stringify(user_records));
}
}
I know that this is not how registration should be done. I am just doing it to learn new things.
A: function saveAndTestUser() {
// here use const as they are not updated
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
// Get all the records of the users
// prefer camelcase : not a rule though but it's better this way
const storedUsers = localStorage.getItem('users')
// if there are no stored users then assign empty array
// so that we don't get unexpected errors
const userRecords = storedUsers ? JSON.parse(storedUsers): []
// Checking if email already exists
if(userRecords.some(user => user.email === email)){
alert("user already exists")
return false; // stops the function execution
}
// If email doesn't exists then the code below will be executed
// Similar to if-else
// Add current record to existing records
const newRecords = [...storedUsers, {name, email, password}]
// Set the new record to storage
localStorage.setItem("users", JSON.stringify(newRecords));
}
A: this is a basic login, when you verify that the emmail and password are right, you can do wathever you want
function checkData() {
const name = document.getElementById('username').value;
const password = document.getElementById('password').value;
let user_records = JSON.parse(localStorage.getItem('users')) || [];
if (
user_records.find((user) => {
return user.name == name && user.password == password;
})
) {
alert('Logged in');
// do your things here
} else {
alert('wrong email or password');
// do your things here
}
}
<input id="username" />
<input id="password" />
<input type="submit" value="submit" onClick="checkData()" />
Extra:
This is a thing that you can do only for learning purpose, wich is to add a key to the local storage, for example: localStorage.setItem('loggedIn', true) and set in every page a check for this value, if is true show the page, if is false redirect to login. In the real world we use JWT tokens that contains all the information about the user etc... You can search for JWT token authentication on google and learn that, wich is really usefull in the front-end world
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70172483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Self-Hosted Font with Gatsby & Tailwind (PostCSS) I was using a self-hosted font in Gatsby and that was working well. Basically I had -
*
*a fonts/ folder in which all the .woff2 files were placed, with a fonts.css that had all the @font-face calls (this way because there were almost 15 @font-face calls)
*I had configured the gatsby-source-filesystem plugin in gatsby-config.js as below
resolve: "gatsby-source-filesystem",
options: {
name: "fonts",
path: `${__dirname}/src/fonts/`
}
},
I've now installed Tailwind with PostCSS as below -
*
*installed tailwindcss and gatsby-plugin-postcss using yarn
*configured gatsby-config.js as below -
{
resolve: `gatsby-plugin-postcss`,
options: {
postCssPlugins: [
require(`tailwindcss`),
require(`autoprefixer`)
],
},
},
*
*imported tailwind into gatsby-browser.js as below
import "tailwindcss/base.css"
import "tailwindcss/components.css"
import "tailwindcss/utilities.css"
Tailwind is working fine but it isn't using the font I want to use.....even though I have configured it correctly (I think) in tailwind.config.js
extend: {
fontFamily: {
sans: ["Custom Font Family Name", ...defaultTheme.fontFamily.sans],
},
A: Perhaps the fonts you have in ./src/fonts are not copied to public? You can check by navigate to the Network tab in the developer tools of your preferred browser, filter by font and see the response. It's likely that they're 404.
A quick fix would be to manually copy the fonts to static directory (create one if you don't have it.)
If you're doing something special with the fonts (for example, subfontting) you might be interested in adding hash to the fonts file & replace the file name in your font.css.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62877686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trapping and handling taskkill in Windows Python I am using Python 2.6.6 for Windows (on Windows XP SP3) with pywin32-218.
In my Python application, I have a second thread (apart from the main thread) which spawns a subprocess to run another Windows executable.
My problem is that when the main process (python.exe) is killed (e.g. using taskkill), I want to terminate the subprocess (calc.exe) and perform some cleaning up.
I tried various methods (atexit, signal and win32api.handleConsoleCtrl), but none seem to be able to trap the taskkill signal.
My code as follows (test.py):
import sys
import os
import signal
import win32api
import atexit
import time
import threading
import subprocess
class SecondThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.secondProcess = None
def run(self):
secondCommand = ['C:\WINDOWS\system32\calc.exe']
self.secondProcess = subprocess.Popen(secondCommand)
print 'calc.exe running'
self.secondProcess.wait()
print 'calc.exe stopped'
# do cleanup here
def stop(self):
if self.secondProcess and self.secondProcess.returncode == None:
self.secondProcess.kill()
secondThread = SecondThread()
def main():
secondThread.start()
def cleanup():
print 'cleaning up'
secondThread.stop()
print 'cleaned up'
atexit.register(cleanup)
def handleSignal(signalNum, frame):
print 'handleSignal'
cleanup()
sys.exit(0)
for signalNum in (signal.SIGINT, signal.SIGILL, signal.SIGABRT, signal.SIGFPE, signal.SIGSEGV, signal.SIGTERM):
signal.signal(signalNum, handleSignal)
def handleConsoleCtrl(signalNum):
print ('handleConsoleCtrl')
cleanup()
win32api.SetConsoleCtrlHandler(handleConsoleCtrl, True)
main()
The application is launched using
python.exe test.py
The console then prints "calc.exe running", and the Calculator application runs, and using Process Explorer, I can see calc.exe as a sub-process of python.exe
Then I kill the main process using
taskkill /pid XXXX /f
(where XXXX is the PID for python.exe)
What happens after this is that the command prompt returns without further output (i.e. none of "cleaning up", "handleSignal" or "handleConsoleCtrl" gets printed), the Calculator application continues running, and from Process Explorer, python.exe is no longer running but calc.exe has re-parented itself.
A: Taskkill (normally) sends WM_CLOSE. If your application is console only and has no window, while you can get CTRL_CLOSE_EVENT via a handler set by SetConsoleCtrlHandler (which happens if your controlling terminal window is closed) you can't receive a bare WM_CLOSE message.
If you have to stick with taskkill (rather than using a different program to send a Ctrl-C) one solution is to set the aforementioned handler and ensure your application has its own terminal window (e.g. by usingstart.exe "" <yourprog> to invoke it). See https://stackoverflow.com/a/23197789/4513656 for details an alternatives.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20394092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Select specific substing - dynamic indexing
I have several .csv files with 2 slightly different formats.
Format 1: X-XXX_2020-11-05_13-54-55-555__XX.csv
Format 2: X-XXX_2020-11-05_13-54-55-555__XXX.csv
I need to extract dametime field to add it to pandas dataframe.
Normally I would just use simple slicing
datetime.datetime.strptime(string1[-31:-8], "%Y-%m-%d_%H-%M-%s-%f")
which would give me desired result, but only for Format1.
For Format2 I need to move indexes for slicing by 1 because of the different ending.
Also I can not index from the start because of other operations.
At the moment I got around it by using IF statement looking like this:
def tdate():
if string1[-7]=='X':
return datetime.datetime.strptime(string1[-32:-9], "%Y-%m-%d_%H-%M-%s-%f")
else:
return datetime.datetime.strptime(string1[-31:-8], "%Y-%m-%d_%H-%M-%s-%f")
is there simpler way to make "dynamic" indexes so I could avoid creating additional def?
Thank you!
A: Using str.split with list slicing
Ex:
import datetime
for i in ("X-XXX_2020-11-05_13-54-55-555__XX.csv", "X-XXX_2020-11-05_13-54-55-555__XXX.csv"):
print(datetime.datetime.strptime("_".join(i.split("_")[1:3]), "%Y-%m-%d_%H-%M-%S-%f"))
OR using regex.
Ex:
import re
import datetime
for i in ("X-XXX_2020-11-05_13-54-55-555__XX.csv", "X-XXX_2020-11-05_13-54-55-555__XXX.csv"):
d = re.search(r"(?<=_)(.+)(?=__)", i)
if d:
print(datetime.datetime.strptime(d.group(1), "%Y-%m-%d_%H-%M-%S-%f"))
Output:
2020-11-05 13:54:55.555000
2020-11-05 13:54:55.555000
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64698131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating a dialog that will hide if not active using Popup (or something else?) I need to create a non modal Silverlight 4.0 control that would appear (pop up?) when user enters specific TextBox on top of it to enable a richer way to edit its contents. This control has other controls and it has to hide when user clicks mouse elsewhere in SL application other than inside its borders. So I cannot use lostfocus event cause controls that are located in my usercontrol fire lostfocus when they are used.
I don't know which is the best solution for this, I've added canvas.MouseDown event where I check whether point is inside or outside my control, and this works OK but when user enters another control - like opens a combobox for example event is not fired and my control doesnt become invisible.
Id like to know which events - logic to use for this to work simplest and clearest.
I've been thinking about using popup, its unclear to me how exactly to use it for my scenario, and what exact functionality does it provide.
As I understand it will be shown on top of everything, which is good. However how can I hide popup if user clicks anywhere , but not on control hosted in popup?
My control doesn't have any "ok" button that could trigger hiding it. It has a slider that and a textbox that can be edited.
after some thought appears to be duplicate for :
How to dismiss a popup in Silverlight when clicking outside of the control?
A: You seem to be describing the function of the Silverlight Popup class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4479673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Combine Hibernate class with @Bindable for SwingBuilder without Griffon? I have implemented a back-end for my application in Groovy/Gradle, and am now trying to implement a GUI.
I am using Hibernate for my data storage (with HSQLDB) per
http://groovy.codehaus.org/Using+Hibernate+with+Groovy
(with Jasypt for encryption) and it is working quite well.
I was wondering if there are any good tips for using @Bindable with, e.g., an @Entity class such as
@Entity class Book {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public Long id
@OneToMany(cascade=CascadeType.ALL)
public Set<Author> authors
public String title
String toString() { "$title by ${authors.name.join(', ')}" }
}
or if I am:
(i) asking for Griffon
(ii) completely on the wrong track?
Thank you!
Misha
A: Alright, looks like I can use @Bindable in a Hibernate @Entity!!
Misha
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3065949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add a custom legend in ggplot2 in R I want to plot a data set where the size of the points are proportional to the x-variable and have a regression line with a 95% prediction interval. The "sample" code I have written is as follows:
# Create random data and run regression
x <- rnorm(40)
y <- 0.5 * x + rnorm(40)
plot.dta <- data.frame(y, x)
mod <- lm(y ~ x, data = plot.dta)
# Create values for prediction interval
x.new <- data.frame(x = seq(-2.5, 2.5, length = 1000))
pred <- predict(mod,, newdata = x.new, interval = "prediction")
pred <- data.frame(cbind(x.new, pred))
# plot the data w/ regression line and prediction interval
p <- ggplot(pred, aes(x = x, y = upr)) +
geom_line(aes(y = lwr), color = "#666666", linetype = "dashed") +
geom_line(aes(y = upr), color = "#666666", linetype = "dashed") +
geom_line(aes(y = fit)) +
geom_point(data = plot.dta, aes(y = y, size = x))
p
This produces the following plot:
Obviously, the legend is not too helpful here. I would like to have one entry in the legend for the points, say, labeled "data", one grey, dashed line labeled "95% PI" and one entry with a black line labeled "Regression line."
A: As Hack-R alluded in the provided link, you can set the breaks and labels for scale_size() to make that legend more meaningful.
You can also construct a legend for all your geom_line() calls by adding linetype into your aes() and use a scale_linetype_manual() to set the values, breaks and labels.
ggplot(pred, aes(x = x, y = upr)) +
geom_line(aes(y = lwr, linetype = "dashed"), color = "#666666") +
geom_line(aes(y = upr, linetype = "dashed"), color = "#666666") +
geom_line(aes(y = fit, linetype = "solid")) +
geom_point(data = plot.dta, aes(y = y, size = x)) +
scale_size(labels = c("Eensy-weensy", "Teeny", "Small", "Medium", "Large")) +
scale_linetype_manual(values = c("dashed" = 2, "solid" = 1), labels = c("95% PI", "Regression Line"))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40598015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a GitHub API scope that links to a single repository? I'm writing an application that links to a user's github account. It will push some files to their github account. I only need access to a single repo (of their choosing), but from the github docs it seems that there's only:
*
*read/write access to all public repos
*read/write access to all repos (public AND private)
No way to lock down auth to a single repo, is that correct? I mostly wanted to do this for the user's peace of mind, rather than any requirements at my end (from my app I can get them to select which repo to push to).
Source: Github oauth docs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40511585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: string conversion error in array codeigniter On my controller I have a error on this line 'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
When I refresh my page it throws the error Array to string conversion
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: user/users_group_update.php Line Number: 47
Not sure what to do on that because I need to add variable $controller in to $this->getId($controller);
What changes is best suited to make this work.
<?php
class Users_group_update extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user_group');
}
public function index() {
$data['title'] = "Users Group Update";
$controller_files = $this->getInstalled($this->uri->segment(3));
$data['controller_files'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$do_not_list = array(
'customer_total',
'dashboard',
'footer',
'header',
'login',
'logout',
'menu',
'online',
'permission',
'register',
'user_total'
);
if (!in_array($controller, $do_not_list)) {
$data['controller_files'][] = array(
'name' => $controller,
'installed' => in_array($controller, $controller_files),
'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
);
}
}
}
$this->load->view('template/user/users_group_form_update', $data);
}
public function getInstalled($name) {
$controller_data = array();
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $name);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$controller_data[] = $result['controller'];
}
return $controller_data;
}
public function getId($controller) {
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $this->uri->segment(3));
$this->db->where('controller', $controller);
$query = $this->db->get();
return $query->row('user_group_id');
}
}
View
<?php echo Modules::run('admin/common/header/index');?>
<div id="wrapper">
<?php echo Modules::run('admin/common/menu/index');?>
<div id="page-wrapper" >
<div id="page-inner">
<?php
$data = array(
'class' =>
'form-horizontal',
'id' =>
'form-users-group'
);
echo form_open_multipart('admin/users_group_update' .'/'. $this->uri->segment(3), $data);?>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="pull-left" style="padding-top: 7.5px"><h1 class="panel-title"><?php echo $title;?></h1></div>
<div class="pull-right">
<a href="<?php echo base_url('admin/users_group');?>" class="btn btn-primary">Cancel</a>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
<div class="panel-body">
<?php echo validation_errors('<div class="alert alert-warning text-center">', '</div>'); ?>
<div class="form-group">
<?php
$data = array(
'class' => 'col-sm-2'
);
echo form_label('User Group Name', 'name', $data)
;?>
<div class="col-sm-10">
<?php
$data = array(
'id' => 'name',
'name' => 'name',
'class' => 'form-control',
'value' => set_value('name')
);
echo form_input($data)
;?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<tbody>
<?php if ($controller_files) { ?>
<?php foreach ($controller_files as $controllers) { ?>
<tr>
<td>
<div class="clearfix">
<div class="pull-left">
<?php echo $controllers['name']; ?>
</div>
<div class="pull-right">
<?php if ($controllers['installed']) { ?>
<span class="label label-success">Installed</span>
<span class="label label-danger"><a style="color: #FFF; text-decoration: none;" href="<?php echo $controllers['edit'];?>">Edit Individual Controller</a></span>
<?php } else { ?>
<span class="label label-primary">Not Installed</span>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
</div>
<div class="panel-footer">
</div>
</div><!-- Panel End -->
<?php echo form_close();?>
</div><!-- # Page Inner End -->
</div><!-- # Page End -->
</div><!-- # Wrapper End -->
<?php echo Modules::run('admin/common/footer/index');?>
A: Change this line
'edit' => site_url('admin/users_group_controller_update') .'/'. $this->getId($controller)
to
'edit' => site_url('admin/users_group_controller_update' .'/'. $this->getId($controller))
A: With in my files variable I had to use the db function to get it to work. No errors show now all fixed.
<?php
class Users_group_update extends Admin_Controller {
public function __construct() {
parent::__construct();
$this->load->model('admin/user/model_user_group');
}
public function index() {
$data['title'] = "Users Group Update";
$controller_files = $this->getInstalled($this->uri->segment(3));
$data['controller_files'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
if ($files) {
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
$do_not_list = array(
'customer_total',
'dashboard',
'footer',
'header',
'login',
'logout',
'menu',
'online',
'permission',
'register',
'user_total'
);
if (!in_array($controller, $do_not_list)) {
$this->db->where('name', $this->uri->segment(3));
$this->db->where('controller', $controller);
$query = $this->db->get($this->db->dbprefix . 'user_group');
if ($query->num_rows()) {
$row = $query->row();
$data['controller_files'][] = array(
'name' => $controller,
'installed' => in_array($controller, $controller_files),
'edit' => site_url('admin/users_group_controller_update' .'/'. $row->user_group_id)
);
}
}
}
}
$this->load->view('template/user/users_group_form_update', $data);
}
public function getInstalled($name) {
$controller_data = array();
$this->db->select();
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->where('name', $name);
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$controller_data[] = $result['controller'];
}
return $controller_data;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29149029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reducing the number of collide methods in a Java Game I'm making a simple game in java, and I have many methods which test if two object collide. Objects include a man, enemy, arrow, wall, coin and so on. I have a bunch of methods which count for every type of collision which could occur, they look like this:
public boolean collide(Arrow a, Enemy b)
{
Rectangle a1 = a.getBounds();
Rectangle b1 = b.getBounds();
if(a1.intersects(b1)) return true;
else return false;
}
Is there away to create a generic method? I tried using object a and object b as the arguments but the compiler compained it couldn't find getBounds() for the objects.
A: You can do something like :
public boolean collide(HasBounds a, HasBounds b){...
With the interface :
public interface HasBounds{
Rectangle getBounds();
}
That you should define on your objects Arrow,Enemy etc... (you may already have an object hierarchy suitable for that).
A: what do you think of this..
public boolean collide(Rectangle a1, Rectangle b1)
{
return a1.intersects(b1);
}
or may be Create an interface
public interface CanCollide {
Rectangle getBounds();
}
and use it in the method...
public boolean collide(CanCollide a, CanCollide b)
{
Rectangle a1 = a.getBounds();
Rectangle b1 = b.getBounds();
if(a1.intersects(b1)) return true;
else return false;
}
Hope you find it usefull.
Thanks!
@leo.
A: Just make abstract class GameObject with method: Rectangle2D getShape(). This method could look like:
abstract class GameObject {
private Image image;
GameObject(String path) {
try {
image = ImageIO.read(new File(path));
} catch (IOException ex) {}
}
Rectangle2D getShape() {
return new Rectangle2D.Float(0, 0, (int)image.getWidth(), (int)image.getHeight());
}
}
Player, Enemy, Arrow, Wall would be subclasses of GameObject class
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15312820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does CGContextDrawImage decompress PNG on the fly? I'm trying to write an iPhone app that takes PNG tilesets and displays segments of them on-screen, and I'm trying to get it to refresh the whole screen at 20fps. Currently I'm managing about 3 or 4fps on the simulator, and 0.5 - 2fps on the device (an iPhone 3G), depending on how much stuff is on the screen.
I'm using Core Graphics at the moment and currently trying to find ways to avoid biting the bullet and refactoring in OpenGL. I've done a Shark time profile analysis on the code and about 70-80% of everything that's going on is boiling down to a function called copyImageBlockSetPNG, which is being called from within CGContextDrawImage, which itself is calling all sorts of other functions with PNG in the name. Inflate is also in there, accounting for 37% of it.
Question is, I already loaded the image into memory from a UIImage, so why does the code still care that it was a PNG? Does it not decompress into a native uncompressed format on load? Can I convert it myself? The analysis implies that it's decompressing the image every time I draw a section from it, which ends up being 30 or more times a frame.
Solution
-(CGImageRef)inflate:(CGImageRef)compressedImage
{
size_t width = CGImageGetWidth(compressedImage);
size_t height = CGImageGetHeight(compressedImage);
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (width * 4);
bitmapByteCount = (bitmapBytesPerRow * height);
colorSpace = CGColorSpaceCreateDeviceRGB();
context = CGBitmapContextCreate (NULL,
width,
height,
8,
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease( colorSpace );
CGContextDrawImage(context, CGRectMake(0, 0, width, height), compressedImage);
CGImageRef result = CGBitmapContextCreateImage(context);
CFRelease(context);
return result;
}
It's based on zneak's code (so he gets the big tick) but I've changed some of the parameters to CGBitmapContextCreate to stop it crashing when I feed it my PNG images.
A: To answer your last questions, your empirical case seems to prove they're not uncompressed once loaded.
To convert them into uncompressed data, you can draw them (once) in a CGBitmapContext and get a CGImage out of it. It should be well enough uncompressed.
Off my head, this should do it:
CGImageRef Inflate(CGImageRef compressedImage)
{
size_t width = CGImageGetWidth(compressedImage);
size_t height = CGImageGetHeight(compressedImage);
CGContextRef context = CGBitmapContextCreate(
NULL,
width,
height,
CGImageGetBitsPerComponent(compressedImage),
CGImageGetBytesPerRow(compressedImage),
CGImageGetColorSpace(compressedImage),
CGImageGetBitmapInfo(compressedImage)
);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), compressedImage);
CGImageRef result = CGBitmapContextCreateImage(context);
CFRelease(context);
return result;
}
Don't forget to release the CGImage you get once you're done with it.
A: This question totally saved my day! thanks!! I was having this problem although I wasn't sure where the problem was. Speed up UIImage creation from SpriteSheet
I would like to add that there is another way to load the image directly decompressed, qithout having to write to a context.
NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
forKey:(id)kCGImageSourceShouldCache];
NSData *imageData = [NSData dataWithContentsOfFile:@"path/to/image.png"]];
CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)(imageData), NULL);
CGImageRef atlasCGI = CGImageSourceCreateImageAtIndex(source, 0, (__bridge CFDictionaryRef)dict);
CFRelease(source);
I believe it is a little bit faster this way. Hope it helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3964011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Do functions not update React hooks (particularly useState) depending on how they are called? I am trying to figure out why I have a function that can not read in a value from a useState hook. I now that the useState value of "questionIndex" is updating properly in my verifyAnswer function, but I cannot determine why the function "renderQuestion" is not aware that the value of questionIndex is updating.
I do not receive any error messages, and I have conosole logged the outputs. The questionIndex updates as expected but the renderQuestion function doesn't at all.
Earlier I was trying to use useEffect and it was working fine, but the code was kind of messy. Now I'm second guessing my understanding of React in general because the code seems like it should work just fine, and I am lost trying to track down the solution.
Code:
const [questionIndex, setQuestionIndex] = useState(0)
function renderQuestion() {
console.log(`questionIndex from render question function is : ${questionIndex}`)
setWordToTranslate(Data[questionIndex].word);
setAnswer(Data[questionIndex].translation)
}
function verifyAnswer(value) {
if (value === answer) {
console.log("answer is correct!");
if (questionIndex < questionsLength) {
setQuestionIndex(questionIndex + 1)
renderQuestion()
}
}
}
function handleInputChange(event) {
const {value} = event.target;
setUserInput(value);
verifyAnswer(value);
}
A: setState is asynchronous.
I think you should handle the renderQuestion in a useEffect
const [questionIndex, setQuestionIndex] = useState(0)
function renderQuestion() {
console.log(`questionIndex from render question function is : ${questionIndex}`)
setWordToTranslate(Data[questionIndex].word);
setAnswer(Data[questionIndex].translation)
}
useEffect(() => {
renderQuestion()
}, [questionIndex])
function verifyAnswer(value) {
if (value === answer) {
console.log("answer is correct!");
if (questionIndex < questionsLength) {
setQuestionIndex(questionIndex + 1)
}
}
}
function handleInputChange(event) {
const {value} = event.target;
setUserInput(value);
verifyAnswer(value);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65986091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I put multiple integers into int* tab; in two different loops separated by 0 eg. [1,1,1,0,1,1] in VS 2019 in C I am writing a emulator for Turing machine subtraction and, to start, I need to have the m and n converted into 1s and one 0s. For example, if m = 3, n = 2, the output would be [1,1,1,0,1,1] in the int array.
I tried using malloc to allocate memory for int* tab and, after that, I simply put the first ones in the first loop, then append a 0, then, in another loop, I'm adding the n 1s.
The problem is with Visual Studio, I think, because I tried the same code in vim and the output was correct. In VS, the output of 1s is correct but, instead of 0, I get some random negative number.
Here's the code:
scanf_s("%d", &m);
printf("n = ");
scanf_s("%d", &n);
int* tab = malloc(sizeof(int) * (n + m + 1));
int i;
for (i = 0; i < m; i++)
{
tab[i] = 1;
}
tab[i + 1] = 0;
int j = 0;
for (j = i + 1; j < n + i + 1; j++)
{
tab[j] = 1;
}
for (int k = 0; k < n + m + 1; k++)
{
printf("%d", tab[k]);
}
The bad output from VS
A: I believe
tab[i + 1] = 0;
is the problem. From previous loop execution the control will only come out when i<m is false, i.e., for the case when i == m, as per the increment statement.
Now, you want to put the 0 at this index, not at index + 1.
Change to tab[i] = 0;.
Now, the probable reason for the negative number: The content of the memory location returned by malloc() is indeterminate, so if you miss to write the index when i == m (you were writing from 0 to m-1, then from m+1 to m+n-1), while reading it'll return that indeterminate value.
A: The problem is in your tab[i + 1] = 0; line. When the preceding loop has finished, then i will be equal to m — that is to say, the i value will already be "one beyond the end".
So, just change that to: tab[i] = 0; and you should be fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65341144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Display text progressively with libgdx I am looking for a way to display text progressively with libgdx, but I can't find a way to do it exactly the way I want. Here is what I did:
*
*I have a text label that is being updated periodically to display a different text. The label is set to setWrap(true); and setAlignment(Align.center);
*Every time I change the text of the label I use a custom Action which I built like this
public class DisplayTextAction extends TemporalAction{
private CharSequence completeText;
@Override
protected void update(float percent) {
((Label)actor).setText(
completeText.subSequence(
0,
(int)Math.round(completeText.length()*percent));
}
public void setText(String newText){
completeText = newText;
}
}
*Every text update, I call the action from a pool, change the text and add the action to the label.
Here is my problem: This doesn't work the way I want with a centered and wrapped text.
This happens when text isn't centered (dots represent space):
|h........|
|hel......|
|hello....|
(Works as intended)
This is what happens when the text is centered:
|....h....|
|...hel...|
|..hello..|
And this is how I want it to behave:
|..h......|
|..hel....|
|..hello..|
My original idea to fix this was to use 2 sets of strings, one that is the visible text, and one invisible that acts as "padding". I came up with something like this:
CharSequence visibleText = completeText.subSequence(
0,
(int)Math.round(completeText.length()*percent));
CharSequence invisibleText = completeText.subSequence(
(int)Math.round(completeText.length()*percent),
completeText.length());
So I have my two sets of strings, but I can't find a way to display two different fonts (one visible, and another one which is the same but with an alpha of 0) or styles in the same label with Libgdx.
I'm stuck, I don't know if my approach is the right one or if I should look into something completely different, and if my approach is correct, I don't know how to follow it up using libgdx tools.
EDIT:
I followed Jyro117's instructions and I could make great progress, but I couldn't make it work with centred text on multiple lines.
imagine this text:
|all those lines are|
|..for a very long..|
|........text.......|
And it has to be displayed like this
|all th.............|
|...................|
|...................|
|all those line.....|
|...................|
|...................|
|all those lines are|
|..for a ve.........|
|...................|
|all those lines are|
|..for a very long..|
|........text.......|
Jyro117's solution give either
|all those lines are|
|for a very long....|
|text...............|
displayed correctly.
or
|...................|
|......all tho......|
|...................|
|...................|
|...all those lin...|
|...................|
|all those lines are|
|......for a v......|
|...................|
A: You are over-complicating the solution. All you really need is to determine the size of the label when all the text is added. Once you have determined that, lock the label size to those dimensions, put it inside of a table that expands to fill up the area around it, and then update your label with the action. (You can use a pool and such as needed, but for simplicity I left that out of the code below).
You will have to obviously adapt the code to yours, but this gives you a code reference to what I mean.
Here is a code snippet on one way to do it:
stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
Gdx.input.setInputProcessor(stage);
uiSkin = new Skin(Gdx.files.internal("skin/uiskin.json"));
Table fullScreenTable = new Table();
fullScreenTable.setFillParent(true);
final String message = "hello";
final Label progressLabel = new Label(message, this.uiSkin);
final TextBounds bounds = progressLabel.getTextBounds(); // Get libgdx to calc the bounds
final float width = bounds.width;
final float height = bounds.height;
progressLabel.setText(""); // clear the text since we want to fill it later
progressLabel.setAlignment(Align.CENTER | Align.TOP); // Center the text
Table progressTable = new Table();
progressTable.add(progressLabel).expand().size(width, height).pad(10);
final float duration = 3.0f;
final TextButton button = new TextButton("Go!", this.uiSkin);
button.addListener(new ClickListener() {
@Override public void clicked(InputEvent event, float x, float y) {
progressLabel.addAction(new TemporalAction(duration){
LabelFormatter formatter = new LabelFormatter(message);
@Override protected void update(float percent) {
progressLabel.setText(formatter.getText(percent));
}
});
}
});
stage.addActor(button);
fullScreenTable.add(progressTable);
fullScreenTable.row();
fullScreenTable.add(button);
stage.addActor(fullScreenTable);
Edit:
Added code to center and top align text in label. Also added code to fill spaces on the end to allow for proper alignment. Note: Only useful for mono-spaced fonts.
class LabelFormatter {
private final int textLength;
private final String[] data;
private final StringBuilder textBuilder;
LabelFormatter(String text) {
this.textBuilder = new StringBuilder();
this.data = text.split("\n");
int temp = 0;
for (int i = 0 ; i < data.length; i++) {
temp += data[i].length();
}
textLength = temp;
}
String getText(float percent) {
textBuilder.delete(0, textBuilder.length());
int current = Math.round(percent * textLength);
for (final String row : data) {
current -= row.length();
if (current >= 0) {
textBuilder.append(row);
if (current != 0) {
textBuilder.append('\n');
}
} else {
textBuilder.append(row.substring(0, row.length() + current));
// Back fill spaces for partial line
for (int i = 0; i < -current; i++) {
textBuilder.append(' ');
}
}
if (current <= 0) {
break;
}
}
return textBuilder.toString();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18278415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: same app, different interface I'm writing a WPF Application with ModernUI. It looks great on my computer(win 7).
However, it looks different on my colleague's(also win 7).
What can I do to make it look always like the same way, just as on my computer?
A: I finally found the reason why the implicit style didn't work.
I'm using ModernUI with WPF4.0 and I deleted the
<Style TargetType="{x:Type Rectangle}"/>
in app.xaml the other day.
Well, it's that simple and everything looks fine now. Except that I still don't know how the empty style works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22826893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Should I add the information in both side I am new to unity ,plz forgive me asking these questions
It bumps out : default reference will only be applied in edit mode
Is it important, what is that?
Should I need to add the information(food and border ) to both sides?
A: The second image are default references. If you set them they are automatically applied after adding this script to an object.
They are not required. And only apply to a script added via the Editor (not by script!). What matters later on runtime are only the values on the GameObject.
Further you can only reference assets from the Assets folder here. They make sense e.g. if you have a button script that uses a certain Click sound, a texture and e.g. a prefab. For these three you now could already define default values so someone using your component doesn't have to assign everything everytime but already has the default references as a kind of fallback.
So in your case it would only make sense, if the borders are prefabs from the Assets that are spawned by this script. The FoodPrefab is even called like this and makes sense to have as a default reference so you don't have to drag it into each and every instance of SpawnFood you create.
And btw just by looking at your settings you should probably directly make your fields of type RectTransform so you can't accidentally reference another object there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59808196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find where library functions sit in memory Assume we have a C application that uses a large library.
I am trying to find a way to know at what memory address library functions and symbols are located. Or say exactly to compiler/linker where to put them in memory. What's the approach?
Edit: This is an embedded application so I can't use desktop compiler toolchains.
A: Function names, like arrays, decay into pointers when used. That means you can just:
printf("%p", myFunction);
On most systems, anyway. To be strictly standard-compliant, check out How to format a function pointer?
A: There are a few ways to get at this. The easiest is probably to use a debugger.
Using GDB
With gdb you can connect to a running program. Say for example I want to connect to a running vim process. First I need to know it's PID number:
$ pidof vim
15425
I can now connect to the process using gdb:
$ gdb `which vim` 15425
At the prompt, I can now enquire about different symbols:
$ info symbol fprintf
fprintf in section .text of /lib/x86_64-linux-gnu/libc.so.6
$ info address fprintf
Symbol "fprintf" is at 0x7fc9b44314a0 in a file compiled without debugging.
Using /proc
Another way to get a dump of memory locations of libraries from /proc.
Again, you need the PID (see above) and you can dump out the libraries and their locations in the virtual memory of a process.
$ cat /proc/15425/maps
7fc9a9427000-7fc9a9432000 r-xp 00000000 fd:02 539295973 /lib/x86_64-linux-gnu/libnss_files-2.19.so
7fc9a9432000-7fc9a9631000 ---p 0000b000 fd:02 539295973 /lib/x86_64-linux-gnu/libnss_files-2.19.so
7fc9a9631000-7fc9a9632000 r--p 0000a000 fd:02 539295973 /lib/x86_64-linux-gnu/libnss_files-2.19.so
7fc9a9632000-7fc9a9633000 rw-p 0000b000 fd:02 539295973 /lib/x86_64-linux-gnu/libnss_files-2.19.so
Each library will have multiple sections and this will depend on how it was compiled/linked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28354689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Running MongoDB Globally in Google App Engine Prefacing this with I am very new to GCP so please bear with me if this is an obvious fix :) I am trying to deploy a MERN application to Google App Engine. So far I was able to upload my react files with ease and everything works the way it should. The only problem is I have to run my backend on a terminal myself for the data to be fetched from MongoDB in my project in App Engine (nodemon server), in addition to the fact that even once I do this the data only appears on the computer that established that connection with the database
How do I make it so my server.js file (which establishes Mongo Connection) stays running globally so I can interact with the app on any device? I stored all my backend code in a separate file called "backend" which is inside my react app parent directory.
This is my package,json file if it helps at all:
{
"name": "matchmeds-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"react": "^16.13.1",
"react-datepicker": "^3.1.3",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Thank you for your help in advance.
A: I realized I have to push my serverside code to App Engine the same way I pushed my React code, with different yaml configs for node.js files. Thanks everyone!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63539861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can't edit mysql table: Getting odd error that I can't find anything on: #1305 - PROCEDURE db_name.limit_control does not exist There are threads about "Procedure does not exist", but I can find nothing about "limit_control". I don't even have any stored procedures.
I can't edit one mysql table (named 'control' - is that where the 'control' in the error is coming from?) because of this error. An example sql command that triggers the error is: UPDATEzenbership_test.controlSETcurrissue= '336' WHEREcontrol.id= 1
I am able to edit other tables in the database. Can anyone help me fix this problem? Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61153424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to get the index path of a cell from a collection view, from a textfield using textFieldDidBeginediting I have made a collection view which is populated with textfields. I've got the textFieldDidBeginEditing working. I've assigned the textfield in the cell for item at indexpath as delegate. the question is how do i get the indexPath.row in the field that i have selected in the code below? any help would be much appreciated
func textFieldDidBeginEditing(textField: UITextField)
{
print("")
}
A: You should convert CGPoint(x: 0.0, y: 0.0) to a point relative to the collection view's frame of reference (textField.convertPoint(point: yourZeroPoint, toView: yourCollectionView)), then use yourCollectionView.indexPathForItemAtPoint to get the indexPath at that point.
A: func textFieldDidBeginEditing(textField: UITextField) {
let point: CGPoint = textField.convertPoint(CGPointZero, toView: collview1);
let indexPath:NSIndexPath? = collview1.indexPathForItemAtPoint(point)
print(point)
print(indexPath)
}
collview1 is a collection view outlet
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32364149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: EOFException while loading avro schema I am trying to load an avro schema file using maven.I have saved the avsc file in my classpath but I get EOFEception while a run it. I know the problem is the that the schema file could not be found because when I write the schema inside my code, it runs perfectly. I need some help please.Thanks in advance.
Here is the trace:
[root@dev MapReduce]# hadoop jar target/MapReduce-0.0.1-SNAPSHOT.jar com.hadoop.bi.MapReduce.AvroScTest StringPair.avsc
Exception in thread "main" java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2444)
at org.codehaus.jackson.map.ObjectMapper._readValue(ObjectMapper.java:2377)
at org.codehaus.jackson.map.ObjectMapper.readTree(ObjectMapper.java:1234)
at org.codehaus.jackson.map.ObjectMapper.readTree(ObjectMapper.java:1209)
at org.apache.avro.Schema$Parser.parse(Schema.java:931)
at org.apache.avro.Schema$Parser.parse(Schema.java:914)
at com.hadoop.bi.MapReduce.AvroScTest.main(AvroScTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.main(RunJar.java:208)
and here is the code which I try to load the schema:
Schema.Parser parser = new Schema.Parser();
Schema schema =parser.parse(AvroScTest.class.getResourceAsStream(args[0]));
here is the structure of project:
MapReduce
src
main
test
target
classes
MapReduce-0.0.1-SNAPSHOT.jar
pom.xml
StringPair.avsc
schema content:
{
"type": "record",
"name": "StringPair",
"doc": "A pair of strings.",
"fields": [
{"name": "left", "type": "string"},
{"name": "right", "type": "string"}
]
}
A: You can be sure about the StringPair.avsc file is in your jar by
mvn tf MapReduce-0.0.1-SNAPSHOT.jar
(If it's not listed maven can simply build it into the jar if you place it under the src/main/resources/StringPair.avsc)
For the "No content to map to Object due to end of input" error message the magic was for me to place a slash before the file name because it is in the root of the jar.
Schema.Parser parser = new Schema.Parser();
Schema schema =parser.parse(AvroScTest.class.getResourceAsStream("/StringPair.avsc"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24012861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails Duplicate Comment Issue When I create a comment in my feed, rails is duplicating all the previous comments.
Comments Contoller
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
Posts Show
<div class="content">
<%= markdown(@post.content) %>
<ul class="comments">
<% @post.comments.each do |comment| %>
<%= render @post.comments %>
<% end %>
</ul>
<%= render "comments/form" %>
</div>
_comment.html.erb
<li>
<%= link_to comment.name, comment.url, :title => "visit website", :target => "_blank", :rel => "nofollow" %>
<p><%= comment.body %></p>
<time><%= comment.created_at.utc.strftime("%m.%d.%Y") %></time>
<%= link_to 'X', [comment.post, comment],
:confirm => 'Are you sure?',
:method => :delete %>
</li>
Post.rb
has_many :comments, :dependent => :destroy
Comment.rb
belongs_to :post
After I create first comment
After I create first comment
A: from your code:
<% @post.comments.each do |comment| %>
<%= render @post.comments %>
<% end %>
this should either be:
<%= render @post.comments %>
or:
<% @post.comments.each do |comment| %>
<%= render comment %>
<% end %>
A: I have a feeling what you want in your loop is this:
<ul class="comments">
<% @post.comments.each do |comment| %>
<%= render comment %>
<% end %>
</ul>
And not render, again, the whole collection @post.comments
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9861041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I ignore DTD validation but keep the Doctype when writing an XML file? I am working on a system that should be able to read any (or at least, any well-formed) XML file, manipulate a few nodes and write them back into that same file. I want my code to be as generic as possible and I don't want
*
*hardcoded references to Schema/Doctype information anywhere in my code. The doctype information is in the source document, I want to keep exactly that doctype information and not provide it again from within my code. If a document has no DocType, I won't add one. I do not care about the form or content of these files at all, except for my few nodes.
*custom EntityResolvers or StreamFilters to omit or otherwise manipulate the source information (It is already a pity that namespace information seems somehow inaccessible from the document file where it is declared, but I can manage by using uglier XPaths)
*DTD validation. I don't have the referenced DTDs, I don't want to include them and Node manipulation is perfectly possible without knowing about them.
The aim is to have the source file entirely unchanged except for the changed Nodes, which are retrieved via XPath. I would like to get away with the standard javax.xml stuff.
My progress so far:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setAttribute("http://xml.org/sax/features/namespaces", true);
factory.setAttribute("http://xml.org/sax/features/validation", false);
factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setNamespaceAware(true);
factory.setIgnoringElementContentWhitespace(false);
factory.setIgnoringComments(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(inStream));
This loads the XML source into a org.w3c.dom.Document successfully, ignoring DTD validation. I can do my replacements and then I use
Source source = new DOMSource(document);
Result result = new StreamResult(getOutputStream(getPath()));
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
to write it back. Which is nearly perfect. But the Doctype tag is gone, no matter what I do. While debugging, I saw that there is a DeferredDoctypeImpl [log4j:configuration: null] object in the Document object after parsing, but it is somehow wrong, empty or ignored. The file I tested on starts like this (but it is the same for other file types):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
[...]
I think there are a lot of (easy?) ways involving hacks or pulling additional JARs into the project. But I would rather like to have it with the tools I already use.
A: Sorry, got it right now using a XMLSerializer instead of the Transformer...
A: Here's how you could do it using the LSSerializer found in JDK:
private void writeDocument(Document doc, String filename)
throws IOException {
Writer writer = null;
try {
/*
* Could extract "ls" to an instance attribute, so it can be reused.
*/
DOMImplementationLS ls = (DOMImplementationLS)
DOMImplementationRegistry.newInstance().
getDOMImplementation("LS");
writer = new OutputStreamWriter(new FileOutputStream(filename));
LSOutput lsout = ls.createLSOutput();
lsout.setCharacterStream(writer);
/*
* If "doc" has been constructed by parsing an XML document, we
* should keep its encoding when serializing it; if it has been
* constructed in memory, its encoding has to be decided by the
* client code.
*/
lsout.setEncoding(doc.getXmlEncoding());
LSSerializer serializer = ls.createLSSerializer();
serializer.write(doc, lsout);
} catch (Exception e) {
throw new IOException(e);
} finally {
if (writer != null) writer.close();
}
}
Needed imports:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
I know this is an old question which has already been answered, but I think the technical details might help someone.
A: I tried using the LSSerializer library and was unable to get anywhere with it in terms of retaining the Doctype. This is the solution that Stephan probably used
Note: This is in scala but uses a java library so just convert your code
import com.sun.org.apache.xml.internal.serialize.{OutputFormat, XMLSerializer}
def transformXML(root: Element, file: String): Unit = {
val doc = root.getOwnerDocument
val format = new OutputFormat(doc)
format.setIndenting(true)
val writer = new OutputStreamWriter(new FileOutputStream(new File(file)))
val serializer = new XMLSerializer(writer, format)
serializer.serialize(doc)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/582352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using apache cxf to dynamicly create web service client (fix no operation found unchecked exception), invoke operation with authentication So I wanted to to find a way to invoke web service operation dynamically with authentication.
This is what I found.
A: Here is an example for how to create dynamic web service client with apache cxf, avoid the "no operation found for name" unchecked exception and use authentication.
DynamicClientFactory dcf = DynamicClientFactory.newInstance();
Client client = dcf.createClient("WSDL Location");
AuthorizationPolicy authorization = ((HTTPConduit) client.getConduit()).getAuthorization();
authorization.setUserName(
"user name"
);
authorization.setPassword(
"password"
);
Object[] res = client.invoke(new QName("http://targetNameSpace/", "operationName"), params...);
System.out.println("Echo response: " + res[0]);
the new QName with the name space fixed the exception.
Enjoy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16582764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: java wrapper around log4j logger and java.util.logging I am writing a library. The library can be used by applications that use log4j loggers and java.util.logging loggers.
So, I wrote a quick wrapper class, that encapsulates both loggers. I allow the application to set one or both loggers. And in my library I use the encapsulated class to print to either logger.
My question is, since many threads can simultaneously be using the same instance of the wrapper class to log messages using the class' methods (for example: fatal() below), what steps should be taken to make these methods thread safe?
public class MultiLogger {
private static org.apache.log4j.Logger _log4jLogger = null;
private static java.util.logging.Logger _javaUtilLogger = null;
private MultiLogger () {
}
// log4j FATAL, log util SEVERE
public void fatal (Object message) {
if (_log4jLogger != null) {
_log4jLogger.log("", Level.FATAL, message, null);
}
if (_javaUtilLogger != null) {
_javaUtilLogger.severe((String) message);
}
}
...
}
Any other comments appreciated too.
A: Option 1: slf4j, as per comment on question.
Option 2: cxf.apache.org has such a device in it. We use it instead of slf4j because slf4j lacks internationalization support. You are welcome to grab the code.
A: See my comment:
You should check out slf4j before you proceed with this library. It wraps all the major logging libraries and is very high quality.
But I presume that your wrapper class will be used in the same manner as the loggers that it wraps. In that case, the wrapped classes should handle the synchronization for you.
A: Provided that you're just using log4j and util Loggers as shown above, I don't think you'll run into any sync problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1767716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to check for an exact string match in parameters that being passed for API call Python I am passing the parameters with a Soap Call to AdPoint platform. My parameters look like this:
[{'nUID': '39', 'Query': [{'MaxRecords': '40', 'OrderName': 'Forecast Placeholder - 100', 'CustomerID': '15283'}]}]
Passing the parameters below:
response = client.service.GetOrders(**params[0])
Because CustomerID is not unique, and 'Forecast Placeholder - 100' is a string. The response I get back might be Forecast Placeholder - 1005 or 1007 etc. I wonder if there is a way in Python to tell the code to only return the exact match. AdPoints API sucks so there is nothing that can help from API side, but Python is very powerful, so I am hoping there is a way...
A: If someone could make this a comment, that would be very helpful. I don't have enough reputation to do so.
@Chique_Code, when you say:
The response I get back might be Forecast Placeholder - 1005 or 1007 etc. I wonder if there is a way in Python to tell the code to only return the exact match
Do you mean getting 1005 or 1007 as a number from the string Forecast Placeholder - 1005? If so, you could use the [:] notation.
>>> int("Forecast Placeholder - 1005"[23:]) # Returns an integer from the 23rd character to the end of the string
1005
Bear in mind, if you take this route [23:] will return a string that contains the 23rd character to the end. So if you get "Placeholder - 1234" and do [23:] you will get an empty string, as the 23rd character does not exist, so it returns an empty string.
And BTW, if you hate the API you are using, why are you using it then?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61231332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery Sort nested list by different values (not alphabetically) I am attempting to sort a nested list using different variables. So, I have something like the following:
<div id="title">
<h2>AWARDS by TYPE</h2>
<span>
<p>Sort by: </p>
<a href="#" class="sort-by-trophy">Trophy</a>
<a href="#" class="sort-by-gold">Gold</a>
<a href="#" class="sort-by-silver">Silver</a>
<a href="#" class="sort-by-bronze">Bronze</a>
<a href="#" class="sort-by-other">Other</a>
</span>
</div>
And the lists:
<ul id="accolade-display-list">
<li class="accolade-display-list-item"> <img src="/images/us/law/accolades/organisation/27.jpg">
<ul>
<li class="accolades-org-name"> Argentina Wine Awards </li>
<li class="accolades-org-details">Silver Medal - 2012, Argentina</li>
</ul>
</li>
<li class="accolade-display-list-item"> <img src="/images/us/law/accolades/organisation/2.jpg">
<ul>
<li class="accolades-org-name"> Royal Adelaide Wine Show </li>
<li class="accolades-org-details">Regional Trophy - 2012, Argentina</li>
</ul>
</li>
<li class="accolade-display-list-item"> <img src="/images/us/law/accolades/organisation/57.jpg">
<ul>
<li class="accolades-org-name"> Wines of Chile Awards </li>
<li class="accolades-org-details"> Blue Gold Medal - 2012, Argentina</li>
</ul>
</li>
</ul>
What I would like to do is to be able to click, say "trophy" and sort the items with "trophy" at the top, then click "gold" and have those items together at the top, etc. There are currently one of each in my example, but there may be several "gold" items, "silver" items, and so on. I've tried a number of methods, but I have at the most been able to get the list to sort alphabetically, which is not what I need.
These are coming in from a JSP and I may be able to add additional classes to things as appropriate - I can also alter the list structure if necessary. The reason I have the nested lists is simply to make the alignment with the images easier, and because it is possible that there may be an additional line (<li>) in the future.
The way I've gotten the list to sort alphabetically, if it helps:
$("a.sort-by-trophy").click(function(){
console.log('sort-by-trophy clicked');
var list = $("ul#accolade-display-list");
var desc = false;
list.append(list.children().get().sort(function(a, b) {
var aProp = $(a).find(".accolades-org-name").text(),
bProp = $(b).find(".accolades-org-name").text();
return (aProp > bProp ? 1 : aProp < bProp ? -1 : 0) * (desc ? -1 : 1);
}));
});
Anyway, if anyone has any ideas as to something I might try, I would really appreciate it.
A: what i recommend is to have the values you should have, then generate the output (check underscore.js) and each time you click a sort, then generate it again and replace it.
what i mean, is that you havethe primivitve data:
var list = [{name: 'Argentina Wine Awards', medal: 'silver', ... }, {}, ...];
then, when is clicked a sort link, you sort the list array by the correct property and generate a new html (using underscore templates) and replace the old html with the new one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12730418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Torchvision cannot save a tensor on integer type I try to use Torch to resize some images which I did successfully. The resized images have integer type and when I try to save them I get the error below:
RuntimeError: result type Float can't be cast to the desired output type Byte
I used the code below to resize and save images:
image_temp = torchvision.transforms.Resize([200,200], antialias = True)(image_temp)
torchvision.utils.save_image(image_temp , './test.png')
If I convert the tensor or the image to float type, I can save it without error. Does someone know what the problem with integer data type and saving it is?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71960639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass a variable from View to Controller in ASP .NET I found similar questions to mine, but in all of those examples, the variable was part of the model. I am trying to pass a variable that is created in javascript, which is not part of the model.
Code:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "@@mymail.ca";
/* Check directory to see if this email exists */
@Html.Action("CheckDirectory", "Home", new { email = ???});
}
});
Is there a way to fill in the ??? with the email above?
A: You can pass your value as a GET parameter in the controller URL:
$(document).ready(function () {
var url = document.URL;
var index = url.indexOf("?email=");
var email;
/* If there is an EMAIL in URL, check directory to confirm it's valid */
if (index > -1) {
/* There is an email */
email = url.substr((index + 7));
email = email.substr(0, (email.length - 4)) + "@@mymail.ca";
/* Check directory to see if this email exists */
window.location.href = '/CheckDirectory/Home?email=' + email;
}
});
A: To answer your question of
Is there a way to fill in the ??? with the email above?
No. The Razor code is similar to, say, PHP, or any other server-side templating language - it's evaluated on the server before the response is sent. So, if you had something like
@Url.Action("checkdirectory", "home")
in your script, assuming it's directly in a view, it would get replaced by a generated URL, like
/home/checkdirectory
Your code, which uses
@Html.Action("checkdirectory", "home")
actually executes a separate action, and injects the response as a string into the view where it's called. Probably not what you were intending.
So, let's try to get you on the right path. Assuming your controller action looks something like
[HttpGet]
public ActionResult CheckDirectory(string email = "")
{
bool exists = false;
if(!string.IsNullOrWhiteSpace(email))
{
exists = YourCodeToVerifyEmail(email);
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
You could, using jQuery (because XMLHttpRequests are not fun to normalize), do something like
$(function(){
var url = '@Url.Action("checkdirectory", "home")';
var data = { email : $('#email').val() };
$.get(url, data)
.done(function(response, status, jqxhr) {
if(response.exists === true) {
/* your "email exists" action */
}
else {
/* your "email doesn't exist" action */
}
})
.fail(function(jqxhr, status, errorThrown) {
/* do something when request errors */
});
});
This assumes you have an <input /> element with an id of email. Adjust accordingly. Also, the Url helper can only be used within a view; if you're doing this in a separate JavaScript file, replace it with a hard-coded string (or whatever else works for you).
Edit:
Since it seems I didn't entirely get what you were trying to do, here's an example of returning a different view based on the "type" of user:
public ActionResult ScheduleMe(string email = "")
{
if(!string.IsNullOrWhiteSpace(email))
{
ActionResult response = null;
var userType = YourCodeToVerifyEmail(email);
// Assuming userType would be strings like below
switch(userType)
{
case "STAFF":
response = View("StaffScheduler");
break;
case "STUDENT":
response = View("StudentScheduler");
break;
default:
response = View("ReadOnlyScheduler");
break;
}
return response;
}
return View("NoEmail");
}
This assumes you would have 4 possible views: the three you mentioned, plus an "error" view when no email parameter was given (you could also handle that by redirecting to another action). This variation also assumes a user has somehow navigated to something like hxxp://yourdomain.tld/home/[email protected]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32360431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I can't read mouse data in STM32F407VG-Discovery I am trying to get data from computer mouse with USB to TTL converter but I read nothing in rfBuff1.
I check the USB to TTL whether it works or not. I connected it to computer and stm32f4, and used HTerm to send some data, it worked. Seems the problem is not the converter.
Variables
#define RX_BUFFERSIZE 2000
char rxBuff1[RX_BUFFERSIZE];
USART_InitTypeDef USART_InitStructure;
USART Configs
void USART_Configuration(void){
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure); // USART configuration
USART_Cmd(USART1, ENABLE);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
This is the Interrupt Part
void USART1_IRQHandler(void) {
rxBuff1[i++] = USART_ReceiveData(USART1);
if (i == RX_BUFFERSIZE ){i = 0;}
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
This is my main code :
int main(void)
{
RCC_Configuration();
GPIO_Configuration();
USART_Configuration();
NVIC_Configuration();
while(1);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62658600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is Scala for: getline(), std::cin.eof(), std::cin.bad()? Here is a fragment of C++ code:
int AskBase::ask_user(){
for (int tries_left = MAX_TRIES; tries_left;){
std::cout << prompt.c_str();
std::string response;
getline(std::cin, response);
if ("^Z" == response || std::cin.eof() || std::cin.bad())
return -9;
else if ("?V" == response)
std::cout << SSVID_ICON << SSVID << std::endl;
else if ("?" == response)
std::cout << "Enter ? for help, ?V for version, ^Z for exit.\n"
else if (validate(response)){
answer_string = response;
return 1;
else
--tries_left;
}
return -9;
}
What would the Scala be for these:
*
*getline()
*std::cin.eof()
*std::cin.bad()
A: In Scala (and Java), reaching the eof means getting null when trying to read. I don't know how cin.bad translates, but it may be exceptions.
Your example is equivalent to:
def askUser( tries_left: Int = MAX_TRIES ):Int =
Console.readLine match {
case "^Z" | null => -9
case "?V" => {
println( SSVID_ICON + SSVID )
askUser( tries_left )
}
case "?" => {
println( "Enter ? for help, ?V for version, ^Z for exit.")
askUser( tries_left )
}
case response if validate(response) => {
answer_string = response
1
}
case _ => if( tries_left == 0) -9 else askUser( tries_left - 1)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6740382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: oracle sql ranking and count with conditional statements I am stuck with the process of categorizing rows based on particular conditions. I am hoping to get through this with the support from you guys!
Basically, I am trying to create two new columns to the table by applying some particular formulas. Those columns are for ranking volume for each year and also for categorization by specifying whether each prac was included in the top 3 claims in 2014 or not. In the below examples, the columns highlighted in light blue are the ones I want to create.
My query is as below - right now I have a problem with writing codes for the two last lines above from, group by and having do not seem to work within those parentheses. Please help!!
select
fiscal_year,
prac,
count(*) "CLAIMS",
sum(paid_amount) "COST",
row_number() over (group by fiscal_year order by count(*) desc) "Annual Rank by Claims",
case
when row_number() over (having fiscal_year = '2014' order by count(*) desc) < 4
then 'YES'
else 'NO'
end "PRAC TOP 3 IN CLAIMS 2014"
from mys.mv_claim
where category = 'V'
group by fiscal_year,
prac
/
A: Missing the original data, let the given (intermediate) output be the starting point - the first statement (resulting in MV_Claim_Ranked) could be replaced with your selection from mys.mv_claim:
WITH
MV_Claim_Ranked AS (
SELECT
fiscal_year,
prac,
claims,
cost,
annual_rank_by_claim,
RANK() OVER (PARTITION BY fiscal_year ORDER BY claims DESC) annual_rank_by_claim_calc,
prac_top_3_in_claims_2014
FROM MV_Claim_Grouped
)
SELECT
T1.*,
CASE WHEN (SELECT annual_rank_by_claim_calc
FROM MV_Claim_Ranked T2
WHERE T1.prac = T2.prac
AND T2.fiscal_year = 2014) < 4
THEN 'YES' ELSE 'NO' END AS prac_top_3_in_claims_2014_calc
FROM MV_Claim_Ranked T1
ORDER BY prac, fiscal_year
;
Your aggregates are kept for reference.
See it in action: SQL Fiddle.
Please comment, if and as this requires adjustment / further detail.
A: I've never seen GROUP BY and HAVING used in a partitioning spec; I suspect it's a syntax error. I think your query needs to look more like:
WITH t as (
select
fiscal_year,
prac,
count(*) "CLAIMS",
sum(paid_amount) "COST"
from mys.mv_claim
where category = 'V'
group by fiscal_year, prac
)
SELECT
t.*,
rank() over (partition by fiscal_year order by claims desc) "Annual Rank by Claims",
case
when prac in(select prac from (select * from t where fiscal_year = 2014 order by claims desc ) where rownum <= 3)
then 'YES'
else 'NO'
end "PRAC TOP 3 IN CLAIMS 2014"
from t
I've used rank instead of row number, as two identical claim counts will produce a rank value the same. Rank will then skip the next rank (two 999 claim counts will each rank 1, a 998 claim count will rank 3. If you want it to rank 2 use dense_rank)
Let me know if you get any errors with this, as the only thing I'm not certain will work out is the subselect that retrieves the top 3 pracs. That can be done with a left join instead (which i have greater confidence in)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48027748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Rest Framework serializer field incorrectly named When I run api request I get a following error:
AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the tuple instance.
Original exception text was: 'tuple' object has no attribute 'email'.
New user gets inserted in database anyway, email field is filleld properly.
View:
class Register(APIView):
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
return Response(serializer.data, status=status.HTTP_201_CREATED)
Serializer:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['email', 'username', 'name', 'password']
def create(self, validated_data):
user = User.objects.create_user(**validated_data),
return user
Model:
class User(AbstractBaseUser):
email = models.EmailField(max_length=254, unique=True)
username = models.CharField(max_length=30, unique=True)
name = models.CharField(max_length=60)
date_of_birth = models.DateField(blank=True, null=True)
bio = models.CharField(default='', max_length=10000)
photo = models.ImageField(max_length=255, null=True, blank=True)
email_verified_at = models.DateTimeField(null=True, blank=True)
email_token_time = models.DateTimeField(null=True, blank=True)
email_token = models.CharField(default='', max_length=64)
password_token_time = models.DateTimeField(null=True, blank=True)
password_token = models.CharField(default='', max_length=64)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
last_seen = models.DateTimeField(null=True, blank=True)
USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'name']
objects = UserManager()
class Meta:
db_table = "User"
def __str__(self):
return self.username
I also have custom user manager, but that is probably irrelevant, and works as user does get inserted to database.
A: You have typo in this line:
user = User.objects.create_user(**validated_data),
It contains comma , in the last of line. So user become a tuple of user instance, not just user instance. It become (user,).
Should return user instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64565555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing nested repeater's textbox in client side How to get the nested repeater textbox control in client side event of parent Repeater control.
I have a checkbox in each repeater item of the parent repeater control and textbox in each repeater item of the child Repeater. On the checkbox change event I need to find if there is any value in the child repeater textbox of that item in the client side.
I gave a class to the textbox, but the below code loops through all the textboxes inside the parent repeater.
$('.RepeaterTextBox').each(function () {
var txtvalue= $(this).val();
Rendered HTML for a single parent looks like this
<table>
<tr>
<td>
<input id="chkActive_0" name="chkActive" />
</td>
</tr>
<tr>
<td>
<div id="divText" style="padding-left: 15px; display: none;">
<table style="width: 100%">
<tr>
<td>
<div id="Category_0">
<textarea name="txtCategoryText" rows="2" cols="20" id="CategoryText_0" class="RepeaterTextbox"></textarea>
</div>
</td>
<td>
<div id="Category_1">
<textarea name="txtCategoryText" rows="2" cols="20" id="CategoryText_1" class="RepeaterTextbox"></textarea>
</div>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
A: You can use the checklist parent() property
Assuming your rendered html look like this
<div id="repeater_435734957439857435">
<input type="text" class="RepeaterTextbox">Test</input>
<input type="checkbox">
</div>
Your checkbox select event can be something like
$(this).parent().find(".RepeaterTextbox")[0].text();
A: This should work with your markup:
$(document).ready(function () {
$(document).on("click", "input:checkbox[name='chkActive']:checked", function () {
var nexttr = $(this).closest('tr').next('tr');
$(nexttr).find('textarea').each(function () {
alert($(this).val());//Or whatever you want
})
});
});
A: Try this, it seems there are multiple textarea you have in nested repeater so the second line in the event handler will loop through each textarea and print value in console.
$("[type=checkbox]").on("change", function () {
var oTexts = $(this).parents("tr").next().find("textarea");
$(oTexts).each(function (ind, val) { console.log($(val).val()); });
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24175385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why jquery .live() and .on() don't work as expected for ASP.NET Updatepanels? I have 1 page which has 1 updatepanel which contains 1 user control(lets call it user.ascx) and 2 buttons.
My user.ascx has some checkboxes which can disable/enable other controls. I am doing it in javascript added to user.ascx, but when updatepanel updates( async postback after clicking 1 of those 2 buttons) my javascript events for checkboxes (click or change) arem't fired.
I know I can just wrapp $().ready() with function pageLoad(sender,args) and it works perfect but according to that page http://blog.dreamlabsolutions.com/post/2009/03/25/jQuery-live-and-ASPNET-Ajax-asynchronous-postback.aspx it is better to use live() function.
Unfortunately all available ways to bind event like .click(), .change(), .bind(), .live() and .on() work after postback can't after asynchronus postback.
Sample of code which doesn't work:
<script type="text/javascript">
$().ready(function () {
var ddlAge= $("#<%= ddlAge.ClientID %>");
var cboxFirst= $("#<%= cboxFirst.ClientID %>");
var cboxSecond= $("#<%= cboxSecond.ClientID %>");
$(document).on("change", cboxFirst, function () {
if (cboxFirst.is(":checked")) {
ddlAge.attr("disabled", "disabled");
ddlAge.val("");
}
else { ddlAge.removeAttr("disabled"); }
});
cboxSecond.live('change',function () {
if (cboxSecond.is(":checked")) {
ddlAge.attr("disabled", "disabled");
ddlAge.val("");
}
else { ddlAge.removeAttr("disabled"); }
});
});
</script>
Both checkboxes work only after postbacks. What may I do wrong? Does anyhone have such problem? I am using Jquery 1.7.1 and I am not getting any js errors.
I will be grateful for any help.
A: I'm surprised that the .on works at all. According to the documentation http://api.jquery.com/on/ it's second parameter should be a selector string and not a jquery object.
I would try something like this:
$(document).on("change", "#<%= cboxFirst.ClientID %>", function () {
if ($(this).is(":checked")) {
ddlAge.attr("disabled", "disabled");
ddlAge.val("");
}
else { ddlAge.removeAttr("disabled"); }
});
As long as the ClientID stays the same the event will still work even when the UpdatePanel replaces all its content.
Also, .live has been deprecated in favor or .on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12039757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error with Scanner I'm trying to get database from the internet but the bug has disapear.
package space;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Scanner;
import java.net.URL;
public class ArrayIntro {
public static void main(String[] args) throws Exception {
String urlbase = "https://learnjavathehardway.org/txt/";
double[] temps = arrayFromUrl(urlbase + "avg-daily-temps-atx.txt");
System.out.println( temps.length + " temperatures in database.");
double lowest = 9999.99;
for ( int i=0; i<temps.length; i++ ) {
if ( temps[i] < lowest ) {
lowest = temps[i];
}
}
System.out.print( "The lowest average daily temperature was " );
System.out.println( lowest + "F (" + fToC(lowest) + "C)" );
}
public static double[] arrayFromUrl( String url ) throws Exception {
Scanner fin = new Scanner((new URL(url)).openStream());
int count = fin.nextInt();
double[] dubs = new double[count];
for ( int i=0; i<dubs.length; i++ )
dubs[i] = fin.nextDouble();
fin.close();
return dubs;
}
public static double fToC( double f ) {
return (f-32)*5/9;
}
}
The value count is 6717. I'm trying to find the lowest temperature in the link https://learnjavathehardway.org/txt/avg-daily-temps-atx.txt.
And the error is this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at space.ArrayIntro.arrayFromUrl(ArrayIntro.java:43)
at space.ArrayIntro.main(ArrayIntro.java:20)
C:\Users\Administrator\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
A: In Scanner you can use it with Locale to specify Locale like dot . as decimal separator:
Scanner fin = new Scanner((new URL(url)).openStream()).useLocale(Locale.ENGLISH);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46036953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Microsoft Visual C++ Build Tools compiler with Eclipse Recently I decided to move from Microsoft Visual Studio to Microsoft Visual C++ Build Tools. I am working with the latest Eclipse and want to utilize the Microsoft C++ compiler.
While having Microsoft Visual Studio installed there was an option to choose the Microsoft compiler in the tool-chain options which went away and I can't seem to get it back with Microsoft Visual C++ Build Tools.
I have added the folders to user path and tried launching Eclipse from within the build tools "special" terminal but with no success.
Has anyone managed to achieve compilation within eclipse with the build tools and if yes how is it possible?
P.S.: I deliberately changed from Microsoft Visual Studio to Microsoft Visual C++ Build Tools, as the difference in disk size is vast.
A: I have Eclipse 4.6 Neon. In Help > Install New software make sure you installed C/C++ Visual C++ Support. Restart Eclipse after installation.
I can see Microsoft Visual C++ in Toolchains now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41428294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: RNN Architecture for a Many to Many time series forecasting problem I am trying to forecast the yield curve (multiple time series) with a RNN/LSTM/GRU model in Keras.
As input I have the 12 interest rate price series (which make up the yield curve) and some more variables like SP500, etc. As an output I would like only a forecast of the 12 interest rates.
I am very new to NN time series forecasting and I was wondering if this is possible in Keras and what kind of things I should be aware of. I also appreciate any tips.
thank you!
A: Tensorflow documentation offers amazing tutorial to start with.
You can explore the tutorial here to understand the timeseries using Tensorflow.
Also, refer to some of the blogs mentioned below and use the method which fits your requirement.
*
*Multi-step LSTM time series.
*Multivariate Time series.
*Many to Many LSTM with TimeDistributed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68790251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is a correct overpass-turbo query for getting all streets in a city? I want to get all streets in NYC using http://overpass-turbo.eu/. I tried this:
[out:json]; area[name = "New York"]; (node(area)[highway=street]; ); out;
However it returns
{
"version": 0.6,
"generator": "Overpass API 0.7.55.1009 5e627b63",
"osm3s": {
"timestamp_osm_base": "2019-11-13T19:26:03Z",
"timestamp_areas_base": "2019-11-13T18:05:02Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
]
}
No elements. However this query:
[out:json]; area[name = "New York"]; ( node(area)[amenity=cinema]; node(area)[highway=street]; ); out;
for getting streets and cinemas, works:
{
"version": 0.6,
"generator": "Overpass API 0.7.55.1009 5e627b63",
"osm3s": {
"timestamp_osm_base": "2019-11-13T19:29:02Z",
"timestamp_areas_base": "2019-11-13T18:05:02Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 344994897,
"lat": 41.7680892,
"lon": -73.9291000,
"tags": {
"amenity": "cinema",
"created_by": "Potlatch 0.10f",
"name": "Roosevelt Theater"
}
},
...
How should I modify the initial query to get the streets?
A: There are two errors in your query.
Error 1: highway=street
Where does this tag come from? street is not a valid value for the highway key. In fact, since you want to obtain all streets you have to omit the value completely and just query for highway.
Error 2: node()
A road is not a node but a way. So you have to query for way(area)[...] instead. This also requires a recurse-up step (>;) to retrieve all nodes of these ways.
Corrected query
[out:json]; area[name = "New York"]; (way(area)[highway]; ); (._;>;); out;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58844414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you convert start and end date records into timestamps? For example (input pandas dataframe):
start_date end_date value
0 2018-05-17 2018-05-20 4
1 2018-05-22 2018-05-27 12
2 2018-05-14 2018-05-21 8
I want it to divide the value by the # of intervals present in the data (e.g. 2018-05-12 to 2018-05-27 has 6 days, 12 / 6 = 2) and then create a time series data like the following:
date value
0 2018-05-14 1
1 2018-05-15 1
2 2018-05-16 1
3 2018-05-17 2
4 2018-05-18 2
5 2018-05-19 2
6 2018-05-20 2
7 2018-05-21 1
8 2018-05-22 2
9 2018-05-23 2
10 2018-05-24 2
11 2018-05-25 2
12 2018-05-26 2
13 2018-05-27 2
is this possible to do without an inefficient loop through every row using pandas? Is there also a name for this method?
A: You can use:
#convert to datetimes if necessary
df['start_date'] = pd.to_datetime(df['start_date'])
df['end_date'] = pd.to_datetime(df['end_date'])
For each row generate list of Series by date_range, then divide their length and aggregate by groupby with sum:
dfs = [pd.Series(r.value, pd.date_range(r.start_date, r.end_date)) for r in df.itertuples()]
df = (pd.concat([x / len(x) for x in dfs])
.groupby(level=0)
.sum()
.rename_axis('date')
.reset_index(name='val'))
print (df)
date val
0 2018-05-14 1.0
1 2018-05-15 1.0
2 2018-05-16 1.0
3 2018-05-17 2.0
4 2018-05-18 2.0
5 2018-05-19 2.0
6 2018-05-20 2.0
7 2018-05-21 1.0
8 2018-05-22 2.0
9 2018-05-23 2.0
10 2018-05-24 2.0
11 2018-05-25 2.0
12 2018-05-26 2.0
13 2018-05-27 2.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50392832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding a MVC 4 controller using entity framework 5 database first I'm trying to configure an MVC 4 application using EF 5 against the System.Web.Providers Membership DB. The ADO.NET Entity Data Model appears correct. The classes generated by the EF 5.x code generator look ok, but do not have a [Key] attribute. When I try to create a User Controller, I get the following error:
Microsoft Visual Studio
Unable to retrieve metadata for 'Citrius.Admin.User'. One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Membership' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Profile' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Memberships' is based on type 'Membership' that has no keys defined.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Profiles' is based on type 'Profile' that has no keys defined.
I thought I saw a walkthrough of this, using these versions, but cannot find it. I've tried to find a solution but all the examples are of previous versions.
Am I too far out on the bleeding edge?? Any help would be appreciated...
A: Why dont you assign the Key manually?
Go into each one and add [Key] above the field that should be the Key.
That should get rid of these errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11752484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MUI Override Slider color options with module augmentation I'm trying to solve a typescript error regarding the chosen color on my slider component:
<Slider
color="brown"
/>
The error is: Type '"brown"' is not assignable to type '"primary" | "secondary" | undefined'.
I have set the brown color on my theme, by augmenting the createPalette file.
declare module '@mui/material/styles/createPalette' {
interface Palette {
brown: PaletteColor
}
interface PaletteOptions {
brown: PaletteColorOptions
}
}
So now that I still have the error I looked in the Slider.d.ts file and found an interface: SliderPropsColorOverrides.
export interface SliderPropsColorOverrides {}
...
color?: OverridableStringUnion<'primary' | 'secondary', SliderPropsColorOverrides>;
I try to merge it with my brown color:
declare module '@mui/material/Slider' {
interface SliderPropsColorOverrides {
darkest_blue: PaletteColorOptions
}
}
But with no luck. Either my IDE (PhpStorm 2021.3) isn't compiling the new typescript code, or I'm missing something.
A: You were very close to something that would work, but the value for the augmentation of SliderPropsColorOverrides should just be true rather than PaletteColorOptions.
In my example sandbox I have the following key pieces:
createPalette.d.ts
import "@mui/material/styles/createPalette";
declare module "@mui/material/styles/createPalette" {
interface Palette {
brown: PaletteColor;
}
interface PaletteOptions {
brown: PaletteColorOptions;
}
}
Slider.d.ts
import "@mui/material/Slider";
declare module "@mui/material/Slider" {
interface SliderPropsColorOverrides {
brown: true;
}
}
There was one other problem that I addressed in a rather ugly fashion. The Slider prop-types were still causing a runtime validation message for the color prop. I found comments in some open issues about color customization that mention this prop-types aspect and I suspect it will eventually be addressed by MUI, but it might not be addressed for a while. In my sandbox, I work around this by creating a SliderPropTypesOverride.ts file in which I copied MUI's SliderRoot.propTypes.ownerState and then modified the color portion to include "brown". This copying of the prop-types definitely isn't ideal from a maintenance standpoint, but at the moment I don't see another way to address the runtime warning in dev mode.
Then this all gets used as follows:
demo.tsx
import React from "react";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import "./SliderPropTypesOverride";
import Slider from "@mui/material/Slider";
const defaultTheme = createTheme();
const theme = createTheme({
palette: {
brown: defaultTheme.palette.augmentColor({
color: {
main: "#A52A2A"
},
name: "brown"
})
}
});
export default function Demo() {
return (
<ThemeProvider theme={theme}>
<Slider color="brown" />
</ThemeProvider>
);
}
Related answers:
*
*Typescript Module augmentation is not working: Property 'main' does not exist on type 'PaletteColorOptions'
*How to add custom colors name on Material UI with TypeScript?
A: I would review the documentation on this.
https://mui.com/customization/palette/
It doesn't seem that you're able to override the color of the component directly and instead (if you have one) need to create a global theme object with the appropriate declaration files in order to override the color.
Also see this answer:
Extending the color palette with TS
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70451008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android BluetoothAdapter Mocking I'm trying to mock test Bluetooth application but my first step of creating a mock object of BluetoothAdapter class is not working!!
I'm using powermockito with easy mock.
mBluetoothAdapter = (BluetoothAdapter)PowerMock.createMock(BluetoothAdapter.class);
this fails. with the following stack trace
java.lang.IllegalArgumentException: No visible constructors in class android.bluetooth.BluetoothAdapter
at org.easymock.internal.DefaultClassInstantiator.getConstructorToUse(DefaultClassInstantiator.java:94)
at org.easymock.internal.AndroidClassProxyFactory.createProxy(AndroidClassProxyFactory.java:48)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:114)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:88)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:79)
at org.powermock.api.easymock.PowerMock.doCreateMock(PowerMock.java:2212)
at org.powermock.api.easymock.PowerMock.doMock(PowerMock.java:2163)
at org.powermock.api.easymock.PowerMock.createMock(PowerMock.java:89)
at com.xxx.blesimplesample.test.MainActivityTest.setUp(MainActivityTest.java:59)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1710)
Any one has used any mocking framework for Bluetooth app mocking? Any suggestions will be v helpful
A: BluetoothAdapter in the Android framework is declared final, so at the time you asked this question, it couldn't be mocked, neither with Mockito nor using Robolectric.
However, Android unit testing has changed a lot since then. With recent versions of the tools, when you build unit tests the tools generate a patched android.jar with all the finals removed. This makes all Android classes available for mocking. Nowadays, if you want to mock any Bluetooth code, you can do so in the standard way. The code you've already tried will "just work" if you update to the latest tools. Alternatively, Robolectric has a ShadowBluetoothAdapter class built in now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26731994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: FTDI D2XX Xamarin Forms I'm making a Xamarin Forms project for Android & IOS and wanting to be able to use the FTDI D2XX API. There are NuGet packages for D2XX here and here. I have also tried to integrate the Android implementation discussed here. I am quite new to C# and Xamarin, but fairly experienced with Android development. I have managed to add the FTD2XX_NET file as an Assembly file in the project as in the attached image. But I get the exception shown below when I try and access the DLL using FTDI newDevice = new FTDI(); as suggested in example 3 here. Any help would be much appreciated.
Assembly File Location:
Exception:
A: You can download the latest FTD2XX_Net dll from official FTDI site here. The latest version is 1.1.0 so both nuget packages you mentioned are outdated because they are version 1.0.14.
As an alternative to the dll, and I think that will be interesing for your case, you can directly include the source of the .Net wrapper. It can be downloaded here. Using the sources for debugging has the advantage that you gain more insight in whats happening when errors occure. You also directly get compiler errors when parts of the ftdi warpper implementation cannot be compiled for mono.
Addidtionally you have to ensure that the ftdi driver is installed at all. FTD2XX_Net is just a wrapper around the native ftdi driver.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64922303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenAPI: Standard Location and Name of OpenAPI Document I was looking at the OAS and can see where it lists the recommended file name as being openapi.json but I have two questions:
*
*There evidentially isn't a standard location to put it in but is there a de facto standard that people seem to follow? Like is the assumption that the most "normal" place to make it accessible under /openapi.json ?
*Why is this left out of the spec and why is even just the document name only recommended instead of being required? Isn't part of the point of this to make it discoverable? Seems like relocating the OpenAPI document cuts against that by giving you something you just kind of have to know. Is there an advantage to leaving it out though?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63676429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Upload multiple images with JavaScript in ASP.NET For uploading multiple images, I am using this javascriptL
function AddMoreImages() {
if (!document.getElementById && !document.createElement)
return false;
var fileUploadarea = document.getElementById("fileUploadarea");
if (!fileUploadarea)
return false;
var newLine = document.createElement("br");
fileUploadarea.appendChild(newLine);
var newFile = document.createElement("input");
newFile.type = "file";
newFile.setAttribute("class", "fileUpload");
if (!AddMoreImages.lastAssignedId)
AddMoreImages.lastAssignedId = 100;
newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
var div = document.createElement("div");
div.appendChild(newFile);
div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
fileUploadarea.appendChild(div);
AddMoreImages.lastAssignedId++;
}
<div id="fileUploadarea">
<asp:FileUpload ID="UploadImage" runat="server" CssClass="fileUpload" />
</div>
But the problem is, when I am uploading multiple images with 2MB size, the JavaScript is not working and the page doesn't postback to my page.
A:
But problem is when am upload multiple images with 2mb size...
It's likely your running into the default maximum upload size that's set for ASP.NET (4MB). you can add this to your web.config to increase from the default:
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
</system.web>
This would increase the maximum upload size to 20MB at a time.
There's a pretty detailed article about this topic here if you'd like to read further: Large file uploads in ASP.NET.
Note: You said the "javascript was not working", but didn't really elaborate. If you could expand on that, I'd be glad to take another look
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10245965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Quirk with .GLB files in Firefox I loaded a .GLB into my Three.js project using Three's GLTF Loader, and the object worked perfectly in all browsers except for Firefox.
A: Firefox loads the children within the scene from a .GLB file in the opposite order of all other browsers. This is detrimental if you plan on manipulating the contents such as alpha maps, etc... of a .GLB object using Three.js.
I figured out the issue by loading a simple .GLB object into a project and it worked in Firefox just fine. So why wouldn't my more complicated object that utilized alpha maps work in Firefox?
Eventually I noticed that the children array of the GLTF scene was in the reverse order while running in Firefox thus causing my code to not match the indexes of the children.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59015389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel not loading view. Error in a storage\framework\view file I'm unable to access my orders_index view from my OrdersController.
orders_index.blade.php
location: \resources\views\orders
@extends 'app'
@section('heading')
Orders Index
@endsection
@section('content')
<section>
content section
</section>
@endsection
OrdersController
location: app\Http\Controllers
public function index(){
return view('orders.orders_index');
}
routes.php
Route::get('orders', 'OrdersController@index');
file in which error is indicated: f2e7d6f3f58a0e30e17a0c631c812b28
'/app'
<?php $__env->startSection('heading'); ?>
Orders Index
<?php $__env->stopSection(); ?>
<?php $__env->startSection('content'); ?>
<section>
content section
</section>
<?php $__env->stopSection(); ?>
<?php echo $__env->make(, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
I think it has something to do with namespacing, which I have not quite figured out yet. I haven't seen any information online yet about namespacing in the view, so I do not know if I am to use namespace in the views.
A: It should be @extends('app') not @extends 'app'. For Laravel what you did now was like writing: @extends() 'app' So it tries to call the function make with an empty first parameter (because you didn't pass anything to @extends) and hence you get that syntax error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28637347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.