text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Select value from text based Postgres field I would like to extract some information that store in one field.
for example :
{"Dtl":"{\"title\"campaignId\":\"12345\",\"offerId\":\"67789\"}
I need the information of campaignid and also offerid
the expected result should be : 12345 and 67789
is there any way to extract that information?
A: SELECT '{"Dtl": {"campaignId":"12345","offerId":"67789"}}' :: jsonb #> '{Dtl,campaignId}' => "12345"
SELECT '{"Dtl": {"campaignId":"12345","offerId":"67789"}}' :: jsonb #> '{Dtl,offerId}' => "67789"
see test result in dbfiddle
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71393758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How to change color of specific cell's label in collection view from array of labels in swift I'm pretty new to Swift and I have a question, I have a collection view, with a cell inside, and a label inside of this cell. I created an array and returned it, so I have multiple cells with labels. My question is, how to change a color of specific labels, for example if I want the labels "2", "7", "13"(from the image) and etc to be not green, but other color. THANK YOU
screen of simulator
A: Implement method below and set desired colour.
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// Access label of cell object and set desired colour
}
Tells the delegate that the specified cell is about to be displayed in
the collection view.
https://developer.apple.com/reference/uikit/uicollectionviewdelegate/1618087-collectionview
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43597886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How should I detect an observable is idle and inject data every minute? I have an observable returning data sporadically. If there is no data for one minute, I need to repeat the last data, every minute until it generates data again. How can I achieve this?
Thank you.
A: Here's a one liner to do what you want. I've tested it and it seems to be correct.
var results = source
.Publish(xs =>
xs
.Select(x =>
Observable
.Interval(TimeSpan.FromMinutes(1.0))
.Select(_ => x)
.StartWith(x))
.Switch());
Let me know if this does the trick.
A: I would wrap the observable in an observable that is guaranteed to return a value at least once per minute. The wrapper could do this by running a timer that is restarted whenever the wrapped observable returns a value.
Thus, the wrapper returns data whenever the wrapped observable returns data or when a minute has passed after the last event.
The rest of the application conveniently just observes the wrapper.
A: Here's a (non-threadsafe, in case your source is multithreaded) implementation of a RepeatAfterTimeout operator:
EDIT Updated as Timeout didn't work as I expected
// Repeats the last value emitted after a timeout
public static IObservable<TSource> RepeatAfterTimeout<TSource>(
this IObservable<TSource> source, TimeSpan timeout, IScheduler scheduler)
{
return Observable.CreateWithDisposable<TSource>(observer =>
{
var timer = new MutableDisposable();
var subscription = new MutableDisposable();
bool hasValue = false;
TSource lastValue = default(TSource);
timer.Disposable = scheduler.Schedule(recurse =>
{
if (hasValue)
{
observer.OnNext(lastValue);
}
recurse();
});
subscription.Disposable = source
.Do(value => { lastValue = value; hasValue = true; })
.Subscribe(observer);
return new CompositeDisposable(timer, subscription);
});
}
public static IObservable<TSource> RepeatAfterTimeout<TSource>(
this IObservable<TSource> source, TimeSpan timeout)
{
return source.RepeatAfterTimeout(timeout, Scheduler.TaskPool);
}
A: I had the exact same requirement once. I chose to include a default value to use if no value triggers before the first timeout. Here's the C# version:
public static IObservable<T>
AtLeastEvery<T>(this IObservable<T> source, TimeSpan timeout,
T defaultValue, IScheduler scheduler)
{
if (source == null) throw new ArgumentNullException("source");
if (scheduler == null) throw new ArgumentNullException("scheduler");
return Observable.Create<T>(obs =>
{
ulong id = 0;
var gate = new Object();
var timer = new SerialDisposable();
T lastValue = defaultValue;
Action createTimer = () =>
{
ulong startId = id;
timer.Disposable = scheduler.Schedule(timeout,
self =>
{
bool noChange;
lock (gate)
{
noChange = (id == startId);
if (noChange) obs.OnNext(lastValue);
}
//only restart if no change, otherwise
//the change restarted the timeout
if (noChange) self(timeout);
});
};
//start the first timeout
createTimer();
var subscription = source.Subscribe(
v =>
{
lock (gate)
{
id += 1;
lastValue = v;
}
obs.OnNext(v);
createTimer(); //reset the timeout
},
ex =>
{
lock (gate)
{
id += 1; //'cancel' timeout
}
obs.OnError(ex);
//do not reset the timeout, because the sequence has ended
},
() =>
{
lock (gate)
{
id += 1; //'cancel' timeout
}
obs.OnCompleted();
//do not reset the timeout, because the sequence has ended
});
return new CompositeDisposable(timer, subscription);
});
}
If you don't want to have to pass a scheduler every time, just make an overload that picks a default one and delegates to this method. I used Scheduler.ThreadPool.
This code works by using the behavior of SerialDisposable to "cancel" the previous timeout call when a new value from the source comes in. There is also a counter I use in case the timer has already elapsed (in which case Disposing the return from Schedule will not help) but the method has not yet actually run.
I investigated the possibilities of changing timeouts but did not need them for the problem I was working on. I recall that it was possible but don't have any of that code handy.
A: I think this should work the Rx way (no recursion but still involving a side effect):
public static IObservable<TSource> RepeatLastValueWhenIdle<TSource>(
this IObservable<TSource> source,
TimeSpan idleTime,
TSource defaultValue = default(TSource))
{
TSource lastValue = defaultValue;
return source
// memorize the last value on each new
.Do(ev => lastValue = ev)
// re-publish the last value on timeout
.Timeout(idleTime, Observable.Return(lastValue))
// restart waiting for a new value
.Repeat();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8585368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use each method to put result in view Instead of creating a foreach loop I want to iterate over the results and
I am using the each() method:
$collection = Comment::all();
$comment = $collection->each(function ($comment){
dd($comment->comment);
});
when I dd() I get:
"Hatter; 'so I should think."
But when I pass to view:
return view('welcome')->with('comment',$comment);
I get
[{"id":1,"post_id":5,"comment":"Hatter; 'so I should think.","created_at":"2018-04-05 15:23:20","updated_at":"2018-04-05 15:23:20"},
{"id":2,"post_id":5,"comment":"Alice gently remarked;.","created_at":"2018-04-05 15:23:20","updated_at":"2018-04-05 15:23:20"},
and so on..
This is the view:
{{$comment}}
I want to iterate through the collection and put data into $comment and then show it in the view.
A: It is quite simple like this.
Iterate then -> following the property name
@foreach($comment as $row)
<li>{{ $row->id }}</li>
<li>{{ $row->post_id}}</li>
//AND SO ON
@endforeach
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49701697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not overloading operator Good day, I'm doing some Codeforces exercises in my free time, and I had a problem to test if the user was a boy or a girl, well, my problem isn't that, i have just demonstrated the code.
While compiling my code in my computer ( I'm using version 3.0.4 for i386 ) i get no error, but codeforces gives me this error
program.pas(15,16) Error: Operator is not overloaded: "freq(Char;AnsiString):LongInt;" + "ShortInt"
program.pas(46,4) Fatal: There were 1 errors compiling module, stopping
The error wasn't clear enough to me, as the same script was perfectly compiled with my version.
The platform is using ( version 3.0.2 i386-Win32 ).
program A236;
uses wincrt, sysutils;
var
username : String;
function freq(char: char; username : String): Integer;
var
i: Integer;
begin
freq:= 0;
for i:= 1 to length(username) do
if char = username[i] then
freq:= freq + 1;
//writeln(freq);
end;
function OddUserName(username : String): Boolean;
var
i, counter: Integer;
begin
OddUserName:= false; // even
counter:= 0;
for i:= 1 to length(username) do
if freq(username[i], username) <> 1 then
delete(username, i, 1)
else
counter:= counter + 1;
if counter mod 2 <> 0 then
OddUserName:= true; // odd
//writeln(counter);
//writeln(OddUserName);
end;
begin
readln(username);
if not OddUserName(username) then
writeln('CHAT WITH HER!')
else
writeln('IGNORE HIM!');
//readkey();
end.
The error is supposed to be at this line probably :
function freq(character: char; username : String): Integer;
Thanks for everyone who helps.
A: Inside of a function, the function's name can be used as a substitute for using an explicit local variable or Result. freq() and OddUserName() are both doing that, but only freq() is using the function name as an operand on the right-hand side of an assignment. freq := freq + 1; should be a legal statement in modern Pascal compilers, see Why i can use function name in pascal as variable name without definition?.
However, it would seem the error message is suggesting that the failing compiler is treating freq in the statement freg + 1 as a function type and not as a local variable. That would explain why it is complaining about not being able to add a ShortInt with a function type.
So, you will have to use an explicit local variable instead, (or the special Result variable, if your compiler provides that), eg:
function freq(charToFind: char; username : String): Integer;
var
i, f: Integer;
begin
f := 0;
for i := 1 to Length(username) do
if charToFind = username[i] then
f := f + 1;
//writeln(f);
freq := f;
end;
function freq(charToFind: char; username : String): Integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to Length(username) do
if charToFind = username[i] then
Result := Result + 1;
//writeln(f);
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63831783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Insert IoT message array as multiple rows in DynamoDB I'm starting a new project that involves some IoT devices sending every 5 minutes their status and other info to AWS IoT.
The structure of the message is the following:
{
"SNC":"C_SN_15263217541",
"STATUS":"enable",
"PLANT":{
"PNAME":"nomeimpianto",
"DVS":{
"SD":[{
"SDSN":"LD_SN_15263987543",
"TT":"30/11/17 4:37 PM",
"STATUS":"Enable",
"TON":"3sec",
"TOFF":"6min",
"QTAC":"125",
"ALCODE":"201",
"ALDESC":"assenza scarico"
},
{
"SDSN":"LD_SN_15263987543",
"TT":"30/11/17 4:39 PM",
"STATUS":"Enable",
"TON":"3sec",
"TOFF":"6min",
"QTAC":"125",
"ALCODE":"201",
"ALDESC":"assenza scarico"
},
{
"SDSN":"LD_SN_15263997545",
"TT":"30/11/17 4:37 PM",
"STATUS":"Enable",
"TON":"3sec",
"TOFF":"6min",
"QTAC":"125"
},
{
"SDSN":"LD_SN_15263997545",
"TT":"30/11/17 4:39 PM",
"STATUS":"Enable",
"TON":"3sec",
"TOFF":"6min",
"QTAC":"125"
},
{
"SDSN":"LD_SN_15123987543",
"TT":"30/11/17 4:37 PM",
"STATUS":"Enable",
"TON":"3sec",
"TOFF":"6min",
"QTAC":"125"
},
{
"SDSN":"LD_SN_15123987543",
"TT":"30/11/17 4:39 PM",
"STATUS":"Enable",
"TON":"3sec",
"TOFF":"6min",
"QTAC":"125"
}
]
}
}
}
I created a rule that inserts the message on DynamoDB, and it's working nicely, but I'd need to create, for each message received, one row for each item in PLANT.DVS.SD.
My DynamoDB table has as hashkey the field PLANT.DVS.SD[x].SDSN and as sort field PLANT.DVS.SD[x].TT.
I tried with a DynamoDBv2 rule and I managed only to create one row per message with the whole array, but it's not what I'm looking for.
So basically the problem is that I don't know how to structure the SQL statement in the rule definition.
I know that PLANT.DVS.SD's max length is 12, so the only idea that I've got is to create 12 IoT rules that insert on DynamoDB only the element at a specific position. Although if there is a better way to solve this problem dynamically, it'd be appreciated!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48296716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WSS 3.0: change parent type for a content type I have created a hierarchy of content types. The root of my hierarchy has the content type "Document" as a parent. There are about 20 other content types derived from my root.
Now, I want to change the parent from "Document" to something else. Is it possible? Either in the web interface or in code? Can the definition of content types be dumped to a text file and then recreated? Or any other trick?
A: If you can create a feature that contains all your custom content types, you will be able to change the XML that defines each content type and it's columns.
This will give you the ability to change the content types for your site by removing the feature and installing it again with the changes (using a Solution is best).
Note that any content using the older content types will still use them after updating the feature (content types are stored at the site level, list level and on the actual item).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/122642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Migrating from XML + dataset to SQL + Entity Framework Migrating XML + .xsd dataset version to SQL + Entity Framework.
I'm a novice to SQL databases now I have to.
Current scenario: my project has many XML files (40,000+) which can be loaded to one of .xsd dataset schema(~30). There are a lot of XML separation made to quickly choose one of the dataset and load data into it. Later the dataset is loaded into the UI but going on we expect maintainability and performance issues.
So now we want to migrate to SQL + Entity Framework.
How can I best utilize the existing code to migrate?
My main concern is how can I leverage existing code to create tables and load data to those created tables in SQL server.
How can existing XML files or dataset (.xsd) be used to develop tables and data in a SQL database?
Any other suggestions in order achieve my goal will help me a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48107734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery failed: parsererror with error thrown: SyntaxError: Unexpected end of JSON input I have a contact form which is passed to a PHP script through ajax. Once the form is processed, The ajax will perform some actions depending on the response received from json_encode() function in the PHP script. The problem is I get the following error message:
parsererror SyntaxError: Unexpected end of JSON input
readyState:4 responseText:"" status:200 statusText:"OK"
When the dataType is text in the ajax call and the PHP script simply echos a text message, then code works fine, but with json, I get the above error.
I have tried header("Content-Type: application/json")and JSON.parse() with no success. I have added charset="UTF-8" in the header and tried encode_utf8() function on the array passed to json_encode too, but nothing seems to work for me.
I am posting the code for the relevant files below. Any help to resolve this problem will be highly appreciated.
contact.php
<form action="" method="post" name="contactForm" id="contactForm">
<div class="form-row">
<div id="contactFormResponse"></div>
<div class="form-col">
<label for="orderNumer">Order Number</label>
<input type="text" name="orderNumber" id="orderNumber" value="<?php echo ($_POST['orderNumber']); ?>" />
</div>
<div class="form-col">
<label for="comment">Comment *</label>
<textarea name="message" id="comment" maxlength="2000" rows="5"><?php echo ($_POST['comment']); ?></textarea>
</div>
<div class="form-col">
<label for="title">Title *</label>
<select name="title" id="title">
<option value="" <?php if ($_POST['title'] == "") {echo "selected='selected'";} ?>>Select a title...</option>
<option value="ms" <?php if ($_POST['title'] =="ms") {echo "selected='selected'";} ?>>Ms</option>
<option value="miss" <?php if ($_POST['title'] == "miss") {echo "selected='selected'";} ?>>Miss</option>
<option value="mrs" <?php if ($_POST['title'] == "mrs") {echo "selected='selected'";} ?>>Mrs</option>
<option value="mr" <?php if ($_POST['title'] == "mr") {echo "selected='selected'";} ?>>Mr</option>
<option value="other" <?php if ($_POST['title'] == "other") {echo "selected='selected'";} ?>>Other</option>
</select>
</div>
<div class="form-col">
<label for="firstName">First Name *</label>
<input type="text" name="firstName" id="firstName" value="<?php echo ($_POST['firstName']); ?>" />
</div>
<div class="form-col">
<label for="surname">Surname *</label>
<input type="text" name="surname" id="surname" value="<?php echo ($_POST['surname']); ?>" />
</div>
<div class="form-col">
<label for="email">Email Address *</label>
<input type="text" name="email" id="email" value="<?php echo ($_POST['email']); ?>" />
</div>
<div class="form-col">
<input type="submit" name="submitContactForm" id="submitContactForm" value="Submit" class="btn" />
</div>
</div>
</form>
jsCode.js
// process contact form
$("#contactForm").submit(function(e) {
e.preventDefault();
// some jQuery validation goes here...
$.ajax({
type:"POST",
url: "functions.php",
dataType: "json",
data: new FormData(this),
//data: $('form').serialize(),
processData: false,
contentType: false,
success:function(response) {
if(response.status === "OK") {
$("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$("#contactForm")[0].reset();
$(window).scrollTop(0);
} else if (response.status === "error") {
$("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$(window).scrollTop(0);
}
},
error:function(jqXHR, textStatus, errorThrown) {
console.log("JQuery failed: " + textStatus + " with error thrown: " + errorThrown);
console.log(jqXHR);
}
});
});
functions.php
// send email
function sendMessage() {
if (isset($_POST["submitContactForm"])) {
if (!$_POST["comment"]) {
$error .= "<br />Comment is required.";
}
if (!$_POST["firstName"]) {
$error .= "<br />First name is required.";
}
// validation for other form fields goes here...
if ($error) {
echo json_encode(array("status" => "error", "message" => "There were error(s)in your form: " . $error));
} else {
$to = "[email protected]";
$subject = "Message from the website";
$order_number = $_POST["orderNumber"];
$comment = $_POST["comment"];
$title = $_POST["title"];
$first_name = $_POST["firstName"];
$surname = $_POST["surname"];
$email_address = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$headers = "From: " . $title . " " . $first_name . " " . $surname . " <" . $email_address . " >";
$message = "Order Number: " . $order_number . "/r/n" . "Topic: " . $topic . "/r/n" . "Comment: " . $comment;
$result = mail($to, $subject, $message, $headers);
if (!$result) {
echo json_encode(array("status" => "error", "message" => "Message failed."));
} else {
echo json_encode(array("status" => "OK", "message" => "Message sent."));
}
}
}
}
A: you are not parsing the json response in your success function,you need to use $.parseJSON(response) like below
success:function(res) {
var response=$.parseJSON(res);
if(response.status === "OK") {
$("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$("#contactForm")[0].reset();
$(window).scrollTop(0);
} else if (response.status === "error") {
$("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$(window).scrollTop(0);
}
},
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47239264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scraping source view image link with SwiftSoup I'm trying to grab faveIcon image from a website using SwiftSoup
if rel == "icon", try element.attr("type") == "image/x-icon", element.hasAttr("href") {
favIconUrl = try element.absUrl("href")
}
The issue is, in href, there is no any direct url, and it looks like an hyperlink (not so expert on HTML), it's href="/favicon.ico" , which favicon.ico is clickable and it will open the url. My question is, how I can access to the link inside the favicon.ico? Your help would be appreciated.
Many thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73964675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing hadoop from remote machine I have hadoop set up (pseudo distributed) on a server VM and I'm trying
to use the Java API to access the HDFS.
The fs.default.name on my server is hdfs://0.0.0.0:9000 (as with localhost:9000 it wouldn't accept requests from remote sites).
I can connect to the server on port 9000
$ telnet srv-lab 9000
Trying 1*0.*.30.95...
Connected to srv-lab
Escape character is '^]'.
^C
which indicates to me that connection should work fine. The Java code I'm using is:
try {
Path pt = new Path(
"hdfs://srv-lab:9000/test.txt");
Configuration conf = new Configuration();
conf.set("fs.default.name", "hdfs://srv-lab:9000");
FileSystem fs = FileSystem.get(conf);
BufferedReader br = new BufferedReader(new InputStreamReader(
fs.open(pt)));
String line;
line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
but what I get is:
java.net.ConnectException: Call From clt-lab/1*0.*.2*2.205 to srv-lab:9000 failed on connection exception: java.net.ConnectException: Connection refused; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
Thus, any hints on why the connection is refused even though connecting through telnet works fine?
A: Your hdfs entry is wrong. fs.default.name has to be set as hdfs://srv-lab:9000. Set this and restart your cluster. that will fix the issue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35034872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: error when using cronTrigger with an expression that contains a year value I'm observing a strange behavior scheduling a job in Quartz using a CronTrigger that contains a year value.
Here is how I am creating a trigger and scheduling a job with it:
CronTrigger trigger = cronJobTriggerFactory.getObject();
trigger.setName(triggerName);
trigger.setGroup(triggerGroupName);
trigger.setCronExpression(cronSchedule);
trigger.setVolatility(false);
JobDetail job = schedulableJobFactory.getObject();
job.setName(jobName);
job.setGroup(jobGroupName);
job.setVolatility(false);
job.setDurability(true);
Date scheduleTime1 = scheduler.scheduleJob(job, trigger);
logger.info(job.getKey() + " will run at: " + scheduleTime1);
and then in my unit test I determines the "now" date, add 5 minutes to it, calculate cron expression for this date/time and call my main class schedule a job with this schedule. Here is the out put of the unit test that shows which cron expression is passed :
NotificationSchedulerTest - Today is: 9 May 2012 05:32 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 05:37 PM
NotificationSchedulerTest - cron schedule is: 0 37 17 * 4 ? 2012
However, when trying to schedule a job with this cron expression - I'm getting the following error:
org.quartz.SchedulerException: Based on configured schedule, the given trigger will never fire.
As you can see, the date is in the future relative to the date/time I am running the test... So, it should not be a problem with trying to schedule a job to run at a time in the past.
Now the next strange thing: notice that I do specify the year value in my cron expression: " 0 37 17 * 4 ? 2012".
If I modify generation of the cron expression and leave the year field as unspecified (since it is optional): " 0 37 17 * 4 ?"
Then the scheduling DOES succeed, however, the scheduler shows that the next time the job will fire is in the year 2013! (one year later.... - and of course I cannot wait that long to verify it is fired...):
NotificationSchedulerTest - Today is: 9 May 2012 06:11 PM
NotificationSchedulerTest - 5 min later is: 9 May 2012 06:16 PM
NotificationSchedulerTest - cron schedule is: 0 16 18 * 4 ?
...
NotificationScheduler - myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013
Am I missing something in these cron expressions?
A: Months in cron expressions are 1-based. That's why 0 37 17 * 4 ? 2012 is never executed: today is 10th of May and you want it to run on every day of April. When you remove the year it prints next scheduled date in 2013, but in April! myJobKey will run at: Mon Apr 01 18:16:00 EDT 2013.
Obviously your expression should be:
0 37 17 * 5 ? 2012
or to avoid confusion in the future:
0 37 17 * May ? 2012
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10524862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ipad app with two UIWebViews I have an iPad app with two UIWebviews, one on top of the other. Is there a way to have all the links that are clicked in one, open in only the other view?
A: Use this in the delegate for your first UIWebView:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[otherWebView loadRequest:request];
return NO;
}
return YES;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3273534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Optimize Kruskal Wallis Test Spotfire On spotfire i had created several Kruskal Wallis test. First i had created a pivot table and after i did a data relationship (Kruskal Wallis). Then i reflate my tests with a button (script python).
That is my code :
kruskal = Document.Calculations[0]
settings = Document.Calculations[0].CalculationSettings
settings.XColumns.Clear()
settings.YColumns.Clear()
for col in EWSWAFER.Columns:
if "HB" in col.ToString():
settings.YColumns.Add(col)
if col.ToString() == "SPLIT":
settings.XColumns.Add(col)
kruskal.Execute(CalculationExecutionPromptMode.Never)
I would like to know if it possible to optimize my code so that the test takes less time. Because sometimes my datatable has 1500 columns and 500 rows.
Thanks for your help and your ideas.
Regards, Laurent
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40842080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the difference between printf and printf_s in C? I just want to know the difference and I've already tried search on google.
printf()
printf_s()
A: I learned something new today. I've never used the _s functions and always assumed they were vendor-supplied extensions, but they are actually defined in the language standard under Annex K, "Bounds-checking Interfaces". With respect to printf_s:
K.3.5.3.3 The printf_s function
Synopsis
1 #define _ _STDC_WANT_LIB_EXT1_ _ 1
#include <stdio.h>
int printf_s(const char * restrict format, ...);
Runtime-constraints
2 format shall not be a null pointer. The %n specifier394) (modified or not by flags, field
width, or precision) shall not appear in the string pointed to by format. Any argument
to printf_s corresponding to a %s specifier shall not be a null pointer.
3 If there is a runtime-constraint violation, the printf_s function does not attempt to
produce further output, and it is unspecified to what extent printf_s produced output
before discovering the runtime-constraint violation.
Description
4 The printf_s function is equivalent to the printf function except for the explicit
runtime-constraints listed above.
Returns
5 The printf_s function returns the number of characters transmitted, or a negative
value if an output error, encoding error, or runtime-constraint violation occurred.
394) It is not a runtime-constraint violation for the characters %n to appear in sequence in the string pointed
at by format when those characters are not a interpreted as a %n specifier. For example, if the entire
format string was %%n.
C 2011 Online Draft
To summarize, printf_s performs additional runtime validation of its arguments not done by printf, and will not attempt to continue if any of those runtime validations fail.
The _s functions are optional, and the compiler is not required to support them. If they are supported, the macro __STDC_WANT_LIB_EXT1__ will be defined to 1, so if you want to use them you'll need to so something like
#if __STDC_WANT_LIB_EXT1__ == 1
printf_s( "%s", "This is a test\n" );
#else
printf( "%s", "This is a test\n" );
#endif
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55634311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: REACT : How to render component inside a div with specific classname? I'm not sure what is the best method to do this but - I have outputted list of divs. When I click on one of them, it gets given a class active. I need to show a component I made (to render) inside this particular class once the div has been clicked on. I am using next.js with react and having been using CSS modules.
Currently I tried: ReactDOM.render( <InnerDisc/>, document.getElementsByClassName(styles.active) );
but I get an error Error: Target container is not a DOM element.
Child (InnerDisc) Component
const InnerDisc = (props) => {
const active = props.active;
if (active) {
return (
<div className={styles.wrapper}>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
</div>
);
}
}
export default InnerDisc;
Main App Component
export default function Home() {
const [discs, setDiscs] = useState([
{ id: 1, top: 100 },
{ id: 2, top: 200 },
{ id: 3, top: 300 },
{ id: 4, top: 400 },
{ id: 5, top: 500 },
{ id: 6, top: 600 },
{ id: 7, top: 700 },
{ id: 8, top: 800 },
{ id: 9, top: 900 },
{ id: 10, top: 1000 },
{ id: 11, top: 1100 },
{ id: 12, top: 1200 }
])
function enlargeDisc(e, num) {
let t = e.target
if (t.classList.contains(styles.active)) {
t.classList.remove(styles.active)
discRender()
} else {
t.classList.add(styles.active)
discRender()
}
}
function discRender() {
ReactDOM.render(
<InnerDisc/>, document.getElementsByClassName(styles.active)
);
}
return (
<div className={styles.container}>
<div className={styles.wrapper}>
{discs.map((item) => (
<div className ={styles.disc} key={item.id} style=.
{{top: item.top + 'px'}} onClick={(e)=>
enlargeDisc(e, item.id)}> </div>
))}
</div>
</div>
</div>
)
}
A:
First, you're not using "num" at the function, so it can be like this:
function enlargeDisc(e) {
let t = e.target
if (t.classList.contains(styles.active)) {
t.classList.remove(styles.active)
discRender()
} else {
t.classList.add(styles.active)
discRender()
}
}
Now that you only have the event has parameter, you could just put the onClick like:
{discs.map((item) => (
<div className ={styles.disc} key={item.id} style=.
{{top: item.top + 'px'}} onClick={enlargeDisc}> </div>
Test what is reciving "enlargeDisc" event with a console.log inside the function, if there is the e.target, you could handle better using const clsList = e.target.classList, so you just need if(classList."property").
Also, you can instead using ReactDOM.render(), make a component Disc and use a State to handle when the class property gonna change or remove.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71340519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React navigation not showing the right screen I have created a navigation setup for my application that should start off with a welcome screen on the welcome screen you find two buttons, one for registering and the other for logging in.
When the user registers or logs in he get sent to other screens. I have created a stack navigator between the log in and register screen and put them in a loginFlow constant and another between the welcome screen and the loginFlow constant and the navigation between these screens works, but for some reason the welcome screen doesn't get shown first instead I get the sign up screen (register screen).
Why is that the case and how can i make the welcomeScreen get shown first
import React from "react";
import { View } from "react-native";
import WeclomeScreen from "./app/screens/WelcomeScreen";
import MainScreen from "./app/screens/MainScreen";
import AccountScreen from "./app/screens/AccountScreen";
import { Provider as AuthProvider } from "./app/context/AuthContext";
import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs";
import SignupScreen from "./app/screens/SignupScreen";
import { createAppContainer, createSwitchNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import ResultShowScreen from "./app/screens/ResultShowScreen";
import ResolveAuthScreen from "./app/screens/ResolveAuthScreen";
import SigninScreen from "./app/screens/SigninScreen";
import ArticleSaveScreen from "./app/screens/ArticleSaveScreen";
import { setNavigator } from "./app/navigationRef";
const articleListFlow = createStackNavigator({
Main: MainScreen, // screen with diffrent articles categories
ResultsShow: ResultShowScreen, // article details screen
});
const loginFlow = createStackNavigator({
Signup: SignupScreen,
Signin: SigninScreen,
});
loginFlow.navigationOptions = () => {
return {
headerShown: false,
};
};
articleListFlow.navigationOptions = {
title: "News Feed",
tabBarIcon: ({ tintColor }) => (
<View>
<Icon style={[{ color: tintColor }]} size={25} name={"ios-cart"} />
</View>
),
activeColor: "#ffffff",
inactiveColor: "#ebaabd",
barStyle: { backgroundColor: "#d13560" },
};
const switchNavigator = createSwitchNavigator({
ResolveAuth: ResolveAuthScreen,
MainloginFlow: createStackNavigator({
WelcomeScreen: WeclomeScreen,
loginFlow: loginFlow,
}),
mainFlow: createMaterialBottomTabNavigator(
{
articleListFlow: articleListFlow,
ArticleSave: ArticleSaveScreen, // we dont need this one
Account: AccountScreen,
},
{
activeColor: "#ffffff",
inactiveColor: "#bda1f7",
barStyle: { backgroundColor: "#6948f4" },
}
),
});
const App = createAppContainer(switchNavigator);
export default () => {
return (
<AuthProvider>
<App
ref={(navigator) => {
setNavigator(navigator);
}}
/>
</AuthProvider>
);
};
here is the content of ResolveAuthscreen :
import React, { useEffect, useContext } from "react";
import { Context as AuthContext } from "../context/AuthContext";
const ResolveAuthScreen = () => {
const { tryLocalSignin } = useContext(AuthContext);
useEffect(() => {
tryLocalSignin();
}, []);
// not returning anything since just waiting to check the token
// will transition to signin or signup very quickly
return null;
};
export default ResolveAuthScreen;
A: As you have mentioned in your comments, you have an issue in your tryLocalSignin method. In that method, if there is no any token, you are navigating the user to the Signup screen. Instead of navigating to the Signup screen, navigate to the WelcomeScreen screen like:
const tryLocalSignin = (dispatch) => async () => {
const token = await AsyncStorage.getItem("token");
if (token) {
dispatch({ type: "signin", payload: token });
navigate("Main");
} else {
navigate("WelcomeScreen");
}
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62002774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Defining own CONTROL exception The subject says it all: can I define own control exception which would handled by the CONTROL block? Applying the X::Control role is useless:
class CX::Whatever does X::Control {
method message { "<whatever control exception>" }
}
do {
CX::Whatever.new.throw;
CONTROL {
say "CONTROL!!!";
default {
say "CONTROL: ", $_.WHAT;
}
}
}
By looking into the core sources I could guess that only a predefined set of exceptions is considered suitable for CONTROL, but not sure I didn't miss a thing.
A: This hasn't been possible in the past, however you're far from the first person to ask for it. Custom control exceptions would provide a way for framework-style things to do internal control flow without CATCH/default in user code accidentally swallowing the exceptions.
Bleeding edge Rakudo now contains an initial implementation of taking X::Control as an indication of a control exception, meaning that the code as you wrote it now does as you expect. This will, objections aside, appear in the 2019.01 Rakudo release, however should be taken as a draft feature until it also appears in a language specification release.
Further, a proposed specification test has been added, so unless there are objections then this feature will be specified in a future Perl 6 language release.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54155892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to handle c# WPF thread in MVVM view model I am having a bear of a time figuring out how to handle a Thread from a class outside my ViewModel.
The Thread originates from a Track class. Here is the ResponseEventHandler code in Track:
public delegate void ResponseEventHandler(AbstractResponse response);
public event ResponseEventHandler OnResponseEvent;
When a "command" method is processed from within my Track object, the following code runs the OnResponseEvent, which sends a message in a Thread back to my ViewModel:
if (OnResponseEvent != null)
{
OnResponseEvent(GetResponseFromCurrentBuffer());
}
GetResponseFromCurrentBuffer() merely returns a message type which is a pre-defined type within the Track.
My MainWindowViewModel constructor creates an event handler for the OnResponseEvent from the Track:
public MainWindowViewModel()
{
Track _Track = new Track();
_Track.OnResponseEvent +=
new Track.ResponseEventHandler(UpdateTrackResponseWindow);
}
So, the idea is that every time I have a new message coming from the OnResponseEvent Thread, I run the UpdateTrackResponseWindow() method. This method will append a new message string to an ObservableCollection<string> list property called TrackResponseMessage:
private void UpdateTrackResponseWindow(AbstractResponse message)
{
TrackResponseMessage.Add(FormatMessageResponseToString(message));
}
The FormatMessageResponseToString() method merely compares the message with all pre-defined message types within the Track, and does some nifty string formatting.
The main problem is: The UI disappears when TrackResponseMessage.Add() is run. The executable is still running in the background, and the only way to end the task is to shut down Visual Studio 2010.
TrackResponseMessage is a public property within my ViewModel:
public ObservableCollection<String> TrackResponseMessage
{
get { return _trackResponseMessage; }
set
{
_trackResponseMessage = value;
RaisePropertyChanged("TrackResponseMessage");
}
}
Is there a need for me to marshal the Thread coming from the Track object to my ViewModel? Any example code would be very appreciated!
A:
Is there a need for me to marshall the thread comming from the Track.cs object to my viewmodel? Any example code would be very appreciated!
Yes. Unfortunately, while INotifyPropertyChanged will handle events from other threads, INotifyCollectionChanged does not (ie: ObservableCollection<T>). As such, you need to marshal back to the VM.
If the VM is being create from the View (View-First MVVM) or is known to be created on the UI thread, there's a good option using .NET 4 tasks:
TaskScheduler uiScheduler;
public MainWindowViewModel()
{
uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Track _Track = new Track();
_Track.OnResponseEvent += new Track.ResponseEventHandler(UpdateTrackResponseWindow);
}
Then, later, your event handler can do:
private void UpdateTrackResponseWindow(AbstractResponse message)
{
Task.Factory.StartNew(
() => TrackResponseMessage.Add(FormatMessageResponseToString(message)),
CancellationToken.None, TaskCreationOptions.None,
uiScheduler);
}
This has the nice advantage of not pulling WPF or Silverlight specific resources and types into your ViewModel class (ie: Dispatcher), while still providing all of the benefits. It also works, unchanged, in other routines with thread affinity (ie: WCF service work).
A: If the RaisePropertychanged is executed on a thread other than the UI thread AND the event handler for the event touches the UI you need to switch to the UI thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6538633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there a simple way to remove one dependency from the local gradle cache? The local gradle cache stores copies of maven/gradle dependencies. How to clear gradle cache? covers how to clear the whole cache, but not individual packages.
Is there a simple way to remove one package from the local gradle cache? This would be useful, for example, when actively developing a library. To test a minor library change, I currently have to clear the entire cache from the filesystem so an old cached version of the library is not used.
I understand it is also possible to use the gradle ResolutionStrategy described in How can I force gradle to redownload dependencies?. I would prefer not to change the gradle configuration because most of the time and for most developers, the default caching behavior is fine.
A: So here's a quick script I whipped up:
seekanddestroy.gradle
defaultTasks 'seekAndDestroy'
repositories{ //this section *needs* to be identical to the repositories section of your build.gradle
jcenter()
}
configurations{
findanddelete
}
dependencies{
//add any dependencies that you need refreshed
findanddelete 'org.apache.commons:commons-math3:3.2'
}
task seekAndDestroy{
doLast {
configurations.findanddelete.each{
println 'Deleting: '+ it
delete it.parent
}
}
}
You can invoke this script by running gradle -b seekanddestroy.gradle
Demo of how it works:
if your build.gradle looks like this:
apply plugin:'java'
repositories{
jcenter()
}
dependencies{
compile 'org.apache.commons:commons-math3:3.2'
}
First time build, includes a download of the dependency:
λ gradle clean build | grep Download
Download https://jcenter.bintray.com/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar
Second clean build, uses cached dependency, so no download:
λ gradle clean build | grep Download
Now run seekanddestroy:
λ gradle -b seekanddestroy.gradle -q
Deleting: .gradle\caches\modules-2\files-2.1\org.apache.commons\commons-math3\3.2\ec2544ab27e110d2d431bdad7d538ed509b21e62\commons-math3-3.2.jar
Next build, downloads dependency again:
λ gradle clean build | grep Download
Download https://jcenter.bintray.com/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar
A: Works great, but for newer versions of gradle, use this instead:
task seekAndDestroy{
doLast {
configurations.findanddelete.each{
println 'Deleting: '+ it
delete it.parent
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36507115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Cannot run python file I am trying to run a stand-alone python file partitions.py that is in my home folder. When I type the command "python3 partition.py" the script runs.
However, when I type "python3 -m partition.py" it gives me an error
"/usr/local/bin/python3: No module named partition.py"
I do not know why this is the case. Any help would be greatly appreciated.
Thanks
A: To run the module as script directly use:
python3 -m partition
(without the .py ending).
That will cause python to search sys.path for a module called partition and execute it. partition.py in this context would mean a module in a file partition/py.py.
A: See the doc, specifically that the module must be on the path, and the extension shouldn't be included.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21269481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I saved an image in local database. whenever i try to open using glide. i get the following log enter image description here
fail to get the list and getting null pointer exception.
whenever i add the product into cart then it proceed into cart but image is not loaded and getting error of null pointer exception
class CartFragment : Fragment() {
private lateinit var binding: FragmentCartBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentCartBinding.inflate(layoutInflater)
val preference = requireContext().getSharedPreferences("info", AppCompatActivity.MODE_PRIVATE)
val editor = preference.edit()
editor.putBoolean("isCart",false)
editor.apply()
val dao = AppDatabase.getInstance(requireContext()).productDao()
dao.getAllProducts().observe(requireActivity()){
binding.cartRecycler.adapter = CartAdapter(requireContext(),it)
totalCost(it)
}
return binding.root
}
private fun totalCost(data: List<ProductModel>) {
var total = "0"
for (item in data){
total += item.productSp!!.toString()
}
binding.textView12.text = "Total item in cart is ${data.size}"
binding.textView13.text = "Total Cost $total"
binding.checkout.setOnClickListener {
val intent = Intent(context, AddressActivity::class.java)
intent.putExtra("totalCost",total)
startActivity(intent)
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74811731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to create geohash tree in neo4j Based on a problem here an expert have answered with this code:
CALL spatial.addPointLayerGeohash('my_geohash_layer_name')
CREATE (n:Node {latitude:60.1,longitude:15.2}) WITH n
CALL spatial.addNode('my_geohash_layer_name',n) YIELD node
RETURN node
to create a geohash tree that organise spatial nodes.
so i tried that with two spatial nodes but unlike R-tree the spatial nodes aren't linked to the layer with any connection !? is this code true ? or what is wrong ?
A: If you want an in-graph tree structure as an index, you need to use the RTree index (which is the default in Neo4j Spatial). If you want a geohash index, there will be no tree in the graph because geohashes are being stored as strings in a lucene index for string prefix searches. String prefix searches are a common way of searching geohash based indexes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50913970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why my text box's border color doesn't grow? I have a textbox as follow.
<div class="form-group">
<label for="passwordr">Repeat Password</label>
<input type="password" class="form-control" required="" name="passwordr" value="">
<span class="help-block">Type the password again. Passwords must match.</span>
</div>
I am expecting to have a textbox with a glowing colour when the user click the textbox.
But it doesn't happen now.
Please see it here.
I have another setting, it works here.
I think pretty much the same.
The second one has rounded corner and the light grows.
Why the first one doesn't have rounded corner and the light doesn't glow?
EDIT:
A: !imporant for apply css forcefully and effects same as bootstrap.
.form-control:focus{
box-shadow: 0 0 5px rgba(81, 203, 238, 1) !important;
border: 1px solid rgba(81, 203, 238, 1) !important;
}
Working Fiddle
A: If you want an input to have a different/special appearance once selected, use the :focus CSS pseudo-class.
A simple example:
#myInput:focus {
border: 1px solid red;
}
PS. I assume you mean "glow", not "grow", and certainly not "blow" :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35810144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: list of numbers to a stack back to a list Imagine four railroad cars positioned on the input side of the track in the figure above, numbered 1, 2, 3, and 4, respectively. Suppose we perform the following sequence of operations (which is compatible with the direction of the arrows in the diagram and does not require cars to "jump over" other cars):
As a result of these operations the original order of the cars, 1234, has been changed into 2431.
The operations above can be more concisely described by the code SSXSSXXX, where S stands for move a car from the input into the stack, and X stands for move a car from the stack into the output. Some sequences of S's and X's specify meaningless operations, since there may be no cars available on the specified track; for example, the sequence SXXSSXXS cannot be carried out. (Try it to see why.)
Write and test a function that emulates the train car switching:
# [import statements]
import q2_fun
# [constants]
# [rest of program code]
cars = [1, 2, 3, 4]
s_x = input("enter a code with s's and x's to move one stack to another")
list1 = q2_fun.train_swicth(cars, s_x)
print(list1)
from stack_array import Stack
def train_swicth(cars, s_x):
s = Stack()
list1 = []
for i in range(len(s_x)):
if s_x[i] == "s":
a = s_x.append()
s.push(a)
elif s_x[i] == "x":
b = s.pop()
list1.append(b)
return list1
I keep getting [] as the return and it should be 2431 with ssxssxxx. Can I get some help?
A: if I understood you right you could do:
def train_swicth(cars, s_x):
i=0
s=[]
out=[]
for c in s_x:
if c=="s":
s.append(cars[i])
i+=1
elif c=="x":
out.append(s.pop())
return out
as lists can be used as stacks with append as push-operation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21420443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ImageProcessing in WPF (Fant BitmapScalingMode) My application presents an image that can be scaled to a certain size. I'm using the Image WPF control with the scaling method of FANT.
However, there is no documentation how this scaling algorithm works.
Can anyone reference me to the relevant link for this algorithm description?
Nir
A: Avery Lee of VirtualDub states that it's a box filter for downscaling and linear for upscaling. If I'm not mistaken, "box filter" here means basically that each output pixel is a "flat" average of several input pixels.
In practice, it's a lot more blurry for downscaling than GDI's cubic downscaling, so the theory about averaging sounds about right.
A: I know what it is, but I couldn't find much on Google either :(
http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4056711 is the appropriate paper I think; behind a pay-wall.
You don't need to understand the algorithm to use it. You should explicitly make the choice each time you create a bitmap control that is scaled whether you want it high-quality scaled or low quality scaled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2018881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: My jQuery script makes always the first look like focused when not Thing is, no matter which <select> I'm clicking, it always looks like the first one gets focused when actually the second one isn't.
The code works, but I want to implement the $(this) thing so the button I press is the one who must look focused, and I can't figure how to do it.
Here's my jsfiddle: http://jsfiddle.net/Arkl1te/TeNaf/
A: You have all <div>s with the same ID. You should not duplicate the IDs. They should be unique. And also, a <label> cannot have a <div> inside it.
Since you are using $("#select"), it selects only the first <div>. Make sure your IDs are unique and try it. This code works for you:
$(document).ready( function(){
$('select').focus( function(){
$(this).closest("div").addClass('selected');
});
$('select').focusout( function(){
$(this).closest("div").removeClass('selected');
});
});
Fiddle: http://jsfiddle.net/praveenscience/TeNaf/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16901841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to align two figures with different labels? These are two figures in my paper. Apparently, the two axes are not in alignment. How can I make sure that two figures generated independently align with each other? The problem is that the two figures have different labels and different ticklabels. That makes the positions of the axes different.
A: For each subplot, find the x/y/width/height. Then adjust the second (or both) to be the same height and the same "y"
get(gca,'position')
set(gca, 'position', [0.1300 0.15 0.3347 0.3412]) %x y width height, dummy numbers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55762269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSIS "Bad text encoding" compilation error from _EndSwitch macro We've been using NSIS 2.50 for some time now and I'm trying to update to the newest 3.0x version. I'm using Unicode true. I've ran into an issue, which I'm failing to understand. We use a switch for mapping native language names to language IDs, more or less like this:
${Switch} "${LANGNAME}"
${Case} "${LANGFILE_ALBANIAN_NAME}"
StrCpy $0 "${LANG_ALBANIAN}"
${Break}
${Case} "${LANGFILE_ARABIC_NAME}"
StrCpy $0 "${LANG_ARABIC}"
${Break}
; Other cases
${EndSwitch}
The error I'm getting from compilation:
Bad text encoding: C:\Users\me\AppData\Local\Temp\nst9352.tmp:9
!include: error in script: "C:\Users\me\AppData\Local\Temp\nst9352.tmp" on line 9
Error in macro _EndSwitch on macroline 9
The temporary file is apparently created by LogicLib, which then tries to include it. The file really doesn't have any valid Unicode encoding (I'm posting just a snippet from the file):
!insertmacro _== `$2` `Shqip` _LogicLib_Label_433 ""
!insertmacro _== `$2` `???????` _LogicLib_Label_434 ""
!insertmacro _== `$2` `Catal�` _LogicLib_Label_441 ""
The strings with invalid UTF-8 characters seem to be encoded in various ANSI encodings (some seem to be Western European, some Central European etc.), while the question marks are saved as real question marks (0x3F). ${LANGFILE_NLFID_NAME} is defined in language files as native name using the LANGFILE macro from LangFile.nsh. I looked at the language files and they are encoded in UTF-8 BOM and look all right. So it looks like the native name is re-encoded to ANSI or something for ${LANGFILE_NLFID_NAME}?
I'm pretty sure I'm making some stupid mistake, but I can't really figure out what it is.
A: Looks like a bug, it will be fixed in the next release.
Since you are not using the fall-through Switch feature you can just use Select or If/ElseIf instead:
${Select} "${LANGNAME}"
${Case} "${LANGFILE_ALBANIAN_NAME}"
DetailPrint LANG_ALBANIAN
${Case} "${LANGFILE_ARABIC_NAME}"
DetailPrint LANG_ARABIC
${EndSelect}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73530905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recursively get every nth element from array Javascript I have an array of colors that I need to recursively get every nth element to generate a legend. The colors array might look something like this:
[
'red',
'dark_red',
'dark_dark_red',
'green',
'dark_green',
'dark_dark_green',
'blue',
'dark_blue',
'dark_dark_blue'
]
I have a variable amount of legend items that I want to generate colors for. I want to be able to generate the colors based off of the index when looping through the legend items in a pattern like so:
1 - green
2 - blue
3 - dark_red
4 - dark_green
5 - dark_blue
6 - etc...
How might I go about this? I tried using modulus and a double-loop statement but was not able to generate the colors properly.
A: To get the nthItems:
function nthItems(array, n){
const r = [];
for(let i=n-1,l=array.length; i<l; i+=n){
r.push(array[i]);
}
return r;
}
const a = [
'red',
'dark_red',
'dark_dark_red',
'green',
'dark_green',
'dark_dark_green',
'blue',
'dark_blue',
'dark_dark_blue'
];
console.log(nthItems(a, 2));
console.log(nthItems(a, 3));
A: StackSlave's answer is the most efficient way but if you want a recursive way you could do
const a = [
'red',
'dark_red',
'dark_dark_red',
'green',
'dark_green',
'dark_dark_green',
'blue',
'dark_blue',
'dark_dark_blue'
];
const nthItems = (array, n) => {
const results = [];
const addItem = index => {
if (index < array.length) {
results.push(array[index]);
addItem(index + n);
}
};
addItem(0);
return results;
};
console.log(nthItems(a, 2));
console.log(nthItems(a, 3));
But this is recursive purely for the sake of recursion, it adds values to the stack unnecessarily when a for loop will do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62886285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rxjava StackOverflowError exception in long chain I build very long rxjava chain (with retrofit request) with a lot of operators: doOnNext, doOnError, switchIfEmpty, onErrorResumeNext, flatMap
On some devices (Android 4.1 for example) it throws StackOverflowError exception when chain go by the longest route.
Are there some ways or best practices to optimize chains or prevent StackOverflowError?
Now I see only one way - break chain, and call second part from first onComplete(OnNext), but it is not reactive way, I think.
Yet another way - change threads with .subscribeOn(Schedulers.newThread()); operator. Seems not the best solution too.
My code:
1) code with subscribing
fastSearch(keyphrase)
.onErrorResumeNext(throwable -> {
return correctKeyphraseAndSearch(keyphrase);
})
.doOnNext(resultsDao -> {...})
.subscribe(...)
2) helper methods
public static Observable<SearchResultsDao> fastSearch(final String keyphrase) {
String SRD = "true";
final HttpQueryParams params = new HttpQueryParams();
//read from cache chain
Observable<SearchResultsDao> cacheChain = getCache().fastSearch(keyphrase, SRD)
.doOnNext(...)
.doOnError(...)
.onErrorResumeNext(new HandleNoCacheEntry<SearchResultsDao>(params)); //save some data to "params", and return Observable.empty
//network request chain
Observable<SearchResultsDao> networkChain = getApi().fastSearch(keyphrase, SRD)
.retryWhen(new OnNewSessionRequired())
.doOnNext(new WriteToCacheAction<SearchResultsDao>(params)); //save to cache
//combine cache+network chains
return cacheChain
.switchIfEmpty(networkChain)
.doOnNext(resultsDao -> resultsDao.setKeyphrase(keyphrase));
}
public static Observable<SearchResultsDao> correctKeyphraseAndSearch(final String keyphrase) {
return mainDiv()
.flatMap(str -> syntax(str, keyphrase, true))
.flatMap(syntaxDao -> {
//get corrected keyphrase from server
StringBuilder newKeyphrase = ... ;
//repeat search request with new keyphrase
return fastSearch(newKeyphrase.toString());
});
}
3) some comments:
mainDiv() and syntax() methods identical to fastSearch() method, but doing another requests to server
getCache().fastSearch() - create observable that reads data from own cache (retrofit-like: getCache() implements retrofit Api methods interface)
Stacktrace:
Uncaught Exception
java.lang.IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:150)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:264)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.StackOverflowError
okhttp3.HttpUrl.newBuilder (HttpUrl.java:633)
retrofit2.RequestBuilder.addQueryParam (RequestBuilder.java:144)
retrofit2.ParameterHandler$Query.apply (ParameterHandler.java:109)
retrofit2.ServiceMethod.toRequest (ServiceMethod.java:108)
retrofit2.OkHttpCall.createRawCall (OkHttpCall.java:178)
retrofit2.OkHttpCall.execute (OkHttpCall.java:162)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request (RxJavaCallAdapterFactory.java:171)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OnSubscribeRedo$2$1.setProducer (OnSubscribeRedo.java:272)
rx.Subscriber.setProducer (Subscriber.java:205)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:152)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:138)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OnSubscribeRedo$2.call (OnSubscribeRedo.java:278)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue (TrampolineScheduler.java:80)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule (TrampolineScheduler.java:59)
rx.internal.operators.OnSubscribeRedo$5.request (OnSubscribeRedo.java:366)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.setProducer (OperatorSwitchIfEmpty.java:106)
rx.Subscriber.setProducer (Subscriber.java:205)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:358)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:55)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.subscribeToAlternate (OperatorSwitchIfEmpty.java:78)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onCompleted (OperatorSwitchIfEmpty.java:71)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4$1.onCompleted (OperatorOnErrorResumeNextViaFunction.java:125)
rx.Observable$EmptyHolder$1.call (Observable.java:1123)
rx.Observable$EmptyHolder$1.call (Observable.java:1120)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:56)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorMerge$MergeSubscriber.emitScalar (OperatorMerge.java:368)
rx.internal.operators.OperatorMerge$MergeSubscriber.tryEmit (OperatorMerge.java:330)
rx.internal.operators.OperatorMerge$InnerSubscriber.onNext (OperatorMerge.java:807)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onNext (OperatorSwitchIfEmpty.java:89)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onNext (OperatorOnErrorResumeNextViaFunction.java:153)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:53)
com.testrx.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onNext (OperatorSwitchIfEmpty.java:89)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onNext (OperatorOnErrorResumeNextViaFunction.java:153)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
rx.internal.operators.OperatorDoOnEach$1.onNext (OperatorDoOnEach.java:85)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:53)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.onError (OperatorSwitchIfEmpty.java:116)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OnSubscribeRedo$4$1.onError (OnSubscribeRedo.java:331)
rx.internal.operators.OperatorMerge$MergeSubscriber.reportError (OperatorMerge.java:243)
rx.internal.operators.OperatorMerge$MergeSubscriber.checkTerminate (OperatorMerge.java:779)
rx.internal.operators.OperatorMerge$MergeSubscriber.emitLoop (OperatorMerge.java:540)
rx.internal.operators.OperatorMerge$MergeSubscriber.emit (OperatorMerge.java:529)
rx.internal.operators.OperatorMerge$InnerSubscriber.onError (OperatorMerge.java:813)
rx.Observable$ThrowObservable$1.call (Observable.java:10200)
rx.Observable$ThrowObservable$1.call (Observable.java:10190)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:235)
rx.internal.operators.OperatorMerge$MergeSubscriber.onNext (OperatorMerge.java:145)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OperatorMap$1.onNext (OperatorMap.java:54)
rx.internal.operators.OnSubscribeRedo$3$1.onNext (OnSubscribeRedo.java:307)
rx.internal.operators.OnSubscribeRedo$3$1.onNext (OnSubscribeRedo.java:289)
rx.internal.operators.NotificationLite.accept (NotificationLite.java:150)
rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext (SubjectSubscriptionManager.java:253)
rx.subjects.BehaviorSubject.onNext (BehaviorSubject.java:160)
rx.internal.operators.OnSubscribeRedo$2$1.onError (OnSubscribeRedo.java:242)
retrofit2.adapter.rxjava.OperatorMapResponseToBodyOrError$1.onNext (OperatorMapResponseToBodyOrError.java:43)
retrofit2.adapter.rxjava.OperatorMapResponseToBodyOrError$1.onNext (OperatorMapResponseToBodyOrError.java:38)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request (RxJavaCallAdapterFactory.java:173)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OnSubscribeRedo$2$1.setProducer (OnSubscribeRedo.java:272)
rx.Subscriber.setProducer (Subscriber.java:205)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:152)
retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call (RxJavaCallAdapterFactory.java:138)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OnSubscribeRedo$2.call (OnSubscribeRedo.java:278)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue (TrampolineScheduler.java:80)
rx.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule (TrampolineScheduler.java:59)
rx.internal.operators.OnSubscribeRedo$5.request (OnSubscribeRedo.java:366)
rx.internal.producers.ProducerArbiter.setProducer (ProducerArbiter.java:126)
rx.internal.operators.OperatorSwitchIfEmpty$AlternateSubscriber.setProducer (OperatorSwitchIfEmpty.java:106)
rx.Subscriber.setProducer (Subscriber.java:205)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:358)
rx.internal.operators.OnSubscribeRedo.call (OnSubscribeRedo.java:55)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.subscribeToAlternate (OperatorSwitchIfEmpty.java:78)
rx.internal.operators.OperatorSwitchIfEmpty$ParentSubscriber.onCompleted (OperatorSwitchIfEmpty.java:71)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4$1.onCompleted (OperatorOnErrorResumeNextViaFunction.java:125)
rx.Observable$EmptyHolder$1.call (Observable.java:1123)
rx.Observable$EmptyHolder$1.call (Observable.java:1120)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError (OperatorOnErrorResumeNextViaFunction.java:141)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
rx.internal.operators.OperatorDoOnEach$1.onError (OperatorDoOnEach.java:71)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:56)
com.testrx.app.retrofit.api.CacheHelper$1.call (CacheHelper.java:46)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable$2.call (Observable.java:162)
rx.Observable$2.call (Observable.java:154)
rx.Observable.unsafeSubscribe (Observable.java:8314)
rx.internal.operators.OperatorSubscribeOn$1.call (OperatorSubscribeOn.java:94)
rx.internal.schedulers.ScheduledAction.run (ScheduledAction.java:55)
java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:442)
A: Stackoverflows rarely happen with typical streams; without code I can't be sure what's wrong.
In earlier versions of RxJava, there were reentrancy problems in some operators that could result in StackOverflows but we haven't received any bug reports like it in some time now. Please make sure you are using the latest RxJava from the 1.x line (the RxAndroid plugin's dependency may need overriding as it is infrequently updated in this regard).
There are a few things you can do:
*
*compact subsequent doOnNext and doOnError calls into doOnEach
*add observeOn(Schedulers.computation()) occasionally
*avoid chaining too many mergeWiths, collect up sources into a List and use merge(Iterable)
*upgrade to RxJava 2.x which should have less stack depth (have not verified)
Edit:
Based on the stacktrace, my undestanding is that you have too many empty sequences and switchIfEmpty keeps deepening the stack when switching from one empty sequence to the next. As you found out, subscribeOn helps "restart" the stack. I'll investigate possible resolutions within RxJava itself.
A: The cause of this problem was Jack compiler (https://source.android.com/source/jack.html) which I use in the project for lambdas support. I switched it off and now everything works fine
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42363452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to prevent Visual C Compiler from optimizing out "unused" global variable
Possible Duplicate:
Why does const imply internal linkage in C++, when it doesn’t in C?
What is external linkage and internal linkage in C++
I have a two C files that I'm trying to compile to an executable. One file contains only a single declaration as follows (simplifed).
const char *foo[2] = {"thing1", "thing2"};
The second c file does this
extern const char *foo[2];
main()
{
//Code that does stuff with foo
}
When compiling I get a linker error that foo is an unresolved external symbol. I'm assuming the compiler is optimizing out foo. Any ideas here?
A: There's nothing wrong with your declarations. The code should compile and link as is, assuming you add explicit int as the return type of your main. The only explanation for the linker error I can come up with is that you are forgetting to supply all required object files to the linker.
The answers that attempt to explain this issue through the fact that in C++ const objects have internal linkage are misleading and irrelevant. The above object foo is not a const object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13887120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Oracle: Finding the stored procedure that modifies record on a table I've got a C# code that calls stored procedures and UPDATES a table. Can I monitor each operation made on this table by a SID.
A: Yes, you can do this at the database level using Oracle auditing. See here for good writeup and examples of its use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9136798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating new variables in sas I am trying to create 3 new variables and have used this code however keep getting an error in my log, I am not sure what this issue is:
Data birthdata
SET birthdata;
native=.;
if race=3 THEN native=1;
if race=1 THEN native=0;
aarace=.;
if race=2 then aarace=1;
if race=1 then aarace=0;
nonwhite=.;
if (1<race=.) then nonwhite=1;
if race=1 then nonwhite=0;
label native = "Maternal race"
aarace = "Maternal race"
nonwhite = "Maternal race";
FORMAT native native. aarace aarace. nonwhite nonwhite.;
run;
`
A: You missed ; in first line of data step.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71820917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Export data to pdf in Laravel downloading only 2 pages irrespective of data I have huge amount of data in my DB. But when I try to export data to pdf in Laravel only 2 pages are downloading.
$members = DB::table('members')->where('id_card_issued',0)->get();
$pdf = PDF::loadView('admin.myPDF', compact('members'));
return $pdf->download('id_card.pdf');
I want all the data to be downloaded. But now only getting last 2 data in my database table
A: Are you trying to do to download large files from the server, I have changed the below settings in php.ini file in mine to do so :
Upload_max_filesize - 1500 M
Max_input_time - 1000
Memory_limit - 640M
Max_execution_time - 1800
Post_max_size - 2000 M
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57790141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript unit testing framework that doesn't work in strict mode Is there a way to unit test code from not strict mode. Most of the testing frameworks, mocha, jest, etc are strict mode only. My code involves use of eval that needs non-strict mode scope that I cannot rewrite into strict mode compatible form. Any idea or do I need to write my own unit testing framework.
A: I ended up using Karma with jasmine. Setting it to browser mode means no modules and no strict mode, yay.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71093181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Clear filter from Table I'm trying to run a macro that replaces data in a table in Excel, when the data might initially be filtered.
The code should remove the filter first, then run the rest of the code.
I tried the "Autofilter" command, but then the normal filter option on the table's range weren't visible, and I had to manually create the filter option again (not a big deal to me, but other people use this file).
Is there a way to clear the filter WITHOUT removing filters from the table?
A: For a Table, you can simply use the ShowAllData method of its Autofilter object:
activesheet.listobjects(1).autofilter.showalldata
Note this won't error even if there is no filter currently applied.
A: This expands on the answer from @Rory (the go-to-answer I look up every time I can't remember the syntax). It avoids errors that occur when the table doesn't contain an auto-filter.
The section If Not .AutoFilter Is Nothing checks for the AutoFilter object property of the ListObject (table). If it Is Nothing then that table had it's auto-filter removed.
With Activesheet.Listobjects(1)
If not .AutoFilter Is Nothing Then .AutoFilter.ShowAllData
End With
A: Hi Guys use this "Worksheets("Sheet1").ListObjects(1).Range.AutoFilter = False" and please note if already filter applied it will remove filter on the other hand if filter not applied before it will apply the filter.
A: I am finding that the "...ClearAllData" method fails.
Sneaky - not hugely elegant solution - that works by field (so cumbersome if you need to do the whole table), but easy if you just have one field (e.g. field 2 in my example) is to use the wildcard:
ActiveSheet.ListObjects(1).Range.AutoFilter Field:=2, Criteria1:="=*"
A: ActiveSheet.ShowAllData
Or
Cells.AutoFilter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33197641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: decrypt web.config file for specific project on a local machine I have a project that is running on the server. I want to modify it on a local machine, but connection strings in the web.config file are encrypted using regiis. To decrypt it I tried this article:
http://ryaremchuk.blogspot.com/2012/11/encrypting-and-decrypting-webconfig.html
I copied the project to a folder on the hard desk on my local machine; so its path is C:\project1.
In the prompt interface I reached: C:\windows\Microsoft.NET\Framework\v4.0.30319. Then I used this command with no luck:
aspnet_regiis -pd "connectionStrings" -app "C:\project1"
Is my command wrong? Should the project be in a different path?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40005823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get the detached object from the session in the Hibernate events PostLoadEvent and PostUpdateEvent I have an entity which has transient fields, after the merge / load i loose all the values of these transient fields in the returned managed object.
What i want to do , is to copy the values of the transient fields from the detached object to the managed object.
The solution that i want to follow is based on the events in Hibernate, but i only have access to the detached object (the original entity) in the MergeEventListener and not in the PostUpdateEventListener and PostLoadEventListener .
Do you have any suggestion to find a solution to this issue ?
Thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51872268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Window 200x200 with circle 200x200 doesn't fit I'm trying to do something very simple. I'm trying to create a window that has a circle in it that fits perfectly. I made the window 200x200 and the circle 200x200 and it looks like this
This is the code I made:
using System.Windows.Forms;
using System.Drawing;
class HalloForm : Form
{
public HalloForm()
{
this.Text = "Hallo";
this.BackColor = Color.LightGray;
this.Size = new Size(200, 200);
this.Paint += this.tekenScherm;
this.AutoScaleMode = AutoScaleMode.Font;
}
void tekenScherm(object obj, PaintEventArgs pea)
{
tekenSmiley(pea, 0, 0, 200);
/*pea.Graphics.DrawString("Hallo!"
, new Font("Tahoma", 30)
, Brushes.Blue
, 10, 10
);*/
//pea.Graphics.DrawArc(Pens.Black, )
//pea.Graphics.FillEllipse(Brushes.Black, new Rectangle(new Point(x + 40, y + 40), new Size(50, 50)));
//pea.Graphics.FillEllipse(Brushes.Black, new Rectangle(new Point(x + 110, y + 40), new Size(50, 50)));
//pea.Graphics.FillPolygon(Brushes.Black, new Point[] { new Point(x + 85, x + 120), new Point(x + 115, y + 120), new Point(x + 100, x + 90) });
}
private void tekenSmiley(PaintEventArgs pea, int x, int y, int grootte)
{
pea.Graphics.FillEllipse(Brushes.Yellow, new Rectangle(new Point(x, y), new Size(grootte, grootte)));
}
}
class HalloWin3
{
static void Main()
{
HalloForm scherm;
scherm = new HalloForm();
Application.Run(scherm);
}
}
I tried different auto scale modes and none of them changed anything. Can you help me find out why the circle doesn't fit in the window. I understand that maybe it wouldn't fit vertically because the top bar might be included in the height, but then it should still fit horizontally.
A: As you already mentioned, the Size of the form includes borders, title bars etc. So, try to set the ClientSize which defines the client area of the form:
this.ClientSize = new Size(200, 200);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52355466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Displaying an image in a jsp from a byte array using struts I can get an image as a byte[] and store it in my database using form.jsp and FormFile.
Now I need to be able to retrieve that byte[] and display it back in the JSP as an image. Is there a way to create a resource and retrieve that image?
A: public ActionForward pageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
b.setImageData(loadImageData());
return a.findForward("toPage");
}
public ActionForward imageLoad(ActionMapping a,ActionForm b,HttpServletRequest c,HttpServletResponse d){
byte[] tempByte = b.getImageData();
d.setContentType("image/jpeg");
ServletOutputStream stream = d.getOutputStream();
/*
Code to write tempByte into stream here.
*/
return null;
}
Write the tempByte into stream, flush and close it. return null from the action.
now call the action from inside an <img src="yourAction.do">
A: <%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/Test";
ResultSet rs = null;
PreparedStatement psmnt = null;
InputStream sImage;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "Admin", "Admin");
psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?");
psmnt.setString(1, "11"); // here integer number '11' is image id from the table
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
}
catch(Exception ex){
out.println("error :"+ex);
}
finally {
rs.close();
psmnt.close();
connection.close();
}
%>
By this u can retrive Image from Database
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12055092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using SIFT and OpenCV for object recognition I have an image that is an image of one of a set of objects, and I'd like to use SIFT in Open CV to figure out which object it. I have this code:
Mat pic = imread(...);
vector<KeyPoint> picKP;
Mac picDesc;
Mat obj1 = imread(...);
Mat obj2 = imread(...);
Mat obj3 = imread(...);
vector<KeyPoint> obj1KP;
vector<KeyPoint> obj2KP;
vector<KeyPoint> obj3KP;
Mat obj1Desc;
Mat obj2Desc;
Mat obj3Desc;
SIFT sifter = SIFT();
sifter.detect(pic, picKP);
sifter.detect(obj1, obj1KP);
sifter.detect(obj2, obj2KP);
sifter.detect(obj3, obj3KP);
sifter.compute(pic, picKP, picDesc);
sifter.compute(obj1, obj1KP, obj1Desc);
sifter.compute(obj2, obj2KP, obj1Desc);
sifter.compute(obj3, obj3KP, obj1Desc);
FlannBasedMatcher matcher;
vector<DMatch> matches1;
vector<DMatch> matches2;
vector<DMatch> matches3;
matcher.match(picDesc, obj1Desc, matches1);
matcher.match(picDesc, obj2Desc, matches2);
matcher.match(picDesc, obj3Desc, matches3);
It generates a vector<DMatch> to compare my picture with each potential picture. But I don't know what to do with the 3 vector<DMatch>es to figure out which one is the best match.
Note: I'm doing this mostly to try and learn about SIFT, so even though I know better ways are available for my particular dataset, I still want to try to do it with SIFT.
A: See the API for DMatch data type here:
http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_descriptor_matchers.html#dmatch
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30046935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Aws lambda java - Implement simple cache to read a file I have a lambda process in java and it reads a json file with a table everytime is triggered. I'd like to implement a kind of cache to have that file in memory and I wonder how to do something simple. I don't want to use elasticchache or redis.
I read something similar to my approach in javascript declaring a global variable with let but not sure how to do it in java, where it should be declared and how to test it. Any idea or example you can provide me? Thanks
A: *
*There are global variables in lambda which can be of help but they have to be used wisely.
*They are usually the variables declared out side of lambda_handler.
*There are pros and cons of using it.
*You can't rely on this behavior but you must be aware it exists. When you call your Lambda function several times, you MIGHT get the same container to optimise run duration and setup delay Use of Global Variables
*At the same time you should be aware of the issues or avoid wrong use of it caching issues
*If you don't want to use ElastiCache/redis then i guess you have very less options left.......may be dynamoDB or S3 that's all i can think of
again connection to dynamoDB or S3 can be cached here. It won't be as fast as ElastiCache though.
A: In Java it's not too hard to do. Just create your cache outside of the handler:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SampleHandler implements RequestStreamHandler {
private static final Logger logger = LogManager.getLogger(SampleHandler.class);
private static Map<String, String> theCache = null;
public SampleHandler() {
logger.info( "filling cache...");
theCache = new HashMap<>();
theCache.put("key1", "value1");
theCache.put("key2", "value2");
theCache.put("key3", "value3");
theCache.put("key4", "value4");
theCache.put("key5", "value5");
}
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
logger.info("handlingRequest");
LambdaLogger lambdaLogger = context.getLogger();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(inputStream);
String requestedKey = jsonNode.get("requestedKey").asText();
if( theCache.containsKey( requestedKey )) {
// read from the cache
String result = "{\"requestedValue\": \"" + theCache.get(requestedKey) + "\"}";
outputStream.write(result.getBytes());
}
logger.info("done with run, remaining time in ms is " + context.getRemainingTimeInMillis() );
}
}
(run with the AWS cli with aws lambda invoke --function-name lambda-cache-test --payload '{"requestedKey":"key4"}' out with the output going the the file out)
When this runs with a "cold start" you'll see the "filling cache..." message and then the "handlingRequest" in the CloudWatch log. As long as the Lambda is kept "warm" you will not see the cache message again.
Note that if you had hundreds of the same Lamda's running they would all have their own independent cache. Ultimately this does what you want though - it's a lazy load of the cache during a cold start and the cache is reused for warm calls.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57915701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the list of all children in Firebase android? I have this model below in Firebase
I am trying to get all the values from child node posts using below code
databasePostsReference =
FirebaseDatabase.getInstance().getReference().child("posts");
final List<UserPostPOJO> list = Collections.EMPTY_LIST;
databasePostsReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: entered list adding");
UserPostPOJO post = snapshot.getValue(UserPostPOJO.class);
list.add(post);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
but I am getting error java.lang.UnsupportedOperationException.
in the above scenario i know that error is because list is declared final and i am trying to assign value in onDataChangeMethod so is throwing error but if i am not declaring the list variable final then i cant access list variable from within the onDataChange() method how to solve this
public class UserPostPOJO {
String uid;
Double elevation;
String uri;
String feel;
public UserPostPOJO() {
}
public UserPostPOJO(String uid, Double elevation, String uri, String feel) {
this.uid = uid;
this.elevation = elevation;
this.uri = uri;
this.feel = feel;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public Double getElevation() {
return elevation;
}
public void setElevation(Double elevation) {
this.elevation = elevation;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getFeel() {
return feel;
}
public void setFeel(String feel) {
this.feel = feel;
}
}
Error Log:
05-08 22:19:49.706 6421-6421/redeyes17.com.abhi.android.iamat
D/recentfragment: onDataChange: entered list adding
05-08 22:19:49.726 6421-6421/redeyes17.com.abhi.android.iamat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: redeyes17.com.abhi.android.iamat, PID: 6421
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:404)
at java.util.AbstractList.add(AbstractList.java:425)
at redeyes17.com.abhi.android.iamat.UI.tabs
.RecentFragment$1.onDataChange(RecentFragment.java:78)
at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
at com.google.android.gms.internal.zzbqx.zzZT(Unknown Source)
at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7230)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller
.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
A: To get all those values please use this code:
databasePostsReference = FirebaseDatabase.getInstance().getReference().child("posts").child(postId);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<UserPostPOJO> list = new ArrayList<>();
String elevation = (String) dataSnapshot.child("elevation").getValue();
String feel = (String) dataSnapshot.child("feel").getValue();
String uid = (String) dataSnapshot.child("uid").getValue();
String uri = (String) dataSnapshot.child("uri").getValue();
UserPostPOJO userPostPOJO = new UserPostPOJO();
userPostPOJO.setElevation(elevation);
userPostPOJO.setFeel(feel);
userPostPOJO.setUid(uid);
userPostPOJO.setUri(uri);
list.add(userPostPOJO);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
databasePostsReference.addListenerForSingleValueEvent(eventListener);
In which postId is the unique id generated by the push() method. And notice, that the declaration of your list must be inside the onDataChange() method, otherwise, you'll get null.
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43859513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using an varray type in a select statement I am trying to use an varray-type in a select statement:
CREATE OR REPLACE PROCEDURE ARRAYTEST IS
type array_t is varray(2) of int;
array_test array_t := array_t(10,11);
BEGIN
select * from STATISTIK where abschluss1 in array_test;
END;
But it is giving me an error:
PLS-00428: an INTO clause is expected in this SELECT statement
PLS-00642: local collection types not allowed in SQL statement
The first Exception seems to be misleading, I don't want to select something into a variable I want an aquivalent of:
select * from STATISTIK where abschluss1 in (10,12);
But (10,12) substituted by an array (varray).
Is it possible to convert the varray to be used in a select-statement?
A: It is possible but your type must be global
create type array_t is varray(2) of int;
Then use array as a table (open p for only for compiling)
declare
array_test array_t := array_t(10,11);
p sys_refcursor;
begin
open p for
select * from STATISTIK where abschluss1 in (select column_value from table(array_test ));
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31699448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: html5 validate form with required="true" and custom check What I'm looking for: way to have innate html 5 form validation using the required="true", where if the user clicks the "Submit" button, the first thing that happens is the automatic html 5 validation where it checks to see if "username" is provided by the user. If it's not, then it displays the ugly error bubble.
If it is provided, however, I then have my own custom validation for checking against the db if the username exists. If it does, then return true (allow submission), false otherwise. What's happening: the form is getting submitted. It's like it does not wait for the success callback to return true/false on whether or not it should be submitted.
I hope that's clear enough! Code below:
html:
<form>
<input type="text" required="true" id="username" />
<button type="submit">Submit</button>
</form>
js:
$("form").submit(function() {
$.ajax({
url: 'usernamechecker.php?username=' + $("#username").val(),
success: function(resp) {
if (!resp.UsernameExists) {
return true; // allow form submission
}
return false; // do not allow form submission
}
});
});
A: You can't return a value through a callback like that. The callback for "success" won't run until the "ajax" call has completed, long after the "submit" handler has already returned.
Instead of that, I'd just do the submit and let it return with an error if there are server-side issues (like "username in use" or whatever). There's no point making two round-trips. If there are no problems, it can just complete the operation and return whatever results page you want.
A: You need to add "async: false" as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.
$("form").submit(function(event) {
$.ajax({
async: false,
url: 'usernamechecker.php?username=' + $("#username").val(),
timeout: 1000,
success: function(resp) {
if (resp.UsernameExists) {
event.preventDefault(); // do not allow form submission
},
error: function() {
//fall back code when there's an error or timeout
},
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8042844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Firebase Google Analytics Console weird behavior. Events are logged but don't show up on User Snapshot I'm using Firebase Analytics and I'm still exploring the Google Analytics Console.
I think there's something wrong with my data, or the way I'm logging it. I have a Single Page App built with React + Firebase.
Since my app is all client side routes, for every page that it renders, I'm firing the following effect to log the screen_view event:
useEffect(() => {
firebase.analytics().logEvent("screen_view", {
screen_name: window.location.pathname,
page_title: "My Page Title"
});
},[firebase]);
So far, so good. It runs without any errors, and it seems to be logging the event (or at least, I can see the events in some parts of the console).
Here is the test I did that came back with weird results.
Note: I'm monitoring through the Realtime tab over on Google Analytics Console.
I accessed my website, and click on 5 different links. After each page loaded, the screen_view event was fired and I could see this number for total events going from 20 to 25. I.e: my effects were fired and my events were logged!
When you click on "Trending" you open up a window with the count per event type in the last minutes, and I could see the screen_view events going from 12 to 17, which is all correct, so far.
But since this is a new website and I'm currently the only user, I was able to click on "View user snapshot" and see my own activity in the report, and it's supposed to be in real time.
But the weird thing is that my screen_view events don't show up in the snapshot AT ALL. Not on real time and it's not a delay issue. They just don't appear in my user activity.
QUESTION
What is going on here? Am I doing something wrong? Weren't my events supposed to appear in my user's snapshot timeline on Real Time (or even with some delay)? This is getting really difficult to learn and test if I can't see the results of my code logged on screen.
Is there a better way to test this? I mean, I need to update my code and be able to see the changes in the events a user triggers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59944747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Electron (Windows) How does manual distribution work? I am trying to follow the instructions on this page: https://electronjs.org/docs/tutorial/application-distribution#manual-distribution however it is very vague and unclear.
I am trying to build an app that is simply an index.html with some static assets (JS, CSS, images.) There are no calls to server-side APIs from the client side.
The docs say to use this layout:
electron/resources/app
- package.json
- main.js
- index.html
But it's not working for me.
What is main.js? I assume this is the electron script that should create the main browser window and set the url to my local index.html, not something that is run within the webview window.
Why does it say index.html has to be there? I would think the URL to index.html is specified in main.js? (I have all client assets in a "public" folder.)
Why does it need a package.json? I have no scripts and don't use any additional npm modules.
I have tried a number of layouts but all that happens when I double-click electron.exe is that it exits immediately without any errors. From what I can tell it never executes my main.js script.
I can't find any additional resources on setting up a simple manual distribution.
A: I got it working after expanding the default_app.asar distributed with the Electron build. The instructions on the page linked above neglected to mention that the package.json should contain something like:
{
"name": "electron",
"productName": "Electron",
"main": "main.js"
}
The only file that needs to be in resources/app is the package.json file. You can set main to the location of your your app's entry point script and you can put any other files wherever you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59721270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What access modifier to use Suppose I have a base class:
public class A {
public float someValue;
<Access Modifier Here> float SomeValue {
get {
return someValue;
}
}
}
And I want to derive from it:
public class B : A {
public float SomeProperty {
get {
return SomeValue;
}
}
}
What access modifier would I use if I want to make the SomeValue property only available to the deriving class and not anywhere else?
A: for only derived classes.. use protected
Protected means that access is limited to the containing class or types derived from the containing class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36318000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to set hard coded HTML in UWP WebView I have some hard coded html:
string myHtml = "<html>some html</html>"
How can I set it as my WebView source? Something like this:
webView.HtmlSource = myHtml;
A: In general, we use WebView.NavigateToString(htmlstring); to load and display html string. For source of WebView, only apply for Uri parameters. But you can create an attached property like HtmlSource for WebView and when it changes to call NavigateToString to load.
public class MyWebViewExtention
{
public static readonly DependencyProperty HtmlSourceProperty =
DependencyProperty.RegisterAttached("HtmlSource", typeof(string), typeof(MyWebViewExtention), new PropertyMetadata("", OnHtmlSourceChanged));
public static string GetHtmlSource(DependencyObject obj) { return (string)obj.GetValue(HtmlSourceProperty); }
public static void SetHtmlSource(DependencyObject obj, string value) { obj.SetValue(HtmlSourceProperty, value); }
private static void OnHtmlSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WebView webView = d as WebView;
if (webView != null)
{
webView.NavigateToString((string)e.NewValue);
}
}
}
.xaml:
<WebView x:Name="webView" local:MyWebViewExtention.HtmlSource="{x:Bind myHtml,Mode=OneWay}"></WebView>
For more details, you can refer to Binding HTML to a WebView with Attached Properties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59537299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: The type arguments for method cannot be inferred from the usage. (c#, lambda) Firstly, I am a complete beginner to advanced level programming. All I have done are tutorials to C++ found on the web. I'm facing this problem at work. I have seen similar queries but nothing has helped me understand.
Please note: I am terrible at terminologies like method, object, interface, etc. So I might have made a mistake somewhere further. I'm slowly learning.
Code Block 1:
public static class DummyClassName
{
public static T DummyTemplateFunc<T>(DummyInterfaceName aaa1, Func<T> action)
{
T DummyVal = action();
// blah blah code
// blah blah code
return val;
}
}
Code Block 2:
public class ClassName2 : blah1 , blah2, blah3
{
public void Method1(string DummyString)
{
DummyClassName.DummyTemplateFunc(_aaa1, ()=>Function1(_arg1, arg2));
}
}
I'll try to explain what's happening to the best of my ability. The second bit of code is used over and over in the program with different Functions (or methods?) in place of Function1. (These functions come from a C++ program linked with this one. I don't know how)
If these functions are of any return type EXCEPT void, the program runs fine.
If a void-return-type function is used, I get the error
"The type arguments for method '****.****.DummyClassName.DummyTemplateName<T>
(****.****.DummyInterfaceName, System.Func<T>)' cannot be inferred from the usage.
Try specifying the type arguments explicitly.'
From what I understand, this is because when a void function is passed it takes the place of T in the first block of code and tries returning 'val'. That's why an error is thrown.
Can somebody help me find a workaround to this? I don't mind defining a completely different class/method specifically to handle void functions. I know which functions are of return type void.
A: Create another overload, taking Action instead of Func<T>:
public static class DummyClassName
{
public static void DummyTemplateFunc(DummyInterfaceName aaa1, Action action)
{
// you cannot assign result to variable, because it returns void
action();
// I also changed method to return void, so you can't return anything
// return something;
// ofc you can make it return something instead
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21194025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Retain Cycle in Class Causing Potential Memory Leak So using the graph debugger tool and instruments I have noticed that there is a memory leak in my app. After many hours I have or the graph debugger has tracked it down to this function.
override func didUpdate(to object: Any) {
comment = object as? CommentGrabbed
}
Which is contained in this bigger class
import UIKit
import IGListKit
import Foundation
import Firebase
protocol CommentsSectionDelegate: class {
func CommentSectionUpdared(sectionController: CommentsSectionController)
}
class CommentsSectionController: ListSectionController,CommentCellDelegate {
weak var delegate: CommentsSectionDelegate? = nil
weak var comment: CommentGrabbed?
let userProfileController = ProfileeViewController(collectionViewLayout: UICollectionViewFlowLayout())
var eventKey: String?
var dummyCell: CommentCell?
override init() {
super.init()
// supplementaryViewSource = self
//sets the spacing between items in a specfic section controller
inset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
}
// MARK: IGListSectionController Overrides
override func numberOfItems() -> Int {
return 1
}
override func sizeForItem(at index: Int) -> CGSize {
let frame = CGRect(x: 0, y: 0, width: collectionContext!.containerSize.width, height: 50)
dummyCell = CommentCell(frame: frame)
dummyCell?.comment = comment
dummyCell?.layoutIfNeeded()
let targetSize = CGSize(width: collectionContext!.containerSize.width, height: 55)
let estimatedSize = dummyCell?.systemLayoutSizeFitting(targetSize)
let height = max(40+8+8, (estimatedSize?.height)!)
return CGSize(width: collectionContext!.containerSize.width, height: height)
}
override var minimumLineSpacing: CGFloat {
get {
return 0.0
}
set {
self.minimumLineSpacing = 0.0
}
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: CommentCell.self, for: self, at: index) as? CommentCell else {
fatalError()
}
// print(comment)
cell.comment = comment
cell.delegate = self
return cell
}
override func didUpdate(to object: Any) {
comment = object as? CommentGrabbed
}
override func didSelectItem(at index: Int){
}
func optionsButtonTapped(cell: CommentCell){
print("like")
let comment = self.comment
_ = comment?.uid
// 3
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// 4
if comment?.uid != User.current.uid {
let flagAction = UIAlertAction(title: "Report as Inappropriate", style: .default) { _ in
ChatService.flag(comment!)
let okAlert = UIAlertController(title: nil, message: "The post has been flagged.", preferredStyle: .alert)
okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
self.viewController?.present(okAlert, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let replyAction = UIAlertAction(title: "Reply to Comment", style: .default, handler: { (_) in
//do something here later to facilitate reply comment functionality
print("Attempting to reply to user \(comment?.user.username) comment")
})
alertController.addAction(replyAction)
alertController.addAction(cancelAction)
alertController.addAction(flagAction)
}else{
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let deleteAction = UIAlertAction(title: "Delete Comment", style: .default, handler: { _ in
ChatService.deleteComment(comment!, (comment?.eventKey)!)
let okAlert = UIAlertController(title: nil, message: "Comment Has Been Deleted", preferredStyle: .alert)
okAlert.addAction(UIAlertAction(title: "Ok", style: .default))
self.viewController?.present(okAlert, animated: true, completion: nil)
self.onItemDeleted()
})
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
}
self.viewController?.present(alertController, animated: true, completion: nil)
}
func onItemDeleted() {
delegate?.CommentSectionUpdared(sectionController: self)
}
func handleProfileTransition(tapGesture: UITapGestureRecognizer){
userProfileController.user = comment?.user
if Auth.auth().currentUser?.uid != comment?.uid{
self.viewController?.present(userProfileController, animated: true, completion: nil)
}else{
//do nothing
}
}
deinit {
print("CommentSectionController class removed from memory")
}
}
The CommentGrabbed class looks like this
import Foundation
import IGListKit
class CommentGrabbed {
let content: String
let uid: String
let user: User
let creationDate: Date
var commentID: String? = ""
let eventKey:String
init(user: User, dictionary: [String:Any]) {
self.content = dictionary["content"] as? String ?? ""
self.uid = dictionary["uid"] as? String ?? ""
self.eventKey = dictionary["eventKey"] as? String ?? ""
self.user = user
let secondsFrom1970 = dictionary["timestamp"] as? Double ?? 0
self.creationDate = Date(timeIntervalSince1970: secondsFrom1970)
}
}
extension CommentGrabbed: Equatable{
static public func ==(rhs: CommentGrabbed, lhs: CommentGrabbed) ->Bool{
return rhs.commentID == lhs.commentID
}
}
extension CommentGrabbed: ListDiffable{
public func diffIdentifier() -> NSObjectProtocol {
return commentID! as NSObjectProtocol
}
public func isEqual(toDiffableObject object: ListDiffable?) ->Bool{
guard let object = object as? CommentGrabbed else {
return false
}
return self.commentID==object.commentID
}
}
Are there any retain cycles being created here that I don't noice?
This controller is ultimately in control of displaying all the comments and it has a UserService method which works through this code base
static func show(forUID uid: String, completion: @escaping (User?) -> Void) {
let ref = Database.database().reference().child("users").child(uid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let user = User(snapshot: snapshot) else {
return completion(nil)
}
completion(user)
})
}
The User model object looks like this
import Foundation
import FirebaseDatabase.FIRDataSnapshot
class User : NSObject {
//User variables
let uid : String
let username : String?
let profilePic: String?
var isFollowed = false
var dictValue: [String : Any] {
return ["username" : username as Any,
"profilePic" : profilePic as Any]
}
//Standard User init()
init(uid: String, username: String, profilePic: String) {
self.uid = uid
self.username = username
self.profilePic = profilePic
super.init()
}
//User init using Firebase snapshots
init?(snapshot: DataSnapshot) {
guard let dict = snapshot.value as? [String : Any],
let username = dict["username"] as? String,
let profilePic = dict["profilePic"] as? String
else { return nil }
self.uid = snapshot.key
self.username = username
self.profilePic = profilePic
}
//UserDefaults
required init?(coder aDecoder: NSCoder) {
guard let uid = aDecoder.decodeObject(forKey: "uid") as? String,
let username = aDecoder.decodeObject(forKey: "username") as? String,
let profilePic = aDecoder.decodeObject(forKey: "profilePic") as? String else { return nil }
self.uid = uid
self.username = username
self.profilePic = profilePic
super.init()
}
init?(key: String, postDictionary: [String : Any]) {
//var dict : [String : Any]
//print(postDictionary as? [String:])
let dict = postDictionary
//print(dict)
let profilePic = dict["profilePic"] as? String ?? ""
let username = dict["username"] as? String ?? ""
self.uid = key
self.profilePic = profilePic
self.username = username
}
//User singleton for currently logged user
private static var _current: User?
static var current: User {
guard let currentUser = _current else {
fatalError("Error: current user doesn't exist")
}
return currentUser
}
class func setCurrent(_ user: User, writeToUserDefaults: Bool = true) {
//print(user)
// print("")
if writeToUserDefaults {
let data = NSKeyedArchiver.archivedData(withRootObject: user)
UserDefaults.standard.set(data, forKey: "currentUser")
UserDefaults.standard.synchronize()
}
_current = user
//print(_current ?? "")
}
}
extension User: NSCoding {
func encode(with aCoder: NSCoder) {
aCoder.encode(uid, forKey: "uid")
aCoder.encode(username, forKey: "username")
aCoder.encode(profilePic, forKey: "profilePic")
}
}
When I change user in commentGrabbed class to weak my code begins to crash if it has to deal with anything related to a user like so
weak var comment: CommentGrabbed?{
didSet{
guard let comment = comment else{
return
}
// print("apples")
// textLabel.text = comment.content
//shawn was also here
profileImageView.loadImage(urlString: (comment.user?.profilePic!)!)
// print(comment.user.username)
let attributedText = NSMutableAttributedString(string: (comment.user?.username!)!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])
attributedText.append(NSAttributedString(string: " " + (comment.content), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]))
attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))
let timeAgoDisplay = comment.creationDate.timeAgoDisplay()
attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12), NSAttributedStringKey.foregroundColor: UIColor.gray]))
textView.attributedText = attributedText
}
}
Code block where commentGrabbed is init
UserService.show(forUID: uid, completion: { [weak self](user) in
if let user = user {
let commentFetched = CommentGrabbed(user: user, dictionary: commentDictionary)
commentFetched.commentID = snapshot.key
let filteredArr = self?.comments.filter { (comment) -> Bool in
return comment.commentID == commentFetched.commentID
}
if filteredArr?.count == 0 {
self?.comments.append(commentFetched)
}
self?.adapter.performUpdates(animated: true)
}else{
print("user is null")
}
self?.comments.sort(by: { (comment1, comment2) -> Bool in
return comment1.creationDate.compare(comment2.creationDate) == .orderedAscending
})
self?.comments.forEach({ (comments) in
})
})
})
This is what I see in debugger tool. If I comment out that line nothing loads btw for those who are wondering why not just comment it out
Code for CommentCell as requested
import Foundation
import UIKit
import Firebase
protocol CommentCellDelegate: class {
func optionsButtonTapped(cell: CommentCell)
func handleProfileTransition(tapGesture: UITapGestureRecognizer)
}
class CommentCell: UICollectionViewCell {
weak var delegate: CommentCellDelegate? = nil
override var reuseIdentifier : String {
get {
return "cellID"
}
set {
// nothing, because only red is allowed
}
}
var didTapOptionsButtonForCell: ((CommentCell) -> Void)?
weak var comment: CommentGrabbed?{
didSet{
guard let comment = comment else{
return
}
// print("apples")
// textLabel.text = comment.content
//shawn was also here
profileImageView.loadImage(urlString: (comment.user?.profilePic!)!)
// print(comment.user.username)
let attributedText = NSMutableAttributedString(string: (comment.user?.username!)!, attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14)])
attributedText.append(NSAttributedString(string: " " + (comment.content), attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)]))
attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))
let timeAgoDisplay = comment.creationDate.timeAgoDisplay()
attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12), NSAttributedStringKey.foregroundColor: UIColor.gray]))
textView.attributedText = attributedText
}
}
lazy var textView: UITextView = {
let textView = UITextView()
textView.font = UIFont.systemFont(ofSize: 14)
textView.isScrollEnabled = false
textView.textContainer.maximumNumberOfLines = 0
textView.textContainer.lineBreakMode = .byCharWrapping
textView.isEditable = false
return textView
}()
lazy var profileImageView: CustomImageView = {
let iv = CustomImageView()
iv.clipsToBounds = true
iv.isUserInteractionEnabled = true
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleProfileTransition)))
iv.contentMode = .scaleAspectFill
return iv
}()
lazy var flagButton: UIButton = {
let flagButton = UIButton(type: .system)
flagButton.setImage(#imageLiteral(resourceName: "icons8-Info-64"), for: .normal)
flagButton.addTarget(self, action: #selector(optionsButtonTapped), for: .touchUpInside)
return flagButton
}()
@objc func optionsButtonTapped (){
didTapOptionsButtonForCell?(self)
}
@objc func onOptionsTapped() {
delegate?.optionsButtonTapped(cell: self)
}
@objc func handleProfileTransition(tapGesture: UITapGestureRecognizer){
delegate?.handleProfileTransition(tapGesture: tapGesture)
// print("Tapped image")
}
override init(frame: CGRect){
super.init(frame: frame)
addSubview(textView)
addSubview(profileImageView)
addSubview(flagButton)
textView.anchor(top: topAnchor, left: profileImageView.rightAnchor, bottom: bottomAnchor, right: flagButton.leftAnchor, paddingTop: 4, paddingLeft: 4, paddingBottom: 4, paddingRight: 4, width: 0, height: 0)
profileImageView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 40, height: 40)
profileImageView.layer.cornerRadius = 40/2
flagButton.anchor(top: topAnchor, left: nil, bottom: nil, right: rightAnchor, paddingTop: 4, paddingLeft: 0, paddingBottom: 0, paddingRight: 4, width: 40, height: 40)
flagButton.addTarget(self, action: #selector(CommentCell.onOptionsTapped), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
sizeForItem
override func sizeForItem(at index: Int) -> CGSize {
let frame = CGRect(x: 0, y: 0, width: collectionContext!.containerSize.width, height: 50)
weak var dummyCell = CommentCell(frame: frame)
dummyCell?.comment = comment
dummyCell?.layoutIfNeeded()
let targetSize = CGSize(width: collectionContext!.containerSize.width, height: 55)
let estimatedSize = dummyCell?.systemLayoutSizeFitting(targetSize)
let height = max(40+8+8, (estimatedSize?.height)!)
return CGSize(width: collectionContext!.containerSize.width, height: height)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48621724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Still having Java install problems Please review my script, all I want to do is check to see if a particular Java Verison is installed (latest version) if it is not installed, then to go to the install command...
Having problems with the For /F command though.
PLease see what I have so far:
@echo On
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME="BrowserJavaVersion"
FOR /F "usebackq skip=1 tokens=3" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME% 2^>nul`) DO (
set ValueValue=%%A
)
if defined ValueValue (
@echo the current Java runtime is %ValueValue%
) else (
@echo %KEY_NAME%\%VALUE_NAME% not found
This is the key I am trying to interrogate from within the Windows Registry (BrowserJavaVersion):
!http://i393.photobucket.com/albums/pp11/Mikoyan_2008/Screenshot.jpg
If the version doesnt match latest Java version to then:
if "%ValueValue%"=="Latest Java Version" ( goto eof ) ELSE ( goto Install )
Can anyone please provide assistance?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22991060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to trace where Xcode program crash I'm getting an error in debugger. In Thread my app crash on line:
0x37265f78: ldr r3, [r4, #8]
with:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x50000008)
How to find out where app actually crash? There is a something like "call stack"?
A: http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
Best tutorial for trace the error.
A: Run your app under the debugger, then when your app crashes you will have access to the call stack.
Furthermore, if you display the console window, you will get more textual information (including a call stack) at the moment of the crash.
If you are using Xcode 4, have a look at the attached picture.
A: You have to set Exception Breakpoint
Go to the Breakpoints navigator, click the + button at the bottom, and add an Exception Breakpoint.
Now you will know the exact line where any of your exception will occur (e.g. line of crash). best of luck!!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10878035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: admob impressions is half then request please guide what is the issue also rewarded ads not showing with real id in test is it works Hello I am working with admob but i dont know in my account their is no ads limit but still number of impressions is less then request
Please help me out what is issue why i am getting impressions less then request
second question is in my app rewarded ads are not loading i dont know why in test it works fine but when i put live id its not work and didnot shows ads
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75556819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Avoid changing the background of Status Bar on iOS in Ionic I'm doing a mobile app using Ionic 6.1.4 and Capacitor 3.5.1.
Android, looks good by default, black background and white icons on any screen.
iOS, always has whatever the background color I have in the ion-content with black icons. Is always like this on any screen. In my app, I have 2 screens with a dark background and the ion-content with the attribute fullscreen.
iOS, as I said, I have two screen with a very dark background, let's replicate it using a black background. See how the icons are not visible anymore?
Component:
<ion-header class="ion-no-border">
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button color="white"></ion-menu-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true">
</ion-content>
Style:
ion-toolbar {
--background: transparent;
}
ion-content {
--background: black;
}
How can I change iOS Status Bar to always have a style just like Android?
or even better, how can I leave the Status Bar untouched on iOS (app not modifying the Status Bar at all)?
I have tried:
.ios {
ion-header {
margin-top: var(--ion-safe-area-top);
}
ion-toolbar {
margin-top: var(--ion-safe-area-top);
--padding-top: var(--ion-safe-area-top);
padding-top: var(--ion-safe-area-top);
}
}
But this just moves all the content down and Status Bar is keeping the background color of my app.
I was thinking to use the plugin called @capacitor/status-bar to change the Status Bar style just on iOS, but it's not so simple in my case. Since I have 2 screens with dark background, I will need to make the Status Bar Dark when enter, and when onDestroy is called, make it back to Light so my other screens which have white background looks good too. I think this is a tedious process. I think there must be a way to avoid this.
My goal is to keep the Status Bar on iOS always the same and with a color that makes the icons visible. I would prefer leaving the Status Bar untouched just like Android do.
A: Well, I suggest trying one of the followings:
*
*If you are using Cordova, use the cordova-status-bar plugin and try setting the statusBar color in the config.xml:
<preference name="StatusBarBackgroundColor" value="#000000" />
or
<preference name="StatusBarBackgroundColor" value="#ffffff" />
setting it to a value in hex color, probably you want it black, and then setting the text and icons to light or lightcontent as you did in Android by using:
<preference name="StatusBarStyle" value="lightcontent" />
*If you are using Capacitor, install the Capacitor plugin
npm install @capacitor/status-bar
npx cap sync
and then set the color of the background and text using
import { StatusBar, Style } from '@capacitor/status-bar';
// iOS only
window.addEventListener('statusTap', function () {
console.log('statusbar tapped');
});
const setStatusBarStyleDark = async () => {
await StatusBar.setStyle({ style: Style.Dark });
};
*Finally, if none of that works, or you just want to change it on iOS try setting it in the global.scss as you were doing but also changing the backgound color and the color:
.ios {
ion-header {
margin-top: var(--ion-safe-area-top);
background-color: black;
color: white;
}
ion-toolbar {
margin-top: var(--ion-safe-area-top);
--padding-top: var(--ion-safe-area-top);
padding-top: var(--ion-safe-area-top);
background-color: black;
color: white;
}
}
A: I don't know about Capacitor, but I know that on Cordova for iOS, you need to include viewport-fit=cover in the <meta name="viewport" content="..."> tag of your index.html to do this, e.g.
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
This works for me when using the cordova-plugin-statusbar plugin, anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72223035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Qt creator - The process "/usr/bin/make" exited with code 2 default project I installed QT Creator 4.0 on OS X 10.11, when I try to build any project template I get the following: Error output screenshot.
Any idea what causes this issue? Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37598743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting a working code from double-precision to quadruple-precision: How to read quadruple-precision numbers in FORTRAN from an input file I have a big, old, FORTRAN 77 code that has worked for many, many years with no problems.
Double-precision is not enough anymore, so to convert to quadruple-precision I have:
*
*Replaced all occurrences of REAL*8 to REAL*16
*Replaced all functions like DCOS() into functions like COS()
*Replaced all built-in numbers like 0.d0 to 0.q0 , and 1D+01 to 1Q+01
The program compiles with no errors or warnings with the gcc-4.6 compiler on
*
*operating system: openSUSE 11.3 x86_64 (a 64-bit operating system)
*hardware: Intel Xeon E5-2650 (Sandy Bridge)
My LD_LIBRARY_PATH variable is set to the 64-bit library folder:
/gcc-4.6/lib64
The program reads an input file that has numbers in it.
Those numbers used to be of the form 1.234D+02 (for the double-precision version of the code, which works).
I have changed them so now that number is 1.234Q+02 , however I get the runtime error:
Bad real number in item 1 of list input
Indicating that the subroutine that reads in the data from the input file (called read.f) does not find the first number in the inputfile, to be compatible with what it expected.
Strangely, the quadruple-precision version of the code does not complain when the input file contains numbers like 1.234D+02 or 123.4 (which, based on the output seems to automatically be converted to the form 1.234D+02 rather than Q+02), it just does not like the Q+02 , so it seems that gcc-4.6 does not allow quadruple-precision numbers to be read in from input files in scientific notation !
Has anyone ever been able to read from an input file a quadruple-precision number in scientific notation (ie, like 1234Q+02) in FORTRAN with a gcc compiler, and if so how did you get it to work ? (or did you need a different compiler/operating system/hardware to get it to work ?)
A: Almost all of this is already in comments by @IanH and @Vladimi.
I suggest mixing in a little Fortran 90 into your FORTRAN 77 code.
Write all of your numbers with "E". Change your other program to write the data this way. Don't bother with "D" and don't try to use the infrequently supported "Q". (Using "Q" in constants in source code is an extension of gfortran -- see 6.1.8 in manual.)
Since you want the same source code to support two precisions, at the top of the program, have:
use ISO_FORTRAN_ENV
WP = real128
or
use ISO_FORTRAN_ENV
WP = real64
as the variation that changes whether your code is using double or quadruple precision. This is using the ISO Fortran Environment to select the types by their number of bits. (use needs to between program and implicit none; the assignment statement after implicit none.)
Then declare your real variables via:
real (WP) :: MyVar
In source code, write real constants as 1.23456789012345E+12_WP. The _type is the Fortran 90 way of specifying the type of a constant. This way you can go back and forth between double and quadruple precision by only changing the single line defining WP
WP == Working Precision.
Just use "E" in input files. Fortran will read according to the type of the variable.
Why not write a tiny test program to try it out?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18137127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: POST and PUT methods are not working in Postman but working in Swagger So the documentation is required from me on Postman. The problem is my APIs requires authentication so I can't use Swagger to test them. When I remove authorization from my controller and use Swagger it works, but using Postman it returns the following error.
Postman headers for the request:
A: Set header Content-Type: application/json.
A: Set header Content-Type: application/json.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66474715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting the list of available languages How can I get the list of available languages (the short symbol to be passed when calling a method that represents the language) for CodeRay syntax highlighter?
I tried
require "coderay"
CodeRay::Scanners.constants
but that doesn't seem to give the information. (Even if I were able to get the constants that correspond to the languages, I still need another step to get the symbols that correspond to them.)
A related question is, I can do something like:
CodeRay::Scanners::Ruby # => CodeRay::Scanners::Ruby
but CodeRay::Scanners.constants doesn't include that. Why is that?
A: Method you are looking for is:
CodeRay::Scanners.list
#=> [:c, :clojure, :cpp, :css, :debug, :delphi, :diff, :erb, :go, :groovy,
# :haml, :html, :java, :java_script, :json, :lua, :php, :python, :raydebug,
# :ruby, :sass, :scanner, :sql, :taskpaper, :text, :xml, :yaml]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36860395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Drupal escaping url in dynamically created meta tags I am trying to add open graph meta tags dynamically to drupal 8 using the the page_attachments hook.
The meta tags are generated correctly however image and the website urls are being encoded by drupal and the result is broken links.
function module_page_attachments(array &$page)
{
$tags = [
["name" => "twitter:card", "content" => "summary"],
["name" => "og:url", "content" => "https://example.net/index.php?param1=1¶m2=2¶m3=3"],
["name" => "og:title", "content" => "My title"],
["name" => "og:description", "content" => "My description"],
["name" => "og:image", "content" => "https://example.net/images?id=1&size=400"],
];
foreach ($tags as $tag) {
$headerTag = array(
'#tag' => 'meta',
'#attributes' => array(
'property' => $tag['name'],
'content' => $tag['content'],
),
);
$page['#attached']['html_head'][] = [$headerTag, $tag['name'] . "Id"];
}
}
The result is the following
<html>
<head>
<meta charset="utf-8" />
<meta property="twitter:card" content="summary" />
<meta property="og:url"
content="https://example.com/index.php?param1=1&param2=2&param3=3" />
<meta property="og:title" content="My title" />
<meta property="og:description"
content="My description" />
<meta property="og:image"
content="https://example.net/images?id=1&size=400" />
</head>
<body>
</body>
</html>
All the & characters have been encoded and transformed into &. How can I prevent Drupal from encoding the characters?
A: DrupalCoreRenderMarkup should do the trick:
<?php
use Drupal\Core\Render\Markup;
function module_page_attachments(array &$page)
{
$tags = [
["name" => "twitter:card", "content" => "summary"],
["name" => "og:url", "content" => Markup::create("https://example.net/index.php?param1=1¶m2=2¶m3=3")],
["name" => "og:title", "content" => "My title"],
["name" => "og:description", "content" => "My description"],
["name" => "og:image", "content" => Markup::create("https://example.net/images?id=1&size=400")],
];
foreach ($tags as $tag) {
$headerTag = array(
'#tag' => 'meta',
'#attributes' => array(
'property' => $tag['name'],
'content' => $tag['content'],
),
);
$page['#attached']['html_head'][] = [$headerTag, $tag['name'] . "Id"];
}
}
A: There is an open ticket for issue with the status needs work on drupal's website.
The issue can be found here:
www.drupal.org/project/drupal/issues/2968558
A work around to solve the issue is to intercept the page and alter its template in the module file like the example here below shows:
file name: example.module
/**
* Drupal bug caused the application to escape links. Therefore the og:image and og:url
* were not working. Drupal kept converting `&` to `&`
* The solution here below converts the tags into inline templates
*/
function spa_seo_page_attachments_alter(array &$attachments)
{
if (isset($attachments['#attached']['html_head'])) {
foreach ($attachments['#attached']['html_head'] as $key => $item) {
$property = !empty($item[0]['#attributes']['property']) ? $item[0]['#attributes']['property'] : '';
if ($property == "og:url" || $property == "og:image") {
$content = $item[0]['#attributes']['content'];
$property = $item[0]['#attributes']['property'];
$attachments['#attached']['html_head'][$key][0] = [
'#type' => 'inline_template',
'#template' => "{{ meta|raw }}",
'#context' => [
'meta' => '<meta property="' . $property . '" content="' . $content . '" />',
]
];
}
}
}
}
Note
Please note that DrupalCoreRenderMarkupdoes not solve the issue as this is a bug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62149447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show an Eclipse view like an intro I am having an eclipse view which I am trying to display as an intro page.
I am now opening the view with maximize but still the toolbars are visible.
So is there any way to make the view opening same as intro page in eclipse.
I am not using intro as I want to make my own welcome page so I am not sure about the attitude of intro as it is mentioned that intro is basically for internal.
Please correct me if I am wrong anywhere.
A: I would still use IIntroPart (or have a look to CustomizableIntroPart):
The intro part is a visual component within the workbench responsible for introducing the product to new users. The intro part is typically shown the first time a product is started up.
The intro part implementation is contributed to the workbench via the org.eclipse.ui.intro extension point.
(See this thread as an example).
There can be several intro part implementations, and associations between intro part implementations and products.
The workbench will only make use of the intro part implementation for the current product (as given by Platform.getProduct().
There is at most one intro part instance in the entire workbench, and it resides in exactly one workbench window at a time.
See "[Eclipse Intro] Make my own welcome page." as an example.
If you don't use it, at least have a look at the code of IIntroPart to see how it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4965610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: webformmailer.php not sending user text entries So I can't find anything about why my form isn't sending the text the users are entering. Its only submitting blank fields using webformmailer.php and can't find any help on godaddy site either. I know I'm using the same id for the name and email fields so if that is really the problem I'll change it but I wouldn't think it is. Heres my code.
<form id="contact-form" action="/webformmailer.php" method="POST" >
<textarea id="textarea" placeholder="Message Here"></textarea>
<input type="text" id="username" name="Firstname" placeholder="Full Name" />
<input type="text" id="username" name="email" placeholder="Email" />
<input type="submit" name ="submit" value="Submit" />
</form>
the file is generated from godaddy.com but heres the code. I also have a simple form with no textarea for messages that seems to work fine.
<?php
if ( !isset($_SERVER['SPI'])) {
die();
}
if (!isset($_SERVER['DOCUMENT_ROOT'])) {
echo("CRITICAL: we seem to be running outside of the norm.\n");
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
die("CRITICAL: Document root unavailable.\n");
}
$request_method = $_SERVER["REQUEST_METHOD"];
if($request_method == "GET") {
$query_vars = $_GET;
}
elseif ($request_method == "POST") {
$query_vars = $_POST;
}
reset($query_vars);
function customsort($a,$b) {
// $a is array for form vars, $b is comma seperated case sensitive field order
// this is case sensitive -- good idea to hrc that.
$data = array();
if ( strstr($b,',') == FALSE ) {
$b = $b.",";
}
$ordering = split(',',$b);
foreach ($ordering as $orderitem) {
if ( ($orderitem != null) && ($orderitem != "") ) {
if (isset($a[$orderitem])) {
$data[$orderitem] = $a[$orderitem];
}
}
}
foreach ($a as $key=>$val) {
$data[$key] = $a[$key];
}
return $data;
}
function xmlentities($string) {
return str_replace ( array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $string);
}
$t = date("U");
$formhomedir = preg_replace('/.*\/home\/content/','',$_SERVER['DOCUMENT_ROOT']);
$formhomedir = explode('/',$formhomedir);
if (count($formhomedir) <= 4) {
$formhome="/home/content/".$formhomedir[1]."/".$formhomedir[2]."/data/";
}
else {
$formhome="/home/content/".$formhomedir[1]."/".$formhomedir[2]."/".$formhomedir[3]."/".$form homedir[4]."/data/";
}
$file_order = ".default";
$file_format = ".text";
$file_interval = ".15m";
$field_order = "";
if (isset($query_vars['form_order'])) {
if ($query_vars['form_order'] != "alpha") {
$field_order=$query_vars['form_order'];
$file_order=".custom";
$query_vars = customsort($query_vars,$field_order);
}
else {
switch ($query_vars['form_order']) {
case "alpha":
uksort($query_vars,'strnatcasecmp');
$file_order=".alpha";
break;
default:
$file_order=".default";
break;
}
}
}
if (isset($query_vars['form_format'])) {
switch ($query_vars['form_format']) {
case "csv":
$file_format = ".csv";
break;
case "html":
$file_format = ".html";
break;
case "xml":
$file_format = ".xml";
break;
case "text":
case "default":
default:
$file_format = ".text";
break;
}
}
if (isset($query_vars['form_delivery'])) {
switch ($query_vars['form_delivery']) {
case "hourly":
$file_interval = ".60m";
break;
case "hourly_digest":
$file_interval = ".60mc";
break;
case "daily":
$file_interval = ".24h";
break;
case "daily_digest":
$file_interval = ".24hc";
break;
case "digest":
$file_interval = ".15mc";
break;
case "default":
default:
$file_interval = ".15m";
break;
}
}
$file = $formhome."form_".$t.$file_order.$file_format.$file_interval;
$fp = fopen($file,"w");
reset($query_vars);
switch ($file_format) {
case ".csv":
$csvkeys = "";
$csvvals= "";
$firsttime = "";
while (list ($key, $val) = each ($query_vars)) {
if ( ($key == "form_order") ||
($key == "form_format") ||
($key == "form_delivery") ||
($key == "redirect") ) {
}
else {
if ($csvkeys != "") {
$firsttime=",";
}
$tmpkey=escapeshellcmd($key);
$csvkeys = $csvkeys.$firsttime."'".$tmpkey."'";
$tmpval=escapeshellcmd($val);
$csvvals = $csvvals.$firsttime."'".$tmpval."'";
}
}
fputs($fp,"$csvkeys\n");
fputs($fp,"$csvvals\n");
break;
case ".html":
fputs($fp,"<table border=\"1\" cellspacing=\"1\" cellpadding=\"2\">\n");
break;
case ".xml":
fputs($fp,"<form>\n");
break;
}
reset($query_vars);
while (list ($key, $val) = each ($query_vars)) {
if ($key == "redirect") {
$landing_page = $val;
}
if ( ($key == "form_order") ||
($key == "form_format") ||
($key == "form_delivery") ||
($key == "redirect") ) {
}
else {
switch ($file_format) {
case ".html":
fputs($fp,"\t<tr>\n");
fputs($fp,"\t\t<td><b>$key</b></td>\n");
fputs($fp,"\t\t<td>$val</td>\n");
fputs($fp,"\t</tr>\n");
break;
case ".csv":
// content is already output
break;
case ".xml":
fputs($fp,"\t<field>\n");
fputs($fp,"\t\t<fieldname>".xmlentities($key)."
</fieldname>\n");
fputs($fp,"\t\t<fieldvalue>".xmlentities($val)
</fieldvalue>\n");
fputs($fp,"\t</field>\n");
break;
case ".text":
default:
fputs($fp,$key.": ".$val."\n");
break;
}
}
}
switch ($file_format) {
case ".html":
fputs($fp,"</table>\n");
break;
case ".xml":
fputs($fp,"</form>\n");
break;
}
fclose($fp);
if ($landing_page != "") {
header("Location: http://".$_SERVER["HTTP_HOST"]."/$landing_page");
}
else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
?>
A: *
*Your <textarea> doesn't have a name, so it can't be a successful control.
*You never attempt to access $_POST['Firstname'] (or $query_vars['Firstname] for that matter)
*Ditto $_POST['email']
Also your HTML is invalid (use a validator) and you are abusing the placeholder attribute as a label.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17581164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EF 5 & MVC 4: unable to get tables with no reference in Controller using Databse first I am using MVC 4, EF 5 and Database first approach. I have added 2 new tables(UserDetails and UserAddress) with no reference in existing database. I am able to see all tables including these 2 new table in EDMX file and created model also. But when im trying to get the tables in controller, its showing all Models except UserDetails and UserAddress - in following way.
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
private DbRestaurantEntities db = new DbRestaurantEntities();
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
var userId = WebSecurity.GetUserId(User.Identity.Name);
//db.UserDetails -- Not showing
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
return View(model);
}
}
Am i missing something?
A: WebSecurity uses different dbContext
, you need to use the same dbContext, which is used to create the database tables. you can check it out in the web.config file for the connectionstring.. and use the exact dbContext
Add this in AuthConfig.cs
WebSecurity.InitializeDatabaseConnection(
"specifyTheDbContextHere",
"UserProfile",
"UserId",
"UserName",
autoCreateTables: true
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18886845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to implement PHP file_get_contents() function in JSP(java)? In PHP we can use file_get_contents() like this:
<?php
$data = file_get_contents('php://input');
echo file_put_contents("image.jpg", $data);
?>
How can I implement this in Java (JSP)?
A: Here's a function I created in Java a while back that returns a String of the file contents. Hope it helps.
There might be some issues with \n and \r but it should get you started at least.
// Converts a file to a string
private String fileToString(String filename) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filename));
StringBuilder builder = new StringBuilder();
String line;
// For every line in the file, append it to the string builder
while((line = reader.readLine()) != null)
{
builder.append(line);
}
reader.close();
return builder.toString();
}
A: This will read a file from an URL and write it to a local file. Just add try/catch and imports as needed.
byte buf[] = new byte[4096];
URL url = new URL("http://path.to.file");
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(target_filename);
int bytesRead = 0;
while((bytesRead = bis.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.flush();
fos.close();
bis.close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5471406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Invalid Argument Running Google Go Binary in Linux I’ve written a very small application in Go, and configured an AWS Linux AMI to host. The application is a very simple web server. I’ve installed Go on the Linux VM by following the instructions in the official documentation to the letter. My application runs as expected when invoked with the “go run main.go” command.
However, I receive an “Invalid argument” error when I attempt to manually launch the binary file generated as a result of running “go install”. Instead, if I run “go build” (which I understand to be essentially the same thing, with a few exceptions) and then invoke the resulting binary, the application launches as expected.
I’m invoking the file from within the $GOPATH/bin/ folder as follows:
./myapp
I’ve also added $GOPATH/bin to the $PATH variable.
I have also moved the binary from $GOPATH/bin/ to the src folder, and successfully run it from there.
The Linux instance is a 64-bit instance, and I have installed the corresponding Go 64-bit installation.
A: go build builds everything (that is, all dependent packages), then produces the resulting executable files and then discards the intermediate results (see this for an alternative take; also consider carefully reading outputs of go help build and go help install).
go install, on the contrary, uses precompiled versions of the dependent packages, if it finds them; otherwise it builds them as well, and installs under $PATH/pkg. Hence I might suggest that go install sees some outdated packages which screw the resulting build.
Consider running go install ./... in your $GOPATH/src.
Or may be just selective go install uri/of/the/package for each dependent package, and then retry building the executable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31335579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Docker run on sub domains My goal is to deploy multiple webapps and access them through sub-domains, I'm currently running them on different ports, I have nginx on the server and the containers are running apache.
docker run -p 8001:80 -d apache-test1
docker run -p 8002:80 -d apache-test2
and I'm able to access them by going to
http://example.com:8001
or
http://example.com:8002
But I like to access them through sub-domains instead
http://example.com:8001 -> http://test1.example.com
http://example.com:8002 -> http://test2.example.com
I have nginx running on the server with the following server settings
server {
server_name test1.anomamedia.com;
location / {
proxy_redirect off;
proxy_set_header Host $host ;
proxy_set_header X-Real-IP $remote_addr ;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
proxy_pass http://localhost:8001;
}
}
server {
server_name test2.anomamedia.com;
location / {
proxy_redirect off;
proxy_set_header Host $host ;
proxy_set_header X-Real-IP $remote_addr ;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for ;
proxy_pass http://localhost:8002;
}
}
If its of any help this is my Dockerfile
FROM ubuntu
RUN apt-get update
RUN apt-get -y upgrade
RUN sudo apt-get -y install apache2 php5 libapache2-mod-php5
# Install apache, PHP, and supplimentary programs. curl and lynx-cur are for debugging the container.
RUN DEBIAN_FRONTEND=noninteractive apt-get -y install apache2 libapache2-mod-php5 php5-mysql php5-gd php-pear php-apc php5-curl curl lynx-cur
# Enable apache mods.
RUN a2enmod php5
RUN a2enmod rewrite
EXPOSE 80
# Copy site into place.
ADD html /var/www/html
# Update the default apache site with the config we created.
ADD apache-config.conf /etc/apache2/sites-enabled/000-default.conf
# By default, simply start apache.
CMD /usr/sbin/apache2ctl -D FOREGROUND
A: I have similar problems. Also I often need to add and remove containers, so I don't whant to edit nginx conf everytime. My solution was using jwilder/nginx-proxy.
then you just start containers with exposed port (--expose 80, not -p 80:80) and add env variables:
-e VIRTUAL_HOST=foo.bar.com
Don't forget to transfer with your main nginx traffic with right headers:
server {
listen 80;# default_server;
#send all subdomains to nginx-proxy
server_name *.bar.com;
#proxy to docker nginx reverse proxy
location / {
proxy_set_header X-Real-IP $remote_addr; #for some reason nginx
proxy_set_header Host $http_host; #doesn't pass these by default
proxy_pass http://127.0.0.1:5100;
}
}
A: Have a look at the nginx-proxy project (https://github.com/jwilder/nginx-proxy). I wrote a tutorial in my blog which demonstrates exactly what you want to achieve using it: https://blog.florianlopes.io/host-multiple-websites-on-single-host-docker
This tool automatically forwards requests to the appropriate container (based on subdomain via the VIRTUAL_HOST container environment variable).
For example, if you want to access your container through test1.example.com, simply set the VIRTUAL_HOST container environment variable to test1.example.com.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33586062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to improve look and feel of JAVA swing GUI? I am working on a project that uses Java Swing. The default look and feel of the Java Swing GUI is very boring. Is there any way I can use a better look and feel? Something like on web pages...
A: You can set the look and feel to reflect the platform:
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
If this is not nice enough for you, take a look at SWT for Eclipse.
A: if you're good with Photo shop you could declare the JFrame as undecorated and create your own image that will server as your custom GUI.
in this example refer to the JFrame as frame.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
//If you want full screen enter frame.setExtendedState(JFrame.MAXIMIZE_BOTH);
frame.setUndecorated(true);
now that the JFrame has its own border and custom GUI, if you defined your own custom buttons for minimize, maximize, and exit you need to lay a JPanel over the buttons and declare what those buttons will do in a action listener function(lol sorry...I don't know if it's called function like c++ or class...)
for example we will refer to the JPanel as panel and we will set up a exit button.
panel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.exit(JFrame.EXIT_ON_CLOSE);
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2592207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: smoothing between pixels of imagesc\imshow in matlab like the matplotlib imshow When I use matplotlib's imshow() in python to represent a small matrix, it produces a some sort if smoothing between pixels. Is there any way to have this in Matlab when using imshow or imagesc?
For example, using matplotlib this is the output of the identity matrix imshow(eye(3)):
while in matlab, imagesc(eye(3)):
A solution I can think of is to extrapolate and smooth using some filter, but that won't be relevant for the single pixel levels. I've also tried myaa and export_fig, but they are not satisfactory. Myaa is taking all GUI usabily after being applied, so I can't zoom in or out, and export_fig makes me save the figure to a file and then operate on that file, too cumbersome. So, is there a way to tell the figure engine of matlab (java or what not) to do this smoothing while keeping the nice usability of the figure GUI?
A: It is due to the default interpolation which is set to 'bilinear'. I think 'none' would be a more intuitive default. You can change the default interpolation method (eg interpolation=None) with:
mpl.rcParams['image.interpolation'] = 'none'
More information about customising Matplotlib can be found on the website
The code below will give you an overview of all interpolation methods:
methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', \
'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']
grid = np.random.rand(4,4)
fig, ax = plt.subplots(3,6,figsize=(12,6), subplot_kw={'xticks': [], 'yticks': []})
fig.subplots_adjust(hspace=0.3, wspace=0.05)
ax = ax.ravel()
for n, interp in enumerate(methods):
ax[n].imshow(grid, interpolation=interp)
ax[n].set_title(interp)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14722540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Why java ThreadPoolExecutor kill thread when RuntimeException occurs? Why the unhanded exception is rethrown in worker when calling execute method ? As result new Thread will be created on next execution to maximize threads count
A:
Why java ThreadPoolExecutor kill thread when RuntimeException occurs?
I can only guess that the reason why ThreadPoolExecutor.execute(...) has the thread call runnable.run() directly and not wrap it in a FutureTask is so you would not incur the overhead of the FutureTask if you didn't care about the result.
If your thread throws a RuntimeException, which is hopefully a rare thing, and there is no mechanism to return the exception to the caller then why pay for the wrapping class? So worst case, the thread is killed and will be reaped and restarted by the thread-pool.
A: There is no way to handle exception properly. Exception can't be propagated to caller thread and can't be simply swallowed.
Unhandled exception is thrown in thread is delegated to ThreadGroup.uncaughtException method, which prints output to System.err.print, until desired behavior is overridden for ThreadGroup.
So this is expected behavior, it can be compared with throwing unhanded exception in main method. In this case, JVM terminates execution and prints exception to the output.
But I'm not sure, why ThreadPoolExecutor does not handle it itself, ThreadPoolExecutor can log it itself. Creating new Thread is not so cheap.
Maybe there is an assumption, that some resources (native, threadLocal, threadStack, etc) associated with Thread should be released.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19123533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Array Compatiblilty java These are my instructions:
Two arrays are said to be compatible if they are of the same size and
if the ith element in the first array is greater than or equal to the
ith element in the second array for all elements. If the array size is
zero or less then display the message "Invalid array size". Write a Java
program to find whether 2 arrays are compatible or not. If the arrays
are compatible display the message as "Arrays are Compatible", if not
then display the message as "Arrays are Not Compatible".
My solution is as follows:
class CompaibleArrays {
public static void main(String []args){
int n1=0;
int n2=0;
int flag=0;
int []a1 = new int[20];
int []a2 = new int[20];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size for First array:");
n1 = sc.nextInt();
if(n1<1){
System.out.println("Invalid array size");
}
else{
System.out.println("Enter the elements for First array:");
for(int i=0 ; i<n1 ; i++){
a1[i] = sc.nextInt();
}
System.out.println("Enter the size for Second array:");
n2 = sc.nextInt();
if(n1<1){
System.out.println("Invalid array size");
}
else{
System.out.println("Enter the elements for Second array:");
for(int j=0 ; j<n2 ; j++){
a2[j] = sc.nextInt();
}
}
}
if(n1==n2){
System.out.println("Arrays are Not Compatible");
}
else{
for(int x=0 ; x<n1 ; x++){
if(a1[x]>=a2[x]){
flag++;
}
}
if(flag==n1){
System.out.println("Arrays are Compatible");
}
else{
System.out.println("Arrays are Not Compatible");
}
}
}
}
Sample Input 1 :
Enter the size for First array:
5
Enter the elements for First array:
5
14
17
19
15
Enter the size for Second array:
5
Enter the elements for Second array:
2
5
9
15
7
Sample Output 1:
Arrays are Compatible
Sample Input 2 :
Enter the size for First array:
3
Enter the elements for First array:
1
4
7
Enter the size for Second array:
5
Enter the elements for Second array:
2
5
9
5
7
Sample Output 2:
Arrays are Not Compatible
Sample Input 3 :
Enter the size for First array:
-2
Sample Output 3:
Invalid array size
** Help me out **
A: There are a few issues in your code.
*
*In your else block, you need to replace (n1<1) with (n2<1).
*Replace if(n1==n2) with if(n1!=n2)
*You do not need to iterate through all the elements. If at any point you find the index elements of both the arrays do not satisfy the condition, you should break the loop. Use a boolean flag for this.
public class CompaibleArrays {
public static void main(String []args){
int n1=0;
int n2=0;
boolean flag=true;
int []a1 = new int[20];
int []a2 = new int[20];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size for First array:");
n1 = sc.nextInt();
if(n1<1){
System.out.println("Invalid array size");
}
else{
System.out.println("Enter the elements for First array:");
for(int i=0 ; i<n1 ; i++){
a1[i] = sc.nextInt();
}
System.out.println("Enter the size for Second array:");
n2 = sc.nextInt();
if(n2<1){
System.out.println("Invalid array size");
}
else{
System.out.println("Enter the elements for Second array:");
for(int j=0 ; j<n2 ; j++){
a2[j] = sc.nextInt();
}
}
}
if(n1!=n2){
System.out.println("Arrays are Not Compatible");
}
else{
for(int x=0 ; x<n1 ; x++){
if(a1[x]<a2[x]){
flag = false;
break;
}
}
if(flag==true){
System.out.println("Arrays are Compatible");
}
else{
System.out.println("Arrays are Not Compatible");
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61717916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Use LIKE for strings in sql server 2008 I want to make a function that search in a table and returns rows that contain a certain word that I Insert like below. But when I use LIKE it give me an error: Incorrect syntax near '@perberesi'
CREATE FUNCTION perberesit7
(@perberesi varchar(100))
RETURNS @menu_rest TABLE
(emri_hotelit varchar(50),
emri_menuse varchar(50),
perberesit varchar(255))
AS
Begin
insert into @menu_rest
Select dbo.RESTORANTET.Emri_Rest, dbo.MENU.Emri_Pjatës, dbo.MENU.Pershkrimi
From RESTORANTET, MENU
Where dbo.MENU.Rest_ID=dbo.RESTORANTET.ID_Rest and
dbo.MENU.Pershkrimi LIKE %@perberesi%
return
End
Pleae help me...How can I use LIKE in this case
A: try using:
'%' + @perberesi + '%'
instead of:
%@perberesi%
Some Examples
A: Ok, I just realized that you are creating a function, which means that you can't use INSERT. You should also really take Gordon's advice and use explicit joins and table aliases.
CREATE FUNCTION perberesit7(@perberesi varchar(100))
RETURNS @menu_rest TABLE ( emri_hotelit varchar(50),
emri_menuse varchar(50),
perberesit varchar(255))
AS
Begin
return(
Select R.Emri_Rest, M.Emri_Pjatës, M.Pershkrimi
From RESTORANTET R
INNER JOIN MENU M
ON M.Rest_ID = R.ID_Rest
Where M.Pershkrimi LIKE '%' + @perberesi + '%')
End
A: Why do you have to define the return table?
The following is a inline table variable function that performs better than a multi-line table. I wrote one to return columns that have the two letters 'id'. Just modify for your own case.
See article from Wayne Sheffield.
http://blog.waynesheffield.com/wayne/archive/2012/02/comparing-inline-and-multistatement-table-valued-functions/
-- Use tempdb
use tempdb;
go
-- Simple ITVF
create function search_columns (@name varchar(128))
returns TABLE
return
(
select * from sys.columns where name like '%' + @name + '%'
)
go
-- Call the function
select * from search_columns('id');
go
However, since you have a '%' in the like clause at the front of the expression, a full table or index scan is likely. You might want to look at full text indexing if you data is large.
http://craftydba.com/?p=1629
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21414990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can Multiple WSO2 API manager integrate with single WSO2IS-KM 5.7.0? We have installed WSO2 IS-KM version 5.7.0 and we want to integrate Multiple WSO2 API Manager version 2.6.0 with WSO2 IS-KM.
Requesting you to please suggest and share the link to configure multiple WSO2 API manager with WSO2 IS-KM version 5.7.0
A: Please find a simple set of configurations on setting up multiple API Manager nodes with a single IS as Key Manager. It is required to front the API Manager nodes with a load balancer (with sticky sessions enabled & data-sources are shared among all the nodes) and configure the API Manager nodes as follows
API Manager Nodes: api-manager.xml (assumption IS-KM port offset 1, therefore 9444)
<AuthManager>
<!-- Server URL of the Authentication service -->
<ServerURL>https://localhost:9444/services/</ServerURL>
...
</AuthManager>
...
<APIKeyValidator>
<!-- Server URL of the API key manager -->
<ServerURL>https://localhost:9444/services/</ServerURL>
...
</APIKeyValidator>
IS Key Manager Node: api-manager.xml
<APIGateway>
<Environments>
<Environment type="hybrid" api-console="true">
...
<!-- Server URL of the API gateway -->
<ServerURL>https://loadbalancer/services/</ServerURL>
...
</APIGateway>
Sample NGINX
upstream mgtnode {
server localhost:9443; # api manager node 01
server localhost:9443; # api manager node 02
}
server {
listen 443;
server_name mgtgw.am.wso2.com;
proxy_set_header X-Forwarded-Port 443;
...
location / {
...
proxy_pass https://mgtnode;
}
}
References
*
*Configuring IS as Key Manager
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58324562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Tensorflow did not save the required models I ask tensorflow to save models every 100 iterations in every epoch, the following is my code. But after 900 iterations, only trained models for the 500th, 600th, 700th, 800th, 900th iterations were saved.
with tf.Session(config = tf.ConfigProto(log_device_placement = True)) as sess:
sess.run(init_op)
for i in range(args.num_epochs):
start_time = time.time()
k = 0
acc_train = 0
# initialize the iterator to train_dataset
sess.run(train_init_op)
while True:
try:
accu, l, _ = sess.run([accuracy, loss, optimizer], feed_dict = {training: True})
k += 1
acc_train += accu
if k % 100 == 0:
print('Epoch: {}, step: {}, training loss: {:.3f}, training accuracy: {:.2f}%'.format(i, k, l, accu * 100))
saver.save(sess, args.saved_model_path, global_step = (i+1) * k)
except tf.errors.OutOfRangeError:
break
The following is the training accuracies:
Epoch: 0, step: 100, training loss: 0.669, training accuracy: 59.38%
Epoch: 0, step: 200, training loss: 0.806, training accuracy: 54.69%
Epoch: 0, step: 300, training loss: 0.781, training accuracy: 57.81%
Epoch: 0, step: 400, training loss: 0.725, training accuracy: 64.06%
Epoch: 0, step: 500, training loss: 0.347, training accuracy: 89.06%
Epoch: 0, step: 600, training loss: 0.193, training accuracy: 89.06%
Epoch: 0, step: 700, training loss: 0.003, training accuracy: 100.00%
Epoch: 0, step: 800, training loss: 0.190, training accuracy: 98.44%
Epoch: 0, step: 900, training loss: 0.009, training accuracy: 100.00%
My question is why tensorflow did not saved models for the 100th, 200th, 300th, 400th iterations? Thank you!
A: It did, but I'm guessing the Saver instance you created had the default max_keep value of 5, so it overwrote them as the last 5 were created. To keep 10, change your saver creation line to
saver = tf.train.Saver(max_keep=10)
You might also want to play with the keep_checkpoint_every_n_hours argument if you don't want to save -every- one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50439794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Embedding Loops with 2 Variables Dim rng As Range, cell As Range, copyToCell As Range
For j = 9 To 23
For i = 2 To 23
Set rng = ThisWorkbook.Sheets("Sheet A").Range(Cells(3, j), Cells(11, j))
Set copyToCell = ThisWorkbook.Sheets("Sheet B").Cells(3, i)
For Each cell In rng
If cell.Value <> vbNullString Then
copyToCell.Value = cell.Value
Set copyToCell = copyToCell.Offset(1, 0)
End If
Next cell
i = i + 2
Next i
j = j + 2
Next j
I'm trying to copy an array of cells from one sheet and have them pasted to another. The code I wrote places the values that are copied from "Sheet A" to "Sheet B" correctly, however, the values are incorrect.
The pic above is Sheet A. I'm trying to copy values from Range I3:Ill (Sheet A) and then have them pasted to the following Sheet B Range B3:B11 and so on for each plan listed.
I created a loop so that the values under Plan 2 and so on in Sheet A will transfer those values under Plan 2 and so on in Sheet B.
When I run my code it results in all 0's in each plan on Sheet B instead of 5,5,4 (under Plan 1) and 5 (under plan 2). Any ideas or another way around it besides having to use 2 variables in a loop?
A: Why the loop? Just put the loop values in the Range statements:
Dim rng As Range, cell As Range, copyToCell As Range
Set rng = ThisWorkbook.Sheets("Sheet1").Range(Cells(9, "j"), Cells(23, "j"))
Set copyToCell = ThisWorkbook.Sheets("Sheet2").Cells(3, "i")
rng.Copy copyToCell
End Sub
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62582814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular directive - update parent scope when another directive as also isolated scope I have written an angular directive that needs to update the parent scope.
angular.module('app').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
$scope.property1 = 'some val';
$scope.property2 = 'another val';
$scope.$apply();
};
});
But in my controller I do this:
MyCtrl = function($scope){
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
When doSave runs, I'm getting undefined values in my console. How can I get it applied to the parents scope WITHOUT isolating the scope. I don't have this option because another directive on the same element isolates the scope.
A: It should work. By default if you don't specify scope in your directive it uses the parent scope so property1 and property2 should be set. try setting the scope in your directive to false. As a side note is not a good practice what you are doing. It will be better isolate the scope and add the property as attributes. This way you will have good encapsulation.
for example
angular.module('app').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
property1: '=',
property2: '='
}
link: function ($scope, element, attributes, model) {
//here you have access to property 1 and 2
};
});
function MyCtrl($scope) {
$scope.property1 = null;
$scope.property2 = null;
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
And your html
<div ng-control="MyCtrl">
<div google-place property1='property1' property2='property2'></div>
</div>
A: I don't know what you are doing wrong, because it seems to work: http://jsfiddle.net/HB7LU/2865/
var myApp = angular.module('myApp',[]);
angular.module('myApp').directive('googlePlace', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attributes, model) {
$scope.property1 = 'some val';
$scope.property2 = 'another val';
$scope.$apply();
}
}
});
angular.module('myApp').controller('MyCtrl', MyCtrl);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.doSave = function(){
// do some logic
console.log($scope.property1);
console.log($scope.property2);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22750051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Use API v2 to work with Customer Group Prices We are using a tool to integrate our financial software with Magento.
Does anyone know a way to write and read the Customer Group Prices with API v2?
Each customer has a different agreed price for products in Dynamics GP and we need to match this price in Magento.
This way, when a Customer logs into the Magento site, their agreed price will be displayed in all simple products.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28564137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Instance variable to stop a running thread Header :
@interface CodeTest : NSObject {
BOOL cancelThread;
}
-(void) testCode;
-(void) stopRunning;
-(void) startRunning;
@property (assign) BOOL cancelThread;
@end
Implementation :
-(void)stopRunning{
self.cancelThread = YES;
}
-(void)startRunning{
self.cancelThread = NO;
[NSThread detachNewThreadSelector:@selector(testCode) toTarget:self withObject:nil];
}
-(void)testCode{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"STARTED");
/* Std C99 code */
while( conditions ){
if(self.cancelThread){
conditions = NO;
}
...
...
}
/* end of C code */
[pool release];
}
As you can see, it tires to execute testCode on a separate thread and using the cancelThread BOOL as a stop execution flag in the separate thread.
I have the following issue :
*
*The compiler signals that self.cancelThread in the middle of the std c code is not valid (self is not defined). I think, it tries to interpret that statement as c code but this is obj-c.
There is something missing ?
UPDATE : It's not related to missing {}'s as one of you suggested... The code works perfectly without the if(self.cancelThread){ conditions = NO; }.
A:
-[CodeTest setCancelThread:]: unrecognized selector.
Means that you don't have a setter defined for the cancelThread property. You're missing
@synthesize cancelThread;
(in your @implementation section)
A: What do you mean by " /* Std C99 code */"?
If that code is really being compiled as C99 code, then self.cancelThread is problematic because it is an Objective-C expression. First, it is the equivalent of [self cancelThread], a method call and, secondly, it requiresself` which wouldn't be present in the body of a C99 function.
However, given that the code you showed has it in a method, the comment doesn't make sense.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4782938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Obfuscating Android library projects I'm using AndEngine and two AndEngine extensions, for a total of 3 library projects. I really wish that I could obfuscate and optimize these library projects to improve application size, but I haven't seen anywhere how to do that with library projects.
Does anyone know what the Proguard configuration to do this is?
A: When Application is compiled, all *.java files in references Library Projects are compiled into Application's bin/classes folder. And obfuscation step is done using .class files in this folder. This means that all referenced Library Projects are automatically obfuscated when you obfuscate your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7074314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySqlException: Unable to connect to any of the specified MySQL hosts. MySql.Data.MySqlClient.NativeDriver.Open() Here is the code that connects to MySql and attemps to query data, and these are the errors i'm getting:
An unhandled exception occurred while processing the request.
MySqlException: Timeout expired. The timeout period elapsed prior to
completion of the operation or the server is not responding.
MySql.Data.Common.StreamCreator.GetTcpStream(MySqlConnectionStringBuilder
settings)
MySqlException: Unable to connect to any of the specified MySQL hosts.
MySql.Data.MySqlClient.NativeDriver.Open()
public async Task<List<Store>> getStores(double lat, double lng)
{
List<Store> stores = new List<Store>();
using (MySqlConnection connection = GetConnection())
{
await connection.OpenAsync(); // the code blows up here from time to time
// request to return nearby stores
MySqlCommand cmd = new MySqlCommand("SELECT * FROM Stores WHERE ABS(latitude- @latitude) < 0.006 AND ABS(longitude - @longtitude) < 0.006", connection);
cmd.Parameters.Add(new MySqlParameter("@latitude", lat));
cmd.Parameters.Add(new MySqlParameter("@longtitude", lng));
cmd.CommandTimeout = 120;
// MySqlDataAdapter dataAdapter = new MySqlDataAdapter(cmd);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
stores.Add(new Store()
{
id = Convert.ToInt32(reader["id"]),
address = reader["address"].ToString(),
latitude = Convert.ToDouble(reader["latitude"]),
longtitude = Convert.ToDouble(reader["longitude"])
});
}
}
}
return stores;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61860087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HighCharts: align rotated multiline label I'm trying to align axis labels in HighCharts
Labels should not be trimed, so ellipsis is not allowed
How it looks now:
How I want it to be:
Code: https://jsfiddle.net/9xw6dL3f/25/
{
"chart": {
"width": 500,
"height": 300,
"type": "column"
},
"title": {
"text": null
},
"xAxis": {
"type": "category",
"labels": {
"rotation": -90,
"style": {
"textOverflow": "none"
}
}
},
"series": [
{
"name": "",
"data": [
{ "name": "Follow me into my theatre of lunacy", "y": -10, "color": "#ABC" },
{ "name": "1", "y": 1, "color": "#000" },
{ "name": "2", "y": 2, "color": "#000" },
{ "name": "3", "y": 3, "color": "#000" },
{ "name": "4", "y": 4, "color": "#000" },
{ "name": "5", "y": 5, "color": "#000" },
]
}
]
}
A: It is possible to move label depending on it's rows count
Add render function to the chart object
{
"chart": {
...
events: {
render() {
for (let i = 0; i < this.xAxis[0].names.length; i++) {
const label = this.xAxis[0].ticks[i].label;
const rows = (label.element.innerHTML.match(/<\/tspan>/g) || []).length;
label.translate(-8 * rows, 0);
}
}
}
where 8 is half of row size in px
https://jsfiddle.net/kLz1uoga/5/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72054718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why syntax error when import my own modules in Python I created my own python package with "python setup.py bdist_wheel" and "pip install /path/to/dist/my_own_package.wheel". After installing it, when importing it, there is error of "SyntaxError: invalid syntax". Could you help? thanks.
>>> import my-modules
File "<stdin>", line 1
import my-modules
^
SyntaxError: invalid syntax
But there is module installed in Continuum\anaconda3\Lib\site-packages
A: Your module has a minus symbol in the title. That's the reason. Sometimes (nearly never) the underline symbol may be the fault. If you name your module like "myModules" or "modules", there would be no error.
WRONG:
>>> import my-modules
File "<stdin>", line 1
import my-modules
^
SyntaxError: invalid syntax
VALID:
>>> import myModules
#No error
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57840684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you pull certain substrings(ip addresses) out of strings(Wireshark Output)? I am reading the contents of a wireshark dump from a text file, line by line. One of the things I can pick out easily is the protocol used in that specific line of the wireshark output(as shown in the code below). The problem I'm running into is pulling out the ip addressess from the line. As you can see in the sample output below, and my code, it was fairly easy to pull out the protocol because it was always capitialized and there was a space on either side of it. The ip addresses however, aren't as uniform and I'm not quite sure how to pull them out as well. This is mostly due to the fact that I'm not quite sure how all the parts of the re.match() work. Can somebody help me out in this, and possibly explain how the re.match() parameters work?
file = open('tcpdump.txt', 'r');
for line in file:
matchObj = re.match(r'(.*) TCP (.*?) .*', line, re.M)
Sample Wireshark Output:
604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0
A: The first regex group is greedy (.*) and is matching everything, you can make it non-greedy by adding ?, i.e.:
file = open('tcpdump.txt', 'r');
for line in file:
matchObj = re.match(r"->\s(.*?)\s(\w+)\s(.*?)\s", line, re.M)
The above example is will capture 3 groups containing the remote address 114.113.226.43, protocol TCP and port 54 respectively.
Regex101 Demo
A: Start by look at the regex documentation, for python it is here:
https://docs.python.org/3/library/re.html
There are also many sites that have good tutorials, samples and interactive testers such as:
http://regexr.com/
I don't know the output format of wireshark, but I would imagine it is documented somewhere.
This should get your ip addresses:
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b
A: As people have already responded, regex is the way to go. A sample code for the purpose
import unittest
import re
from collections import namedtuple
protocol = namedtuple('Protocol', ['source', 'destination', 'protocol'])
def parse_wireshark(input):
pat = re.findall(r"(\d+\.\d+\.\d+\.\d+) -> (\d+\.\d+\.\d+\.\d+) (\w+)", input)[0]
return protocol(source=pat[0], destination=pat[1], protocol=pat[2])
class TestWireShark(unittest.TestCase):
def test_sample(self):
self.assertEqual(parse_wireshark("604 1820.381625 10.200.59.77 -> 114.113.226.43 TCP 54 ssh > 47820 [FIN, ACK] Seq=1848 Ack=522 Win=16616 Len=0"),
protocol(source='10.200.59.77',
destination='114.113.226.43',
protocol='TCP'))
if __name__ == '__main__':
unittest.main()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36928007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Merge two Arraylist & retains all the value in Java I have 2 arrayList of PresentErrorList & PastErrorList both having 3 fields errorCode,presentErrorCount & pastErrorCount .
presentErrorList
[errorCode=1000,presentErrorCount=10,pastErrorCount =0]
[errorCode=1100,presentErrorCount=2,pastErrorCount =0]
pastErrorList
[errorCode=1003,presentErrorCount=0,pastErrorCount =10]
[errorCode=1104,presentErrorCount=0,pastErrorCount =12]
[errorCode=1000,presentErrorCount=0,pastErrorCount =12]
While calculating for Present, pastErrorCount =0 and viceversa . My finalArrayList should be
[errorCode=1000,presentErrorCount=10,**pastErrorCount =12**]
[errorCode=1100,presentErrorCount=2,pastErrorCount =0]
[errorCode=1003,presentErrorCount=0,pastErrorCount =10]
[errorCode=1104,presentErrorCount=0,pastErrorCount =12]`
As you can see in the final list for errorCode=1000 as it is duplicate in past so there will be only 1 object with both present & past error count .
A: So there was not easy to find a way but a the end that's what I do :
public static void main(String[] args) {
List<ErrorCodeModel> presentErrorList = new ArrayList<>();
presentErrorList.add(new ErrorCodeModel("1000", 10, 0));
presentErrorList.add(new ErrorCodeModel("1100", 2, 0));
List<ErrorCodeModel> pastErrorList = new ArrayList<>();
pastErrorList.add(new ErrorCodeModel("1003", 0, 10));
pastErrorList.add(new ErrorCodeModel("1104", 0, 12));
pastErrorList.add(new ErrorCodeModel("1000", 0, 12));
Map<String, ErrorCodeModel> map = Stream.of(presentErrorList, pastErrorList)
.flatMap(Collection::stream)
.collect(Collectors.toMap(ErrorCodeModel::getErrorCode,
Function.identity(),
(oldValue, newValue)
-> new ErrorCodeModel(oldValue.getErrorCode(),
oldValue.getPresentErrorCount()+newValue.getPresentErrorCount(),
oldValue.getPastErrorCount()+newValue.getPastErrorCount())));
List<ErrorCodeModel> errorList = new ArrayList<>(map.values());
errorList.sort((err1, err2) //line 20*
-> Integer.compare(Integer.parseInt(err1.getErrorCode()),
Integer.parseInt(err2.getErrorCode())));
System.out.println(errorList.toString());
//*line 20 : Optionnal, if you want to sort by errorCode
//(need to parse to int to avoir alphabetical order
}
So after add your elements, this is what is done :
*
*A stream of each 2 List is done
*the goal is to add them in a Map : (object's code, object)
*the (oldValue,newValue) lambda-exp is used is the key is always in the map, I tell it to add a new Object which has the sum of previous and the new to add
*after the map, a List is generated from the values which represents the ErrorCodeModel as you ask
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45167208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 315 error when tryin to connect to ADS Database
This error occurs when i try to connect to a remote ads data dictionary. When researching the error code 315 results only came up for error code 314.
A: Fixed this issue by installing aceapi and setting the path of the vendor lib to the syswow path of ace32.dll in FDDrivers.ini
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67726153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mergesort of multi-dimensional array in Java I have a function which should sort a 2D String array according to a feature index. Here is my 2D array of 4 elements (4 x 10).
String[][] testArr = {
{"192.168.1.101-67.212.184.66-2156-80-6","192.168.1.101","2156","67.212.184.66","80","6","13/06/2010 06:01:11","2328040","2","0"}
,{"192.168.1.101-67.212.184.66-2159-80-6","192.168.1.101","2159","67.212.184.66","80","6","13/06/2010 06:01:11","2328006","2","0"}
,{"192.168.2.106-192.168.2.113-3709-139-6","192.168.2.106","3709","192.168.2.113","139","6","13/06/2010 06:01:16","7917","10","9"}
,{"192.168.5.122-64.12.90.98-59707-25-6","192.168.5.122","59707","64.12.90.98","25","6","13/06/2010 06:01:25","113992","6","3"}
};
I want to sort these elements according to lets say their 7th index, which is (2328040,2328006,7917,113992) in each element respectively. Here is the function I wrote for it:
// ************MERGE SORT***************************
public static void mergeSort(String[][] arr,int featureIndex){
mergeSort(arr,new String [arr.length][10],0,arr.length-1,featureIndex);
}
// MERGE SORT HELPER FUNCTION
public static void mergeSort(String[][] arr,String [][] temp,int leftStart,int rightEnd,int featureIndex){
if(leftStart >= rightEnd){
return;
}
int mid = (leftStart + rightEnd)/2;
mergeSort(arr,temp,leftStart, mid,featureIndex);
mergeSort(arr,temp,mid + 1, rightEnd,featureIndex);
mergeHalves(arr,temp,leftStart,rightEnd,featureIndex);
}
// Merge 2 Halves
public static void mergeHalves(String[][] arr,String[][] temp,int leftStart,int rightEnd,int featureIndex){
int leftEnd = (rightEnd + leftStart)/2;
int rightStart = leftEnd + 1;
int size = rightEnd - leftStart + 1;
int left = leftStart;
int right = rightStart;
int index = leftStart;
while(left <= leftEnd && right <= rightEnd){
if(Double.parseDouble(arr[left][featureIndex]) <= Double.parseDouble(arr[right][featureIndex])){
temp[index][featureIndex] = arr[left][featureIndex];
left++;
}else{
temp[index][featureIndex] = arr[right][featureIndex];
right++;
}
index++;
}
// Copy the arrays
System.arraycopy(arr, left, temp, index, leftEnd - left + 1);
System.arraycopy(arr, right, temp, index, rightEnd - right + 1);
System.arraycopy(temp, leftStart, arr, leftStart, size);
}
When I run the program it prints out 7917 7917 7917 113992 respectively for each element.
A: This is a great question because it brings up the complicated problem of sorting a table with columns of unlike types. Later versions of Java implement new sorting tools you can use. Here's my solution to your problem using JDK 1.8 (Java 8). It's printing only fields 0,1,7 although you can easily add in the rest of the fields.
First class file:
package intquestions;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.out;
import intquestions.StaffComparator;
public class SortDataList {
public static void main(String[] args) {
runit(); }
public static void runit() {
Object[] list1 = {"192.168.1.101-67.212.184.66-2156-80-6","192.168.1.101","2156","67.212.184.66","80","6","13/06/2010 06:01:11",2328040,"2","0" };
Object[] list2 = {"192.168.1.101-67.212.184.66-2159-80-6","192.168.1.101","2159","67.212.184.66","80","6","13/06/2010 06:01:11",2328006,"2","0"};
Object[] list3 = {"192.168.2.106-192.168.2.113-3709-139-6","192.168.2.106","3709","192.168.2.113","139","6","13/06/2010 06:01:16",7917,"10","9"};
Object[] list4 = {"192.168.5.122-64.12.90.98-59707-25-6","192.168.5.122","59707","64.12.90.98","25","6","13/06/2010 06:01:25",113992,"6","3"};
ArrayList<DataList> mList=new java.util.ArrayList<DataList>();
mList.add(new DataList(list1));
mList.add(new DataList(list2));
mList.add(new DataList(list3));
mList.add(new DataList(list4));
String sep = " | " ;
out.println("BEFORE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ---------------------- : " );
out.println(mList.get(0).s.toString() +sep+ mList.get(0).f.toString() +sep+ mList.get(0).eighth.toString());
out.println(mList.get(1).s.toString() +sep+ mList.get(1).f.toString() +sep+ mList.get(1).eighth.toString());
out.println(mList.get(2).s.toString() +sep+ mList.get(2).f.toString() +sep+ mList.get(2).eighth.toString());
out.println(mList.get(3).s.toString() +sep+ mList.get(3).f.toString() +sep+ mList.get(3).eighth.toString());
StaffComparator myComparator = new StaffComparator();
try { Collections.sort(mList, myComparator);
} catch (Exception e) { out.println(e); }
out.println("\nDONE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ----------------------- : " );
out.println(mList.get(0).s.toString() +sep+ mList.get(0).f.toString() +sep+ mList.get(0).eighth.toString());
out.println(mList.get(1).s.toString() +sep+ mList.get(1).f.toString() +sep+ mList.get(1).eighth.toString());
out.println(mList.get(2).s.toString() +sep+ mList.get(2).f.toString() +sep+ mList.get(2).eighth.toString());
out.println(mList.get(3).s.toString() +sep+ mList.get(3).f.toString() +sep+ mList.get(3).eighth.toString());
}
}
class DataList extends DataListAbstract {
public DataList(Object[] myObj) {
super(myObj); }
public Integer getEighth(DataList locVarDataList) {
return locVarDataList.eighth; }
@Override
public int compareTo(DataListAbstract o) {
return 0; }
}
abstract class DataListAbstract implements Comparable<DataListAbstract> {
String f; // first
String s; //second
Integer eighth;
DataListAbstract(Object[] myo) {
this.eighth = (Integer)myo[7];
this.f = (String)myo[0];
this.s = (String)myo[1];
}
}
Second class:
package intquestions;
import java.util.Comparator;
public class StaffComparator implements Comparator<DataList> {
public int compare(DataList c1, DataList c2) {
Integer firstInt = c1.getEighth(c1);
Integer secondInt = c2.getEighth(c2);
return firstInt.compareTo(secondInt);
}
}
Output:
BEFORE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ---------------------- :
192.168.1.101 | 192.168.1.101-67.212.184.66-2156-80-6 | 2328040
192.168.1.101 | 192.168.1.101-67.212.184.66-2159-80-6 | 2328006
192.168.2.106 | 192.168.2.106-192.168.2.113-3709-139-6 | 7917
192.168.5.122 | 192.168.5.122-64.12.90.98-59707-25-6 | 113992
DONE SORTING - ONLY PRINTING FIELDS 1,2,8 (0,1,7) ----------------------- :
192.168.2.106 | 192.168.2.106-192.168.2.113-3709-139-6 | 7917
192.168.5.122 | 192.168.5.122-64.12.90.98-59707-25-6 | 113992
192.168.1.101 | 192.168.1.101-67.212.184.66-2159-80-6 | 2328006
192.168.1.101 | 192.168.1.101-67.212.184.66-2156-80-6 | 2328040
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49214896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java -Sorting Strings, some kind of Basicly I have two arrays of Strings. One of the String contains a number, the second string contains text and a number.
How can I match these together, please?
Example:
private String[] StringArray1 = {"5648", "4216", "3254", "2541", "10"};
private String[] StringArray2 = {"Derp: 10", "Herp: 3254", "peter: 2541", "jdp: 4216", "dieter: 5648"};
Output should be:
dieter: 5648
jdp: 4216
Herp: 3254
peter: 2541
Derp: 10
Well, all I want is to sort StringArray2 for values, so it starts with the highest and I can print it out then.
A: It will be good if you convert the second array into MAP then you can easily complete your task.Key will be number and value will be text of array in MAP
A: Use a HashMap:
HashMap<String,String> hashMap = new HashMap<String,String>();
String[] string1 = {"5648", "4216", "3254", "2541", "10"};
String[] string2 = {"Derp: 10", "Herp: 3254", "peter: 2541", "jdp: 4216", "dieter: 5648"};
for (String str : string2)
{
String[] keyVal = str.split(": ");
hashMap.put(keyVal[1],keyVal[0]);
}
for (String key : string1)
{
String val = hashMap.get(key);
System.out.println(val+": "+key);
}
A: Using the Map is good solution.
for example:
Map<String, Integer> data = new HashMap<String, Integer>();
data.put("Herp", 3254);
data.put("peter", 2541);
//...
for (String name: data.keySet()) {
System.out.println(name + ": " + data.get(name) );
}
Yes, if this data is your input, collect the map as described in previous answer. But if possible, use the map initially.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21366227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to fast search a string in a Excel file I am writing a JAVA program to search a string in a Excel file and extract the row which contains this certain string. I found all the related methods are looking all the rows one by one, and use .contain() method to tell whether this row contain the string or not. But the problems are:
a. There are large amount of strings to match.
b. The Excel files are very very large.
So I am curious about is there anyway to quickly search the string in a Excel file without iterating each line? Thanks a lot!
A: Search algorithms in general have a performance of O(n) on a not presorted list. If there is no information given about the Excel file you are searching in, there is no algorithm with a better worst-case performance than O(n).
So, that means, iterating over each line until the derised line(s) is found is necessary, no matter what. If you want to improve performance, you can try to use parallelization, for instance MapReduce: https://en.wikipedia.org/wiki/MapReduce
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37777785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linux C Programming - FTP server won't respond through sockets So I am trying to make my own FTP client, I was able to connect to a ftp server and get the "220" response code but when I try to send ANY command the recv function just gets blocked. This is my code:
I have tried multiple free ftp servers and I was able to connect to all of them and get a 220 response code but from there I couldn't communicate with them at all.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define ERR(str) {printf("%s errno says: %s\n", str, strerror(errno));}
int getFTPcode(int sock){
char response[2550];
if(0 > recv(sock, response, 2550, 0)){
ERR("ftp response failed to recv");
return 0;
}
printf("%s\n", response);
while(1){
char msg[2000];
printf("Enter command:");
scanf("%s", msg);
if(0 > send(sock, msg, strlen(msg), 0)){
ERR("failed to send to server");
return 0;
}
if(0 > recv(sock, response, 2000, 0)){
ERR("failed to recv from server");
return 0;
}
printf("Response: %s\n", response);
}
printf("%s\n", response);
}
int connToOrig(char* ip, short port){
struct sockaddr_in addrin;
memset(&addrin, '0', sizeof(struct sockaddr_in));
addrin.sin_family = AF_INET;
addrin.sin_port = htons(port);
if(inet_pton(AF_INET, ip, &addrin.sin_addr) < 0){
ERR("inet_pton failed");
return 0;
}
int sock;
if(0 > (sock = socket(AF_INET, SOCK_STREAM, 0))){
ERR("socket() failed");
return 0;
}
if(connect(sock, (struct sockaddr*)&addrin, sizeof(addrin)) < 0){
ERR("connection to the origin server failed");
return 0;
}
printf("connection succesfull\n");
getFTPcode(sock);
return 1;
}
int main(int argc, char** argv){
connToOrig(argv[1], 21);
return 0;
}
A: Well jokes on me, the problem was that I was not appending '\n' to the messages that I was sending to the ftp server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47727995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Loading Glide image I am working on developing an app to play songs, I use Glide to get the image of the song and display it in the ListView,
the first problem
when I scrolling in my ListView the application becomes slow, and I have another problem which is when I scrolling Up the Glide load the images that have already been loaded Is there a way to fix these problems?
here is my code to get the image of songs
`
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class ListAdapter
extends BaseAdapter {
private Context context;
private static ArrayList<ListItemFromPhone> newList = new ArrayList<>();
ListAdapter(){}
ListAdapter(Context context, ArrayList<ListItemFromPhone> list) {
notifyDataSetChanged();
this.context = context;
newList = list;
}
@Override
public int getCount() {
return newList.size();
}
@Override
public Object getItem(int position) {
return newList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.view,null);
TextView textView = view.findViewById(R.id.textView);
final ImageView imageView = view.findViewById(R.id.imageView);
byte [] imgArtist = getImg(newList.get(position).data);
if (imgArtist != null){
Glide.with(context).asBitmap()
.load(imgArtist)
.placeholder(R.drawable.music_img)
.into(imageView);
}
else imageView.setImageResource(R.drawable.music_img);
textView.setText(newList.get(position).name);
return view;
}
private byte[] getImg(String path){
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(path);
byte[] img = retriever.getEmbeddedPicture();
retriever.release();
return img;
}
}
A: To avoid this problem you must use RecyclerView. There are a lot of tutorials on youtube on how to implement it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67709309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Show tree structure hierarchy via JSON Schema I'm trying to achieve orgchart tree structure via JSON Schema. I'm trying to map Id with BossId and Id is unique and whoever has BossId of Id is the sub-employee of that BossId. I've tried a jQuery plugin and Google Org Chart. But both of those have different schema as to mine. My JSON Schema is
[
{
"BossId": "3",
"DateOfBirth": "1966-09-27T00:00:00",
"FamilyName": "Montejano",
"Gender": "Unspecified",
"GivenName": "Trinh",
"Id": "08",
"Title": "Tech Manager"
},
{
"BossId": "0",
"DateOfBirth": "1927-01-29T00:00:00",
"FamilyName": "Fetzer",
"Gender": "Unspecified",
"GivenName": "Winfred",
"Id": "00",
"Title": "CEO"
},
{
"BossId": "1",
"DateOfBirth": "1927-08-20T00:00:00",
"FamilyName": "Dandrea",
"Gender": "Male",
"GivenName": "Erich",
"Id": "02",
"Title": "VP of Marketing"
},
{
"BossId": "1",
"DateOfBirth": "1929-02-07T00:00:00",
"FamilyName": "Nisbet",
"Gender": "Male",
"GivenName": "Reinaldo",
"Id": "03",
"Title": "VP of Technology"
},
{
"BossId": "1",
"DateOfBirth": "1932-06-13T00:00:00",
"FamilyName": "Bufford",
"Gender": "Unspecified",
"GivenName": "Alleen",
"Id": "04",
"Title": "VP of HR"
},
{
"BossId": "2",
"DateOfBirth": "1936-09-26T00:00:00",
"FamilyName": "Klopfer",
"Gender": "Female",
"GivenName": "Kristyn",
"Id": "05",
"Title": "Director of Marketing"
},
{
"BossId": "1",
"DateOfBirth": "1937-11-23T00:00:00",
"FamilyName": "Duhon",
"Gender": "Male",
"GivenName": "Sophie",
"Id": "01",
"Title": "Tech Manager"
},
{
"BossId": "3",
"DateOfBirth": "1948-04-05T00:00:00",
"FamilyName": "Mirabal",
"Gender": "Female",
"GivenName": "Suanne",
"Id": "07",
"Title": "Tech Manager"
},
{
"BossId": "4",
"DateOfBirth": "1966-10-13T00:00:00",
"FamilyName": "Maslowski",
"Gender": "Unspecified",
"GivenName": "Norah",
"Id": "09",
"Title": "Tech Manager"
},
{
"BossId": "6",
"DateOfBirth": "1967-08-25T00:00:00",
"FamilyName": "Redford",
"Gender": "Female",
"GivenName": "Gertrudis",
"Id": "10",
"Title": "Tech Lead"
},
{
"BossId": "6",
"DateOfBirth": "1968-12-26T00:00:00",
"FamilyName": "Tobey",
"Gender": "Male",
"GivenName": "Donovan",
"Id": "11",
"Title": "Tech Lead"
},
{
"BossId": "9",
"DateOfBirth": "1969-10-16T00:00:00",
"FamilyName": "Vermeulen",
"Gender": "Male",
"GivenName": "Rich",
"Id": "12",
"Title": "Trainer Lead"
},
{
"BossId": "9",
"DateOfBirth": "1972-10-16T00:00:00",
"FamilyName": "Knupp",
"Gender": "Male",
"GivenName": "Santo",
"Id": "13",
"Title": "HR Manager"
},
{
"BossId": "12",
"DateOfBirth": "1974-03-23T00:00:00",
"FamilyName": "Grooms",
"Gender": "Female",
"GivenName": "Jazmin",
"Id": "14",
"Title": "Trainer"
},
{
"BossId": "13",
"DateOfBirth": "1978-08-25T00:00:00",
"FamilyName": "Cheeks",
"Gender": "Female",
"GivenName": "Annelle",
"Id": "15",
"Title": "Recruiter"
},
{
"BossId": "15",
"DateOfBirth": "1979-08-21T00:00:00",
"FamilyName": "Harshaw",
"Gender": "Unspecified",
"GivenName": "Eliza",
"Id": "16",
"Title": "Trainer"
},
{
"BossId": "8",
"DateOfBirth": "1980-02-09T00:00:00",
"FamilyName": "Broaddus",
"Gender": "Unspecified",
"GivenName": "Xiomara",
"Id": "17",
"Title": "Senior Software Developer"
},
{
"BossId": "11",
"DateOfBirth": "1981-09-08T00:00:00",
"FamilyName": "Jungers",
"Gender": "Unspecified",
"GivenName": "Erminia",
"Id": "18",
"Title": "Software Developer"
},
{
"BossId": "10",
"DateOfBirth": "1984-03-18T00:00:00",
"FamilyName": "Moffatt",
"Gender": "Female",
"GivenName": "Maria",
"Id": "19",
"Title": "Software Developer"
},
{
"BossId": "10",
"DateOfBirth": "1990-09-24T00:00:00",
"FamilyName": "Grimaldo",
"Gender": "Female",
"GivenName": "Tammera",
"Id": "20",
"Title": "Senior Software Developer"
},
{
"BossId": "10",
"DateOfBirth": "1992-06-18T00:00:00",
"FamilyName": "Das",
"Gender": "Female",
"GivenName": "Sharyl",
"Id": "21",
"Title": "Software Developer"
},
{
"BossId": "8",
"DateOfBirth": "1993-11-15T00:00:00",
"FamilyName": "Harlan",
"Gender": "Unspecified",
"GivenName": "Shan",
"Id": "22",
"Title": "UI Developer"
},
{
"BossId": "11",
"DateOfBirth": "1997-03-23T00:00:00",
"FamilyName": "Almeida",
"Gender": "Female",
"GivenName": "Mariah",
"Id": "23",
"Title": "QA Tester"
},
{
"BossId": "11",
"DateOfBirth": "1998-11-10T00:00:00",
"FamilyName": "Kerfien",
"Gender": "Male",
"GivenName": "Darnell",
"Id": "24",
"Title": "QA Tester"
},
{
"BossId": "11",
"DateOfBirth": "2004-04-22T00:00:00",
"FamilyName": "Vierra",
"Gender": "Female",
"GivenName": "Janell",
"Id": "25",
"Title": "QA Tester"
}
]
BossId : 0 is the CEO and beneath him every other employee is
A: Please see fiddle and code below, JSON unmodified and it currently contains disconnection as seen in fiddle.
Fiddle
https://jsfiddle.net/shL7tjpa/2/
Code
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);
var members = [
{
"BossId": "3",
"DateOfBirth": "1966-09-27T00:00:00",
"FamilyName": "Montejano",
"Gender": "Unspecified",
"GivenName": "Trinh",
"Id": "08",
"Title": "Tech Manager"
},
{
"BossId": "0",
"DateOfBirth": "1927-01-29T00:00:00",
"FamilyName": "Fetzer",
"Gender": "Unspecified",
"GivenName": "Winfred",
"Id": "00",
"Title": "CEO"
},
{
"BossId": "1",
"DateOfBirth": "1927-08-20T00:00:00",
"FamilyName": "Dandrea",
"Gender": "Male",
"GivenName": "Erich",
"Id": "02",
"Title": "VP of Marketing"
},
{
"BossId": "1",
"DateOfBirth": "1929-02-07T00:00:00",
"FamilyName": "Nisbet",
"Gender": "Male",
"GivenName": "Reinaldo",
"Id": "03",
"Title": "VP of Technology"
},
{
"BossId": "1",
"DateOfBirth": "1932-06-13T00:00:00",
"FamilyName": "Bufford",
"Gender": "Unspecified",
"GivenName": "Alleen",
"Id": "04",
"Title": "VP of HR"
},
{
"BossId": "2",
"DateOfBirth": "1936-09-26T00:00:00",
"FamilyName": "Klopfer",
"Gender": "Female",
"GivenName": "Kristyn",
"Id": "05",
"Title": "Director of Marketing"
},
{
"BossId": "1",
"DateOfBirth": "1937-11-23T00:00:00",
"FamilyName": "Duhon",
"Gender": "Male",
"GivenName": "Sophie",
"Id": "01",
"Title": "Tech Manager"
},
{
"BossId": "3",
"DateOfBirth": "1948-04-05T00:00:00",
"FamilyName": "Mirabal",
"Gender": "Female",
"GivenName": "Suanne",
"Id": "07",
"Title": "Tech Manager"
},
{
"BossId": "4",
"DateOfBirth": "1966-10-13T00:00:00",
"FamilyName": "Maslowski",
"Gender": "Unspecified",
"GivenName": "Norah",
"Id": "09",
"Title": "Tech Manager"
},
{
"BossId": "6",
"DateOfBirth": "1967-08-25T00:00:00",
"FamilyName": "Redford",
"Gender": "Female",
"GivenName": "Gertrudis",
"Id": "10",
"Title": "Tech Lead"
},
{
"BossId": "6",
"DateOfBirth": "1968-12-26T00:00:00",
"FamilyName": "Tobey",
"Gender": "Male",
"GivenName": "Donovan",
"Id": "11",
"Title": "Tech Lead"
},
{
"BossId": "9",
"DateOfBirth": "1969-10-16T00:00:00",
"FamilyName": "Vermeulen",
"Gender": "Male",
"GivenName": "Rich",
"Id": "12",
"Title": "Trainer Lead"
},
{
"BossId": "9",
"DateOfBirth": "1972-10-16T00:00:00",
"FamilyName": "Knupp",
"Gender": "Male",
"GivenName": "Santo",
"Id": "13",
"Title": "HR Manager"
},
{
"BossId": "12",
"DateOfBirth": "1974-03-23T00:00:00",
"FamilyName": "Grooms",
"Gender": "Female",
"GivenName": "Jazmin",
"Id": "14",
"Title": "Trainer"
},
{
"BossId": "13",
"DateOfBirth": "1978-08-25T00:00:00",
"FamilyName": "Cheeks",
"Gender": "Female",
"GivenName": "Annelle",
"Id": "15",
"Title": "Recruiter"
},
{
"BossId": "15",
"DateOfBirth": "1979-08-21T00:00:00",
"FamilyName": "Harshaw",
"Gender": "Unspecified",
"GivenName": "Eliza",
"Id": "16",
"Title": "Trainer"
},
{
"BossId": "8",
"DateOfBirth": "1980-02-09T00:00:00",
"FamilyName": "Broaddus",
"Gender": "Unspecified",
"GivenName": "Xiomara",
"Id": "17",
"Title": "Senior Software Developer"
},
{
"BossId": "11",
"DateOfBirth": "1981-09-08T00:00:00",
"FamilyName": "Jungers",
"Gender": "Unspecified",
"GivenName": "Erminia",
"Id": "18",
"Title": "Software Developer"
},
{
"BossId": "10",
"DateOfBirth": "1984-03-18T00:00:00",
"FamilyName": "Moffatt",
"Gender": "Female",
"GivenName": "Maria",
"Id": "19",
"Title": "Software Developer"
},
{
"BossId": "10",
"DateOfBirth": "1990-09-24T00:00:00",
"FamilyName": "Grimaldo",
"Gender": "Female",
"GivenName": "Tammera",
"Id": "20",
"Title": "Senior Software Developer"
},
{
"BossId": "10",
"DateOfBirth": "1992-06-18T00:00:00",
"FamilyName": "Das",
"Gender": "Female",
"GivenName": "Sharyl",
"Id": "21",
"Title": "Software Developer"
},
{
"BossId": "8",
"DateOfBirth": "1993-11-15T00:00:00",
"FamilyName": "Harlan",
"Gender": "Unspecified",
"GivenName": "Shan",
"Id": "22",
"Title": "UI Developer"
},
{
"BossId": "11",
"DateOfBirth": "1997-03-23T00:00:00",
"FamilyName": "Almeida",
"Gender": "Female",
"GivenName": "Mariah",
"Id": "23",
"Title": "QA Tester"
},
{
"BossId": "11",
"DateOfBirth": "1998-11-10T00:00:00",
"FamilyName": "Kerfien",
"Gender": "Male",
"GivenName": "Darnell",
"Id": "24",
"Title": "QA Tester"
},
{
"BossId": "11",
"DateOfBirth": "2004-04-22T00:00:00",
"FamilyName": "Vierra",
"Gender": "Female",
"GivenName": "Janell",
"Id": "25",
"Title": "QA Tester"
}
];
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
$.each(members,function(idx, member){
// For each orgchart box, provide the name, manager, and tooltip to show.
member = JSON.parse(JSON.stringify(member));
data.addRow(
[{v: ""+parseInt(member.Id), f:member.GivenName+ ' ' + member.FamilyName+'<div style="color:red; font-style:italic">'+member.Title+'</div>'}, ""+parseInt(member.BossId), '']);
});
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {allowHtml:true});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53890925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .SetFocus from module VBA I'm trying to set the focus in a form after update. When I do this within the forms class module I have no problem. However, I need to do this in a few forms so I'm trying to write it in the module. My problem is I can't get the .SetFocus to work unless I hardcode the form name within the class module. WHno is the name of the control I'm trying to set focus.
I have attempted a number of options and none seem to work.
Here is the sub. Everything works wonderfully except the .SetFocus procedure.
Sub ValidateWHNO()
Dim EnteredWHNO As Integer
Dim actForm As String
Dim deWHNO As Variant
msg As Integer
Dim ctrlWHNO As Control
EnteredWHNO = Screen.ActiveControl.Value
actForm = Screen.ActiveForm.Name
Set ctrlWHNO = [Forms]![frmEnterBookData]![WHno]
deWHNO = DLookup("[WHno]", "tblDataEntry", "[WHno] = " & EnteredWHNO)
If EnteredWHNO = deWHNO Then
msg = MsgBox("You have already entered " & EnteredWHNO & " as a WHNO. The next number is " & DMax("[WHno]", "tblDataEntry") + 1 & ", use this?", 4 + 64, "Already Used WHno!")
If msg = 6 Then
Screen.ActiveControl.Value = DMax("[WHno]", "tblDataEntry") + 1
Else
Screen.ActiveControl.Value = Null
ctrlWHNO.SetFocus 'CODE THAT WONT RUN
End If
End If
End Sub
I've tried a number of other methods to set focus, such as:
Forms(actForm).WHno.SetFocus,
Forms(actForm).Controls(WHno).SetFocus, Screen.ActiveControl.SetFocus
The current result is that if No is selected in the MsgBox, the value is cleared, but the focus moves to the next control.
Thanks in advanced for any help that may be offered.
A: Does the following make a difference?
Sub ValidateWHNO(frm as Access.Form)
Dim EnteredWHNO As Integer
Dim actForm As String
Dim deWHNO As Variant
msg As Integer
EnteredWHNO = frm.ActiveControl.Value
actForm = frm.Name
deWHNO = DLookup("[WHno]", "tblDataEntry", "[WHno] = " & EnteredWHNO)
If EnteredWHNO = deWHNO Then
msg = MsgBox("You have already entered " & EnteredWHNO & " as a WHNO. The next number is " & DMax("[WHno]", "tblDataEntry") + 1 & ", use this?", 4 + 64, "Already Used WHno!")
If msg = 6 Then
frm.ActiveControl.Value = DMax("[WHno]", "tblDataEntry") + 1
Else
frm.ActiveControl.Value = Null
frm![WHno].SetFocus
End If
End If
End Sub
And your call from each form would be:
VaidateWHNO Me
Instead of using a relative reference to the form (Screen.ActiveForm), the code passes the form reference through directly and uses that reference as the parent of the .setFocus method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24457624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is ASMX technology completely obsolete Some time ago, about 2 years ago, I was working on web portal that was developed in .NET 2.0. and had plenty of asmx pages.
The other day, one of my coleagues that was more adept at ASP .NET said: "ASMX is old and ugly, we shoud rewrite it". So we did it, as far as I remember we moved to ashx handler.
But now, as I'm preparing to pass 70-515, I came across one some materials that still suggest to learn asmx services (with respect to AJAX). So is that approach still valid in new ASP .NET 3.5/4.0 web projects? If so, then when & where should I use it?
Or perhaps 2 years ago, I was soo ignorant, that we used some kind of old version of asmx and we moved to new asmx.
P.S. As I was entering tag "asmx" I saw a message: "asmx is obsolete" : https://stackoverflow.com/tags/asmx/info
A: If you can work with WCF then yes the ASMX services are obsolete because the WCF can fully replace them with more performance and flexibility (multiple binding), functionality. If you can write a WCF service then if you will be requested to create an ASMX service for some reason there will be no problem for you to do it.
And moving from ASMX to ASHX was not a smart move because they are not for replacing each other.
A: Oddly we moved from ASMX to WCF and then back to ASMX. WCF has quite a few downsides, most of all is cross-platform compatibility issues. If everyone consuming your service is on .NET this isn't an issue, but not all other frameworks have supported the full stack, and frequently they just can't do what WCF produces. We also found that dealing with security and testing was a pain in WCF. If your webservice is marked secure, it has to be secure in WCF, even in your testing environment, which means getting actual SSL certs for each developer. A tremendous pain to be sure.
A: ASMX and WCF are technologies to build web services in .NET. WCF was introduced in .NET 3.0. Its goal is to provide a standard abstraction over all communication technologies and is a recommended way of implementing web services in .NET.
What are the differences between WCF and ASMX web services?
ASHX is a way to write HTTPHandlers in .NET. For more information on what are HTTPHandler
http://forums.asp.net/t/1166701.aspx/1
ASMX services are supported in .NET. However migrating to WCF is recommended. Also, you should write all new services in WCF.
A: Yes, asmx is obsolute with WCF service. you can use asmx when you are working with < 4.0 aspx.
ashx will not be exact replace of asmx.
If you have coding format issue / standard / plenty of code then you can go with MVC Web API 2 (4.0 itself). but compare to WCF you must ensure what will be the recipient's response expectation
("WCF is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ. but Web api only for HTTP(s)").
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13100580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to click on the second link in google search result list using selenium web driver I want to click on the second link in result in google search area using selenium-web-driver
( Need a method that suits for any google search result )
example page
This is my code, How can I modify the if statement
import speech_recognition as sr
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("detach", True)
global driver
driver = webdriver.Chrome('C:\Windows\chromedriver.exe', options=chrome_options)
chrome_options.add_argument("--start-maximized")
wait = WebDriverWait(driver, 10)
def google(text):
if "first link" in text:
RESULTS_LOCATOR = "//div/h3/a"
WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.XPATH, RESULTS_LOCATOR)))
page1_results = driver.find_elements(By.XPATH, RESULTS_LOCATOR)
for item in page1_results:
print(item.text)
# driver.find_element_by_class_name().click()
else:
ggwp=text.replace(" ", "")
driver.get("https://www.google.com")
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys(ggwp)
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)
A: Second link can by placed in different div-s.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
browser = webdriver.Chrome(executable_path=os.path.abspath(os.getcwd()) + "/chromedriver")
link = 'http://www.google.com'
browser.get(link)
# search keys
search = browser.find_element_by_name('q')
search.send_keys("python")
search.send_keys(Keys.RETURN)
# click second link
for i in range(10):
try:
browser.find_element_by_xpath('//*[@id="rso"]/div['+str(i)+']/div/div[2]/div/div/div[1]/a').click()
break
except:
pass
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60389233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get a field in a object in db4o in java i have a query method. i use db40 in java
public static void checkQuery(ObjectContainer db, final String nameFish) {
ObjectSet result = db.query(new Predicate<WaterFish>() {
@Override
public boolean match(WaterFish fish) {
// TODO Auto-generated method stub
return fish.getGeneral_information().getVietnamese_name()
.contains("Ông tiên");
}
});
listResult(result);
}
result contains : fish{nameFish, distribution} and image.
how i can get only nameFish field in fish object
how i can get a only field in result ?
thanks
A: db4o (at least until Jan/2012) can only load full objects. You can use some tricks like introduce a new class to hold data (fields) that you don't use very often and rely on transparent activation to load this data when required (something like the code below).
class FishData
{
private Image picture;
// other fields, getters / setters etc
}
class Fish
{
private string name;
private FishData data;
// other fields, getters / setters etc
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24329625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Taking first observation of a series as unobserved parameter in non-linear regression I am trying to estimate the following equation in Stata using non-linear least squares command nl:
π_t= π_t_e+ α (y-y*)
where π_t_e= γ * π_t-1_e+(1-γ) π_(t-1)
π_t, y and y* are already given in the dataset, π_t_e is created from π_t using second equation. There are 34 observations in the dataset. The first observation of π_t_e i.e. π_1_e is treated as an unobserved parameter, along with gamma and alpha.
I wrote the following code but it is not working:
local s "{pi_1_e}"
local s "({gamma}*L.`s'+ (1-{gamma})*L.pi)"
nl ( pi = (`s') + {alpha}*(y-y*))
The first line of the code assigns pi_1_e to s. But the second line replaces s with
({gamma}*L.`s'+ (1-{gamma})*L.pi)
For _n==1, L.s doesn't exist. Hence, it is replaced with a missing value and all other 33 observations are assigned missing values. I wish to run second line of the code from _n>=2. But if condition doesn't work with local macro.
Can someone help me understand how to resolve this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66321301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: debug with PHP script on IE10 I have a js script that uses ajax to post data to a php script. The php script will open a text file and write the data that's passed from the js script. The same script works on chrome on a different machine but after I migrate it to the server where only IE is available, it does not work.
After executing the POST script in js, my browser shows the success message but the data in the text file is not changed. One problem I can think of is the directory I put in my php script is not correct. So I added these lines from w3schools to see if the file is actually found, but nothing peculiar happened:
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
What are some other ways I can do for debugging in this case?
UPDATE
I think my php in general is not working for some reasons. I have replaced everything in my php file with
echo '<script type="text/javascript">alert("hello"); </script>';
I am assuming when I click the button on my webpage, the js will do a $ajax post and the php script will be executed showing the alert message. However nothing yet shows up
A: In a PHP script you can turn error reporting on with:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Error and warnings will show up that will give you possibly a hint where your script is failing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37898931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting the exact system time during program execution I'm doing an alarm clock and I want to print alarm raise if the system time is the same as the one being save but it turn out that while running the program the time became static that's why it didn't raise the alarm while the program is still executed.
How can I make the time not to be static during program execution? Just let me know if you need additional information. :)
def alarmClock(self):
timeString2 = time.strftime("%H:%M:%S")
getData = self.queryResultTable.get_children()
for data in getData:
for dataValue in self.queryResultTable.item(data)['values']: #sample data: 19:00:00 or 20:00:00
for timeData in timeString2:
if timeData == dataValue:
print('alarm Raise')
A: I would just check the time when you get to your conditional. This way it will check the time right before you are checking to see if an alarm should be raised. In my opinion this will be much simpler than having it run in the background the whole time. You don't need to make a new variable it would just look like this:
if time.ctime() == dataValue:
print("alarm Raise")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62622393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Define Global variables from File input C++ I have to define a global array in my C++ code the size of which has to be read from a file. I am using the below code
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
int array[N];
// ------some code here-----
int main(){
int N;
cout << N<<endl;
return 0;
}
But if I place the 3 lines
string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
inside the main loop this code works. Unfortunately I cant put it inside any function because I need to initialise a global array from variable N.
I have asked many people and searched different places but I cant seem to be able to figure this out. Thanks for your help.
A: The size of an array has to be a constant expression, i.e. known at compile-time.
Reading a value from a file is an inherently dynamic operation, that happens at run-time.
One option is to use dynamic allocation:
int array_size()
{
int n;
ifstream infile("input.txt");
if (infile>>n)
return n;
else
throw std::runtime_error("Cannot read size from file");
}
int* array = new int[array_size()];
However it would be better to replace the array with std::vector<int> which can be resized dynamically.
A: Use a global pointer. Define
int* array;
in the global space before your main procedure. Then later, in a loop or not, say
array = new int[N];
to allocate your array. Just remember to also say
delete[] array;
before you exit your main or re-allocate array
A: int array[N]; - N should be know at compile-time.
Instead, use int array[]=new int[N]; /*some code using array*/ delete[] array;
int *array;
int main(){
ifstream infile("input.txt");
unsigned N;
infile>>N;
array=new int[N];
//using array...
delete[] array; //when no longer needed.
//don't use array after this line
//unless it's array=new int[] instruction
//or you know what you're doing.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25528953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: The searchresults.aspx page is picking up an older version of the master page We have master page called custom.master.
We changed the master page of the searchresults.aspx page to this master page:
MasterPageFile="custom.master"
We opened the searchresults.aspx page located in C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\TEMPLATE\ and edited the page.
Now the problem is other aspx pages that we created are using the same master page. But the searchresults.aspx is rendering an older version of the custom.master master page.
We usually edit the custom.master page using share point designer.
Any idea how it is getting the older version of the master page?
How to update the older version of the master page to reflect the new changes that is available in the custom.master page?
A: Ok found the pages. Master pages for both the site pages and application pages are listed on the _catalogs/masterpage/Forms/AllItems.aspx page on the site.
One master page can be found in the Sharepoint designer (after connecting to the site) and the other one is located in the C:\Program Files\Common Files\microsoft shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\ folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13579232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.