text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Converting an existing Nodejs Express application to a aws serverless App I have a Nodejs express app using Mongodb, and I want to go serverless.
Do I have to write again all my endpoints express with aws Lambda ?
How can I convert my mongoose schemas to work with Dynamodb ?
I tried to use aws codestar service and found that I can use Express.js but just as a web service. I still don't understand why I can't use it with a web application.
I Need some clarification, please.
Thanks in advance.
A: if you need to convert your express.js app to serverless. You can use serverless framework and serverless-http module.
add serverless-http moduele to app
npm install --save express serverless-http
Then modify your app this way
const serverless = require('serverless-http');
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
module.exports.handler = serverless(app)
More details read this article .
You can't use mongoose for dynamodb. try to use dynamoose
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48172714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Integer type values in ArrayList in XPages I would like to create an array list and all values in array should be Integer.
But at the end I need to sum all values in arrayList just like this below.
I could not find to correct formula for this.
is it possible to use using like @Sum or another formule without creating any for loop?
var myarraylist:java.util.ArrayList = new java.util.ArrayList();
myarraylist.add(10);
myarraylist.add(20);
myarraylist.add(30);
var result= @Sum(myarraylist);
docTest.replaceItemValue("FaturaTahsil",result);
A: var result gets calculated correct with your SSJS code. The result is 60.
@Sum works for ArrayLists.
Make sure you store result in correct field and save the document.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35886453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is htmlentities($password_string) necessary? I watched a php login tutorial on a commercial platform where it is advised to use htmlentities() on a password string which is given via POST-Method.
As the password is never displayed isn't it wrong to use this function as it alters the password which was entered by the user? I know that this will only affect html codes but is it really non-safe to not use the function as the password is never displayed?
A: The one and only time you use htmlentities for anything is if and when you're outputting data into HTML, right then and there. E.g.:
<p><?php echo htmlentities($data); ?></p>
In any other context HTML entities are generally useless* and will only garble/change/destroy your data. Indeed, using it on a password, probably nowhere near any HTML context, is highly suspect.
* Yes, you can probably find some specialised use case somewhere…
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41343281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to fit title in jquerymobile dialog's Title bar? I am using jquery mobile for web app development , I used jQM-SimpleDialog (jQM-SimpleDialog) to show message to user. My message string truncated. How to show complete sentence?
I got this output in iPhone
But I want to show this message : "Please fill the form properly."
Thanks,
-- regeint
A: What's cutting-off the title are the margins on the left and right. They are set to be large enough to not allow overlapping of the title and any buttons in the header.
You can try some CSS like this:
.ui-dialog .ui-header h1 {
margin-left : 30px;
margin-right : 0px;
}
This may un-center the title but I haven't used the jQM-SimpleDialog plugin so I'm not sure what it adds to the mix.
Here is a demonstration of the above code: http://jsfiddle.net/Y75dE/
A: This can be done through CSS.
Assign a Class to the div/dialog.
Ex:
<div class="mydialog"/>
Put the below css snippet code in the css file and include this in header.
Add a class to the CSS file.
.mydialog {
margin-left : 20px;
margin-right : 1px;
}
This should help you, customize the left,right as per your requirement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8967516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading in .txt files to Apple's Numbers I have a list of .txt files all in the same directory with the name "w_i.txt" where i runs from 1 to n. Each of these files contains a single number (non integer). I want to be able to read in the value from each of these files into a column in Apple's Numbers. I want w_1.txt in row 1 and w_n.txt's value in row n of that column. Should I use Applescript for this and if so what code would be required?
A: I think I would tackle this as a shell script, rather than applescript.
The following script will iterate over your set of files in numerical order, and produce plain text output. You can redirect this to a text file. I don't have access to Apple's Numbers, but I'd be very surprised if you can't import data from a plain text file.
I have hard-coded the max file index as 5. You'll want to change that.
If there are any files missing, a 0 will be output on that line instead. You could change that to a blank line as required.
Also I don't know if your files end in newlines or not, so the cat/read/echo line is one way to just get the first token of the line and not worry about any following whitespace.
#!/bin/bash
for i in {1..5} ; do
if [ -e w_$i.txt ] ; then
cat w_$i.txt | { IFS="" read -r n ; echo -e "$n" ; }
else
echo 0
fi
done
A: If all files end with newlines, you could just use cat:
cd ~/Documents/some\ folder; cat w_*.txt | pbcopy
This works even if the files don't end with newlines and sorts w_2.txt before w_11.txt:
sed -n p $(ls w_*.txt | sort -n)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15324029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clarification on thread pool max threads I've read here that :
In v2.0, 3.5, and 4.0, ASP.NET initializes the CLR ThreadPool with 100 threads per processor(core)
That is correct , I checked it (I have 8 core machine , so 8*100 = 800):
But then I saw this and this:
maxWorkerThreads — Configures the maximum number of worker threads to
use for the process on a per-CPU basis.The range for this attribute is
from 5 through 100. The default is 20.
Question
I don't see how the numbers fits in here :
The first paragraph states that I have max 100 threads per core ( the image prove it , I have 8 cores).
But the second paragraph states that the default maximum worker threads per core is 20. So if I have 8 cores then I must have 8*20 = 160 max threads. not 800.
Can someone please shed light?
Update:
I just found a way to get the key element value via c# code :
So now the number are fit in ,but still - MSDN say the default is 20 , not 100
And then they do mention 100 :
What is going on here?
A: I have looked at source code and have found that default value for MaxWorkerThreads is set to 100
private static readonly ConfigurationProperty _propMaxWorkerThreads = new ConfigurationProperty("maxWorkerThreads", typeof (int), (object) 100, (TypeConverter) null, (ConfigurationValidatorBase) new IntegerValidator(1, 2147483646), ConfigurationPropertyOptions.None);
This field is added to properties collection in static constructor
ProcessModelSection._properties.Add(ProcessModelSection._propMaxWorkerThreads);
In property definition they do set default value to 20
[IntegerValidator(MaxValue = 2147483646, MinValue = 1)]
[ConfigurationProperty("maxWorkerThreads", DefaultValue = 20)]
public int MaxWorkerThreads
But this obviously give no effect. Maybe it's some kind of legacy implementation. By the way it behaves this way only if autoConfig is set to false. When it's set to true I have 32K worker threads in my application. Probably this behavior depends on IIS version.
A: According to the MSDN,
the default maximum [number of threads in the ASP.net server pool] for
.NET 4.5 is 5,000
Source
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24100277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Android set Tag, findViewWithTag I'm trying to find an ImageView by tag. I assign a tag for the ImageView, but when I try to findViewWithTag, it returns null. I read that I should add to the view the childer with addChilder, but the view doesnt have this function. Can someone explaim to me how I can do this?
ImageView principal = (ImageView) findViewById(R.id.imagen_home_0);
principal.setTag("principal");
in other class(AsyncTask) that i pass the context
View noMiembros = new View(context);
ImageView er = (ImageView) noMiembros.findViewWithTag("principal");
er.setImageBitmap(result);
A: Pass an Activity to AsyncTask and just use :
ImageView principal = (ImageView) passedActivity.findViewById(R.id.imagen_home_0);
or get inflater from Context like this :
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(R.layout.your_viw_that_contains_that_image, parent, false);
ImageView principal = (ImageView) row.findViewById(R.id.imagen_home_0);
//or by tag
principal = (ImageView) row.findViewWithTag("principal");
Best wishes.
A: You are calling findViewWithTag on noMiembros
which is a new View.
You need to call findViewWithTag on a parent of the ImageView
you are trying to reach.
But if you want to get your ImageView from within an AsyncTask, just call
findViewById(R.id.imagen_home_0) on your Activity.
A: I believe that you are ... mistaking those two tags.
setTag() can attach ANY object to the view, while the XML tag is only a string - I believe the findViewByTag will try to match the tag passed thru XML, not one attached through code - as it could be any object.
Why not just pass the principal imageView to the asyncthread?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17233271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to setup encrypted payment settings in paypal production? I successfully worked through Ryan Bates screencasts http://railscasts.com/episodes/143-paypal-security and got Paypal Website Payments Standard working with IPN and encrypted payment settings in the Sandbox.
When I try to setup the encrypted payment settings in my production environment though I find the settings page looks completely different to the settings i was getting in my 'business' account in the sandbox. The 'profile' section has no mention of 'encrypted payment settings'.
*
*What is the difference between a business and a personal account in the sandbox? Do i need a 'business' account and what is it?
*Depending on 1, how do i setup my encrypted payment setttings?
*I am using an Australian PayPal account, could that have anything to do with it?
btw - I had no problem taking payments and using IPN on my production account without encryption.
many thanks.
A: 1) Business and test accounts are supposed to mimic the real accounts. For example, when a test user buys your product that money gets added to the business account.
3) Doubt it. Sandbox is meant for everyone.
Update: Looks like the Australian site is different.
A: It appears the reason for my confusion was that the Australian Pay Pal website is presented differently from the international version - and looks nothing like the Sandbox.
So, for the record, provided your account Type is Business the encryption settings on the Australian version are at:
Profile > My Selling Tools > Encrypted Payment Settings (right at the bottom of the page)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7917743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Firefox extensions & XUL: get page source code I am developing my first Firefox extension and for that I need to get the complete source code of the current page. How can I do that with XUL?
A: You will need a xul browser object to load the content into.
Load the "view-source:" version of your page into a the browser object, in the same way as the "View Page Source" menu does. See function viewSource() in chrome://global/content/viewSource.js. That function can load from cache, or not.
Once the content is loaded, the original source is given by:
var source = browser.contentDocument.getElementById('viewsource').textContent;
Serialize a DOM Document
This method will not get the original source, but may be useful to some readers.
You can serialize the document object to a string. See Serializing DOM trees to strings in the MDC. You may need to use the alternate method of instantiation in your extension.
That article talks about XML documents, but it also works on any HTML DOMDocument.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(document);
This even works in a web page or the firebug console.
A: really looks like there is no way to get "all the sourcecode". You may use
document.documentElement.innerHTML
to get the innerHTML of the top element (usually html). If you have a php error message like
<h3>fatal error</h3>
segfault
<html>
<head>
<title>bla</title>
<script type="text/javascript">
alert(document.documentElement.innerHTML);
</script>
</head>
<body>
</body>
</html>
the innerHTML would be
<head>
<title>bla</title></head><body><h3>fatal error</h3>
segfault
<script type="text/javascript">
alert(document.documentElement.innerHTML);
</script></body>
but the error message would still retain
edit: documentElement is described here:
https://developer.mozilla.org/en/DOM/document.documentElement
A: You can get URL with var URL = document.location.href and navigate to "view-source:"+URL.
Now you can fetch the whole source code (viewsource is the id of the body):
var code = document.getElementById('viewsource').innerHTML;
Problem is that the source code is formatted. So you have to run strip_tags() and htmlspecialchars_decode() to fix it.
For example, line 1 should be the doctype and line 2 should look like:
<<span class="start-tag">HTML</span>>
So after strip_tags() it becomes:
<HTML>
And after htmlspecialchars_decode() we finally get expected result:
<HTML>
The code doesn't pass to DOM parser so you can view invalid HTML too.
A: Maybe you can get it via DOM, using
var source =document.getElementsByTagName("html");
and fetch the source using DOMParser
https://developer.mozilla.org/En/DOMParser
A: The first part of Sagi's answer, but use document.getElementById('viewsource').textContent instead.
A: More in line with Lachlan's answer, but there is a discussion of the internals here that gets quite in depth, going into the Cpp code.
http://www.mail-archive.com/[email protected]/msg05391.html
and then follow the replies at the bottom.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2337889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Generating Forms for Lumen I'm searching a pretty way to get HTML forms with the Lumen framework.
I've tried Former (http://formers.github.io/former/), but even with the 4.0 branch, I couldn't get it working at all (tell me if you could and I'm wrong) with Lumen (some Class path.config does not exist - did you try and get the same?).
How can I get forms generated with that framework (I usually use Bootstrap forms)?
Thank you in advance
A: This issue must be fixed by the package's developer or you can send try and fork their project if you want.
There are only a few packages supporting the Lumen framework for now.
Note:
I've just opened an issue asking for Lumen compatibility linking to the following conversation.
- A simple solution would be to not use helpers that are only defined by illuminate/foundation. Then this would allow usage in any app that uses laravel components. I'd always recommend that. :)
- @GrahamCampbell What's a better way to get the config path?
- Resolve 'path.config' from the ioc container.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29803706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to read a txt file and use its data to compare it with other variables? I want to create a program, which reads 2 txt files. The first txt file is a logfile, the second is a short one with names. The task is to read both of the files, and count the specific names(from the second txt) in the first txt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52279755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dependsOnGroups annotation in Test NG @Test(groups = { "init" })
public correctVM() {}
@Test(groups = { "init" })
public serverStartedOk() {}
@Test(dependsOnGroups = { "init.* })
public method1() {}
// Above TestNG code
in method1, for the dependsOnGroups regular expression is used. Is it mandatory to use regEx or is it okay to give "init" as all groups are having name as init.
A: Only if you use the regex will TestNG know that you are not giving an absolute group name but you are indicating a pattern.
So going by your example you would need to mention
@Test(dependsOnGroups = { "init.* })
public method1() {
//code goes here.
}
for TestNG to basically pick up any groups whose names begin with init
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39700441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twitter Bootstrap: How to see the state of a toggle button? How do I see the state of a toggle button?
With a checkbox I can listen to "changed" event of the checkbox and do a $(this).is(":checked") to see what state it has.
<a id="myId" class="btn" data-toggle="button"/>
But not sure how to do that with a toggle button?
A: If you're using jQuery to intercept the click event like so...
$(this).click(callback)
you need to get creative because .hasClass('active') doesn't report the correct value. In the callback function put the following:
$(this).toggleClass('checked')
$(this).hasClass('checked')
A: you can see what classes the button has..
$(this).hasClass('disabled') // for disabled states
$(this).hasClass('active') // for active states
$(this).is(':disabled') // for disabled buttons only
the is(':disabled') works for buttons, but not the link btns
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13323671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: how to find the most repeat word in string? can you please tell me how to find the most repeat word in string ?
Example
If input is this
"how do you do"
Output is "do"
var str="how do you do"
function findMostReaptedWord(str){
var res = str.split(" ");
alert(res.length);
var count;
var compareString;
for(var i=0;i<res.length ;i++){
count=0;
compareString=res[i]
for (j=0;i<res.lenth ;j++){
if(compareString==res[j]){
count++
}
}
}
}
alert(findMostReaptedWord(str))
fiddle
http://jsfiddle.net/omjg9v0q/
A: I gave the idea in a comment. Here it is in code :
function findMostReaptedWord(str){
var counts = {}, mr, mc;
str.match(/\w+/g).forEach(function(w){ counts[w]=(counts[w]||0)+1 });
for (var w in counts) {
if (!(counts[w]<mc)) {
mc = counts[w];
mr = w;
}
}
return mr;
}
A few details :
*
*I use str.match(/\w+/g) for a better decomposition in words. Yours would take anything not a space as a word or part of a word.
*counts is a map giving the number of occurrences of each words (i.e. counts["do"] is 2)
*using a map avoids doing two levels of loop, which is very slow
A: Here is my approach
*
*First, separate the words from the string using Regular Expression.
*Declare an object as a Map which will help you to find the occurrences of each word. (You can use Map Data Structure!)
*Find the most repeated word from that object.
let str = 'How do you do?';
console.log(findMostRepeatedWord(str)); // Result: "do"
function findMostRepeatedWord(str) {
let words = str.match(/\w+/g);
console.log(words); // [ 'How', 'do', 'you', 'do' ]
let occurances = {};
for (let word of words) {
if (occurances[word]) {
occurances[word]++;
} else {
occurances[word] = 1;
}
}
console.log(occurances); // { How: 1, do: 2, you: 1 }
let max = 0;
let mostRepeatedWord = '';
for (let word of words) {
if (occurances[word] > max) {
max = occurances[word];
mostRepeatedWord = word;
}
}
return mostRepeatedWord;
}
A: Here I give you an approach,
*
*Sort the words first. That way "how do you do" becomes "do do how you".
*Iterate the string to count the words that repeat, keep the maximum number of times repeating word in memory while iterating.
-
Mebin
A: This function may help you
function maxWord (str)
{
var max = 0;
var maxword = '';
var words = str.split(' ');
for(i=0;i<words.length;i++)
{
var count = 0;
var word = '';
for(j=0;j<words.length;j++)
{
if(j !== i && words[i] === words[j])
{
count++;
word = words[i];
}
}
if(count>maxword)
{
max = count;
maxword = word;
}
}
return maxword;
}
maxWord('how do you do'); // returns do
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25644056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamically creating javascript file in Rails 3.1 I am attempting to create a plug and play shopping cart in Rails 3.1 that allows users to add a shopping cart to their site by just adding a link to a javascript file. The items for sale are input on my end and stored in this js file and rendered with jquery templates. I currently have an action that renders the corresponding js, but I was wondering if there was a way to create a new minified js file for each site and link to this file in each site instead of the show action that renders the js.
For example, for store#1, I would like to create and save a js file called store1.js and serve that file instead of calling the show.js action that creates the javascipt array for the jquery templates every time.
A: You could try using action caching to have it only render the action once. Then you can utilize cache sweepers to invalidate the cached js when you make any updates that would change the information in the js.
I think that really might be your best option. Your going to go through a lot more trouble trying to get precompiled dynamic JS like that, especially if the content has a tendency to change at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6453520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to sort the array How to sort array by preserving key
$arr = array(strong text
'a' => array('date' => time() - 1000),
'b' => array('date' => time() - 2000),
'c' => array('date' => time() - 3000),
);
I want to sort according to the time().
A: function cmp($a, $b)
{
if($a["date"] == $b["date"]) return 0;
return($a["date"] > $b["date"]) ? 1 : -1;
}
usort($array, "cmp");
A: There is a couple of PHP functions that sort arrays - you can see the overview here: http://php.net/manual/en/array.sorting.php
As you want to neither by key nor value, but by some custom logic of yours, you need to use one of the functions starting with u. Ouf of those 3 functions, 2 can be used to sort by value: usort and uasort. The difference between them is that while the first one doesn't preserve the key-value associations, the second one does, which makes uasort the function you need.
uasort takes 2 parameters - an array to be sorted and a callback, that for 2 given elements should return -1, 0 or 1 if the first element is smaller, equal or larger than the second.
In your case, this will work:
print_r($arr);
uasort($arr, function($e1, $e2) {
if ($e1['date'] == $e2['date']) {
return 0;
}
return ($e1['date'] < $e2['date']) ? -1 : 1;
});
print_r($arr);
Notice: make sure you don't assign the result of uasort to your $arr - the return value of this function is not the sorted array, but a boolean saying if sorting succeeded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31902135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Can I use jQuery to toggle 'reversed' on an ordered list? I'm working with ten <section>'s.
All sections have a header <h1> followed by an ordered list <ol>.
Only two sections have a <span>sort</span> inside their header.
I wish to use those sort-span's to toggle (reverse) the order of only those two lists.
Section with a list appearing in ascending alphabetical order:
<section>
<h1>artists <span>sort</span></h1>
<ol>
<li>Hockney, David</li>
<li>Matisse, Henri</li>
<li>Picasso, Pablo</li>
</ol>
</section>
Artists
*
*Hockney, David
*Matisse, Henri
*Picasso, Pablo
Section with a 'reversed' list appearing in descending alphabetical order:
Note: I have simply added "reversed" to the <ol> ordered list.
<section>
<h1>artists <span>sort</span></h1>
<ol reversed>
<li>03. Hockney, David</li>
<li>02. Matisse, Henri</li>
<li>01. Picasso, Pablo</li>
</ol>
</section>
Artists
*
*Picasso, Pablo
*Matisse, Henri
*Hockney, David
What I am having trouble with is figuring out how to (use jQuery to) toggle 'reversed' to the <ol> as it's not a .class or .id...
As I only have basic understanding of jQuery, and honestly wouldn't know where to start, I was hoping to ask around here if this is even possible, and if so, how best to approach this?
This all I've got so far, am I on the right track?
$('section span').on('click', function(e) {
e.preventDefault();
$(this).closest('ol').toggle().append("reversed");
});
$('section span').on('click', function(e) {
e.preventDefault();
$(this).closest('ol').toggle().append("reversed");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<h1>artists <span>sort</span></h1>
<ol>
<li>Hockney, David</li>
<li>Matisse, Henri</li>
<li>Picasso, Pablo</li>
</ol>
</section>
A: Added a working example, let me know in case HTML structure is change.
$('section span').on('click', function(e) {
var OlObj = $(this).parent('h1').next('ol');
OlObj.append( OlObj.find('li').get().reverse());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<h1>artists <span>sort</span></h1>
<ol>
<li>Hockney, David</li>
<li>Matisse, Henri</li>
<li>Picasso, Pablo</li>
</ol>
</section>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66780135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AngularJS submit on blur and blur on keypress I want to submit some data to the server when a input field is blurred. The User should also be able to blur the input field by pressing enter.
Unfortunately this results in the following: $rootScope:inprog: $apply already in progress error.
Plunkr - thanks in advance!
A: You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/
Provide details event handle related blur,focus,keydow,keyup,keypress
<input ui-event="{ blur : 'blurCallback()' }">
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
A: Here's what's happening:
*
*You press enter
*ng-keydown triggers (digest begins)
*You call target.blur()
*ng-blur triggers and attempts to start another digest cycle
*Angular complains
The blur is executed synchronously and immediately triggers the handler without finishing the first digest.
In my opinion, this is not a problem with your code, but rather an Angular bug. I've been trying to think of a better solution, but I can only find:
app.controller('BlurCtrl', function($scope, $timeout) {
$scope.blurModel = "I'm the value"
$scope.blurOnEnter = function( $event ) {
if ( $event.keyCode != 13 )
return
// this will finish the current digest before triggering the blur
$timeout(function () { $event.target.blur() }, 0, false);
}
$scope.onBlur = function() {
$scope.result = this.blurModel
}
})
A: Here is a small directive :
.directive('ngEnterBlur', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress blur", function (event) {
if(event.which === 13 || event.type === "blur") {
scope.$apply(function (){
scope.$eval(attrs.ngEnterBlur);
});
event.preventDefault();
}
});
};
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18389527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Trying to learn boost::intrusive Q2 if I uncomment these
//BaseList baselist;
//MemberList memberlist;
outside the loop and comment out the ones inside the loop it crashes. I need to be able to have the baselist (and memberlist) outside any loop. How is this achieved?
Edit
The actual problem I am trying to solve in it's simplest form is this.
I want to have a std::vector of MyClass, call it AllThingsBunchedTogether.
I also want to have a std::vector of BaseList, call it AllThingsSpreadOut.
So
*
*AllThingsBunchedTogether might contain (just the anInt1 part for the sake of compactness): 1,2,1,10,2,3,4,4,5,9,10,10.
*AllThingsSpreadOut might contain (zero not used for now) at [1] 1,1 at [2] 2,2 at [3] 3 at [4] 4,4 at [5] 5 at [9] 9 at [10] 10,10,10.
Note that the numbers themselves aren't be stored in the BaseList, but e.g., the MyClass(1, "John").
At [1] it could be "Mike", "John", at [2] it could be "Mike", "Dagobart" at [3]
"John" ... at [10] "John" "Mike" "Dagobart" etc so that there no duplicates in
any of the BaseList at AllThingsSpreadOut[i] since each MyClass in each
BaseList hashes to a different value (anInt1 + Name).
In essence, anInt1 tells where the MyClass lives in AllThingsSpreadOut, but anInt1 + name guarantees uniqueness within each BaseList.
So the idea is that AllThingsSpreadOut is a vector of BaseList where at each BaseList at vector location is a list of similar things.
Then, when I remove things from AllThingsBunchedTogether (not by a clear, but by a search to remove some items like in the code below IsMarkedToDelete), they will automatically disappear from the corresponding AllThingsSpreadOut.
AllThingsSpreadOut acts as a sort for AllThingsBunchedTogether, with intrusive semantics. AllThingsBunchedTogether allows superfast access through [].
End Edit
#include <vector>
#include <iostream>
#include <boost/intrusive/list.hpp>
using namespace boost::intrusive;
class MyClass : public list_base_hook<link_mode<auto_unlink>> // This is a derivation hook
{
public:
std::string name;
bool bIsMarkedToDelete;
int anInt1;
public:
list_member_hook<link_mode<auto_unlink>> member_hook_; // This is a member hook
MyClass(std::string n, int i) : name(n), anInt1(i), bIsMarkedToDelete(false) {}
};
bool IsMarkedToDelete(const MyClass &o)
{
return o.bIsMarkedToDelete;
}
//Define a list that will store MyClass using the public base hook
typedef list<MyClass, constant_time_size<false>> BaseList;
// Define a list that will store MyClass using the public member hook
typedef list<MyClass,
member_hook<MyClass, list_member_hook<link_mode<auto_unlink>>, &MyClass::member_hook_>,
constant_time_size<false> > MemberList;
int main()
{
bool done = false;
std::vector<MyClass> values;
std::string names[] = {"John", "Mike", "Dagobart"};
//BaseList baselist;
//MemberList memberlist;
int i = 0;
while(!done)
{
// Create several MyClass objects, each one with a different value
for (int j = 0; j < 11; ++j)
values.emplace_back(names[j % 3], j);
BaseList baselist;
MemberList memberlist;
// Now insert them in t-he reverse order in the base hook list
for (auto& e : values)
{
baselist.push_front(e);
memberlist.push_back(e);
}
// Now test lists
auto rbit(baselist.rbegin());
auto mit(memberlist.begin());
auto it(values.begin()), itend(values.end());
// Test the objects inserted in the base hook list
for (; it != itend; ++it, ++rbit)
{
if (&*rbit != &*it)
return 1;
}
// Test the objects inserted in the member hook list
for (it = values.begin(); it != itend; ++it, ++mit)
{
if (&*mit != &*it)
return 1;
}
# if 0
for(auto& e : values)
std::cout << e.anInt1 << "\n";
for(auto& e : baselist)
std::cout << e.anInt1 << "\n";
for(auto& e : memberlist)
std::cout << e.anInt1 << "\n";
#endif // 0
if(2 == i)
{
for(auto& e: values)
std::cout << e.name << "\n";
for(auto& e: values)
{
if("Mike" == e.name)
e.bIsMarkedToDelete = true;
}
values.erase(
std::remove_if(values.begin(), values.end(), IsMarkedToDelete), values.end());
}
if(i++ > 3)
{
values.clear();
done = true;
}
std::cout << "\n";
std::cout << values.size() << "\n";
std::cout << baselist.size() << "\n";
std::cout << memberlist.size() << "\n";
}
}
A: I've seen it late, but anyways, here goes:
*
*What you describe matches exactly the implementation of an intrusive hash table of MyClass elements, where
*
*anInt1 is the hash (the bucket identifier) for an element
*the bucket lists are implemented as linked lists
*equality is defined as equality of (anInt1, Name)
So really, your program could just be:
Live On Coliru
std::unordered_set<MyClass> values {
{ "John", 0 }, { "Mike", 1 }, { "Dagobart", 2 },
{ "John", 3 }, { "Mike", 4 }, { "Dagobart", 5 },
{ "John", 6 }, { "Mike", 7 }, { "Dagobart", 8 },
{ "John", 9 }, { "Mike", 10 },
};
for(int i = 0; i<=3; ++i) {
if(2 == i) {
for(auto& e: values) std::cout << e.name << " "; std::cout << "\n";
for(auto& e: values) e.bIsMarkedToDelete |= ("Mike" == e.name);
for(auto it=begin(values); it!=end(values);) {
if (it->bIsMarkedToDelete) it = values.erase(it);
else ++it;
}
}
std::cout << "i=" << i << ", values.size(): " << values.size() << "\n";
}
values.clear();
std::cout << "Done\n";
*if you really wanted contiguous storage, I can only assume you wanted this for performance
*
*you do not want to use pointers instead of objects, since that simply negates the memory layout ("AllThingsBunchedTogether") benefits and you'd be better of with the unordered_set or unodered_map as above
*you do not want to use auto_unlink mode, since it cripples performance (by doing uncontrolled deletion triggers, by inhibiting constant-time size() and by creating thread safety issues)
*instead, you should employ the above stratagy, but with boost::intrusive::unordered_set instead see http://www.boost.org/doc/libs/1_57_0/doc/html/intrusive/unordered_set_unordered_multiset.html
Here, again, is a proof-of-concept:
Live On Coliru
#include <vector>
#include <iostream>
#include <boost/intrusive/unordered_set.hpp>
#include <vector>
//#include <functional>
//#include <algorithm>
namespace bic = boost::intrusive;
struct MyClass : bic::unordered_set_base_hook<bic::link_mode<bic::auto_unlink>>
{
std::string name;
int anInt1;
mutable bool bIsMarkedToDelete;
MyClass(std::string name, int i) : name(name), anInt1(i), bIsMarkedToDelete(false) {}
bool operator==(MyClass const& o) const { return anInt1 == o.anInt1 && name == o.name; }
struct hasher { size_t operator()(MyClass const& o) const { return o.anInt1; } };
};
typedef bic::unordered_set<MyClass, bic::hash<MyClass::hasher>, bic::constant_time_size<false> > HashTable;
int main() {
std::vector<MyClass> values {
MyClass { "John", 0 }, MyClass { "Mike", 1 }, MyClass { "Dagobart", 2 },
MyClass { "John", 3 }, MyClass { "Mike", 4 }, MyClass { "Dagobart", 5 },
MyClass { "John", 6 }, MyClass { "Mike", 7 }, MyClass { "Dagobart", 8 },
MyClass { "John", 9 }, MyClass { "Mike", 10 },
};
HashTable::bucket_type buckets[100];
HashTable hashtable(values.begin(), values.end(), HashTable::bucket_traits(buckets, 100));
for(int i = 0; i<=3; ++i) {
if(2 == i) {
for(auto& e: values) std::cout << e.name << " "; std::cout << "\n";
for(auto& e: values) e.bIsMarkedToDelete |= ("Mike" == e.name);
values.erase(std::remove_if(begin(values), end(values), std::mem_fn(&MyClass::bIsMarkedToDelete)));
}
std::cout << "i=" << i << ", values.size(): " << values.size() << "\n";
std::cout << "i=" << i << ", hashtable.size(): " << hashtable.size() << "\n";
}
values.clear();
std::cout << "Done\n";
}
A: Here's the error message, which you omitted:
Assertion `node_algorithms::inited(to_insert)' failed.
From this we can understand that an element is being inserted twice. This isn't valid with intrusive containers in general.
When you have your lists inside the loop, they are destroyed and recreated each time. But when they are outside, you never clear them, and you also never clear values, so this sequence occurs:
*
*Add 11 elements to values.
*Add all values to the lists.
*Add 11 elements to values; it still has the previous 11 so now 22 elements.
*Add all values to the lists. Crash on the first one, because it is already in a list.
One solution is to add values.clear() at the top of the while(!done) loop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26857832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to block incoming calls from unknown numbers programmatically? I want to create an app that blocks all numbers that are not in contacts.
I have read this but it is not perfect.
How to do this? Thanks for reading
A: This is one way to use it. First, you have to use ITelephony in your project. I will give you an example to use it in below link. Second, you have to insert code to start service when you restart phone as follows:
in AndroidManifest File :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Change this to :
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context,BackgroundService.class);
startService(serviceIntent);
}
The sample code at https://github.com/Levon-Petrosyan/Call_redirect_and_reject
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34175670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Binding to ToolTip.IsOpen reports 'false' the first the ToolTip is opened Currently I am trying to bind the IsOpen property of a ToolTip to a property of my backing view model. Additionally The binding mode is set to 'OneWayToSource'.
This is the Style that is applied to a TreeViewItem and contains the ToolTip definition:
<Style TargetType="TreeViewItem">
<Setter Property="ToolTip">
<Setter.Value>
<ToolTip IsOpen="{Binding IsToolTipOpen, Mode=OneWayToSource}">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding CurrentValue, StringFormat={}Value: {0}}"/>
<TextBlock Text="{Binding UnitName, StringFormat={}Unit: {0}}"
Visibility="{Binding HasUnit, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</ToolTip>
</Setter.Value>
</Setter>
</Style>
Here is the code for the property that it is binding to:
public bool IsToolTipOpen
{
get
{
return mIsToolTipOpen;
}
set
{
PegasusContext.Current.LogMessage( new PegasusMessage( string.Format( "IsTooltipOpen: {0}", value ), LogLevel.Debug ) );
if( mIsToolTipOpen == value ) return;
mIsToolTipOpen = value;
if( mIsToolTipOpen )
{
BackingIO.BeginWatching();
}
else
{
BackingIO.StopWatching();
}
}
}
When the ToolTip is opened for the first time, it will invoke the IsToolTipOpen property setting it's value to false. Additionally when the ToolTip closes, it will set the value of IsToolTipOpen to false...again. Every subsequent time, the value will get set as expected. After opening the first ToolTip, it will perform strange behavior on other items with the ToolTip attached. For instance it will set the IsToolTipOpen property to true and then back to false almost immediately. Again every subsequent time the ToolTip is opened, it works normally.
Here is report from the logging code you can see on the first line of my IsToolTipOpen property set method (with some additional comments I handwrote in):
TreeViewItem A:
IsTooltipOpen: False <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
IsTooltipOpen: True <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
TreeViewItem B:
IsTooltipOpen: True <-- ToolTip Open
IsTooltipOpen: False <-- ToolTip Open, occured at the same time as the previous entry.
IsTooltipOpen: False <-- ToolTip Closed
IsTooltipOpen: True <-- ToolTip Opened
IsTooltipOpen: False <-- ToolTip Closed
So I was curious if anyone had any idea what was going on? and possible solutions?
A: It appears that the events are working as intended with the ToolTip class. So I created an attached property to fix the problem I was having.
I have a attached property to enable the registration of events:
public static readonly DependencyProperty EnableWatchProperty = DependencyProperty.RegisterAttached(
"EnableWatch",
typeof( bool ),
typeof( ToolTipFix ),
new PropertyMetadata( default( bool ), OnEnableWatchPropertyChanged ) );
private static void OnEnableWatchPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
var toolTip = d as ToolTip;
if( toolTip == null ) return;
var newValue = (bool) e.NewValue;
if( newValue )
{
toolTip.Opened += OnTooltipOpened;
toolTip.Closed += OnTooltipClosed;
}
else
{
toolTip.Opened -= OnTooltipOpened;
toolTip.Closed -= OnTooltipClosed;
}
}
I also have an attached property that can be binded to, and it indicates the current state of the ToolTip:
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.RegisterAttached(
"IsOpen",
typeof( bool ),
typeof( ToolTipFix ),
new PropertyMetadata( default( bool ) ) );
The event handlers just set the IsOpen property to true or false depending on the event that was invoked.
Here is how I used the the attached property in XAML:
<ToolTip local:ToolTipFix.EnableWatch="True"
local:ToolTipFix.IsOpen="{Binding IsToolTipOpen, Mode=OneWayToSource}">
...
</ToolTip>
If anyone has another solution, or reason for this problem, I would very much appreciate it.
A: This was confusing the heck out of me, and I couldn't help but poke at it for while to try and understand what's going on. I'm not entirely sure I arrived at a complete understanding, but I'm further than when I started =D
I replicated your behaviour for a very simple ToolTip in a Grid, I had a good look at events and the ToolTipService and got nowhere, then started using WPF Snoop (no affiliation) to examine the DataContext on the ToolTip when the application was first started.
Seemingly, the ToolTip has no DataContext. As soon as you open it for the first time.
The ToolTip inherits the DataContext.
So what I assume is happening (this is where I'm hazy), is that when you first mouse over the ToolTip, the DataContext has not yet been correctly bound, so your get/set can't fire correctly; the reason you see any messages at all is a result of the behaviour of the OneWayToSource binding mode explained here: OneWayToSource Binding seems broken in .NET 4.0.
If you choose TwoWay binding, you'll notice the ToolTip doesn't open at all the first time round, but will function correctly after the late binding of the DataContext.
The reason the ToolTip does this, is a result of the way it's implemented, and the possible sharing of ToolTips that can occur; it doesn't live within the visual tree:
A tooltip (and everything in it) is not part of the visual tree - it is not in a parent-child relationship with the Image, but rather in a property-value relationship.
When a tooltip is actually displayed, WPF does some special work to propagate the values of inheritable properties from the placement-target into the tooltip,
So, I think that's sounding plausible, but is there anything you could actually do about it?
Well, some people have wanted to bind the ToolTip to things on the visual tree, and given the difficulties faced in locating the parent objects, a few workarounds have arisen (I cameacross these while looking for a solution:
http://blogs.msdn.com/b/tom_mathews/archive/2006/11/06/binding-a-tooltip-in-xaml.aspx
Getting a tooltip in a user control to show databound text and stay open
Both rely on a neat property of the ToolTip, PlacementTarget, which "Gets or sets the UIElement relative to which the ToolTip is positioned when it opens. MSDN.
So, in summary, to get the IsOpen property to bind and behave correctly, I did this in my mockup:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow"
DataContext="{Binding RelativeSource={RelativeSource Self}}" Background="#FF95CAFF"
>
<Grid>
<TextBlock Text="{Binding Path=TestObject.Name}">
<TextBlock.ToolTip>
<ToolTip IsOpen="{Binding DataContext.TestObject.IsToolTipOpen}"
DataContext="{Binding Path=PlacementTarget,
RelativeSource={RelativeSource Self}}" >
<StackPanel Orientation="Vertical">
<!-- Show me what the `DataContext` is -->
<TextBlock Text="{Binding Path=DataContext}" />
</StackPanel>
</ToolTip>
</TextBlock.ToolTip>
</TextBlock>
</Grid>
Context found on program load.
In this case, the DataContext is WpfApplication1.MainWindow, and I'm binding to a property on that I'm using for testing, called TestObject. You would probably have to fiddle with the syntax a little bit to locate your desired `DataContext item in your template (it might be easier to do it the way you've already done it depending on your structure).
If I've said anything drastically incorrect, let me know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19717857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to maintain status of failed file I am new in java .I am developing an app in java to transfer a large number of files to server.The requirement is to check the status of failed file and store somewhere and transfer those files later.The application should be maintain a daemon process.
Thanks and Regard
sanjeet
A: The better option for large number of files transfer is to use ftp protocol. For that you need an ftp server. And, using org.apache.commons.net.ftp.FTPClient you may upload files in to the server (and also various file management).
The storeFile(String, InputStream) method of org.apache.commons.net.ftp.FTPClient can give the file upload status, i.e. if the file is uploaded successfully it will return true otherwise false.
Please refer this link for a sample program.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23307737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PostgreSQL function to return text array with two elements I am trying to return a text array with two elements using postgresql function. But the output seems to generate one element.
Here's result from pgAdmin query: Here, it does seem like the result array with two elements
select "address_pts".usp_etl_gis_get_cname_bd_ext(3)
ALLEGHANY,POLYGON((1308185.61436242 959436.119048506,1308185.61436242 1036363.17188701,1441421.26094835 1036363.17188701,1441421.26094835 959436.119048506,1308185.61436242 959436.119048506))
But in Python when I call the function, I see the output array length as only 1.
(partial python code)
pg_cur.execute("SELECT \"VA\".address_pts.usp_etl_gis_get_cname_bd_ext(3)")
for rec in pg_cur:
print(len(rec))
-- output = 1
for rec in pg_cur:
print(rec[0])
-- ouput: ['ALLEGHANY', 'POLYGON((1308185.61436242 959436.119048506,1308185.61436242 1036363.17188701,1441421.26094835 1036363.17188701,1441421.26094835 959436.119048506,1308185.61436242 959436.119048506))']
it generates an error for below code:
for rec in pg_cur:
print(rec[1])
-- Here is the function --
-- postgresql 9.6
CREATE OR REPLACE FUNCTION address_pts.usp_etl_gis_get_cname_bd_ext(
_cid integer
)
RETURNS TEXT[]
LANGUAGE 'plpgsql'
COST 100.0
VOLATILE NOT LEAKPROOF
AS $function$
DECLARE cname TEXT;
DECLARE cbd_ext TEXT;
DECLARE outarr TEXT[];
BEGIN
IF (_cid NOT BETWEEN 1 and 100) THEN
RAISE EXCEPTION '%s IS NOT A VALID COUNTY ID. ENTER A COUNTY BETWEEN 1..100', _cid;
END IF;
select upper(rtrim(ltrim(replace(name10,' ','_'))))
into cname
from "jurisdictions"."CB_TIGER_2010"
WHERE county_id = _cid;
/*
#Returns the float4 minimum bounding box for the supplied geometry,
#as a geometry. The polygon is defined by the corner points of the
#bounding box ((MINX, MINY), (MINX, MAXY), (MAXX, MAXY), (MAXX, MINY), (MINX, MINY)).
#(PostGIS will add a ZMIN/ZMAX coordinate as well).
*/
SELECT ST_AsText(ST_Envelope(geom))
INTO cbd_ext
from "jurisdictions"."CB_TIGER_2010"
where county_id = _cid;
outarr[0] := cname::text;
outarr[1] := cbd_ext::text;
RETURN outarr;
END;
$function$;
questions:
*
*Is postgresql function resulting in array of length 1 or 2?
*If len is 1, how can split the result? for example:
['ALLEGHANY','POLYGON((1308185.614362,...))']
Thank you
A: If you are happy to split the string once you are in Python, you can try with regex and the module re:
# Python3
import re
p = re.compile(r"\['(.*)','(.*)']")
res = p.search("['ALLEGHANY','POLYGON((1308185.614362,...))']")
print(res.group(1)) # 'ALLEGHANY'
print(res.group(2)) # 'POLYGON((1308185.614362,...))'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47041248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Coding a family tree style app I want to code up an app. ( for my own learning) that helps build a family tree. So I want the user to add the users grandparents, parents etc. to this app. and I want to be able to maintain this data. I am wondering what components would go into this. Here's what I am thinking:
- A database - that has all the info.
- front end ( iOS app) that pulls data from this database.
Questions:
- Is a database the right way to go ?
- Any recommendations on the database to use ?
- Any code samples/recommendations on the approach to take ?
I want to make sure the system is scalable and hopefully build a WEB fronted in addition to an app fronted.
Any thoughts from the more experienced coders on how you would approach this problem ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22699716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how can i assign a randomly generated integer to a string in C? i'm trying to make a slot machine type thing and i wanted to assign the randomly generated numbers to certain symbols like 1 = cherry, 2 = bell and so on so i could print out the results in symbol form at the end.
i tried putting the symbols as strings in an array and assigning the numbers to the elements in the array in each slot functions but it didn't work out... is there a way to do this?
here's the code i've written so far, minus the array attempts. any suggestions would be helpful! :D
EDIT: here's an example of what i've tried doing on one of the slots but it keeps saying i need a cast to assign the integer from a pointer (i've tried searching online but idk how to do this)
char * slotOne(int randOne, const char *symbols[])
{
randOne = rand() % 4 + 1;
if (randOne = 1)
{
randOne = *symbols;
}
if (randOne = 2)
{
randOne = *(symbols+1);
}
if (randOne = 3)
{
randOne = *(symbols+2);
}
else
{
randOne = *(symbols+3);
}
return randOne;
}
this is the part of my main function where i've tried declaring the string array:
int main()
{
int x, one, two, three;
const char *symbols[4] = {"bell", "orange", "cherry", "horseshoe"};
srand(time(NULL));
one = slotOne(x);
two = slotTwo(x);
three = slotThree(x);
printf("%s - %s - %s\n", one, two, three);
//...
}
not sure if %s or %c is the right type too...
A: At least these problems:
Code is assigning = when it should compare ==.
// if (randOne = 1)
if (randOne == 1)
The last if () { ... } else { ... } will cause one of the 2 blocks to execute. OP wants an if () { ... } else if () { ... } else { ... } tree.
// Problem code
if (randOne = 3) {
randOne = *(symbols+2);
} else {
randOne = *(symbols+3);
}
Suggest
if (randOne == 1) {
randOne = *symbols;
} else if (randOne == 2) {
randOne = *(symbols+1);
} else if (randOne == 3) {
randOne = *(symbols+2);
} else {
randOne = *(symbols+3);
}
Also research switch.
switch (randOne) {
case 1:
randOne = *symbols;
break;
case 2:
randOne = *(symbols+1);
break;
case 3:
randOne = *(symbols+2);
break;
default:
randOne = *(symbols+3);
break;
}
Or consider a coded solution:
randOne = *(symbols+(randOne-1));
But code needs to return a pointer to a string not an int and has no need to pass in randOne as a parameter.
const char * slotOne(const char *symbols[]) {
int randOne = rand() % 4;
return symbols[randOne];
}
Calling code also needs to adjust to receive a const char *, not an int.
// int one;
// one = slotOne(x);
const char *one = slotOne(symbols);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64830125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unknown error in XPath One of our web application, which has been running in our production environment for a long time, most recently it is running into an weird error when there is a high volume of transactions. We couldn't figure out what is exactly the root cause of the problem, but we found some similar issues in the previous version, WebSphere 6, related to a bug in Xalan version used by the app server. Our application server actually is WebSphere 7, which is supposed to have it fixed, besides it's not using Xalan under the hood anymore. Our application doesn't have Xalan jar embedded too.
To have it fixed we just restart the application itself.
One important note is that the Document is being cached (docs.get(tableName)) and reused to execute the XPath evaluation. We did it to avoid the cost of parsing the Document every time.
The app code is
Document doc = null;
try {
doc = docs.get(tableName);
if (doc == null)
return null;
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath.compile(toUpper(xPathQuery));
Object result = expr.evaluate(doc, XPathConstants.NODESET);
return (NodeList) result;
} catch (XPathExpressionException e) {
logger.error("Error executing XPath", e);
}
And the error stack is here
javax.xml.transform.TransformerException: Unknown error in XPath.
at java.lang.Throwable.<init>(Throwable.java:67)
at javax.xml.transform.TransformerException.<init>(Unknown Source)
at org.apache.xpath.XPath.execute(Unknown Source)
at org.apache.xpath.jaxp.XPathExpressionImpl.evaluate(Unknown Source)
Caused by: java.lang.NullPointerException
at org.apache.xerces.dom.ElementNSImpl.getPrefix(Unknown Source)
at org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.processNamespacesAndAttributes(Unknown Source)
at org.apache.xml.dtm.ref.dom2dtm.DOM2DTM.nextNode(Unknown Source)
at org.apache.xml.dtm.ref.DTMDefaultBase._nextsib(Unknown Source)
at org.apache.xml.dtm.ref.DTMDefaultBase.getNextSibling(Unknown Source)
at org.apache.xml.dtm.ref.DTMDefaultBaseTraversers$ChildTraverser.next(Unknown Source)
at org.apache.xpath.axes.AxesWalker.getNextNode(Unknown Source)
at org.apache.xpath.axes.AxesWalker.nextNode(Unknown Source)
at org.apache.xpath.axes.WalkingIterator.nextNode(Unknown Source)
at org.apache.xpath.axes.NodeSequence.nextNode(Unknown Source)
at org.apache.xpath.axes.NodeSequence.runTo(Unknown Source)
at org.apache.xpath.axes.NodeSequence.setRoot(Unknown Source)
at org.apache.xpath.axes.LocPathIterator.execute(Unknown Source)
... 16 more
This is the similar issue what I mentioned.
http://www-01.ibm.com/support/docview.wss?uid=swg1PK42574
Thakns.
A: Many people don't realise that the DOM is not thread-safe (even if you are only doing reads). If you are caching a DOM object, make sure you synchronize all access to it.
Frankly, this makes DOM unsuited to this kind of application. I know I'm biased, but I would suggest switching to Saxon, whose native tree implementation is not only far faster than DOM, but also thread-safe. One user recently tweeted about getting a 100x performance improvement when they made this switch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12291840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Session Time out problem Dear All
I have a website hosted on the cloud server and I have added
sessionState mode ="InProc" timeout="1440" />
in the web.config file. But the session gets timed out in 1-2 minutes.
I think the web.config settings should override the IIS settings.But it's not working. Is there solution for this?
thanks in advance
Anoop George Thomas
A: With InProc (in-memory) session state, you will lose session if any of the following conditions occur:
*
*IIS worker process restarts
*User is transferred to another worker process on the same webserver, or another webserver
*IIS restarts
I would verify that you are not seeing any strange restart behavior on IIS, or if you are bouncing around in your cloud environment.
A: If your using Forms authentication this has a timeout as well.
<authentication mode="Forms">
<forms timeout="20"/>
</authentication>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5474524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Correct way to pass data from one view to another in django? Currently Im trying to build an app using Django that pull data from fitbit. Im in the process of getting the Oauth2.0 connection to work.
So I generated a authorization url from a bunch of user inputs: fitbit url, fitbit api, fitbit client id, fitbit client secret and redirect url. Once the link is generated and visited, fitbit returns with an access code in the URL like: https://localhost:8000/?code=#=
Im able to extract the access code, but Im not sure what is the correct way to obtain the previous user input data in the newly redirected view. One way I can think of is saving the first user inputs into a DB and then pulling it out when redirected with the new access code. But Im not sure what other options are available and what the standard way of doing this is.
Im still new to django, so any help is appreciated.
Thanks!
A: you can pass in URL query params if data is not sensitive otherwise you can use session value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50049320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Check if any type of user is signed in I'm using devise and have set up helper methods to check if any type of user is signed in. I have player and coach user types and current_player and current_coach are devise methods that exist.
Here is my application_controller:
helper_method :current_account, :account_signed_in?
def current_account
if @current_player
@current_account = current_player
elsif @current_coach
@current_account = current_coach
end
end
def account_signed_in?
current_account != nil
end
The player and coach models are submodels of the user model.
class Player < User
end
class Coach < User
end
This works (but only if there is a current_player):
def current_account
@current_account = current_player
end
If I remove the @ from current_player and current_coach I get an error:
wrong number of arguments (given 10, expected 2)
A: current_account stays nil because neither your if condition nor your elsif condition are true. It means that @current_player and @current_coach are nil (or false)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37195171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: App crashes after adding the AdSupport.framework Hi I get this error on startup:
dyld: Library not loaded: /System/Library/Frameworks/AdSupport.framework/AdSupport
Referenced from: /Users/owner12/Library/Application Support/iPhone Simulator/5.1/Applications/823A0485-7443-4206-B9F5-A84C03DBFB89/BusinessPlan.app/BusinessPlan
Reason: image not found
I added that framework to the Target --> Build Phases --> Link Binary With Libraries.
The strange thing is that this framework started appearing in my project in the navigator in the main area where the files are, and not in the project/Frameworks.
Would anyone know how to fix this? Thanks!
Also, I added some params to the Build Settings under "Other Linker Flags" and they appear like this:
But really they were supposed to appear like this:
-all_load *
-ObjC
Could that be the reason for the error?
A: " Referenced from: /Users/owner12/Library/Application Support/iPhone Simulator/5.1/" - isn't AdSupport available only in iOS 6.0 and later?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15956234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: IQueryable return type with Lambda statements i am facing problem with the return type for this function and not really getting anywhere near solving can someone help me with this?
here goes the function,
public IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>> GetDiscussion_categoriesWithBoards()
{
return GetDiscussion_categories().Select(c =>
new
{
Category = c,
Boards = GetDiscussion_boardsByCategory(c.ID).ToList()
}).ToDictionary(i => i.Category, i => i.Boards.ToList());
}
this is the other function that works which is used in the above function that doen't work,
public IQueryable<discussion_board> GetDiscussion_boardsByCategory(int CategoryID)
{
return this.ObjectContext.discussion_boards.Where(e => e.CategoryID == CategoryID);
}
public IQueryable<discussion_category> GetDiscussion_categories()
{
return this.ObjectContext.discussion_categories;
}
I need this to be the return type:
IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>>
thank you friends!
A: Since you're calling ToDictionary(), your method returns a Dictionary<>, not an IQueryable<>:
public Dictionary<discussion_category, List<discussion_board>>
GetDiscussion_categoriesWithBoards()
{
// ...
}
If you absolutely want to return an IQueryable<> you can write something like:
public IQueryable<Dictionary<discussion_category, List<discussion_board>>>
GetDiscussion_categoriesWithBoards()
{
return new[] {
GetDiscussion_categories().Select(c => new {
Category = c,
Boards = GetDiscussion_boardsByCategory(c.ID).ToList()
}).ToDictionary(i => i.Category, i => i.Boards.ToList())
}.AsQueryable();
}
A: The return type will be:
System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>
as the return type of ToDictionary is Dictionary object and not a Iqueryable of Dictionary
A: Seems that this function will return:
Dictionary<Category, List<Board>>
A: I found the answer :)
public IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>> GetDiscussion_categoriesWithBoards()
{
return (GetDiscussion_categories().Select(c =>
new
{
Category = c,
Boards = GetDiscussion_boardsByCategory(c.ID).ToList()
}).ToDictionary(i => i.Category, i => i.Boards.ToList())).AsQueryable() as IQueryable<System.Collections.Generic.Dictionary<discussion_category, List<discussion_board>>>;
}
this is the solution :)
thank you for all your help your questions and answers lead me to solve this :)
A: Are you asking what is the return type of the lambda? It looks to be a Dictionary<Category,List<Board>>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6223229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: send multiple responses to client via nodejs i am using nodejs and i want to send back multiple responses to client.And my code is below
//addwork
var agenda = require('../../schedules/job-schedule.js')(config.db);
exports.addwork = function(req, res) {
var work = new Work(req.body);
work.user = req.user._id;
var user=req.user;
work.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
console.log('created work....'+work);
console.log('dateeeeeeeeeeeee'+work.created);
console.log('calling agenda job now, user is: '+ JSON.stringify(req.user));
console.log('supervisor-------------------------'+JSON.stringify(user.supervisor));
agenda.now('Work_To_Supervisior_Notify', {supervisor:user.supervisor,title:work.title,details:work.details});
res.jsonp(work);
res.send({message:'An email has been sent to ' + user.supervisor + ' with further instructions.'});
}
});
};`
//job-schedule.js
var Agenda = require("agenda");
var emailJob = require('./jobs/email-job.js');
module.exports = function(agendaDb) {
var agenda = new Agenda({db: { address: agendaDb}});
emailJob.sendWorkToSupervisiorEmail(agenda);
agenda.start();
return agenda;
}
//email-job.js
exports.sendWorkToSupervisiorEmail = function(agenda){
agenda.define('Work_To_Supervisior_Notify',{priority: 'high', concurrency: 10}, function(job, done){
console.log('Send works to supervisior ' + JSON.stringify(job.attrs.data.supervisor)+' ,title '+job.attrs.data.title+' ,details '+job.attrs.data.details);
var smtpTransport = nodemailer.createTransport(config.mailer.options);
var mailOptions = {
to: job.attrs.data.supervisor,
from: config.mailer.from,
subject: 'work done by user',
html: '<b>work title : '+job.attrs.data.title+' <br/>work details : '+job.attrs.data.details+'</b>'
};
smtpTransport.sendMail(mailOptions, function(err) {
if (!err) {
console.log('An email has been sent to ' + job.attrs.data.supervisor + ' with further instructions.');
res.send({message:'An email has been sent to ' + user.supervisor + ' with further instructions.'});
}
});
done();
})
}
Here i want response either from agenda or from res.send() message in addwork function
If i use res.send in addwork function it shows ERROR as "can't set headers after they sent".And if i use res.send message in sendWorkToSupervisiorEmail() it show ERROR as "there is no method send".I am new to nodejs please help me with solution
A: A http request only gets a single http response. Using http, you only get one response. Some options for you:
1) Wait for everything to finish before replying. Make sure each part creates a result, success or failure, and send the multiple responses at once. You would need some control flow library such as async or Promises to make sure everything responded at the same time. A good choice if all parts will happen "quickly", not good if your user is waiting "too long" for a response. (Those terms were in quotes, because they are application dependent).
2) Create some scheme where the first response tells how many other responses to wait for. Then you'd have a different HTTP request asking for the first additional message, and when that returns to your client, ask for the second additional message, and so on. This is a lot of coordination though, as you'd have to cache responses, or even try again if they were not done yet. Using a memory cache like redis (or similar) could fulfill the need to holding responses until ready, with a non-existent meaning 'not ready'
3) Use an eventing protocol, such as WebSockets, that can push messages from the server. This is a good choice, especially if you don't know how long some events would occur after the trigger. (You would not want to stall a HTTP request for tens of seconds waiting for 3 parts to complete - user will get bored, or quit, or re-submit.). Definitely check out the Primus library for this option. It can even serve the client-side script, which makes integration quick and easy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27902277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I update application versioning, are there conventions to follow, are there tools? I do not know why I feel insecure of the things that I am about to do, and I always seek for some advice in the community before doing my move.
Have you used bower and/or npm, they have this cli commands: bower init or npm init that initiates creation of bower.json or package.json files respectively. And now it asks me for a version number. FOllowing semver.org tells me that during development 0.y.z is the way to go. Now after doing npm init, how do you update the version number? by manually editing the package.json? and doing a commit?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26086666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unexpected response from the server. The file may have been uploaded successfully. Check in the Media Library or reload the page. Wordpress media When I try to upload an mp4 file with 84mb. It gives me this error
"Unexpected response from the server. The file may have been uploaded successfully. Check in the Media Library or reload the page."
SSL is activated
A: You may need to adjust the values to higher numbers for larger files.
Try doing following steps:
Open Cpanel -> File manager
Click search and type 'php.ini' -> Right click this file and choose edit.
change value of following
memory_limit
post_max_size
upload_max_filesize
Adjust the values to higher numbers for larger files. Save and try again uploading.
A: I also had this problem
First you need to install a file manager plugin. Open file manager, search for a file with the name: .htaccess
Edit this file, at the bottom add the following:
php_value upload_max_filesize 1000M
php_value post_max_size 2000M
php_value memory_limit 3000M
php_value max_execution_time 180
php_value max_input_time 180
Save and close
Try uploading again, in my case worked.
I followed the instructions from this video:
https://www.youtube.com/watch?v=TnI_h-QjrWo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68581368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't InputStream fill the array fully? Dude, I'm using following code to read up a large file(2MB or more) and do some business with data.
I have to read 128Byte for each data read call.
At the first I used this code(no problem,works good).
InputStream is;//= something...
int read=-1;
byte[] buff=new byte[128];
while(true){
for(int idx=0;idx<128;idx++){
read=is.read(); if(read==-1){return;}//end of stream
buff[idx]=(byte)read;
}
process_data(buff);
}
Then I tried this code which the problems got appeared(Error! weird responses sometimes)
InputStream is;//= something...
int read=-1;
byte[] buff=new byte[128];
while(true){
//ERROR! java doesn't read 128 bytes while it's available
if((read=is.read(buff,0,128))==128){process_data(buff);}else{return;}
}
The above code doesn't work all the time, I'm sure that number of data is available, but reads(read) 127 or 125, or 123, sometimes. what is the problem?
I also found a code for this to use DataInputStream#readFully(buff:byte[]):void which works too, but I'm just wondered why the seconds solution doesn't fill the array data while the data is available.
Thanks buddy.
A: Consulting the javadoc for FileInputStream (I'm assuming since you're reading from file):
Reads up to len bytes of data from this input stream into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.
The key here is that the method only blocks until some data is available. The returned value gives you how many bytes was actually read. The reason you may be reading less than 128 bytes could be due to a slow drive/implementation-defined behavior.
For a proper read sequence, you should check that read() does not equal -1 (End of stream) and write to a buffer until the correct amount of data has been read.
Example of a proper implementation of your code:
InputStream is; // = something...
int read;
int read_total;
byte[] buf = new byte[128];
// Infinite loop
while(true){
read_total = 0;
// Repeatedly perform reads until break or end of stream, offsetting at last read position in array
while((read = is.read(buf, read_total, buf.length - offset)) != -1){
// Gets the amount read and adds it to a read_total variable.
read_total = read_total + read;
// Break if it read_total is buffer length (128)
if(read_total == buf.length){
break;
}
}
if(read_total != buf.length){
// Incomplete read before 128 bytes
}else{
process_data(buf);
}
}
Edit:
Don't try to use available() as an indicator of data availability (sounds weird I know), again the javadoc:
Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. Returns 0 when the file position is beyond EOF. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
In some cases, a non-blocking read (or skip) may appear to be blocked when it is merely slow, for example when reading large files over slow networks.
The key there is estimate, don't work with estimates.
A: Since the accepted answer was provided a new option has become available. Starting with Java 9, the InputStream class has two methods named readNBytes that eliminate the need for the programmer to write a read loop, for example your method could look like
public static void some_method( ) throws IOException {
InputStream is = new FileInputStream(args[1]);
byte[] buff = new byte[128];
while (true) {
int numRead = is.readNBytes(buff, 0, buff.length);
if (numRead == 0) {
break;
}
// The last read before end-of-stream may read fewer than 128 bytes.
process_data(buff, numRead);
}
}
or the slightly simpler
public static void some_method( ) throws IOException {
InputStream is = new FileInputStream(args[1]);
while (true) {
byte[] buff = is.readNBytes(128);
if (buff.length == 0) {
break;
}
// The last read before end-of-stream may read fewer than 128 bytes.
process_data(buff);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24791360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extract elements of multiple sublists in a list and transform to multiple dataframes Hello Dear Community,
Following this post,
I am searching how to create multiple data frames from a list that contains multiple sublists with different names
So, from a list called tier.col I would like to create a function tier2col that returns to multiple data.frames (as much as there is sublist in my list) containing specific elements of the sublist.
I get how to do this manually as so :
phones <- data.frame(tier.col$phones$xmin[-1,3], tier.col$phones$xmax[-1,3], tier.col$phones$text[3])
But in reality "phones" changes in multiple names, so I would need a more generic approach to sublists:
x <- data.frame(tier.col$x$xmin[-1,3], tier.col$x$xmax[-1,3], tier.col$x$text[3])
The function would act as so :
tier2col <- function(list.x) {
for all sublist in my list
select tier.col$sublist$xmin[-1,3], tier.col$sublist$xmax[-1,3], tier.col$sublist$text[3]
and compile them in a dataframe
}
I know that I can call all the xmin & xmax & text by this :
lapply(tier.col[c(1:length(names(tier.col)))], "[", 1)
lapply(tier.col[c(1:length(names(tier.col)))], "[", 2)
lapply(tier.col[c(1:length(names(tier.col)))], "[", 3)
But I don't know how to get pass this or how to use mapply on this kind of datastructure.
I would have like something like tier.col$c(names(tier.col)$xmin to work, but evidently, that is not the proper way to do it.
Can someone help me to compute this in an efficient way?
Stucture of tier.col:
List of 17
$ phones :List of 3
..$ xmin:'data.frame': 2506 obs. of 3 variables:
.. ..$ num.row: num [1:2506] 11 15 19 23 27 31 35 39 43 47 ...
.. ..$ object : chr [1:2506] "xmin" "xmin" "xmin" "xmin" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 20 20 21 22 23 24 26 27 28 29 ...
..$ xmax:'data.frame': 2506 obs. of 3 variables:
.. ..$ num.row: num [1:2506] 12 16 20 24 28 32 36 40 44 48 ...
.. ..$ object : chr [1:2506] "xmax" "xmax" "xmax" "xmax" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 2414 21 22 23 24 26 27 28 29 30 ...
..$ text:'data.frame': 2505 obs. of 3 variables:
.. ..$ num.row: num [1:2505] 17 21 25 29 33 37 41 45 49 53 ...
.. ..$ object : chr [1:2505] "text" "text" "text" "text" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 11 4397 4434 3697 4025 3697 3832 4127 3992 4397 ...
$ syll :List of 3
..$ xmin:'data.frame': 1147 obs. of 3 variables:
.. ..$ num.row: num [1:1147] 10037 10041 10045 10049 10053 ...
.. ..$ object : chr [1:1147] "xmin" "xmin" "xmin" "xmin" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 20 20 21 24 27 30 33 35 37 40 ...
..$ xmax:'data.frame': 1147 obs. of 3 variables:
.. ..$ num.row: num [1:1147] 10038 10042 10046 10050 10054 ...
.. ..$ object : chr [1:1147] "xmax" "xmax" "xmax" "xmax" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 2414 21 24 27 30 33 35 37 40 43 ...
..$ text:'data.frame': 1146 obs. of 3 variables:
.. ..$ num.row: num [1:1146] 10043 10047 10051 10055 10059 ...
.. ..$ object : chr [1:1146] "text" "text" "text" "text" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 11 4431 4028 3879 4430 4442 4405 3783 4159 4327 ...
$ delivery :List of 3
..$ xmin:'data.frame': 1147 obs. of 3 variables:
.. ..$ num.row: num [1:1147] 14627 14631 14635 14639 14643 ...
.. ..$ object : chr [1:1147] "xmin" "xmin" "xmin" "xmin" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 20 20 21 24 27 30 33 35 37 40 ...
..$ xmax:'data.frame': 1147 obs. of 3 variables:
.. ..$ num.row: num [1:1147] 14628 14632 14636 14640 14644 ...
.. ..$ object : chr [1:1147] "xmax" "xmax" "xmax" "xmax" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 2414 21 24 27 30 33 35 37 40 43 ...
..$ text:'data.frame': 1146 obs. of 3 variables:
.. ..$ num.row: num [1:1146] 14633 14637 14641 14645 14649 ...
.. ..$ object : chr [1:1146] "text" "text" "text" "text" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 11 2 2 2 2 2 2 2 2 2 ...
$ link :List of 3
..$ xmin:'data.frame': 807 obs. of 3 variables:
.. ..$ num.row: num [1:807] 19217 19221 19225 19229 19233 ...
.. ..$ object : chr [1:807] "xmin" "xmin" "xmin" "xmin" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 20 20 21 27 30 34 37 40 45 1642 ...
..$ xmax:'data.frame': 807 obs. of 3 variables:
.. ..$ num.row: num [1:807] 19218 19222 19226 19230 19234 ...
.. ..$ object : chr [1:807] "xmax" "xmax" "xmax" "xmax" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 2414 21 27 30 34 37 40 45 1642 1651 ...
..$ text:'data.frame': 806 obs. of 3 variables:
.. ..$ num.row: num [1:806] 19223 19227 19231 19235 19239 ...
.. ..$ object : chr [1:806] "text" "text" "text" "text" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 11 2 2 4025 2 2 2 4025 2 4025 ...
$ words :List of 3
..$ xmin:'data.frame': 807 obs. of 3 variables:
.. ..$ num.row: num [1:807] 22447 22451 22455 22459 22463 ...
.. ..$ object : chr [1:807] "xmin" "xmin" "xmin" "xmin" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 20 20 21 27 30 34 37 40 45 1642 ...
..$ xmax:'data.frame': 807 obs. of 3 variables:
.. ..$ num.row: num [1:807] 22448 22452 22456 22460 22464 ...
.. ..$ object : chr [1:807] "xmax" "xmax" "xmax" "xmax" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 2414 21 27 30 34 37 40 45 1642 1651 ...
..$ text:'data.frame': 806 obs. of 3 variables:
.. ..$ num.row: num [1:806] 22453 22457 22461 22465 22469 ...
.. ..$ object : chr [1:806] "text" "text" "text" "text" ...
.. ..$ value : Factor w/ 4466 levels ""," "," n ",..: 11 4424 3881 4429 3745 3781 4160 4054 3983 4229 ...
Don't hesitate to tell if something is not clear/missing,
Thanks a lot,
A: If you know how to process one item (phones), then just generalize that into a function so you can run it to the whole list via lapply:
process.one <- function(x)
data.frame(xmin = x$xmin[-1,3], xmax = x$xmax[-1,3], text = x$text[3])
out <- lapply(tier.col, process.one)
At this point, out is a list of data.frames. It is recommended you keep it that way, but if what you really wanted are data.frames to be added to an environment (e.g. the global environment) then you can do so with list2env:
list2env(out, envir = .GlobalEnv)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22067166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS : Is there a way to know if GPU is being used? I know some CSS properties, on some browsers, on some OS, can trigger GPU acceleration.
Is there a way to see, somewhere within the browsers' debugging tools, if the GPU is actually being used or not ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36643971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Break string in Javax.Swing.JTextArea without escape characters Is there a way to automatically break a string entered into JTextArea (in package javax.swing), for example via the keyboard, into a readable form, without the need for escape characters, i.e. \n and \r ?
Edit2:
With the help of @matt, I realized that the correct question is about word warp and therefore the answer is the answer function
mytextArea.setLineWrap(true);
A: Breaking a string onto a newline without actually adding a character is a word wrap.
JTextArea has word wrap.
mytextArea.setLineWrap(true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74251435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kafka producer unable to connect to broker via Internet. Works well if in local network as broker. Telnet connectivity working from internet I have a Kafka broker running on a computer on my home network. When I connect my java producer (on another computer) to this broker from the same wifi network, it works absolutely well and is able to post messages without any issues.
As next steps for my application, I have exposed my computer and Kafka's 9092 port over internet. I have also opened all firewall on my system for this port. And when I do telnet/nc connection attempt from any other network, it connects well. The Kafka host also shows the connection made in the netstat output.
telnet DNSHOSTNAME 9092
Trying MYIP...
Connected to DNSHOSTNAME.
Escape character is '^]'.
But from this external network, when I use my exact same kafka java producer to send to my home computer from this outside network, it always fails with the following error. I also do not see any connection attempts or errors in the Kafka logs related to this.
Error while producing message to topic :TP1-0@-1
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for TP1-0: 30005 ms has passed since batch creation plus linger time
Another interesting point is that, I have other apps - RabbitMQ and Tomcat also on the same machine as Kafka with the same firewall and router rules. My same java app is able to publish to them over TCP and HTTP from the internet connection. It's only Kafka which is not working.
Provided that the telnet and nc connections are connecting well, I think this is not a firewall or network routing problem. That leaves me only with the producer code, given below. Is there some type of setting to be applied on Kafka Broker or Kafka Producer side for them to be able to connect over the internet? Same issue with consumer code. It can't connect from internet.
Producer code:
public static void main(String[] args){
Properties props = new Properties();
//props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "DNSHOSTNAME:9092");
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "MYEXTERNALIP:9092");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.RETRIES_CONFIG, 0);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
TestCallback callback = new TestCallback();
Random rnd = new Random();
ProducerRecord<String, String> data = new ProducerRecord<String, String>("TP1", "s2", "TEST DATA" );
producer.send(data, callback);
producer.close();
}
private static class TestCallback implements Callback {
@Override
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
if (e != null) {
System.out.println("Error while producing message to topic :" + recordMetadata);
e.printStackTrace();
} else {
String message = String.format("sent message to topic:%s partition:%s offset:%s", recordMetadata.topic(), recordMetadata.partition(), recordMetadata.offset());
System.out.println(message);
}
}
}
Troubleshooting steps done:
*
*Deployed Kafka on 3 different computers, 2 windows and 1 mac. Same results. Works well from the same network, not when they are on internet. Telnet works with each kafka computer from internet/outside network.
*Tried 3 different external networks, one being my cell phone's hot spot.
*Tried other softwares as well on kafka machine, as mentioned above and they work fine.
*Completely disabled the system firewall just to ensure there is no firewall issue, but no luck.
Can someone please help me here on this thread?
Thanks in advance !
A: The problem you're describing can be solved by "advertising" an address for each broker over the internet via advertised.listeners
telnet and nc check that port is open (listeners config), but cannot check that the brokers bootstrap correctly back to the client, you can instead use kafkacat -L -b <bootstrap> for that, which will return a list of brokers in the cluster, and connecting to each of those should be possible from where you want to run the client
If you have multiple brokers behind your single WAN address, they'll have to advertise / forward separate ports for full connectivity
Alternative solutions include the Kafka REST Proxy
In either case, adding SSL to the connection should be done
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64522336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Interactive Legend onclick or mouseover - D3js I've been looking for a way to have my legend control my chart animation (similar to NVD3 examples). I've run into a problem though - nested selections.
var legend = svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(70,10)")
;
var legendRect = legend.selectAll('rect').data(colors);
legendRect.enter()
.append("rect")
.attr("x", w - 65)
.attr("width", 10)
.attr("height", 10)
.attr("y", function(d, i) {
return i * 20;
})
.style("stroke", function(d) {
return d[1];
})
.style("fill", function(d) {
return d[1];
});
I'm using a bit of a hack to do my animation. Basically setting style to display: none.
I want to be able to click on the rectangles and call the function. But putting a mouseover or onclick within legendRect doesn't work. The bars to animate are not children of the legend. How can I call the function, or chain my function to my legend?
function updateBars(opts) {
var gbars = svg.selectAll("rect.global");
var lbars = svg.selectAll("rect.local");
if (opts === "global") {
gbars.style("display", "block") ;
lbars.style("display", "none");
gbars.transition()
.duration(500)
.attr("width", xScale.rangeBand());
};
if (opts === "local") {
lbars.style("display", "block")
;
gbars.style("display", "none");
lbars.transition()
.duration(500)
.attr("x", 1 / -xScale.rangeBand())
.attr("width", xScale.rangeBand());
};
}
My other obstacle is changing the fill color on click. I want it to almost imitate a checkbox, so clicking (to deselect) would turn the fill white. I tried something similar as .on("click",(".style" ("fill", "white"))). But that is incorrect.
Here is my fiddle. For some reason, the function isn't updating things on Fiddle. It works on my localhost though. Not sure the problem with that.
A: I'm not completely sure I understand you correctly, but if your first question is how to change element X when clicking on element Y, you need something along the lines of:
legendRect.on("click", function() {
gbars.transition()
.duration(500)
.style("display", "block")
// etc...
}
As for changing the fill on click, try:
gbars.on("click", function() {
d3.select(this)
.attr("fill", "white");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16310102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ warning: Not all control paths return a value Well, I have some warnings that cause my program to crash, when I enter size 3.
Not all control paths return a value.
I am trying to solve N matrix, input, output and some operations. I store first column
_vec[0:size-1],last column _vec[size : (size*2)-1]
and diagonal
_vec[size*2 : size*3-2]
of matrix in 1-dimensional array. The size of array is size of matrix * 3 -2. The problem occurs when I overload () operators:
int _size = (_vec.size() +2) /3;
// when I switch from vector size to normal matrix size. f.e vector size: 7,
// my matrix size is 3.
int Matrix::operator()(int i, int j) const
{
int _size = (_vec.size() +2) /3;
if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
if (i != j && j != 0 && j != _size - 1) return 0;
else {
if (j == 0)
{
return _vec[i];
}
else if (j == _size - 1)
{
return _vec[_size + i];
}
else if (i == j && j != 0 && j != _size - 1)
{
return _vec[(_size * 2) + i];
}
}
}
int& Matrix::operator()(int i, int j)
{
int _size = (_vec.size() +2) /3;
if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
if (i != j && j != 0 && j != _size - 1) throw NULLPART;
else {
if (j == 0)
{
return _vec[i];
}
else if (j == _size - 1)
{
return _vec[_size + i];
}
else if (i == j && j != 0 && j != _size - 1)
{
return _vec[(_size * 2) + i];
}
}
}
A: Change the code like below for second function as well.
int Matrix::operator()(int i, int j) const
{
int _size = (_vec.size() + 2) / 3;
if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
if (i != j && j != 0 && j != _size - 1) return 0;
else {
if (j == 0)
{
return _vec[i];
}
else if (j == _size - 1)
{
return _vec[_size + i];
}
else if (i == j && j != 0 && j != _size - 1)
{
return _vec[(_size * 2) + i];
}
}
return 0; // added this line
}
A: It requires some analysis to prove that all cases return.
And it seems your compiler doesn't do the full analysis
int Matrix::operator()(int i, int j) const
{
int _size = (_vec.size() + 2) /3;
if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
if (i != j && j != 0 && j != _size - 1) return 0;
else {
if (j == 0)
{
return _vec[i];
}
else if (j == _size - 1)
{
return _vec[_size + i];
}
else if (i == j && j != 0 && j != _size - 1)
{
return _vec[(_size * 2) + i];
}
else
{
// No return here.
// But is this case reachable?
// yes, for (i, j) respecting:
// (0 <= i && i < _size) && (0 <= j && j < _size)
// && ((i == j) || (j == 0) || (j == _size - 1)) // #2
// && (j != 0) && (j != _size - 1) // #1
// && (i != j || j == 0 || j == _size - 1) // #3
// which after simplification results indeed in false.
// #1 simplifies #2 to (i == j) and #3 to (i != j)
}
}
}
On the other part, that means that you do useless "tests" that you can remove (and so please the compiler):
int Matrix::operator()(int i, int j) const
{
int _size = (_vec.size() + 2) /3;
if ((i >= _size || i < 0) || (j >= _size || j < 0)) throw OVERINDEXED;
if (i != j && j != 0 && j != _size - 1) return 0;
else {
if (j == 0)
{
return _vec[i];
}
else if (j == _size - 1)
{
return _vec[_size + i];
}
else // We have necessary (i == j && j != 0 && j != _size - 1)
{
return _vec[(_size * 2) + i];
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60632921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error in running RMIC via Ant using wsejbdeploy taskdef I get the following exception when trying to generate RMIC using Ant task.
[wsejbdeploy] Error generating RMI code: RMIC command failed on project: .... with message:
[wsejbdeploy] error: The IBM RMIC version 0x1500 does not match the IBM runtime version 0x1600.
Please let me know how to fix this.
I am trying this using the WebSphere 6.1 server that comes bundled with RAD7.5.
This works fine when we use IDE to generate the EAR, and fails only when we use our custom Ant build file.
A: The error means that JAVA_HOME in your shell used to invoke Ant is different from the Java that was included with the embedded WebSphere Application Server. Try using the WAS_HOME/bin/ws_ant script, or set JAVA_HOME to WAS_HOME/java/.
A: The error
Cannot run RMIC because it is not installed. Expected location of RMIC is the following:
will some times confuse. enable the "Capture RMIC verbose output to the workspace .log file.
and see what the exact error your getting. This option will be available in properties > EJBDeployment.
In My case it throwing error due to huge number of jars in class path.It got resolved after shortening the class path jar location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10892737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails - 3 nested models in one view I'm struggling with grasping the fundamentals behind writing model methods, which is I think what I need to do to get this to work. Basically, I have a project view that's showing project_todos that belong to that project. Then nested under that I have project_todo_comments that belong to a project_todo. All in one view.
I've set up the associations so that project has_many project_todos, project_todo belongs_to project and has_many project_todo_comments. Then of course project_todo_comment belongs_to project_todo.
In the projects controller, I'm doing this:
def show
@project = Project.find(params[:id])
# Display the form to create a new todo
@project_todo = ProjectTodo.new
# Create the instance variable to display the loop in the view
@todos = @project.project_todos
# Display the form to create a new comment
@project_todo_comment = ProjectTodoComment.new
# Create the instance variable to display the loop in the view
@comments = @project.project_todo_comments
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @project }
end
end
So this is working to the point where I can add todos on a project and display them, and I can also add comments to project todos and display them too, all in that same view. BUT, I'm having difficulties getting the comments to display ONLY with the todos that they're associated with. Right now, when I add a comment on any todo, every single todo then displays that comment.
In the view, here's where I'm displaying the project_todos and nesting the form to add a comment, then displaying the comments:
<% @todos.each do |todo| %>
<p><%= todo.title %></p>
<%= form_for(@project_todo_comment) do |f| %>
<%= f.hidden_field :project_todo_id, :value => @project_todo.id %>
<%= f.hidden_field :project_id, :value => @project.id %>
<%= f.text_area :comment %>
<%= f.submit 'Add Comment' %>
<% end %>
<% @comments.each do |comment| %>
<%= comment.comment %>
<% end %>
<% end %>
I've been told that I need to write a model method to get this to work, but I'm still trying to understand those. Could anyone just reassure that I do in fact need to write a model method, and point me in a direction to learn about them? Thanks!
A: In your controller you get all of the comments, but in an actual todo item you just want the comments for that item. This can be done with: todo.project_todo_comments
The easiest way to solve:
- <% @comments.each do |comment| %>
- <%= comment.comment %>
- <% end %>
+ <% todo.project_todo_comments.each do |comment| %>
+ <%= comment.comment %>
+ <% end %>
You can remove the line from your controller:
- @comments = @project.project_todo_comments
However in your form (where you create a comment) you use the wrong ID for the todo item:
- <%= f.hidden_field :project_todo_id, :value => @project_todo.id %>
+ <%= f.hidden_field :project_todo_id, :value => todo.id %>
By the way, I would just name those models:
Todo and Comment, there is no point using that long modelnames. You define those associations in the start of your model, so if someone would read it, he/she would see it instantly.
For example see myself, I knew what was the purpose of your models still misused the namings, cause of too long classnames.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13881258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why isn't transition for my input forms working? I have tried to add transitions to my input forms but it doesn't work. I've read a lot of stack overflow posts but they haven't worked for me. A person said that it's because input has display: none but even after changing it, it still didn't work. I tried to be more specific when using transition but that didn't work. So I'm not sure how to fix this issue. The transition applies to the button but not to the input forms.
https://codepen.io/i-am-programming/pen/gOmydqv
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<title>Document</title>
</head>
<body>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Store</a>
<a href="#">Contact Us </a>
</nav>
<div class="container">
<h1 class="login">Log In</h1>
<input type="text" placeholder="Username" class="username info" />
<input type="password" placeholder="Password" class="pass info" />
<input type="button" class="button" value="Submit" />
</div>
<script src="app.js"></script>
</body>
</html>
* {
margin: 0;
padding: 0;
font-size: 25px;
font-family: "Montserrat", sans-serif;
}
body {
background: url("images/background.jpeg");
background-size: cover;
}
a {
text-decoration: none;
margin-right: 30px;
color: #fff;
background-color: rgba(0, 0, 0, 0.7);
padding: 8px;
transition: 0.3s ease;
}
nav {
margin-top: 20px;
display: flex;
flex-direction: row;
justify-content: flex-end;
}
a:hover {
color: black;
background-color: rgba(255, 255, 255, 0.7);
}
.container {
display: flex;
flex-direction: column;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 500px;
height: 450px;
background-color: rgba(0, 0, 0, 0.7);
align-items: center;
}
.login {
color: white;
margin-top: 50px;
font-size: 45px;
}
input {
outline: none;
padding: 5px;
transition: 0.3s;
}
input:hover {
width: 400px;
}
.username {
position: absolute;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
}
.pass {
position: absolute;
top: 65%;
left: 50%;
transform: translate(-50%, -50%);
}
.button {
width: 150px;
margin-top: 250px;
}
A: I think you are missing transition property in the input, it will be like this:
input {
height: 30px;
width: 300px;
outline: none;
transition: all 0.5s ease;
}
input:hover {
width: 500px;
}
Read more of the CSS transition
A: Firstly your code in text and link are different. Secondly you can't use transition on display cause it's not animatable. You cna use opacity and visibility instead of display. If we come to our question..
You want to get bigger input place when user get hover it right? So in your example your input does not has any width and when you hover it you want to get a transition. For this you need to add a width value to your input so it will know where the change began and what you want at the end. Meanwhile the time you passed is your time attribute on your transition. So
input {
height: 30px;
width: 300px;
outline: none;
transition: 0.3s;
}
input:hover {
width: 400px;
}
It will know that when user hover on it, it will grow to 400px from 300px in 0.3s. That's it. Hope you get it.
A: It's because you didn't specify the width of your input
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68123872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can not use http.begin() in HTTPClient Arduino Library to open my IP i have an esp32 cam with 192.168.1.54:8082 IP.
i want use from http.begin ("http://192.168.1.54:8082"); in HTTPClient Arduino Library that not working while when i am using "http://192.168.1.54:8082" in a browser working fine.
any help can be useful.
#include <HTTPClient.h>
HTTPClient http;
http.begin("192.168.1.54:8082"); //Not Working Here (but in a browser 192.168.1.54:8082 works fine)
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end();
A: The API for http.begin(url) assumed standard port of 80 or 443 is used. In order to use port 8082, you need to pass in the port as function argument like this:
http.begin("192.168.1.54", 8082);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67547776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Netsuite PHP Toolkit - Limit returned fields in Saved Search I'm working on an integration for Netsuite. When I return my saved search, there are 300+ fields returned for the searchRowBasic property. I'll include a var_dump below.
My source code is from Magento 2, so the factory methods are out of scope, but you can assume they create a new instance of the class (which i'll note).
I'm also using the composer package for netsuite to utilize namespaces rather than Netsuite's official package that is one file with 1600 classes and no namespaces (seriously).
/** @var Netsuite\Classes\ItemSearchAdvanced $searchRecord */
$searchRecord = $this->itemSearchAdvancedFactory->create();
/** @var Netsuite\Classes\SearchRow $searchRow */
$searchRow = $this->itemSearchRowFactory->create();
/** @var Netsuite\Classes\SearchRowBasic $searchRowBasic */
$searchRowBasic = $this->itemSearchRowBasicFactory->create();
/** @var Netsuite\Classes\SearchRequest */
$request = $this->searchRequestFactory->create();
$searchRecord->savedSearchId = 190;
$request->searchRecord = $searchRecord;
/** @var Netsuite\NetsuiteService $netsuiteService */
// Loaded with authentication values.
$netsuiteService = $this->getNetsuiteService();
$netsuiteService->setSearchPreferences(false, 1000);
// Submit the request - returns successful response.
$searchResponse = $netsuiteService->search($request);
My Request returns a successful response (:thumbsup:)
The problem is that I want to use 4 variables in the entire response, but there are hundreds of indexes in the array that are unused. My biggest concern is that Netsuite is querying these during the response, my secondary concern is returning multiple KB's of data that I won't use within my response for larger requests.
I have tried this, to unset the parameters, hoping that if I undeclared them, Netsuite would ignore them in the response, but I had no luck.
protected function getSearchRecord(): ItemSearchAdvanced
{
$searchRecord = $this->itemSearchAdvancedFactory->create();
$searchRow = $this->itemSearchRowFactory->create();
$searchRowBasic = $this->itemSearchRowBasicFactory->create();
$i = 0;
$fields = $searchRowBasic::$paramtypesmap;
foreach ($fields as $name => $type) {
// use only the first 10 just to see if only these 10 will be used.
// no such luck.
if ($i > 10) {
unset($searchRowBasic::$paramtypesmap[$name]);
unset($searchRowBasic->$name);
}
$i++;
}
$searchRow->basic = $searchRowBasic;
$searchRecord->columns = $searchRow;
return $searchRecord;
}
Question:
I know the fields I want to return before I make the request. How can I specify those fields to only return the data I need, not all the data available?
Here is a var_dump of the response to see the format. I truncated the data a good amount, if anyone needs more I can easily provide it, but I think there is enough info provided currently.
class NetSuite\Classes\SearchResponse#2452 (1) {
public $searchResult =>
class NetSuite\Classes\SearchResult#2449 (8) {
public $status =>
class NetSuite\Classes\Status#2447 (2) {
public $statusDetail =>
NULL
public $isSuccess =>
bool(true)
}
public $totalRecords =>
int(1)
public $pageSize =>
int(1000)
public $totalPages =>
int(1)
public $pageIndex =>
int(1)
public $searchId =>
string(60) "<requst_id_with_personal_data>"
public $recordList =>
NULL
public $searchRowList =>
class NetSuite\Classes\SearchRowList#2475 (1) {
public $searchRow =>
array(1) {
[0] =>
class NetSuite\Classes\ItemSearchRow#2476 (23) {
public $basic =>
class NetSuite\Classes\ItemSearchRowBasic#2477 (322) {
public $accBookRevRecForecastRule =>
NULL
public $accountingBook =>
NULL
public $accountingBookAmortization =>
NULL
public $accountingBookCreatePlansOn =>
NULL
public $accountingBookRevRecRule =>
NULL
public $accountingBookRevRecSchedule =>
NULL
public $allowedShippingMethod =>
NULL
public $alternateDemandSourceItem =>
NULL
public $assetAccount =>
NULL
public $atpLeadTime =>
NULL
(more elements)...
}
public $assemblyItemBillOfMaterialsJoin =>
NULL
public $binNumberJoin =>
NULL
public $binOnHandJoin =>
NULL
public $correlatedItemJoin =>
NULL
public $effectiveRevisionJoin =>
NULL
public $fileJoin =>
NULL
public $inventoryDetailJoin =>
NULL
public $inventoryLocationJoin =>
NULL
public $inventoryNumberJoin =>
NULL
(more elements)...
}
}
}
}
}
A: After searching through the XML response from the server, it looks like Netsuite was responding with only the columns declared in my saved search as I wanted. The other null values I was receiving were initialized as default values when the response object was initialized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57795752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use X,Y coordinates to plot points inside a circle Is there a way in javascript to plot x,y coordinates so they fall into a circle rather than a square?
For example if I have the following code:
circleRadius = 100;
context.drawImage(img_elem, dx, dy, dw, dh);
I need to figure out a combination of x,y values that would fall inside a 100 pixel circle.
Thanks!
A: *
*choose an x at random between -100 and 100
*a circle is defined by x^2 + y^2 = r^2, which in your case equals 100^2 = 10000
*From this equation you can get that y^2 = 10000 - x^2 , therefore the points with a chosen x and y = +/-sqrt(10000 - x^2) will lye on the circle.
*choose an y at random between the two coordinates found at point 3
*You're set!
EDIT:
In JS:
var radius = 100;
x = Math.random() * 2 * radius - radius;
ylim = Math.sqrt(radius * radius - x * x);
y = Math.random() * 2 * ylim - ylim;
Another edit: a jsFiddle Example
A: If you want equidistributed coordinates you better go for
var radius = 100
var center_x = 0
var center_y = 0
// ensure that p(r) ~ r instead of p(r) ~ constant
var r = radius*Math.sqrt(Math.random(1))
var angle = Math.sqrt(2*Math.PI)
// compute desired coordinates
var x = center_x + r*Math.cos(angle);
var y = center_y + r*Math.sin(angle);
If you want more points close to the middle then use
var r = radius*Math.random(1)
instead.
A: not sure what you mean for javascript but
x = R*cos(theta) and y = R*sin(theta) are the Cartesian points for a circle. R is the radius of course and theta is the angle which goes from 0 to 2*Pi.
A: I'm posting this as a solution because this question was the only relevant result in google.
My question/problem was how to add cartesian coordinates inside a circle where x and y would not exceed r.
Examples:
*
*plot: (45,75) inside a circle with a radius of 100 (this would normally fall inside the circle, but not the correct position)
*plot: (100,100) inside a circle with a radius of 100 (this would normally fall outside the circle
Solution
// The scale of the graph to determine position of plot
// I.E. If the graph visually uses 300px but the values only goto 100
var scale = 100;
// The actual px radius of the circle / width of the graph
var radiusGraph = 300;
// Plot the values on a cartesian plane / graph image
var xCart = xVal * radiusGraph;
var yCart = yVal * radiusGraph;
// Get the absolute values for comparison
var xCartAbs = Math.abs( xCart );
var yCartAbs = Math.abs( yCart );
// Get the radius of the cartesian plot
var radiusCart = Math.sqrt( xCart * xCart + yCart * yCart );
// Compare to decide which value is closer to the limit
// Once we know, calculate the largest possible radius with the graphs limit.
// r^2 = x^2 + y^2
if ( xCartAbs > yCartAbs ) { // Less than 45°
diff = scale / xCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( yCartAbs * diff, 2) );
} else if ( yCartAbs > xCartAbs ) { // Greater than 45°
diff = scale / yCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( xCartAbs * diff, 2) );
} else { // 45°
radiusMaximum = Math.sqrt( 2 * ( radiusGraph * radiusGraph ) );
}
// Get the percent of the maximum radius that the cartesian plot is at
var radiusDiff = radiusCart / radiusMaximum;
var radiusAdjusted = radiusGraph * radiusDiff;
// Calculate the angle of the cartesian plot
var theta = Math.atan2( yCart, xCart );
// Get the new x,y plot inside the circle using the adjust radius from above
var xCoord = radiusAdjusted * Math.cos( theta );
var yCoord = radiusAdjusted * Math.sin( theta );
A: Not sure if this is correct JavaScript code, but something like this:
for (x = -r; x < r; x++) {
for (y = -r; x < r; y++) {
if ((x * x + y * y) < (r * r)) {
// This x/y coordinate is inside the circle.
// Use <= if you want to count points _on_ the circle, too.
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4707796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Styling buttons for Microsoft Outlook I am currently setting up my first newsletter i Mailchimp. After checking the newsletter in different email clients I can see that my "buttons" does not look right in Outlook.
Below is my code for the button;
<td align="center" valign="middle" bgcolor="#96d1eb"
style="color: #ffffff;
font-size: 13px;
border-radius: 5px;
display: block;
padding-right: 22px;
padding-left: 22px;
padding-bottom: 8px;
padding-top: 8px;
line-height: 22px;
vertical-align: middle;"
mc:edit="2">
<!--[if !mso]><!--><span style=" font-weight: normal;"><!--<![endif]-->
<a href="#" style="color: rgb(255, 255, 255); font-size: 13px;
text-decoration: none; line-height: 20px;" class="hover">Shop Now</a>
<!--[if !mso]><!--></span><!--<![endif]-->
</td>
This gives me the following result in most email clients;
Although when i look in Outlook the text is not vertical centered and without rounded corners;
How can i make the button in Outlook look the same as in the other email clients?
A: ...I would suggest setting the line-height the same as the font-size and playing with the link's padding to get the same result. I am certain that this is causing the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26619899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dart code acts differently in my Flutter application. List' is not a subtype of type 'List> When I run this in a "Dart" main, everything works, and I get a List of attendees. However, when I call it within my Flutter application, I get the error:
flutter: type 'List' is not a subtype of type 'List>'
I have been round and round with the "not a subtype" error in Dart, and I finally was able to get all of the casts correct for my json data that is coming from a REST interface.
Can someone tell me, why is it bombing in Flutter but not in Dart? How do I resolve this?
Future<List<Attendee>> callLogin() async {
return http.get(
"http://www.somesite.com")
.then((response) {
try {
List<Attendee> l = new List();
final List<Map<String, dynamic>> responseJson =
json.decode(response.body)['attendees'];
responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
return l;
} catch (e) {
print(e); // Just print the error, for SO
}
});
}
class Attendee {
String nameFirst;
String nameLast;
String company;
...
factory Attendee.fromJson(Map<String, dynamic> json) {
return new Attendee(
nameLast: json['nameLast'],
nameFirst: json['tnameFirst'],
company: json['company'],
city: json['city'],
state: json['state'],
country: json['country'],
);
}
class AttendeeSearch extends StatefulWidget {
AttendeeSearch({Key key, this.title}) : super(key: key);
final String title;
@override
_AttendeeSearchPageState createState() => new
_AttendeeSearchPageState();
}
class _AttendeeSearchPageState extends State<AttendeeSearch> {
String search;
final _suggestions = new List<Attendee>();
final _smallerFont = const TextStyle(fontSize: 12.0);
final formKey = new GlobalKey<FormState>();
void _submit() {
final form = formKey.currentState;
if (form.validate()) {
form.save();
}
AttendeeSummaryRequest asr = new AttendeeSummaryRequest();
setState(() {
asr.callLogin().then((item) { // Calling WebService
setState(() {
_suggestions.addAll(item);
});
});
});
}
A: For anyone who hits this issue, I did the following...
Future<List<Attendee>> callLogin() async {
return http.get(
"http://www.somesite.com")
.then((response) {
try {
List<Attendee> l = new List();
// final Map<String, dynamic> responseJson = // REPLACED
final dynamic responseJson = // <<== REMOVED CAST to Map<String, dynamic>
//
json.decode(response.body)['attendees'];
responseJson.forEach((f) => l.add(new Attendee.fromJson(f)));
return l;
} catch (e) {
print(e); // Just print the error, for SO
}
});
Normally I don't attempt to answer my own questions. And, in this case I still do not have a true answer why Flutter acts differently than running the code from the Dart main. I am running them both from Android Studio. So, I would assume that Dart, in both cases would be the same version. But, that is where I am looking next. I will post if I have more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50729769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is this not downcasting? If I do
double d = 34.56;
int i = (int)d;
Am I not "downcasting"?
OR
Is this term only used in terms of classes and objects?
I am confused because in this case we are "downcasting" from a bigger double to a smaller int, but in case of classes, we "downcast" from a smaller base class to a bigger derived class.
Aren't these two conventions, in some sense, opposite?
A:
Downcasting is the act of casting a
reference of a base class to one of
its derived classes.
http://en.wikipedia.org/wiki/Downcasting
No, you do not downcast, since double and int are not classes.
A: No, you are not down casting. You are just casting, and you're chopping off anything after the decimal.
Down casting doesn't apply here. The primitives int and double are not objects in C++ and are not related to each other in the way two objects in a class hierarchy are. They are separate and primitive entities.
Down casting refers to the act of casting one object into another object that derives from it. It refers to the act of moving down from the root of the class hierarchy. It has nothing to do with the sizes of types in question.
A: int and double are both primitives and not classes, so the concepts of classes don't apply to them.
Yes, it is a conversion from a "larger" to a "smaller" type (in terms of numerical size), but it's just a "cast" and not a "downcast"
A: The two aren't so much opposite as simply unrelated. In the example case, we're taking a value of one type, and the cast takes that and produces a similar value of a type that's vaguely similar, but completely unrelated.
In the case of traversing an inheritance tree with something like dynamic_cast, we're taking a pointer (or reference) to an object, and having previously decided to treat it as a pointer to some other type of object, we're basically (attempting to) treat it as (something closer to) the original type of object again. In particular, however, we're not creating a new or different value at all -- we're simply creating a different view of the same value (i.e., the same actual object).
A: You aren't casting -- you're converting. Different thing entirely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2724197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spark Feature Vector Transformation on Pre-Sorted Input I have some data in a tab-delimited file on HDFS that looks like this:
label | user_id | feature
------------------------------
pos | 111 | www.abc.com
pos | 111 | www.xyz.com
pos | 111 | Firefox
pos | 222 | www.example.com
pos | 222 | www.xyz.com
pos | 222 | IE
neg | 333 | www.jkl.com
neg | 333 | www.xyz.com
neg | 333 | Chrome
I need to transform it to create a feature vector for each user_id to train a org.apache.spark.ml.classification.NaiveBayes model.
My current approach is the essentially the following:
*
*Load the raw data into a DataFrame
*Index the features with StringIndexer
*Go down to the RDD and Group by user_id and map the feature indices into a sparse Vector.
The kicker is this... the data is already pre-sorted by user_id. What's the best way to take advantage of that? It pains me to think about how much needless work may be occurring.
In case a little code is helpful to understand my current approach, here is the essence of the map:
val featurization = (vals: (String,Iterable[Row])) => {
// create a Seq of all the feature indices
// Note: the indexing was done in a previous step not shown
val seq = vals._2.map(x => (x.getDouble(1).toInt,1.0D)).toSeq
// create the sparse vector
val featureVector = Vectors.sparse(maxIndex, seq)
// convert the string label into a Double
val label = if (vals._2.head.getString(2) == "pos") 1.0 else 0.0
(label, vals._1, featureVector)
}
d.rdd
.groupBy(_.getString(1))
.map(featurization)
.toDF("label","user_id","features")
A: Lets start with your other question
If my data on disk is guaranteed to be pre-sorted by the key which will be used for a group aggregation or reduce, is there any way for Spark to take advantage of that?
It depends. If operation you apply can benefit from map-side aggregation then you can gain quite a lot by having presorted data without any further intervention in your code. Data sharing the same key should located on the same partitions and can be aggregated locally before shuffle.
Unfortunately it won't help much in this particular scenario. Even if you enable map side aggregation (groupBy(Key) doesn't use is so you'll need custom implementation) or aggregate over feature vectors (you'll find some examples in my answer to How to define a custom aggregation function to sum a column of Vectors?) there is not much to gain. You can save some work here and there but you still have to transfer all indices between nodes.
If you want to gain more you'll have to do a little bit more work. I can see two basic ways you can leverage existing order:
*
*Use custom Hadoop input format to yield only complete records (label, id, all features) instead of reading data line by line. If your data has fixed number of lines per id you could even try to use NLineInputFormat and apply mapPartitions to aggregate records afterwards.
This is definitely more verbose solution but requires no additional shuffling in Spark.
*Read data as usual but use custom partitioner for groupBy. As far as I can tell using rangePartitioner should work just fine but to be sure you can try following procedure:
*
*use mapPartitionsWithIndex to find minimum / maximum id per partition.
*create partitioner which keeps minimum <= ids < maximum on the current (i-th) partition and pushes maximum to the partition i + 1
*use this partitioner for groupBy(Key)
It is probably more friendly solution but requires at least some shuffling. If expected number of records to move is low (<< #records-per-partition) you can even handle this without shuffle using mapPartitions and broadcast* although having partitioned can be more useful and cheaper to get in practice.
* You can use an approach similar to this: https://stackoverflow.com/a/33072089/1560062
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35020895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laravel base64_decode error on fresh install I'm trying to get started with laravel but it seems like hell to get it working.
First of all, here is the error (this happens when i try to access /myapp/public):
Some considerations:
*
*I'm using MAMP Pro with php 5.4.4
*Already installed MCrypt extension
*Already gave app/storage write permission
*Already optimized artisan by running php artisan optimize
Don't know where to go from here, can you help?
Thanks in advance.
EDIT:
I'm using OSX and php5 json is already enabled
A: The error message tells you that you gave an array, not a string.
Basically its saying $paylod = array('something'=>'somethingelse');
So it is expecting you provide it with $payload['something'] so that it knows what string to decode.
have you installed/enabled php5 JSON support?
When I set up laravel on a fresh ubuntu 13.10 server I had to run:
sudo apt-get install php5-json
among other needed modules (like mcrypt) for laravel 4 to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23749471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting an import error while trying to import sqlalchemy When I am trying to import sqlalchemy I am facing the below mentioned error. I have also upgraded the typing_extensions to 4.4.0 version but nothing seems to work for me.
Code:
import sqlalchemy
Error:
ImportError: cannot import name 'dataclass_transform' from 'typing_extensions' (/databricks/python/lib/python3.9/site-packages/typing_extensions.py)
I have also tried to directly import dataclass_transform from type_extensions but I am getting the below error.
code:
from typing_extensions import dataclass_transform
error:
ImportError: cannot import name 'dataclass_transform' from 'typing_extensions' (/databricks/python/lib/python3.9/site-packages/typing_extensions.py)
Complete Error Traceback:
1 import sqlalchemy /databricks/python_shell/dbruntime/PythonPackageImportsInstrumentation/__init__.py in import_patch(name, globals, locals, fromlist, level)
169 # Import the desired module. If you’re seeing this while debugging a failed import,
170 # look at preceding stack frames for relevant error information. --> 171 original_result = python_builtin_import(name, globals, locals, fromlist, level)
172
173 is_root_import = thread_local._nest_level == 1
/local_disk0/.ephemeral_nfs/envs/pythonEnv-ebb7b71d-c04d-448a-acf5-1341a7e23752/lib/python3.9/site-packages/sqlalchemy/__init__.py in <module>
10 from typing import Any
11
---> 12 from . import util as _util
13 from .engine import AdaptedConnection as AdaptedConnection
14 from .engine import BaseRow as BaseRow
/databricks/python_shell/dbruntime/PythonPackageImportsInstrumentation/__init__.py in import_patch(name, globals, locals, fromlist, level)
169 # Import the desired module. If you’re seeing this while debugging a failed import,
170 # look at preceding stack frames for relevant error information.
--> 171 original_result = python_builtin_import(name, globals, locals, fromlist, level)
172
173 is_root_import = thread_local._nest_level == 1
/local_disk0/.ephemeral_nfs/envs/pythonEnv-ebb7b71d-c04d-448a-acf5-1341a7e23752/lib/python3.9/site-packages/sqlalchemy/util/__init__.py in <module>
13
14 from . import preloaded as preloaded
---> 15 from ._collections import coerce_generator_arg as coerce_generator_arg
16 from ._collections import coerce_to_immutabledict as coerce_to_immutabledict
17 from ._collections import column_dict as column_dict
/databricks/python_shell/dbruntime/PythonPackageImportsInstrumentation/__init__.py in import_patch(name, globals, locals, fromlist, level)
169 # Import the desired module. If you’re seeing this while debugging a failed import,
170 # look at preceding stack frames for relevant error information.
--> 171 original_result = python_builtin_import(name, globals, locals, fromlist, level)
172
173 is_root_import = thread_local._nest_level == 1
/local_disk0/.ephemeral_nfs/envs/pythonEnv-ebb7b71d-c04d-448a-acf5-1341a7e23752/lib/python3.9/site-packages/sqlalchemy/util/_collections.py in <module>
37
38 from ._has_cy import HAS_CYEXTENSION
---> 39 from .typing import Literal
40 from .typing import Protocol
41
/databricks/python_shell/dbruntime/PythonPackageImportsInstrumentation/__init__.py in import_patch(name, globals, locals, fromlist, level)
169 # Import the desired module. If you’re seeing this while debugging a failed import,
170 # look at preceding stack frames for relevant error information.
--> 171 original_result = python_builtin_import(name, globals, locals, fromlist, level)
172
173 is_root_import = thread_local._nest_level == 1
/local_disk0/.ephemeral_nfs/envs/pythonEnv-ebb7b71d-c04d-448a-acf5-1341a7e23752/lib/python3.9/site-packages/sqlalchemy/util/typing.py in <module>
34 from typing_extensions import Annotated as Annotated # 3.8
35 from typing_extensions import Concatenate as Concatenate # 3.10
---> 36 from typing_extensions import (
37 dataclass_transform as dataclass_transform, # 3.11,
38 )
ImportError: cannot import name 'dataclass_transform' from 'typing_extensions' (/databricks/python/lib/python3.9/site-packages/typing_extensions.py)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75452661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I read a key and store the value of that key into a variable in ASM? I am working on making a C#-like language that compiles directly to x86 NASM code. I have written a function similar to Console.ReadKey(). It is supposed to wait for a key and then store the value of it in a string. Here is the code for the ASM function:
os_input_char:
pusha
mov di, ax ; DI is where we'll store input (buffer)
call os_wait_for_key ; Moves the next char into al
stosb ; Store character in designated buffer
mov al, 0 ; 0-terminate it
stosb ; ^^
popa
ret
I then call that function in my code. Here it is:
type [kernel]
:start
string key = "a";
graphicsmode;
nasm{
mov bl, 0001b ;blue
call os_clear_graphics ;clear
}nasm
movecursor(#0#, #0#);
print(" ");
print(" Welcome to LightningOS! ");
print(" ");
:main1
readkey -> key;
//I put the key code into the variable "key"
println("you pressed: "+%key%);
//Now print the variable key
goto(main1);
//now loop back to main
and it just keeps printing 'a'. Now I am sure that I am calling the function correctly. My compiler is made in C#, so its not that hard to follow. The 'append' instruction just adds on ASM code to the file. Method for calling:
else if (line.StartsWith("readkey -> ") && line.EndsWith(";"))
{
append("mov ax, " + line.Substring(11, line.Substring(11).Length - 1));
append("call os_input_char");
}
So... How do I actually get that key into the string and then print that string?
A: Some ideas :
You're using stosb but you don't setup ES. Are you sure it's already OK?
Does line.Substring use 0-based or 1-based indexing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27157805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Count number of points outside confidence interval (CI) in qqp (Quantile-Comparison Plot) plot I've like to find any function for calculated number of points outside confidence interval (CI 95%) in qqp (Quantile-Comparison Plot) plot.
In my example:
Packages
require(MASS)
require(car)
Simulated 60 Poisson values
Resp<-rpois(60,1)
Fitting Binomial negative dstribution
nbinom <- fitdistr(Resp, "Negative Binomial")
Plot using qqp
qqp(Resp, "nbinom", size = nbinom$estimate[[1]], mu = nbinom$estimate[[2]])
Now I would like to use any function for create a vector with the numbers of points outside confidence interval (CI) in qqp (Quantile-Comparison Plot) plot. This is possible? Thanks
A: qqp() doesn't count the number of points outside the confidence envelope but it computes the information that's needed to get this count. You can simply modify the code (car:::qqPlot.default) if you change:
outerpoints <- sum(ord.x > upper | ord.x < lower)
print(outerpoints)
if (length(outerpoints) > -1)
outerpoints
else invisible(NULL)
the output show the number of points outside the confidence envelope.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55072784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add newline inside table cell in Markdown in Bitbucket Wiki? How to add newline inside table cell in Markdown in Bitbucket Wiki?
<br> -- doesn't work
<br/> -- doesn't work
bullets -- doesn't work
A: If <br> or <br /> don't work, then you probably can't.
Unfortunately, Bitbucket's documentation regarding table support is rather sparse and consists solely of the following example:
| Day | Meal | Price |
| --------|---------|-------|
| Monday | pasta | $6 |
| Tuesday | chicken | $8 |
However, that syntax looks like the rather common table syntax first introduced by PHP Markdown Extra and later popularized by GitHub, MultiMarkdown, and others.
PHP Markdown Extra's rules state:
You can apply span-level formatting to the content of each cell using regular Markdown syntax:
| Function name | Description |
| ------------- | ------------------------------ |
| `help()` | Display the help window. |
| `destroy()` | **Destroy your computer!** |
GitHub's spec plainly states:
Block-level elements cannot be inserted in a table.
And MultiMarkdown's rules state:
Cell content must be on one line only
In fact, notice that the syntax does not offer any way to define when one row ends and another row begins (unlike the header row, which includes a line to divide it from the body of the table). As you cannot define the division between rows, then the only way it can work is if each line is its own row. For that reason, a row cannot contain multiple lines of text.
Therefore, any text within a table cell must be inline text only, which can be represented on a single line (therefore the Markdown standard of two spaces followed by a newline won't work; neither will bullets as they would be block level list elements). Of course, a raw HTML <br> tag is inline text and would qualify as a way to insert line breaks within table cells. However, some Markdown implementations disallow all raw HTML as a security measure. If you are using such an implementation (which Bitbucket appears to be using), then it is simply not possible to include a line break in a table cell.
I realize some find the above frustrating and limiting. However, it is interesting to note the following advice in MultiMarkdown's documentation regarding tables:
MultiMarkdown table support is designed to handle most tables for most people; it doesn’t cover all tables for all people. If you need complex tables you will need to create them by hand or with a tool specifically designed for your output format. At some point, however, you should consider whether a table is really the best approach if you find MultiMarkdown tables too limiting.
The interesting suggestion is to consider using something other than a table if you can't do what you want with the rather limited table syntax. However, if a table really is the right tool, then you may need to create it by hand. As a reminder, the original rules state:
Markdown is not a replacement for HTML, or even close to it. Its
syntax is very small, corresponding only to a very small subset of
HTML tags. The idea is not to create a syntax that makes it easier
to insert HTML tags. In my opinion, HTML tags are already easy to
insert. The idea for Markdown is to make it easy to read, write, and
edit prose. HTML is a publishing format; Markdown is a writing
format. Thus, Markdown's formatting syntax only addresses issues that
can be conveyed in plain text.
For any markup that is not covered by Markdown's syntax, you simply
use HTML itself. There's no need to preface it or delimit it to
indicate that you're switching from Markdown to HTML; you just use the
tags.
Therefore, creating a table by hand requires using raw HTML for the entire table. Of course, for those implementations which disallow all raw HTML you are without that option. Thus, you are back to considering either non-table solutions or a way to format a table without any line breaks within cells.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48746793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How do I use Crashlytics for my React Native Android App? I am trying to figure out how to use Crashlytics from Fabric for my React Native Android APP. I followed the steps on the Fabric homepage and added some lines in my build.gradle files. But the builds always crash.
Is there a difference using Crashlytics for React Native Android and Crashlytics for Native Android development using Android Studio and Java?
A: For the newer versions of React Native you have to import Bundle and place your own onCreate Method like this:
// Added Bundle to use onCreate which is needed for our Fabrics workaround
import android.os.Bundle;
..........
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fabrics
Fabric.with(this, new Crashlytics());
}
Not sure if this is good or not since they have removed the onCreate but it works for me
A: I got it working in some way, but it may not be the perfect solution...
1: Add fabric/crashlytics into your app/build.gradle - File
(I didn´t have the buildscript in my app/build.gradle so i just included it. But i am not sure if this is good....)
buildscript {
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
// The Fabric Gradle plugin uses an open ended version to react
// quickly to Android tooling updates
classpath 'io.fabric.tools:gradle:1.+'
}
}
// Add this directly under: apply plugin: "com.android.application"
apply plugin: 'io.fabric'
// and this directly under: apply from: "react.gradle"
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
// Last but not least add Crashlytics Kit into dependencies
compile('com.crashlytics.sdk.android:crashlytics:2.5.5@aar') {
transitive = true
}
2: The most important, because it is nowhere mentioned (or i didn´t find it anywhere), import Crashlytics and Fabric into MainActivity:
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
3: In your onCreate - method add:
// Fabrics
Fabric.with(this, new Crashlytics());
When you´ve done this, you will at least get Crashreports which are caused by native Code (Java Code). Crashes which are caused through JS - Syntax or similar wont be notified. There you will get the known RedBox :P
Good luck!
A: Try this : https://fabric.io/kits/android/crashlytics/install
Summarizes all the files you need to edit in your Android installation well.
For the AndroidManifest.xml file, replace the android:value key (e.g. below) with your actual API key. Remember to get your API key from your organization settings... 1. login to https://fabric.io/settings/organizations and 2. click on build secret.
<meta-data
android:name="io.fabric.ApiKey"
android:value="<api key here>"
/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33501522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: numpy insert & append I have an array:
X ndarray 180x360
The following does not work
X = numpy.append(X, X[:,0], 1)
because X[:,0] has the wrong dimensions.
Is not this weird?
This way around the problem seems a bit dirty:
X = numpy.append(X, numpy.array(X[:,0],ndmin=2).T, axis=1)
In MATLAB one could just write: X(:,361) = X(:,1) !!!
I came to realize that this works, too:
X = numpy.insert(X, 361, X[:,0], axis=1)
but why append does not work similarly?
Thank you serpents
A: The reason is that indexing with one integer removes that axis:
>>> X[:, 0].shape
(180,)
That's a one dimensional array, but if you index by giving a start and stop you keep the axis:
>>> X[:, 0:1].shape
(180, 1)
which could be correctly appended to your array:
>>> np.append(a, a[:, 0:1], 1)
array([....])
But all this aside if you find yourself appending and concatenating lots of arrays be warned: These are extremly inefficient. Most of the time it's better to find another way of doing this, for example creating a bigger array in the beginning and then just setting the rows/columns by slicing:
X = np.zeros((180, 361))
X[:, 360] = X[:, 0] # much more efficient than appending or inserting
A: You can create a new axis on X[:,0]:
np.append(X, X[:,0,None], axis=1)
I think the reason why you have to match array shapes is that numpy.append is implemented using concatenate.
A: A key difference is that in MATLAB everything has at least 2 dimensions.
>> size(x(:,1))
ans =
2 1
and as you note, it allows indexing 'beyond-the-end' - way beyond
>> x(:,10)=x(:,1)
x =
1 2 3 1 0 0 0 0 0 1
4 5 6 4 0 0 0 0 0 4
But in numpy indexing reduces the dimensions, without the 2d floor:
In [1675]: x = np.ones((3,4),int)
In [1676]: x.shape
Out[1676]: (3, 4)
In [1677]: x[:,0].shape
Out[1677]: (3,)
That means that if I want to replicate a column I need to make sure it is still a column in the concatenate. There are numerous ways of doing that.
x[:,0][:,None] - use of np.newaxis (alias None) is a nice general purpose method. x[:,[0]], x[:,0:1], x[:,0].reshape(-1,1) also have their place.
append is just concatenate that replaces the list of arguments with 2. It's a confusing imitation of the list append. It is written Python so you can read it (as experienced MATLAB coders do).
insert is a more complicated function (also in Python). Adding at the end it does something like:
In [1687]: x.shape
Out[1687]: (3, 4)
In [1688]: res=np.empty((3,5),int)
In [1689]: res[:,:4] = x
In [1690]: res[:,-1] = x[:,0]
That last assignment works because both sides have the same shape (technically they just have to be broadcastable shapes). So insert doesn't tell us anything about what should or should not work in more basic operations like concatenate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41381266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scrapy: How to send data to the pipeline from a custom filter without downloading To catch all redirection paths, including when the final url was already crawled, I wrote a custom duplicate filter:
import logging
from scrapy.dupefilters import RFPDupeFilter
from seoscraper.items import RedirectionItem
class CustomURLFilter(RFPDupeFilter):
def __init__(self, path=None, debug=False):
super(CustomURLFilter, self).__init__(path, debug)
def request_seen(self, request):
request_seen = super(CustomURLFilter, self).request_seen(request)
if request_seen is True:
item = RedirectionItem()
item['sources'] = [ u for u in request.meta.get('redirect_urls', u'') ]
item['destination'] = request.url
return request_seen
Now, how can I send the RedirectionItem directly to the pipeline?
Is there a way to instantiate the pipeline from the custom filter so that I can send data directly? Or shall I also create a custom scheduler and get the pipeline from there but how?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39222639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding default header for all requests in Unfiltered We have Unfiltered with underlying Jetty server (not sure but I believe Unfiltered uses Jetty 8). And now we would need to add header entry for all responses we return.
I can get underlying Jetty Server and tried adding Handler directly to it. Not sure if I did some silly mistake or does Unfiltered do something because I managed to add that header, but at same time I removed all other functionality. Not good :)
I also found way to do that in jetty.xml, but didn't get that working.
Now trying to get it working with Cycle.Intent but having some trouble with types when add two of them to Plan.
object AllowOrigin {
case class AllowOriginResponseFunctionWrapper[A](req: HttpRequest[A], f: ResponseFunction[Any]) extends ResponseFunction[Any] {
def apply[T](res: HttpResponse[T]) = req match {
case _ =>
val resp = f(res)
resp.header("Access-Control-Allow-Origin", "*")
resp
}
}
def apply[A](inner: Cycle.Intent[A,Any]): Cycle.Intent[A,Any] = {
case req @ _ => {
inner.orElse({ case _ => Pass }: Cycle.Intent[A,Any])(req) match {
case Pass => Pass
case responseFunction => AllowOriginResponseFunctionWrapper(req, responseFunction)
}
}
}
}
A: I figured out how to do it without breaking existing functionality. Unfortunately I have to add code to every Plan I have but it is quite small change any way.
First define intent.
object AllowAllOrigin extends unfiltered.kit.Prepend {
def intent = Cycle.Intent {
case _ ⇒ ResponseHeader("Access-Control-Allow-Origin", Set("*"))
}
}
Then add it to intent in plans, if got two things you want to do before Plan specific stuff just add more.
def intent = AllowAllOrigin { Authentication(config) {
case _ => Ok // or perhaps something more clever here :)
}}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28106755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: user input a list of numbers and use it in a Python function I am trying to run this function with the following user input structure but cannot get a correct answer:
def biggest_number(*args):
print (max(args))
return max(args)
a = (int(x) for x in input().split())
# 3,4,5
print (biggest_number(a))
So far I have tried different type of brackets "(" for tuples and "[" for lists as well as tried converting the strings to integers.
A: You can unpack the generator expression using the splat operator:
print (biggest_number(*a))
Although I think you actually want to use a container such as tuple or list since you can only consume the gen. exp. once so that the next call to max after the print gives you an error:
a = [int(x) for x in input().split()]
Or:
a = tuple(int(x) for x in input().split())
However, you still need to unpack since your function does not take the iterables directly.
A: you can try with raw_input() instead of input().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45868818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing listview items from another form Let's consider I have two forms: Form1 and Form2.
On Form1 I have a listview DataVisualizationList.
If I want to work with selected items of the listview from Form1, foreach (ListViewItem dr in DataVisualizationList.SelectedItems) works perfectly.
How to do the same from Form2 ?
A: You can do it by exposing the ListView public, but don't do that. Instead expose a property in Form for selected items.
class Form1 : Form
{
public ListView.SelectedListViewItemCollection ListViewSelectedItems
{
get { return yourListView.SelectedItems; }
}
}
class Form2 : Form
{
public void SomeMethod()
{
Form1 myForm1Instance = ...;//Get instance somehow
var items = myForm1Instance.ListViewSelectedItems;//Use it
foreach (var item in items)
{
//Do whatever
}
}
}
A: You would have to either have a reference to Form1 in Form2 and have the DataVisualizationList be publicly accessable, or have a reference to DataVisualizationList in Form2.
You could to this with member references.
You would have to set the reference of Form1 in Form2.
Something like this inside Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.f1 = this;
f2.Show();
}
And then inside Form2
public partial class Form2 : Form
{
public Form1 f1;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (f1 != null)
{
foreach (ListViewItem dr in f1.DataVisualizationList.SelectedItems)
{
}
}
}
}
A: Simplest Solution
on Form1
list<your_Type> li = ListView1.items.ToList()
Form2 frm = new Form2(li);
Frm.Show();
on Form2
list<your_Type> li2;
Form2(List<your_Type> li)
{
InitializeComponent();
li2 = li;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21038225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS Speech Recognition crash on installTapOnBus - [AVAudioIONodeImpl.mm:911:SetOutputFormat: (format.sampleRate == hwFormat.sampleRate)] Most times I launch the app, the test-to-speech audio and speech recognition work perfectly. But sometimes I launch it and it crashes when first starting speech recognition. It seems to get on a roll and crash several launches in a row, so it is a little bit consistent, once it gets into one of its 'moods' :)
The recognition starts after a TTS introduction and at the same time as TTS says 'listening' - therefore both are active at once. Possibly the audio takes a few milliseconds to change over and gets crashy, but I am not clear how this works or how to prevent it.
I see the following error:
[avae] AVAEInternal.h:70:_AVAE_Check: required condition is false:
[AVAudioIONodeImpl.mm:911:SetOutputFormat: (format.sampleRate == hwFormat.sampleRate)]
*** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio',
reason: 'required condition is false: format.sampleRate == hwFormat.sampleRate'
I have put some try-catches in, just to see if it prevents this error and it doesn't. I also added a tiny sleep which also made no difference. So I am not even clear which code is causing it. If I put a breakpoint before the removeTapOnBus code, it does not crash until this line executes. If I put the breakpoint on the installTapOnBus line it does not crash until that line. And if I put the breakpoint after the code, it crashes. So it does seem to be this code.
In any case, what am I doing wrong or how could I debug it?
- (void) recordAndRecognizeWithLang:(NSString *) lang
{
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:lang];
self.sfSpeechRecognizer = [[SFSpeechRecognizer alloc] initWithLocale:locale];
if (!self.sfSpeechRecognizer) {
[self sendErrorWithMessage:@"The language is not supported" andCode:7];
} else {
// Cancel the previous task if it's running.
if ( self.recognitionTask ) {
[self.recognitionTask cancel];
self.recognitionTask = nil;
}
//[self initAudioSession];
self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc] init];
self.recognitionRequest.shouldReportPartialResults = [[self.command argumentAtIndex:1] boolValue];
// https://developer.apple.com/documentation/speech/sfspeechrecognizerdelegate
// only callback is availabilityDidChange
self.sfSpeechRecognizer.delegate = self;
self.recognitionTask = [self.sfSpeechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult *result, NSError *error) {
NSLog(@"recognise");
if (error) {
NSLog(@"error %ld", error.code);
// code 1 or 203 or 216 = we called abort via self.recognitionTask cancel
// 1101 is thrown when in simulator
// 1700 is when not given permission
if (error.code==203){ //|| error.code==216
// nothing, carry on, this is bullshit, or maybe not...
[self sendErrorWithMessage:@"sfSpeechRecognizer Error" andCode:error.code];
}else{
[self stopAndRelease];
// note: we can't send error back to js as I found it crashes (when recognising, then switch apps, then come back)
[self sendErrorWithMessage:@"sfSpeechRecognizer Error" andCode:error.code];
return;
}
}
if (result) {
NSMutableArray * alternatives = [[NSMutableArray alloc] init];
int maxAlternatives = [[self.command argumentAtIndex:2] intValue];
for ( SFTranscription *transcription in result.transcriptions ) {
if (alternatives.count < maxAlternatives) {
float confMed = 0;
for ( SFTranscriptionSegment *transcriptionSegment in transcription.segments ) {
//NSLog(@"transcriptionSegment.confidence %f", transcriptionSegment.confidence);
if (transcriptionSegment.confidence){
confMed +=transcriptionSegment.confidence;
}
}
NSLog(@"transcriptionSegment.transcript %@", transcription.formattedString);
NSMutableDictionary * resultDict = [[NSMutableDictionary alloc]init];
[resultDict setValue:transcription.formattedString forKey:@"transcript"];
[resultDict setValue:[NSNumber numberWithBool:result.isFinal] forKey:@"final"];
float conf = 0;
if (confMed && transcription.segments && transcription.segments.count && transcription.segments.count>0){
conf = confMed/transcription.segments.count;
}
[resultDict setValue:[NSNumber numberWithFloat:conf]forKey:@"confidence"];
[alternatives addObject:resultDict];
}
}
[self sendResults:@[alternatives]];
if ( result.isFinal ) {
//NSLog(@"recog: isFinal");
[self stopAndRelease];
}
}
}];
//[self.audioEngine.inputNode disconnectNodeInput:0];
AVAudioFormat *recordingFormat = [self.audioEngine.inputNode outputFormatForBus:0];
//AVAudioFormat *recordingFormat = [[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:1];
NSLog(@"samplerate=%f", recordingFormat.sampleRate);
NSLog(@"channelCount=%i", recordingFormat.channelCount);
// tried this but does not prevent crashing
//if (recordingFormat.sampleRate <= 0) {
// [self.audioEngine.inputNode reset];
// recordingFormat = [[self.audioEngine inputNode] outputFormatForBus:0];
//}
sleep(1); // to prevent random crashes
@try {
[self.audioEngine.inputNode removeTapOnBus:0];
} @catch (NSException *exception) {
NSLog(@"removeTapOnBus exception");
}
sleep(1); // to prevent random crashes
@try {
NSLog(@"install tap on bus");
[self.audioEngine.inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
//NSLog(@"tap");
[self.recognitionRequest appendAudioPCMBuffer:buffer];
}];
} @catch (NSException *exception) {
NSLog(@"installTapOnBus exception");
}
sleep(1); // to prevent random crashes
[self.audioEngine prepare];
NSError* error = nil;
BOOL isOK = [self.audioEngine startAndReturnError:&error];
if (!isOK){
NSLog(@"audioEngine startAndReturnError returned false");
}
if (error){
NSLog(@"audioEngine startAndReturnError error");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60101205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Move object forward in facing direction basically I am trying to make my character dash forward a specific distance in the direction the camera is facing. This a fps and the best I have been able to do so face is dash forward in the global X axes, which obviously is wrong.
I have this function which is called from the update function:
Debug.Log("We are dashing.");
if (!inputDash || !canControl)
dashing.lastButtonDownTime = -100;
if (inputDash && dashing.lastButtonDownTime < 0 && canControl)
dashing.lastButtonDownTime = Time.time;
if (dashing.enabled && canControl && (Time.time - dashing.lastButtonDownTime < 0.2))
{
dashing.dashing = true;
dashing.lastButtonDownTime = -100;
dashing.dashCounter ++;
dashing.dashDir = Camera.mainCamera.transform.position;
//velocity = Vector3.MoveTowards(dashing.dashDir, (dashing.dashDir + Vector3(dashing.dashDir.x + 2, 0, 0)), (2 * Time.deltaTime));
Debug.Log("We just dashed.");
}
return velocity;
I have tried a number of different things for the dashing.dashDir, but none have worked. I know I am bascially looking to dash in the local axes of the camera?
I have also tried this:
dashing.dashDir = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
velocity += dashing.dashDir * dashing.baseDistance;
Any help would be greatly appreciated as this is driving me insane.
Final point. I am looking to dash the player very quickly forward in the facing direction approximately 3m and then carry to velocity when the dash finishes. Sorry if that's unclear.
A: Here is my answer and it works perfectly: Moves forward, Rotates and Collides with Other objects (Having RigidBody and Box/Capsule Collider). tThis is based from Burkhard's answer.
But befor all do this : Create an empty Object set it a child of your Player and drag your camera Object into your empty Object.
NB : You can place the camera behind your player to get a best view.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeControl : MonoBehaviour {
public float speed = 10.0f;
Rigidbody rb;
GameObject playerEmpty;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
float Haxis = Input.GetAxis ("Horizontal");
float Vaxis = Input.GetAxis ("Vertical");
//Go Forward
if(Input.GetKeyDown(KeyCode.UpArrow))
{
//Works perfectly but does no longer collide
//rb.transform.position += transform.forward * Time.deltaTime * 10.0f;
//Not moving in the right direction
//rb.velocity += Vector3.forward * 5.0f;
rb.velocity += Camera.main.transform.forward * speed;
//rb.rotation() += new Vector3 (0.0f, headingAngle, 0.0f) * 5.0f;
//rb.velocity += gameObject.transform.localEulerAngles * Time.deltaTime * 10.0f ;
}
if(Input.GetKeyDown(KeyCode.DownArrow))
{
rb.velocity -= Camera.main.transform.forward * speed;
}
Vector3 rotationAmount = Vector3.Lerp(Vector3.zero, new Vector3(0f, 10.0f * (Haxis < 0f ? -1f : 1f), 0f), Mathf.Abs(Haxis));
Quaternion deltaRotation = Quaternion.Euler(rotationAmount * Time.deltaTime);
this.transform.rotation = (this.transform.rotation * deltaRotation);
}
}
A: To move an object in a along a local axis you need to use that object transform like this
dir = Camera.mainCamera.transform.forward;
If you also want to add to your current speed you need to use it like this
newVelocity = Camera.mainCamera.transform.forward * (baseSpeed + currectVelocity.magnitude);
This will set the direction to your cameras forward and add baseSpeed to your current speed.
If you want to set the distance instead of the speed you can calculate it like this
speed = distance / time;
That is the distance you want to travel and how long the dash lasts. If you do this i wouldn't add it to the current speed since that would change the distance traveled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25854551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I save information to a model on Devise.sessions#destroy? I'm using Devise and Piggybak for a Rails project and Piggybak uses a cookie named cart to store the user cart. The problem is that Piggybak doesn't destroy the cookie on user sign_out so, if I sign_in with another user, it uses the same cookie and therefore, the same cart.
I want to solve that storing that cookie value into my user model, enabling it to get back his cart on another sign_in. What I did was overriding the Devise.sessions#destroy method to save the cookie value on user and destroy the cookie:
# app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
def destroy
current_user.add_cart_cookie(cookies['cart']['value'])
cookies['cart'] = { value: '', path: '/' }
super
end
end
Routing it right in the routes:
# config/routes.rb
...
devise_for :users, controllers: { sessions: 'users/sessions' }
...
And creating the method add_cart_cookie to my user model:
# app/models/user.rb
class User < ActiveRecord::Base
...
def add_cart_cookie(value)
self.cart_cookie = value
end
...
end
But this is not working, it destroy the cookie but don't save it on the user model. Why is this happening?
A: Did it, thank you @Marian.
What I did was change my add_cookie_cart method to accept another parameter:
# app/models/user.rb
class User < ActiveRecord::Base
...
def add_cart_cookie(value, password)
self.cart_cookie = value
self.password = password
self.password_confirmation = password
self.save
end
...
end
And changed my session#destroy accordingly:
class Users::SessionsController < Devise::SessionsController
def destroy
current_user.add_cart_cookie(cookies['cart']['value'], current_user.password)
cookies['cart'] = { value: '', path: '/' }
super
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16215646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DJI SDK UI: Customizing contentViewController in DULDefaultViewController I am using DJI SDK iOS 4.2.2 with DJI UILibrary 4.2 (with Swift)
I want to replace the default FPV view in DULDefaultView/DULDefaultViewController with a custom map view, which the API reference suggests is possible. I have not been able to find any examples of how to do this in the documentation, or in the iOS sample code. How can I accomplish this?
I have tried overriding the property contentViewController in my View Controller inherited from DULDefaultViewController to no avail (it still loads with the FPV view).
It seems to me the API designers have intended for a simple method to do this, but I just can't see it.
A: As of 4.2.2 it's not something that can be done.
EDIT: This was added in 4.3:
// Toggle for the content view for our button. This will swap between our red view controller and the fpv view controller.
@IBAction func switchContent(_ sender: UIButton) {
if (isContentViewSwitched) {
isContentViewSwitched = false
self.contentViewController = self.oldContentViewController
} else {
isContentViewSwitched = true
let newContentViewController = UIViewController()
newContentViewController.view.backgroundColor = UIColor.red
self.oldContentViewController = self.contentViewController as? DULFPVViewController
self.contentViewController = newContentViewController
}
}
For the full version, see this sample code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45072664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I edit .json data with python? So I'm making a Discord bot and I need to edit some data in my .json file
Here's the json file:
"name"'s variable is player
I want to edit the balance, there's gonna be a command to add and subtract, so how do I do that?
I tried writing and deleting it, but either I did it wrong or it doesn't work
A: Python as a built-in module called json, that provides a json.JSONDecoder and a json.JSONEncoder class, a JSON (JavaScript Object Notation) parser (json.loads) and few other functions.
If you have your data.json file, you can convert it to Python...
import json
with open("data.json", 'r+') as file:
my_data = json.load(file)
...edit it...
my_data["Key"] = "New Value"
...and encode it back
json.dump(my_data, file)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71638997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TCP as connection protocol questions I'm not sure if this is the correct place to ask, so forgive me if it isn't.
I'm writing computer monitoring software that needs to connect to a server. The server may send out relatively urgent messages, such as sound or cancel an alarm, and the client may send out data about the computer, such as screenshots. The data that the client sends isn't too critical on timing, but shouldn't be more than a two minutes late.
It is essential to the software that portforwarding need not be set up, and it is assumed that the internet connection will be done through a wireless router that has NAT almost all the time.
My idea is to have a TCP connection initiated from the client, and use that to transfer data. Ideally, I would have no data being sent when it is not needed, but I believe this to be impossible. Would sending the equivalent of a ping every now and again keep the connection alive, and what sort of bandwidth would it use if this program was running all the time on the computer? In addition, would it be possible to reduce the header size for these keep-alives?
Before I start designing the communication and programming, is this plan for connection flawed? Are there better alternatives?
Thanks!
A: 1) You do not need to send 'ping' data to keep the connection alive, the TCP stack does this automatically; one reason for sending 'ping' data would be to detect a connection close on the client side - typically you only find out something has gone wrong when you try and read/write from the socket. There may be a way to change various time-outs so you can detect this condition faster.
2) In general while TCP provides a stream-oriented error free channel, it makes no guarantees about timeliness, if you are using it on the internet it is even more unpredictable.
3) For applications such as this (I hope you are making it for ethical purposes) - I would tend to use TCP, since you don't want a situation where the client receives a packet to raise an alarm but misses that one that turns it off again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21148538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android button shadow/margin top I have a Button and an ImageView in one line. But Button has margin to top. And I use a simple background drawable.
Part of XML Code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="4"
android:background="@color/main_green"
android:text="@string/from"
android:gravity="center"
android:textSize="22dp"
android:textColor="@color/text_color_white"/>
<Button
android:id="@+id/fromCityButton"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:hint="From"
android:background="@drawable/button_blank_border"/>
</LinearLayout>
Button background drawable code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/main_background"/>
<stroke android:width="1px" android:color="#000000" />
</shape>
</item>
</selector>
Now this part looks like this:
But it should look like this:
How should I fix that shadow/margin of the button?
A: This should work
<TextView
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#008080"
android:layout_weight="4"
android:gravity="center"
android:layout_gravity="center" <--------
android:text="IS"
android:textColor="#FFFFFF"
android:textSize="22dp" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30531852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compare and Multiply I want to compare two cells and obtain a percentage, for instance:
A1 is 190
B1 is 200
C1 is the answer
I tried:
B1 >= A1
but the answer is TRUE.
I will create a report if cell B1 s greater than cell A1 then:
IF YES I need to get the 12% percent of cell B1 and the answer would appear on cell C1
IF NOT the value for cell C1 would be 0.00.
Can anyone help me to create a syntax for that?
A: Try =IF(B1>=A1,B1*0.12,0)
check snap below
And for formatting you can select column, right click - Format Cells - select Number and keep 2 Decimal places.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32088917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UDP Broadcast stress I am writing an application that relies on UDP Broadcasting.
Does anyone know what kind of stress this puts on your network? I would like to have multiple clients on the same network broadcasting frequently.
Any information on this would be helpful
Thanks
A: It all depends. It depends on the speed, type & quality of network (e.g. is it micro-segmented or shared, how good are your switches), it depends on the size & frequency of the packets, the number of broadcasting clients, etc. If you're running a routed network i.e. multiple subnets, how (if at all) are you intending to handle broadcasts to the non-native subnets? How will the routers handle this? It depends on the capability of your end devices too, they'll need to process every UDP broadcast frame - at high rates this can slow down low-end machines quite considerably. Don't let this put you off though, if you've ever done a network trace then, unless you're on a microsegmented LAN, you'll probably see quite a bit of background broadcast traffic anyway and it all ticks along happily.
It might be worth reading up on multicast groups and seeing if that might be an option for your application as there are ways, with various types of network equipment, that you can configure your network to handle multicast more efficiently that straight UDP broadcasts.
A: I imagine it would depend on:
*
*your network configuration (do you use switches? Hubs?)
*the amount of data you're sending
*The frequency you're sending the data
*The capacity of your network.
I'd suggest writing a simple test program which attempts to send different amounts of data and the running something like netlimiter to see how much bandwidth you're using. With that information in hand you can judge how close to the limit of your network you're getting and get a firm answer to your question..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2983710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Linux Container on Android without Root Is it possible to start a linux container on a android device without rooting the device?
If so, what would be the best way to go about that? Any hints would be very much appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20629817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get current directory with subprocess? How can i get the current directory to which I am in? like the use of
os.getcwd()
A: First, I presume you're not asking about a particular subprocess that exists simply to tell you the current working directory and do nothing else (Apducer's answer). If that were the case you could simply as os.getcwd() and forget the subprocess. You clearly already know that. So you must be dealing with some other (arbitrary?) subprocess.
Second, I presume you understand, via dr1fter's answer, that you have control over the working directory in which the subprocess starts. I suspect that's not enough for you.
Rather, I suspect you're thinking that the subprocess might, according to its own internal logic, have changed its working directory sometime since its launch, that you can't predict where it has ended up, and you want to be able to send some sort of signal to the subprocess at an arbitrary time, to interrogate it about where it's currently working. In general, this is only possible if the process has been specifically programmed with the logic that receives such a signal (through whatever route) and issues such a response. I think that's what SuperStew meant by the comment, "isn't that going to depend on the subprocess?"
I say "in general" because there are platform-specific approaches. For example, see:
*
*windows batch command to determine working directory of a process
*How do I print the current working directory of another user in linux?
A: by default, subprocesses you spawn inherit your PWD. you can however, specify the cwd argument to the subprocess.Popen c'tor to set a different initial PWD.
A: Unix (Linux, MacOS):
import subprocess
arguments = ['pwd']
directory = subprocess.check_output(arguments)
Windows:
import subprocess
arguments = ['cd']
directory = subprocess.check_output(arguments)
If you want to run in both types of OS, you'll have to check the machine OS:
import os
import subprocess
if os.name == 'nt': # Windows
arguments = ['cd']
else: # other (unix)
arguments = ['pwd']
directory = subprocess.check_output(arguments)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58615929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Porting a Netbeans JavaFx project to Eclipse I'm working on a JavaFx project on NetBeans 7.3 my question is : Is it possible to port a Netbeans JavaFx project to eclipse (juno preferably) successfully, what are the issues I may face, and if it is possible what is the best way to do it
A: Have a look at the plugins provided by e(fx)clipse: http://www.efxclipse.org/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16526488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Generate an independent and identically distributed (i.i.d.) random gaussian matrix What is the best/accurate way to create an i.i.d. random Gaussian matrix using Python?
What is pseudo-random? And would that suffice?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35675378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding images to eclipse java project using ImageIcon(getClass().getResource() Can anyone help why am I getting error for my Java swing application that makes use of
ImageIcon(getClass().getResource()
to load images as shown below. Thanks in advance.
Code where error is shown:
jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/folder63.png")));
Error description:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at frame.foundation.initComponents(foundation.java:282)
at frame.foundation.<init>(foundation.java:21)
at frame.foundation$127.run(foundation.java:3453)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
PS: I have also added "images" folder as the source folder in my project
Folder Structure:
myprojectName
|
|___src
| |
| |___frame //(is my package)
| |
| |__foundation.java // main class
|
|__images
| |
| |__folder63.png
| |__d.jpg
| |__e.jpg
| |__f.jpg
A: Make sure image file is present at correct location. It should be under src/images folder.
You can try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("folder63.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images/folder63.jpg"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/folder63.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/folder63.png"))
Read more...
It's worth reading Java Tutorial on Loading Images Using getResource
A: Try this
InputStream input = classLoader.getResourceAsStream("image.jpg");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24970603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sharekit - Facebook configuration I am trying to integrate sharekit in an ios app. Everything works properly but I have problem with Facebook. What I'have done so far :
*
*created an app on Facebook (no extra configuration on Facebook, like native etc..)
*edited SHKConfig.h and added
#define SHKFacebookAppID @"MyFacebookAppID"
*in my app.plist added the url scheme : fb+appID
Now When I try to share something on Facebook, the Facebook app on the device is opened, showing the message : You are logging into this app as "facebookUsername", when I click ok
I'm redirected to my app but nothing happen, no sharing action.
I am missing something??
A: The solution to my problem is illustrated here sharekit installation guide step 6
A: Things You have to do for Integrate Sharekit With your Application..(Recommended)
1) Actually You dont need to set URL scheme in .plist file for Sharekit. It's only for facebook API users..
2) Check out,Did you fill api key and secret key in SHKConfig.h file like this below
#define SHKFacebookKey @"YOUR_API_KEY"
#define SHKFacebookSecret @"YOUR_APP_SECRET_KEY"
3) Verify Did you "import SHK.h" file..
4) You have to include "MessageUI,SystemConfiguration and Security frameworks".
5) You dont need to do this #define SHKFacebookAppID @"MyFacebookAppID"
6) Invoke sharekit actionsheet as given in documentation.
A: The SHKConfig.h file seems to indicate that you don't include a literal "+" in your URL scheme. Check the last line of this quote:
// Facebook - https://developers.facebook.com/
// SHKFacebookAppID is the Application ID provided by Facebook
// SHKFacebookLocalAppID is used if you need to differentiate between several iOS apps running against a single Facebook app. Leave it blank unless you are sure of what you are doing.
// The CFBundleURLSchemes in your App-Info.plist should be "fb" + the concatenation of these two IDs.
// Example:
// SHKFacebookAppID = 555
// SHKFacebookLocalAppID = funk
//
// Your CFBundleURLSchemes entry: fb555funk
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9093451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: SSAS adding members to server administrator role using PowerShell I am trying to add a member to server administrator role using PowerShell. I am able to add a role and member to each individual database available, but I would like to add it to the top level so that the given user can access the database.
This is what my current code, but I get the error:
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
At D:\Untitled8.ps1:15 char:1
+ $targetsvr.Roles.Members.Add($syncAccount)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
Function Add-NewMember
{
[CmdletBinding()]
param(
[Parameter(Position=0,mandatory=$true)]
[string] $ssasInstance,
[Parameter(Position=1,mandatory=$true)]
[string] $syncAccount ="NT Service\SQLSERVERAGENT")
[void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices")
$targetsvr = new-Object Microsoft.AnalysisServices.Server
$targetsvr.Connect($ssasInstance)
$targetsvr.Roles.Members.Add($syncAccount)
}
Add-NewMember -ssasInstance "localhost" -syncAccount "NT SERVICE\SQLSERVERAGENT"
A: $targetsvr.Roles.Members is a legal expression that results in a collection of all members of all roles (it's equivalent to $targetsvr.Roles | Foreach { $_.Members }). But this collection is synthesized by PowerShell, not an actual member of something, so you can't modify it. You want $targetsvr.Roles["Administrators"].Members instead. And you explicitly need to update the role before the server will see the changes. And you want to give the cmdlet a better name as well. If I may:
Function Add-ASAdministrator {
param(
[Parameter(Mandatory=$True, ValueFromPipeline)]
[string] $User,
[string] $Instance = "."
)
$server = New-Object Microsoft.AnalysisServices.Server
$server.Connect($Instance)
$administrators = $server.Roles["Administrators"]
if ($administrators.Members.Name -notcontains $User) {
$administrators.Members.Add($User) | Out-Null
$administrators.Update()
}
$server.Disconnect()
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43538887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SonataUserBundle with multiple doctrine database: Validators uses default doctrine manager, not the one for the User class I've setup my Symfony project with multiple databases, in the hope to one day implement a modular monolith infrastructure.
My User class is stored in a specific database which is not doctrine default.
I've set this mapping in doctrine_mongodb.yaml:
document_managers:
authentication:
connection: authentication
database: '%env(resolve:AUTHENTICATION_MONGODB_DB)%'
mappings:
Cobredia\Authentication:
is_bundle: false
type: attribute
dir: '%kernel.project_dir%/src/Authentication/Document'
prefix: 'Organization\Authentication\Document'
alias: 'Organization\Authentication'
SonataUserBundle: ~
The mapping is functional, this command works:
symfony console sonata:user:create --super-admin admin [email protected] password
I can use the created user to login in the Sonata Admin interface. The web UI is able to list users, but when trying to add a user using the web UI, the follow error is thrown:
request.CRITICAL: Uncaught PHP Exception Symfony\Component\Validator\Exception\ConstraintDefinitionException:
"Unable to find the object manager associated with an entity of class "Organization\Authentication\Document\User"."
at vendor/symfony/doctrine-bridge/Validator/Constraints/UniqueEntityValidator.php line 81 {"exception":"[object] (Symfony\\Component\\Validator\\Exception\\ConstraintDefinitionException(code: 0): Unable to find the object manager associated with an entity of class \"Organization\\Authentication\\Document\\User\". at vendor/symfony/doctrine-bridge/Validator/Constraints/UniqueEntityValidator.php:81)"} []
The issue is due to Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity defined in vendor/sonata-project/user-bundle/src/Resources/config/validation.xml.
By default, it use service doctrine.orm.validator.unique. For MongoDB, it should be doctrine_odm.mongodb.unique.
How can I fix this cleanly ?
Thank you.
I've tried to add specific Unique constraints to my user class to try to override existing constraints:
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Sonata\UserBundle\Document\BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
#[ODM\Document()]
#[UniqueEntity(fields: "username", ignoreNull: false, em: 'authentication', service: 'doctrine_odm.mongodb.unique')]
#[UniqueEntity(fields: "email", ignoreNull: false, em: 'authentication', service: 'doctrine_odm.mongodb.unique')]
class User extends BaseUser
{
The added constraints seems to work, but the issue remains.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74209900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Objective-c shouldRecognizeSimultaneouslyWithGestureRecognizer disable otherGestureRecognizer I have viewdeck controller and I can open left side-bar menu by swiping to the right.
For my center view controller, I also have uitableview.
Problem is that I can swipe to right to open menu and I also can scroll my tableview at the same time. I need to allow only one gesture at one time.
So, I check here
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;
I found out like this. I need to disable UIPanGestureRecognizer or UIScrollViewPanGestureRecognizer to allow only 1 gesture at one time. May I know how to do?
//(lldb) po gestureRecognizer
//<UIPanGestureRecognizer: 0x79eef4d0; state = Possible; view = <UIView 0x79ee36e0>; target= <(action=panned:, target=<IIViewDeckController 0x79edb1d0>)>>
//(lldb) po otherGestureRecognizer
//<UIScrollViewPanGestureRecognizer: 0x79ff32f0; state = Began; delaysTouchesEnded = NO; view = <UITableView 0x7c301e00>; target= <(action=handlePan:, target=<UITableView 0x7c301e00>)>>
A: You could try setting the enabled property on the other gesture recogniser to NO. I don't have my dev environment up at the moment but I recall having done something similar before. Like so:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizershouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
otherGestureRecognizer.enabled = NO;
return YES;
}
A: You can also try this, and it solved my problem.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
if ([otherGestureRecognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) { // replace `UIScreenEdgePanGestureRecognizer` with any class you don't need.
return NO;
}
return YES;
}
Good luck. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26793003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to enable remote debugging with headless chrome when using ruby and selenium? When I set the option "--remote-debugging-port", it will throw an error. And without this option, it can work properly. However, I want to debug when using the headless chrome. How can I do ?
.rvm/rubies/ruby-2.2.5/lib/ruby/2.2.0/net/protocol.rb:158:in `rescue in rbuf_fill': Net::ReadTimeout (Net::ReadTimeout)
Here is my code:
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--remote-debugging-port') # debug
@driver = Selenium::WebDriver.for(:chrome, options: options)
puts @driver.manage.logs.get :browser
A: As per Getting Started with Headless Chrome to enable remote-debugging you can add the argument remote-debugging-port through Selenium::WebDriver::Chrome::Options.new which will help in:
Navigating to http://localhost:9222 in another browser to open the DevTools interface or use a tool such as Selenium to drive the headless browser.
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--remote-debugging-port=9222')
@driver = Selenium::WebDriver.for(:chrome, options: options)
puts @driver.manage.logs.get :browser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51440216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Change number format and get it as a number I am using MUI and Formik to create form.
I need to change numbers format in the all inputs:
1000.00 -> 1.000,00
A created function formatNumber(num) to do this, it works. But problem is that it returns string, and my API wait number (I can do nothing with that). I tried to use react-number-format but it also returns string.
So I also made function parseNumber(str) to parse the formatted number from string to number back. Now I need to use this function before the form submit, and I don’t know how to do this properly.
The aim is that the user should always see formatted data in the inputs. But after the form submit this data should be sent to the server as a number.
Here is my code:
//"12345678.09" to "12.345.678,09"
export const formatNumber = (num: number | null): string => {
const formatNum = num
? new Intl.NumberFormat()
.format(num)
.replaceAll(",", "_")
.replaceAll(".", ",")
.replaceAll("_", ".")
: "";
return formatNum;
};
// "12.345.678,09" back to "12345678.09"
export const parseNumber = (str: string | null): number | null => {
if (str !== null) {
str = str.trim();
let result = str.replace(/[^0-9]/g, "");
if (/[,.]\d{2}$/.test(str)) {
result = result.replace(/(\d{2})$/, ".$1");
}
return parseFloat(result);
} else {
return null;
}
};
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
>
<Form noValidate onSubmit={handleSubmit}>
<TextField
name=“some_value”
type="string"
value={formatNumber(values.some_value)}// here I format data that I get from server, the user should change it in the field and send back to server
/>
</Form>
<Formik>
A: You can transform values in handleSubmit function before passing it to api.
const handleSubmit = (values) => {
values.some_value = parseNumber(values.some_value);
fetch(apiUrl, { body: values })
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72257821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implicit conversion from std::string to class doesn't work I get an error C2664 in Visual Studio 2010 saying that there is no conversion from std::string to my class Filename.
I don't really understand why this is happening, because I have constructors for accepting an std::string and this works for code like this:
std::string s = "t";
Filename f1 = s;
Filename f2(s);
However I have a function
FileType FileFactory::detectFileType(Filename &oFilename) const;
and in my code when I try to do
Filename fn = "d:\\tmp\\test.txt";
// getBaseDir() returns an std::string
FactoryFileType type = detectFileType(fn.getBaseDir());
it gets this error:
error C2664: 'FileFactory::detectFileType': conversion of parameter 1 from 'std::string' to 'Filename &' is not possible
My Filename class looks like this:
class Filename
{
public:
Filename(std::string const &oFilename, std::string const &oBasePath = "");
Filename(char const *oFilename = NULL, char const *oBasePath = NULL);
Filename(const Filename &oSource);
virtual ~Filename(void);
void setBasePath(std::string const &oBasePath);
void setBasePath(const char *oBasePath);
const std::string &getBasePath(void) const;
std::string getBaseDir(void) const;
std::string getFileDir(void) const;
};
A: Problem is, that you function receives reference to FileName, but you are trying to pass rvalue to it. It's incorrect, temporary value cannot be binded to lvalue-reference, change parameter to const reference, or create FileName object and pass it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32399500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Client application is not registered as a resource server I set up KeyCloak on my Quarkus application. Realm is 'quarkus', as is the client. I successfully get token from KeyCloak, but when I'm about to use it in whatever method on my service, I get this:
Caused by: org.keycloak.authorization.client.util.HttpResponseException: Unexpected response from server: 403 / Forbidden / Response from server: {"error":"invalid_clientId","error_description":"Client application [quarkus] is not registered as a resource server."}
application.properties is set like this:
quarkus.oidc.auth-server-url=http://localhost:8080/realms/quarkus
quarkus.oidc.client-id=quarkus
quarkus.oidc.credentials.secret=dFvRiItg9NjUA56h4nk4xPG4IqKFNPkG
quarkus.oidc.tls.verification=none
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
What I'm doing wrong?
A: I got the same error while trying to set up keycloak in quarkus dev environment.
I found out there was a problem with the resource configuration. First I fixed a part of the problem by setting to true the Authorization Enabled setting in the client setting page.
It gave me another error: invalid_scope, Requires uma_protection scope
I'm guessing it's a client scope to add. I found a issue stating that it should be a scope and not a client scope but can't find it anymore.
anyway, the easiest way I found to fix this configuration for my dev environment was to reimport the quarkus realm from this file: quarkus-realm.json
it seems to be up to date and working. Next you can check the config to find out your missing params.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71861002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LINQ doesn't work with a "select isnull" query..?
Possible Duplicate:
Equivalent of SQL ISNULL in LINQ?
Using IsNull or select COALESCE in Linq..?
I've tried this query in LINQ:
string query = @"SELECT ISNULL(P.firstname, s.firstname) AS Expr1,ISNULL(P.lastname,
s.lastname) AS Expr2 FROM comment AS C LEFT OUTER JOIN professor AS P ON P.ID =
C.PID LEFT OUTER JOIN student AS s ON s.ID = C.SID
WHERE (C.VID = 2)";
ArrayList allNames=null;
using (var context = new NewsReaderEntities())
{
ObjectQuery<string> results = context.CreateQuery<string>(query);
// ObjectQuery<string> results1 = context.CreateQuery<string>
(query1,parameters);
foreach (string result in results )
{
allNames.Add(result);
}
}
return allNames;
}
but it returns the error:
linq 'ISNULL' cannot be resolved into a valid type or function. Near
simple identifier,
I've also tried this query:
SELECT COALESCE(p.firstname, s.firstname), COALESCE(p.lastname, s.lastname)
FROM comment c
LEFT JOIN Professor p
ON c.pid = p.id
LEFT JOIN Student s
ON c.sid = s.id
WHERE c.vid = 2
This also raises an error.
Both work okay in SQL Management. Any ideas?
A: See this example:
var query = from p in Pets select p;
if (OwnerID != null) query = query.Where(x => x.OwnerID == OwnerID);
if (AnotherID != null) query = query.Where(x => x.AnotherID == AnotherID);
if (TypeID != null) query = query.Where(x => x.TypeID == TypeID);
Hope this help you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11063709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: how to fix Copy other pages data below mainActivity data in Android I want develop Android application for one website, i fetch website posts from JSON and show in RecyclerView. I show title, image, description and category in MainActivity and i want when click on Category go to categoryActivity and show this category posts!
I write below codes, but when go to the categoryActivity and back to MainActivity i see removed lasted post and added Category post in instead of MainActivity last post!
For example : my MainActivity is image 1 :
when click on post #2 (from category #2) and back to MainActivity, in MainActivity show such as this image :
Copy this post in below activity and remove the lasted post!
Adapter class: (i use for 2 activities from one adapter)
public class MainAdapter_loadMore extends RecyclerView.Adapter {
private List<MainDataModel> mDateSet;
private Context mContext;
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 7;
private int lastVisibleItem, totalItemCount;
private boolean loading;
private OnLoadMoreListener onLoadMoreListener;
public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
.getLayoutManager();
recyclerView
.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView,
int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager
.findLastVisibleItemPosition();
if (!loading
&& totalItemCount <= (lastVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
if (onLoadMoreListener != null) {
onLoadMoreListener.onLoadMore();
}
loading = true;
}
}
});
}
}
@Override
public int getItemViewType(int position) {
return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.post_card_layout, parent, false);
vh = new DataViewHolder(v);
} else {
View v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.progressbar_item, parent, false);
vh = new ProgressViewHolder(v);
}
return vh;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(mContext)
.load(mDateSet.get(position).getThumbnail())
.placeholder(R.drawable.post_image)
.crossFade()
.into(((DataViewHolder) holder).main_post_image);
((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));
((DataViewHolder) holder).main_dateTime.setText(Html.fromHtml(mDateSet.get(position).getDateTime()));
((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getAuthor()));
((DataViewHolder) holder).main_category.setText(Html.fromHtml(mDateSet.get(position).getCategory()));
((DataViewHolder) holder).main_category.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getCategory())
.putExtra("categoryID", model.getCategoryID()));
}
});
((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail())
.putExtra("content", model.getContent())
.putExtra("dateTime", model.getDateTime())
.putExtra("author", model.getAuthor())
.putExtra("category", model.getCategory()));
}
});
} else {
((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
}
}
public void setLoaded() {
loading = false;
}
@Override
public int getItemCount() {
return mDateSet.size();
}
public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
this.onLoadMoreListener = onLoadMoreListener;
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public class DataViewHolder extends RecyclerView.ViewHolder {
private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
private ImageView main_post_image;
public DataViewHolder(final View itemView) {
super(itemView);
main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
main_author = (TextView) itemView.findViewById(R.id.post_name_text);
main_category = (TextView) itemView.findViewById(R.id.post_category_text);
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
}
MainActivity AsyncTask codes:
public class MainDataInfo_loadMore {
private Context mContext;
private String ServerAddress = ServerIP.getIP();
public void getMainDataInfo_loadMore(Context context, int pageNumber) {
mContext = context;
new getInfo().execute(ServerAddress + "page=" + pageNumber);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
@Override
protected void onPreExecute() {
//CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
String url = (String) params[0];
Request request = new Request.Builder()
.url(url)
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
// Thumbnail
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
// Author
JSONObject Author = postObject.optJSONObject("author");
// Category
JSONArray category = postObject.getJSONArray("categories");
for (int j = 0; j < category.length(); j++) {
JSONObject categoryObject = category.getJSONObject(j);
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String dateTime = postObject.getString("date");
String thumbnail = imagesPair.getString("url");
String authorShow = Author.getString("name");
String categoryShow = categoryObject.getString("title");
String category_id = categoryObject.getString("id");
Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + thumbnail);
Log.d("Data", "Post author: " + authorShow);
Log.d("Data", "Post category: " + categoryShow);
Log.d("Data", "Post category ID: " + category_id);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
@Override
protected void onPostExecute(String result) {
//CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
CategoryActivity AsyncTask:
public class CatDataInfo {
private Context mContext;
private String ServerAddress = ServerIP_cat.getCatIP();
public void getCatDataInfo(Context context, String catID) {
mContext = context;
new getInfo().execute(ServerAddress + "id=" + catID);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
@Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
String url = (String) params[0];
Request request = new Request.Builder()
.url(url)
.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("posts");
infoModels = new ArrayList<>();
for (int i = 0; i < postsArray.length(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
// Thumbnail
JSONObject images = postObject.optJSONObject("thumbnail_images");
JSONObject imagesPair = images.optJSONObject("medium");
// Author
JSONObject Author = postObject.optJSONObject("author");
// Category
JSONArray category = postObject.getJSONArray("categories");
for (int j = 0; j < category.length(); j++) {
JSONObject categoryObject = category.getJSONObject(j);
int id = postObject.getInt("id");
String title = postObject.getString("title");
String content = postObject.getString("content");
String dateTime = postObject.getString("date");
String thumbnail = imagesPair.getString("url");
String authorShow = Author.getString("name");
String categoryShow = categoryObject.getString("title");
String category_id = categoryObject.getString("id");
Log.d("CatData", "Cat Post ID: " + id);
Log.d("CatData", "Cat Post title: " + title);
Log.d("CatData", "Cat Post image: " + thumbnail);
Log.d("CatData", "Cat Post author: " + authorShow);
Log.d("CatData", "Cat Post category: " + categoryShow);
Log.d("CatData", "Cat Post category ID: " + category_id);
Log.d("CatData", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, category_id, thumbnail));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
@Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
}
}
}
}
MainActivity class:
public class Main_page extends AppCompatActivity {
private static final long RIPPLE_DURATION = 250;
private Toolbar toolbar;
private RelativeLayout root;
private ImageView menu_image, toolbar_refresh;
private RecyclerView main_recyclerView;
private MainAdapter_loadMore mAdaper;
private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
protected Handler handler;
private RelativeLayout loadLayout;
private LinearLayoutManager mLayoutManager;
private int pageCount = 1;
String ServerAddress = ServerIP.getIP();
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {//go to the click action
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
// Initializing
handler = new Handler();
context = getApplicationContext();
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
mLayoutManager = new LinearLayoutManager(this);
loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
// Toolbar
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
}
// Load First Data
LoadData();
// Menu
root = (RelativeLayout) findViewById(R.id.main_root);
View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
root.addView(guillotineMenu);
menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
.setStartDelay(RIPPLE_DURATION)
.setActionBarViewForAnimation(toolbar)
.setClosedOnStart(true)
.build();
// RecyclerView and setData
main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
main_recyclerView.setHasFixedSize(true);
main_recyclerView.setLayoutManager(mLayoutManager);
mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
main_recyclerView.setAdapter(mAdaper);
// Load More data
mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
dataModels.add(null);
mAdaper.notifyItemInserted(dataModels.size() - 1);
LoadMoreData(pageCount);
}
});
}
@Subscribe
public void onEvent(List<MainDataModel> mainInfoModels) {
if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdaper.notifyItemRemoved(dataModels.size());
mAdaper.setLoaded();
}
mAdaper.add(mainInfoModels);
mAdaper.notifyDataSetChanged();
pageCount++;
if (dataModels.isEmpty()) {
main_recyclerView.setVisibility(View.GONE);
loadLayout.setVisibility(View.VISIBLE);
} else {
main_recyclerView.setVisibility(View.VISIBLE);
loadLayout.setVisibility(View.GONE);
}
}
private void LoadData() {
MainDataInfo dataInfo = new MainDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getMainDataInfo(this);
}
private void LoadMoreData(int pageNumber) {
MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
// here getMainDataInfo() should return the server response
dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
}
}
Attention : Please don't give me negative points, I search in google but not find answer to my question. I am amateur and I really need you helps! thanks all<3
A: Try removing static so that
public static class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
becomes
public class ProgressViewHolder extends RecyclerView.ViewHolder {
public AVLoadingIndicatorView progressBar;
public ProgressViewHolder(View v) {
super(v);
progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37097182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add image at the end of text line using pdfmake? I'm using pdfmake. I'm trying to figure out how to add image to the end of text line instead of the new line.
For example:
var dd = {
content: [
'Test text',
{image: 'sampleImage.jpg', width: 24, height: 24}
]
}
Using this description pdfmake generates PDF where first line is 'Test text', and second contains image.
I need that text and image would be in single line like 'Test text [image]'.
Has anyone done this before?
I would like to get some advice on how to do it. Thanks.
A: Use columns
var dd = {
content: [
{
columns: [
{
width: 'auto',
text: 'Test text'
},
{
width: '*',
image: 'sampleImage.jpg',
width: 24,
height: 24
}
]
}
]
}
A: If you want the image to be inline with your Multiline text you can use columns + stack
Example:
columns: [
{
image: "URL",
height: 150,
width: 180
},
{
stack: [
{
columns: [
{
text: 'First column first line',
width: '35%'
},
{
text: 'Second column first line',
width: '35%'
},
{
text: 'Third column first line',
width: '30%'
}
]
},
{
columns: [
{
text: 'First column second line',
width: '35%'
},
{
text: 'Second column second line',
width: '35%'
},
{
text: 'Third column second line',
width: '30%'
}
]
}
],
width: '*'
}]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39201585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Add unmarshalling method to JAXB generated POJOs I have a bunch of XSDs that i transform into POJO with the jaxb maven plugin.
For logging purposes, i'd like to have a "unmarshal" method directly integrated inside the JAXB objects, so that i could call something like generatedPOJO.toXMLString(), knowing that generatedPOJO is the POJO generated from the XSD file via JAXB.
I tried to look in the Custom bindings documentation, but i got nothing out of that.
Thank you for your help.
EDIT: What i want is that JAXB, in addition to generating POJOs from XSD files, adds a toXMLString() method to these POJOs.
This method needs to be generated by JAXB, since i can't edit the generated POJOS.
A: In short, don't do this, it won't be a good design.
While, as @j.con pointed out, it is possible to add further methods to the generated classes, using -xinject-code or a custom XJC plugin, adding a marshalling method is not a good idea. With JAXB API, it will be pretty ugly.
To do anything you'll need an instance of JAXBContext. Either you'll pass it to your method or instantiate within the method.
The latter isn't quite good as JAXBContext is instantiated for a collection of classes or packages (context path). So you'll basically have to preset, with which classes your class may be used together. Doing so, you're losing flexibility.
Next, JAXB marshallers produce many things, not just strings/stream results but also DOM or SAX or StAX. JAXB API is quite cool about that. Opting just for strings seems to be a shortsighted choice to be.
Finally, I don't think adding toXMLString() or whatever is so much sweet syntactic sugar compared to a simple utility service or class. And hacking into code generation for that really feels like misplaced effort.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31859059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EF Check a Lazy Property without load it I have an instance of class loaded by db.MyclassSet.AsNoTracking(). So the entity is not tracked on the context. I need to know if the OneToMany property of MyClass is loaded.
If I try to access by reflections I get an exception:
When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.
Any idea?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32862626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Draw inscribe square into the circle I am trying to draw inscribing square into the circle, but I don't know, how should I calculate the start and end point:
import numpy as np
import cv2
img = np.zeros([300,300,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255
imageWithCircle = cv2.circle(img, (150,150), 60, (0, 0, 255), 2)
#startpoint = ...
#endpoint = ...
imageWithInscribingSquare = cv2.rectangle(imageWithCircle, startpoint, endpoint, (0, 0, 255) , 2)
cv2.imshow("Circle", imageWithCircle)
cv2.waitKey(0)
cv2.destroyAllWindows()
A: Check this:
import numpy as np
import cv2
img = np.zeros([300,300,3],dtype=np.uint8)
img.fill(255) # or img[:] = 255
imageWithCircle = cv2.circle(img, (150,150), 60, (0, 0, 255), 2)
r = 60
startpoint = (int(150+(r/(2**0.5))),int(150-(r/(2**0.5))))
endpoint = (int(150-(r/(2**0.5))),int(150+(r/(2**0.5))))
print(startpoint,print(endpoint))
imageWithInscribingSquare = cv2.rectangle(imageWithCircle, startpoint, endpoint, (255, 0, 0) , 2)
cv2.imshow("Circle", imageWithCircle)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
Calculation:
If the radius is 'r', then the side of the square will be √2r, From the center the start point would be √2r/2 less in width and √2r/2 more in height, and vice versa for endpoint.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61330239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to connect reactJS front-end with PHP? I am developing a front-end with ReactJS.
How can I serve this app via PHP (plain PHP or Yii1)?
A: I suppose you'd want to go through the HTTP Protocol to create communication between the two.
In ReactJSX you want to make a fetch/get call that is provided with an EndPoint/REST from your backend.
// at the beginning of your file
import axios from 'axios';
// in your component constructor
state = {
yourStateWithTheRecievedData: "",
}
// as a component method
componentDidMount = () => {
axios
.get('http://localhost:8080/YourBackendAPI')
.then(response => {
this.setState({
yourStateWithTheRecievedData: response.data.yourStateWithTheRecievedData
})
console.log(response.data.yourStateWithTheRecievedData)
})
}
You should now have a state with the data you've recieved. If you have a hard time doing this, i suggest you start off by first applying it to a public API.
You can find a list of public API's here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55276763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: I would like to disable fast forward but not rewind in Youtube I am curious if there is an embed code that will allow me to disable the fast forward feature, but still allow a user to rewind videos in Youtube. I am trying to embed a video used by students.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53179711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Round Robin Matches using mysql I have table like below and Want to generate a round robin match schedule.
Input Table.
TID PlayerID
2 14
2 1
2 21
2 37
2 17
Output
14 V 1
14 V 21
14 V 37
14 V 17
1 V 21
1 V 37
1 V 17
21 V 37
21 V 17
37 V 17
A: If you want all possible combinations regardless or left/right order you can do:
select
a.player_id,
b.player_id
from player a
join player b on b.player_id < a.player_id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59272305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Show only a portion of an image with java If I have a large image that is made up of 25 x 25 smaller images in a grid. How can I use java to only show a portion of that larger grid (such as drawing a portion that starts at 125,25 and ends showing at 150,50)?
A: I'd break up the image into smaller images, put the smaller image cells into their own ImageIcons and then display whichever Icons I desired in JLabels, perhaps several of them. BufferedImage#getSubimage(...) can help you break the big image into smaller ones.
(decided to make it an answer)
A: If you don't need a physical copy of the sub image and only need to display it then you could add the image to a JLabel which you add to a JScrollPane without any scrollbars. Set the preferredSize() of the scrollpane equal to the dimension of your sub images (25x25). Then you can use
scrollPane.getViewport().setViewPosition(...);
to position the viewport to disply any sub image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8526837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Role provider in console/WPF/WinForms application I have written a role provider which assumes Windows authentication and so far works well with WCF services and ASP.NET. Is it possible to use it also with a console/WPF/WinForm application? I tried a configuration like this on a very simple console app but the Initialize method of the provider doesn't even get called (thanks in advance):
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication mode="Windows" />
<roleManager enabled="true"
defaultProvider="Authorization.RoleProvider">
<providers>
<clear/>
<add name="Authorization.RoleProvider"
type="Authorization.RoleProvider, Authorization.RoleProvider"
applicationName="urn:AuthorizationDemo:Program"
authorizationServiceUrl="net.pipe://localhost/Authorization/Authorization.svc"/>
</providers>
</roleManager>
</system.web>
</configuration>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16659130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress plugin uninstall.php I am trying to write a simple plugin that, among other things, creates a custom post type.
I have been searching everywhere but I have really no idea on how to write the uninstall function that delete the custom post type and all its entries from the db.
I have found this on the WordPress codex, but I don't understand what to do with it.. shame
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
exit();
$option_name = 'plugin_option_name';
delete_option( $option_name );
// For site options in multisite
delete_site_option( $option_name );
//drop a custom db table
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );
Can anyone help?
Thanks in advance
Would this be correct?
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) )
exit();
global $wpdb;
$posts_table = $wpdb->posts;
$query = "
DELETE FROM wp_posts
WHERE post_type = 'messages'
";
$wpdb->query($query);
A: The WP codex page http://codex.wordpress.org/Function_Reference/register_uninstall_hook has 2 important pieces of information, only 1 of which you list in your question. You do need to make sure that you register the hook.
That aside, if you want to remove all custom post data (regardless if it is upon uninstallation or as another person commented having a seperate button to remove data as many plugins do) you need to be sure to remove the postmeta records as well.
global $wpdb;
$cptName = 'messages';
$tablePostMeta = $wpdb->prefix . 'postmeta';
$tablePosts = $wpdb->prefix . 'posts';
$postMetaDeleteQuery = "DELETE FROM $tablePostMeta".
" WHERE post_id IN".
" (SELECT id FROM $tablePosts WHERE post_type='$cptName'";
$postDeleteQuery = "DELETE FROM $tablePosts WHERE post_type='$cptName'";
$wpdb->query($postMetaDeleteQuery);
$wpdb->query($postDeleteQuery);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25198700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React parsing Unexpected token I'm having some problems with my React code.
I'm trying to add authentication but it's giving me error like
./src/components/UserInfo/index.js Line 29: Parsing error:
Unexpected token, expected ","
27 | 28 |
29 | {authenticated ? (
| ^ 30 | 31 | 32 |
Here is my code
import React, { Component } from "react";
import { connect } from "react-redux";
import { Avatar, Popover } from "antd";
import { userSignOut } from "appRedux/actions/Auth";
class UserInfo extends Component {
render() {
const { authenticated } = this.props;
const userMenuOptions = (
<ul className="gx-user-popover">
<li>My Account</li>
<li>Connections</li>
<li onClick={() => this.props.userSignOut()}>Logout
</li>
</ul>
);
return (
{authenticated ? (
<Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
trigger="click">
<Avatar src={require("assets/images/w-logo.png")}
className="gx-avatar gx-pointer" alt="" />
</Popover>
) : (
<Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
trigger="click">
<Avatar src={require("assets/images/w-logo.png")}
className="gx-avatar gx-pointer" alt="" />
</Popover>
)}
)
}
}
const mapStateToProps = state => {
//console.log(state.auth.token);
return {
authenticated: state.auth.token !== null,
locale: state.settings.locale
}
}
export default connect(mapStateToProps, { userSignOut })(UserInfo);
A: The problem lies in that line because you are returning
return (
{authenticated ? (...) : (...)});
Which means, that you're trying to return an object, and that's not what you actually want. So you should change it to this:
return authenticated ? (
<Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
trigger="click">
<Avatar src={require("assets/images/w-logo.png")}
className="gx-avatar gx-pointer" alt="" />
</Popover>
) : (
<Popover overlayClassName="gx-popover-horizantal" placement="bottomRight" content={userMenuOptions}
trigger="click">
<Avatar src={require("assets/images/w-logo.png")}
className="gx-avatar gx-pointer" alt="" />
</Popover>
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59482848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using validationRules in Models to validate form Codeigniter 4 So I have these variables $skipValidation (set specifically to FALSE), $validationRules, $validationMessages set according to this documentation
but for the life of me I can't figure out what trigger this $validationRules to run, I just assume that $skipValidation meant Codeigniter-4 already got me covered (automatically validates input before doing any queries)..
I even put $UserModel->errors() in case the validation rules catch an error
if($userModel->insert($data) === false) {
return view('form', ['validation' => $userModel->errors()])
} else {
redirect()->to('home');
}
I have these rules required and min_length[] applied to $validationRules but the model just skips the validationRules and insert it immediately to database rendering $validationRules useless..
Any ideas how to get validationRules in Models working? or how is it supposed to be used? I keep looping in the documentation because I don't know any better.
A: Dumb me, i was trying to figure out what is wrong with the code this whole time when its just a simple problem.. i have two models with the same filename (backup project) and i blindly edits model file that is inside the backup project..
Perhaps for future readers seeking an answer, don't forget to check your folder path for your model file, you might make the same mistake as i did.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66134075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ORA-01427: SELECT * FROM TABLE gives error single-row subquery returns more than one row I tried using the following variants:
SELECT * FROM "DB"."TABLE"
SELECT COUNT(1) FROM "DB"."TABLE"
SELECT reference FROM "DB"."TABLE"
SELECT reference FROM "DB"."TABLE" WHERE rownum < 2
where reference was a specific field of type cx_Oracle.STRING
All of those return the following error:
cx_Oracle.DatabaseError: ORA-01427: single-row subquery returns more than one row
I don't see why the final example would return an error complaining about returning more than one row, nor why returning more than one row would be a problem here in any of the examples.
I've seen a lot of similar problems on SO, but they all have nested selects where I can understand this being problematic, but these should just be simple selects.
The database is Oracle 11g Enterprise Edition, and it is being accessed through the cx_Oracle python interface.
A: It turns out the 'table' I was pulling from was in fact a database view, a sort of pseudo-table, which is composed of sql joining together other tables.
The error actually lay in the view, rather than in my SQL, which is where the subquery referred to in the error was. Thanks for the help in the comments!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52161776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling multiple arguments in an array from a function [PHP] I am trying to call multiple arguments from a function in php using an array.
Class useful {
function callFunctionFromClass($className, $function, $args = array()) {
return $className::$function($args);
}
}
<?php
require("library/class.php");
$u = new useful;
$u::callFunctionFromClass(new useful, "text", "Test", "Test");
?>
I have the function text() created aswell like so:
function text($msg, $msg2) {
echo $msg;
echo $msg2;
}
I am getting this error message:
Warning: Missing argument 2 for useful::text(),
called in htdocs\class\library\class.php on line 16
and defined in htdocs\class\library\class.php on line 11
Test
Notice: Undefined variable: msg2 in htdocs\class\library\class.php on line 13
This works fine without $msg2 & a second argument. So how is multiple arguments pulled off?
A: you must use call_user_func_array. Also you are calling callFunctionFromClass as a static method but it isn't static
Class useful
{
public function callFunctionFromClass($className, $function, $args = array())
{
return call_user_func_array(array($className, $function), $args);
}
public function text($msg, $msg2)
{
echo $msg;
echo $msg2;
}
}
$u = new useful;
$test = $u->callFunctionFromClass('useful', "text", array("Test", "Test"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31725382",
"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.